Exemplo n.º 1
0
    def setUp(self):
        Organization.objects.bulk_create([
            Organization(name='org-01'),
            Organization(name='org-02'),
            Organization(name='org-03'),
        ])
        org_01, org_02, org_03 = Organization.objects.all()
        self.org_01, self.org_02, self.org_03 = org_01, org_02, org_03

        set_current_org(org_01)

        AdminUser.objects.bulk_create([
            AdminUser(name='au-01', username='******'),
            AdminUser(name='au-02', username='******'),
            AdminUser(name='au-03', username='******'),
        ])

        SystemUser.objects.bulk_create([
            SystemUser(name='su-01', username='******'),
            SystemUser(name='su-02', username='******'),
            SystemUser(name='su-03', username='******'),
        ])

        admin_users = AdminUser.objects.all()
        Asset.objects.bulk_create([
            Asset(hostname='asset-01',
                  ip='192.168.1.1',
                  public_ip='192.168.1.1',
                  admin_user=admin_users[0]),
            Asset(hostname='asset-02',
                  ip='192.168.1.2',
                  public_ip='192.168.1.2',
                  admin_user=admin_users[0]),
            Asset(hostname='asset-03',
                  ip='192.168.1.3',
                  public_ip='192.168.1.3',
                  admin_user=admin_users[0]),
        ])

        new_user = User.objects.create
        new_org_memeber = OrganizationMember.objects.create

        u = new_user(name='user-01',
                     username='******',
                     email='*****@*****.**')
        new_org_memeber(org=org_01, user=u, role=ORG_ROLE.USER)
        new_org_memeber(org=org_02, user=u, role=ORG_ROLE.USER)
        self.user_01 = u

        u = new_user(name='org-admin-01',
                     username='******',
                     email='*****@*****.**')
        new_org_memeber(org=org_01, user=u, role=ORG_ROLE.ADMIN)
        self.org_admin_01 = u

        u = new_user(name='org-admin-02',
                     username='******',
                     email='*****@*****.**')
        new_org_memeber(org=org_02, user=u, role=ORG_ROLE.ADMIN)
        self.org_admin_02 = u
Exemplo n.º 2
0
 def setUp(self):
     self.user = get_user_model().objects.create_user(username='******')
     self.user_lookup = UserLookup.objects.create(
         user=self.user, scheme='mock', identifier=self.user.username)
     set_local_user(self.user)
     self.asset = Asset(name='test-asset')
     self.asset.save()
Exemplo n.º 3
0
    def test_create_asset(self):
        """Asset object can be created."""
        asset_uuid = uuid.uuid4()
        asset = Asset(
            id=asset_uuid,
            name="Asset Name",
            asset_class=self.asset_class,
            easy_to_borrow=True,
            exchange=self.exchange,
            marginable=True,
            shortable=True,
            status=Asset.ACTIVE,
            symbol="SYMBOL",
            tradable=True,
        )
        asset.save()

        self.assertIn(asset, Asset.objects.all())
        self.assertEqual(str(asset.id), str(asset_uuid))
        self.assertEqual(asset.name, "Asset Name")
        self.assertEqual(asset.asset_class.pk, self.asset_class.pk)
        self.assertTrue(asset.easy_to_borrow)
        self.assertEqual(asset.exchange.pk, self.exchange.pk)
        self.assertTrue(asset.marginable)
        self.assertTrue(asset.shortable)
        self.assertEqual(asset.status, Asset.ACTIVE)
        self.assertEqual(asset.symbol, "SYMBOL")
        self.assertTrue(asset.tradable)
Exemplo n.º 4
0
    def test_put_with_perms(self):
        """A user with the change asset permission can put an asset."""
        client = APIClient()
        asset_dict = copy.copy(COMPLETE_ASSET)
        asset_dict['department'] = 'TESTDEPT2'
        asset = Asset(**asset_dict)
        asset.save()

        # PUT not in allowed methods
        self.assert_method_is_not_listed_as_allowed('PUT', asset)

        result_put = client.put('/assets/%s/' % asset.pk, COMPLETE_ASSET)

        # Not allowed because the asset belongs to TESTDEPT2
        self.assertEqual(result_put.status_code, 403)

        # Succeeds if use has permission
        perm = Permission.objects.get(
            content_type=ContentType.objects.get_for_model(Asset),
            codename='change_asset')
        self.user.user_permissions.add(perm)
        self.user.save()

        self.refresh_user()

        self.assertTrue(self.user.has_perm('assets.change_asset'))

        # PUT is now in allowed methods
        self.assert_method_is_listed_as_allowed('PUT', asset)

        result_put = client.put('/assets/%s/' % asset.pk, COMPLETE_ASSET)
        self.assertEqual(result_put.status_code, 200)
Exemplo n.º 5
0
def create_asset(user_instance, company_instance):
    A = Asset(asset_tag=get_random_tag(),
              device_type=get_random_type(),
              created_by=user_instance,
              company=company_instance,
              serial_number=get_random_tag())
    A.save()
Exemplo n.º 6
0
def assets_add_apply(request):
    if request.method == "POST":
        asset = Asset(mnfacture=request.POST['mnfacture'],
                      model=request.POST['model'],
                      cpu=request.POST['cpu'],
                      memory=request.POST['memory'],
                      harddisk=request.POST['hardDisk'],
                      is_where=request.POST['where'],
                      is_state=request.POST['state'],
                      purchase_date=request.POST['purchase_date'],
                      comments=request.POST['comments'],
                      member_name_id=request.POST['memberId'],
                      serial=request.POST['serial'])
        asset.save()
        asset_status = int(request.POST['state'])
        if asset_status == ASSET_STATUS_RENTAL:
            asset_rent = Assetrent(stdate=request.POST['rentDate'],
                                   eddate=request.POST['returnDate'],
                                   comments=request.POST['comments'],
                                   asset_id=asset.id,
                                   member_name=request.POST['memberName'])
            asset_rent.save()
        return redirect("assets_main")
    else:
        return render(request, 'assets_main/assets.html',
                      {'permission': REPORT_PERMISSION_DEFAULT})
Exemplo n.º 7
0
 def create_asset(tree, item_type=None):
     if item_type == 1:
         text_item = Text(text=tree)
         text_item.save()
         return text_item.pk
     if item_type == 2:
         uri_item = UriElement(uri=tree)
         uri_item.save()
         return uri_item.pk
     if type(item_type) is dict and \
             len(item_type.keys()) == 1 and \
             "3" in item_type.keys():
         enum_item = Enum(t=EnumType.objects.get(pk=item_type["3"]), item=tree)
         enum_item.save()
         return enum_item.pk
     asset_type = AssetType.objects.get(type_name=tree["type"])
     content_ids = {}
     for key in asset_type.schema.keys():
         if type(asset_type.schema[key]) is list:
             item_ids_list = []
             for list_item in tree[key]:
                 item_ids_list.append(create_or_modify_asset(list_item, item_type=asset_type.schema[key][0]))
             content_ids[key] = item_ids_list
         else:
             content_ids[key] = create_or_modify_asset(tree[key], item_type=asset_type.schema[key])
     asset = Asset(t=asset_type, content_ids=content_ids)
     asset.save()
     return str(asset.pk)
Exemplo n.º 8
0
def _create_asset_on_import(asset_value, scan, asset_type='unknown'):
    Event.objects.create(message="[EngineTasks/_create_asset_on_import()] create: '{}/{}'.".format(asset_value, asset_type), type="DEBUG", severity="INFO", scan=scan)

    # create assets if data_type is ip-subnet or ip-range
    if scan and asset_type == 'ip':
        assets = scan.assets.filter(type__in=['ip-subnet', 'ip-range'])

        # Search parent asset
        parent_asset = None
        for pa in assets:
            if net.is_ip_in_ipset(ip=asset_value, ipset=pa.value):
                parent_asset = pa
                break
        if parent_asset:
            name = "{} (from '{}')".format(asset_value, parent_asset.name)
            criticity = parent_asset.criticity
            owner = parent_asset.owner
        else:
            name = asset_value
            criticity = 'medium'
            owner = User.objects.filter(username='******').first()
    else:
        if net.is_valid_ip(asset_value):
            asset_type = "ip"
        elif net._is_valid_domain(asset_value):
            asset_type = "domain"
        elif net._is_valid_url(asset_value):
            asset_type = "url"
        else:
            asset_type = "fqdn"  # default :/
        name = asset_value
        criticity = 'medium'
        owner = User.objects.filter(username='******').first()

    # Create the new asset ...
    asset_args = {
        'value': asset_value,
        'name': name,
        'type': asset_type,
        'criticity': criticity,
        'description': "Asset dynamically created",
        'owner': owner
    }
    asset = Asset(**asset_args)
    asset.save()
    scan.assets.add(asset)

    # Then add the asset to every related asset groups
    for ag in AssetGroup.objects.filter(assets__type__in=['ip-subnet', 'ip-range']):
        for aga in ag.assets.all():
            if net.is_ip_in_ipset(ip=asset_value, ipset=aga.value):
                ag.assets.add(asset)
                ag.save()
                ag.calc_risk_grade()
                ag.save()

    return asset
Exemplo n.º 9
0
 def test_no_raw_template(self):
     insufficient_type = AssetType(type_name="insufficient_type",
                                   schema={"text": 1},
                                   templates={})
     insufficient_type.save()
     t = Text(text="Foobar!")
     t.save()
     asset = Asset(t=insufficient_type, content_ids={"text": t.pk})
     asset.save()
     self.assertEqual(asset.render_template(), "")
Exemplo n.º 10
0
def make_asset(product_id, path, md5_check, class_label='hirise product'):
    asset = Asset()
    asset.class_label = class_label
    asset.instrument_name = 'HiRISE'
    asset.product_id = product_id
    asset.md5_check = md5_check
    asset.relative_file_path = path.partition(DATA_ROOT)[-1]
    asset.save()
Exemplo n.º 11
0
 def test_foo(self):
     t1 = Text(text="Foo")
     t1.save()
     t1_span = Asset(t=self.at("span-regular"), content_ids={"text": t1.pk})
     t1_span.save()
     self.assertJSONEqual(
         json.dumps(t1_span.content),
         json.dumps({
             'type': "span-regular",
             'id': str(t1_span.pk),
             'text': "Foo"
         }))
Exemplo n.º 12
0
 def test_privacy(self):
     """Test that a User cannot see/access to assets that are private outside their
     department"""
     client = APIClient()
     asset_dict = copy.copy(COMPLETE_ASSET)
     asset_dict['department'] = 'TESTDEPT2'
     asset_dict['private'] = True
     asset = Asset(**asset_dict)
     asset.save()
     result_patch = client.get('/assets/%s/' % asset.pk)
     self.assertEqual(result_patch.status_code, 404)
     list_assets = client.get('/assets/', format='json')
     self.assertEqual(list_assets.json()['results'], [])
Exemplo n.º 13
0
def create_assets():
    sourcedir = '/big/assets/mars_color_merge'
    files = os.listdir(sourcedir)
    assert all(['.tif' in f for f in files])

    ids = []
    for filename in files:
        print "creating asset for %s" % filename
        a = Asset()
        a.relative_file_path = 'mars_color_merge/' + filename
        a.class_label= 'color basemap'
        a.save()
        ids.append(a.id)
    return ids
Exemplo n.º 14
0
 def test_basic_template(self):
     statement = Text(text="Vertrauen ist gut. Kontrolle ist besser.")
     statement.save()
     attribution = Text(text="Lenin")
     attribution.save()
     asset = Asset(t=AssetType.objects.get(type_name="block-citation"),
                   content_ids={
                       "statement": statement.pk,
                       "attribution": attribution.pk
                   })
     asset.save()
     self.assertEqual(
         asset.render_template(),
         "Vertrauen ist gut. Kontrolle ist besser.\n - Lenin\n")
Exemplo n.º 15
0
def make_asset(product_id, path, md5_check, class_label='hirise product'):
    asset = Asset()
    asset.class_label = class_label
    asset.instrument_name = 'HiRISE'
    asset.product_id = product_id
    asset.md5_check = md5_check
    asset.relative_file_path = path.partition(DATA_ROOT)[-1]
    asset.save()
Exemplo n.º 16
0
def transform_asset(asset):
    data = {
        "exchange_id": "XNAS",
        "name": asset['name'],
        "symbol": asset['symbol'],
    }
    return Asset(**data)
Exemplo n.º 17
0
 def test_object_perms_user_can_change(self):
     """check that the object permission is true when
     the user is associated with the asset's existing and updated department"""
     self.request.method = 'PATCH'
     self.request.data['department'] = 'UIS'
     self.request.data['name'] = 'new name'
     self.assertTrue(self.has_object_permission(Asset(department='UIS')))
Exemplo n.º 18
0
class AssetAuditTest(TestCase):
    def setUp(self):
        self.user = get_user_model().objects.create_user(username='******')
        self.user_lookup = UserLookup.objects.create(
            user=self.user, scheme='mock', identifier=self.user.username)
        set_local_user(self.user)
        self.asset = Asset(name='test-asset')
        self.asset.save()

    def tearDown(self):
        clear_local_user()

    def test_no_audits_initially(self):
        """With no changes, there should be no audit."""
        self.assertEqual(Audit.objects.count(), 0)

    def test_create(self):
        """Changing an asset makes an audit record."""
        old_name = self.asset.name
        self.asset.name = 'new-name'
        self.asset.save()
        self.assertEqual(Audit.objects.count(), 1)
        audit = Audit.objects.filter(model_pk=repr(self.asset.pk)).first()
        self.assertIsNotNone(audit)
        self.assertEqual(audit.field, 'name')
        self.assertEqual(audit.old, old_name)
        self.assertEqual(audit.new, self.asset.name)
        self.assertEqual(audit.who.pk, self.user.pk)

    def test_audit_compare_override(self):
        """Changes to MultiSelectField fields are audited correctly."""

        # fixtures
        field = self.asset._meta.get_field('data_subject')
        choices = dict(Asset.DATA_SUBJECT_CHOICES)

        # check blank fields handles correctly
        self.assertFalse(self.asset.audit_compare(field, None, None))
        self.assertFalse(
            self.asset.audit_compare(field, MSFList(choices), set()))

        # check different list orders don't don't trigger an audit record
        self.assertFalse(
            self.asset.audit_compare(
                field,
                MSFList(choices, ['public', 'alumni']),
                ['alumni', 'public'],
            ))

        # check that actual change is detected
        self.assertTrue(
            self.asset.audit_compare(
                field,
                MSFList(choices, ['public', 'alumni']),
                {'alumni', 'public', 'supplier'},
            ))
Exemplo n.º 19
0
def _create_asset_on_import(asset_value, scan, asset_type='ip'):
    Event.objects.create(
        message="[EngineTasks/_create_asset_on_import()] create: '{}'.".format(
            asset_value),
        type="DEBUG",
        severity="INFO",
        scan=scan)

    # Search parent asset
    parent_asset = None
    for pa in scan.assets.filter(type__in=['ip-subnet', 'ip-range']):
        if net.is_ip_in_ipset(ip=asset_value, ipset=pa.value):
            parent_asset = pa
            break
    if parent_asset == None: return False

    # Create the new asset ...
    asset_args = {
        'value':
        asset_value,
        'name':
        "{} (from '{}')".format(asset_value, parent_asset.name),
        'type':
        asset_type,
        'criticity':
        parent_asset.criticity,
        'description':
        "Asset dynamically created. Imported desc: {}".format(
            parent_asset.description),
        'owner':
        parent_asset.owner
    }
    asset = Asset(**asset_args)
    asset.save()
    scan.assets.add(asset)

    # Then the asset to every related asset groups
    for ag in AssetGroup.objects.filter(
            assets__type__in=['ip-subnet', 'ip-range']):
        for aga in ag.assets.all():
            if net.is_ip_in_ipset(ip=asset_value, ipset=aga.value):
                ag.assets.add(asset)
                ag.save()
                ag.calc_risk_grade()
                ag.save()
    return asset
Exemplo n.º 20
0
 def test_cache_usage(self):
     text = Text(text="cached span")
     text.save()
     text_span = Asset(t=self.at("span-regular"),
                       content_ids={"text": text.pk})
     text_span.save()
     self.assertIsNone(text_span.content_cache)
     expected_content = json.dumps({
         'type': "span-regular",
         'id': str(text_span.pk),
         'text': "cached span"
     })
     self.assertJSONEqual(json.dumps(text_span.content), expected_content)
     self.assertIsNotNone(text_span.content_cache)
     self.assertJSONEqual(json.dumps(text_span.content_cache),
                          expected_content)
     self.assertJSONEqual(json.dumps(text_span.content), expected_content)
Exemplo n.º 21
0
 def test_partially_existent_caches(self):
     t1 = Text(text="Text1")
     t1.save()
     t2 = Text(text="Text2")
     t2.save()
     a1 = Asset(t=AssetType.objects.get(type_name="span-regular"),
                content_ids={"text": t1.pk})
     a1.save()
     a2 = Asset(t=AssetType.objects.get(type_name="span-emphasized"),
                content_ids={"text": t2.pk})
     a2.save()
     self.assertIsNone(a1.content_cache)
     self.assertIsNone(a1.raw_content_cache)
     self.assertIsNone(a2.content_cache)
     self.assertIsNone(a2.raw_content_cache)
     self.assertEqual(a1.content, {
         "id": str(a1.pk),
         "type": "span-regular",
         "text": "Text1"
     })
     self.assertIsNotNone(a1.content_cache)
     self.assertIsNone(a1.raw_content_cache)
     self.assertEqual(a1.content_cache, {
         "id": str(a1.pk),
         "type": "span-regular",
         "text": "Text1"
     })
     self.assertEqual(a2.render_template(), "Text2")
     self.assertIsNone(a2.content_cache)
     self.assertIsNotNone(a2.raw_content_cache)
     self.assertEqual(a2.raw_content_cache, "Text2")
     call_command("build_caches")
     r_a1 = Asset.objects.get(pk=a1.pk)
     r_a2 = Asset.objects.get(pk=a2.pk)
     self.assertIsNotNone(r_a1.content_cache)
     self.assertIsNotNone(r_a1.raw_content_cache)
     self.assertIsNotNone(r_a2.content_cache)
     self.assertIsNotNone(r_a2.raw_content_cache)
     self.assertEqual(r_a1.content_cache, {
         "id": str(r_a1.pk),
         "type": "span-regular",
         "text": "Text1"
     })
     self.assertEqual(r_a1.raw_content_cache, "Text1")
     self.assertEqual(r_a2.content_cache, {
         "id": str(r_a2.pk),
         "type": "span-emphasized",
         "text": "Text2"
     })
     self.assertEqual(r_a2.raw_content_cache, "Text2")
Exemplo n.º 22
0
    def test_asset_put_validation(self):
        """User's only allow to PUT an asset that has a department their are part of, and the
        PUT department has to be one he belongs to"""
        client = APIClient()
        asset_dict = copy.copy(COMPLETE_ASSET)
        asset_dict['department'] = 'TESTDEPT2'
        asset = Asset(**asset_dict)
        asset.save()
        result_put = client.put('/assets/%s/' % asset.pk, COMPLETE_ASSET)
        # Not allowed because the asset belongs to TESTDEPT2
        self.assert_method_is_not_listed_as_allowed('PUT', asset)
        self.assertEqual(result_put.status_code, 403)

        # We fix the department, so now the user should be allow but we try to change the
        # department to another that the user doesn't belong to
        asset.department = 'TESTDEPT'
        set_local_user(self.user)
        asset.save()

        # User can, in principle PUT...
        self.assert_method_is_listed_as_allowed('PUT', asset)

        # ... but not this asset
        result_put = client.put('/assets/%s/' % asset.pk, asset_dict)
        self.assertEqual(result_put.status_code, 403)

        # This one should be allowed
        asset_dict['department'] = 'TESTDEPT'
        asset_dict['name'] = 'asset2'
        result_put = client.put('/assets/%s/' % asset.pk, asset_dict)
        self.assert_method_is_listed_as_allowed('PUT', asset)
        self.assertEqual(result_put.status_code, 200)
Exemplo n.º 23
0
    def test_asset_patch_validation(self):
        """User's only allow to PATCH an asset that has a department their are part of, and the
        PATCH department has to be one he belongs to"""
        client = APIClient()
        asset_dict = copy.copy(COMPLETE_ASSET)
        asset_dict['department'] = 'TESTDEPT2'
        asset = Asset(**asset_dict)
        asset.save()
        result_patch = client.patch('/assets/%s/' % asset.pk,
                                    {"name": "asset1"})
        # Not allowed because the asset belongs to TESTDEPT2
        self.assert_method_is_not_listed_as_allowed('PATCH', asset)
        self.assertEqual(result_patch.status_code, 403)

        # We fix the department, so now the user should be allow but we try to change the
        # department to another that the user doesn't belong to
        asset.department = 'TESTDEPT'
        set_local_user(self.user)
        asset.save()

        # User is in principle allowed ...
        self.assert_method_is_listed_as_allowed('PATCH', asset)

        # ... but not in this case
        result_patch = client.patch('/assets/%s/' % asset.pk,
                                    {"department": "TESTDEPT2"})
        self.assertEqual(result_patch.status_code, 403)

        # This one should be allowed
        result_patch = client.patch('/assets/%s/' % asset.pk,
                                    {"name": "asset2"})
        self.assert_method_is_listed_as_allowed('PATCH', asset)
        self.assertEqual(result_patch.status_code, 200)
Exemplo n.º 24
0
 def test_single_asset(self):
     t = Text(text="Foohoo!")
     t.save()
     asset = Asset(t=AssetType.objects.get(type_name="span-regular"),
                   content_ids={"text": t.pk})
     asset.save()
     self.assertIsNone(asset.content_cache)
     self.assertIsNone(asset.raw_content_cache)
     call_command("build_caches")
     reloaded_asset = Asset.objects.get(pk=asset.pk)
     self.assertIsNotNone(reloaded_asset.content_cache)
     self.assertIsNotNone(reloaded_asset.raw_content_cache)
     self.assertEqual(reloaded_asset.content_cache, {
         "id": str(asset.pk),
         "type": "span-regular",
         "text": "Foohoo!"
     })
     self.assertEqual(reloaded_asset.raw_content_cache, "Foohoo!")
Exemplo n.º 25
0
 def can_apply_assets(self):
     from assets.models import Asset
     valid_assets = Asset.valid_assets()
     assets = Asset.objects.none()
     if self.is_groupadmin:
         assets |= valid_assets
     elif self.is_commonuser:
         for manager in self.group_managers:
             assets |= manager.assets
     return assets
Exemplo n.º 26
0
 def granted_assets_direct(self):
     from assets.models import Asset
     valid_assets = Asset.valid_assets()
     asset_perms_list = self.assetpermission_set.filter(
         is_active=True,
         date_expired__gt=timezone.now(),
     ).values_list('id', flat=True)
     nodes_list = self.granted_nodes_direct.values_list('id', flat=True)
     return valid_assets.filter(
         Q(granted_by_permissions__id__in=list(asset_perms_list))
         | Q(nodes__id__in=list(nodes_list))).distinct()
Exemplo n.º 27
0
 def create(self, data):
     print(data)
     if (data.get('asset')):
         assets_data = data.pop('asset')
         print('assets_data:', assets_data)
         asset = Asset.objects.create(**assets_data)
         print('asset_obj:', asset)
     else:
         asset = Asset()
     data['asset'] = asset
     server = Server.objects.create(**data)
     return server
Exemplo n.º 28
0
 def granted_assets_inherit_from_user_groups(self):
     from assets.models import Asset
     from perms.models import AssetPermission
     valid_assets = Asset.valid_assets()
     group_list = self.groups.values_list('id', flat=True)
     asset_perms_list = AssetPermission.objects.all().valid().filter(
         user_groups__id__in=list(group_list)).values_list('id', flat=True)
     nodes_list = self.granted_nodes_inherit_from_user_groups \
         .values_list('id', flat=True)
     return valid_assets.filter(
         Q(granted_by_permissions__id__in=list(asset_perms_list))
         | Q(nodes__id__in=list(nodes_list))).distinct()
Exemplo n.º 29
0
 def test_clear_cache(self):
     text = Text(text="cached text")
     text.save()
     span = Asset(t=self.at("span-regular"), content_ids={"text": text.pk})
     span.save()
     block = Asset(t=self.at("block-paragraph"),
                   content_ids={"spans": [str(span.pk)]})
     block.save()
     self.assertIsNone(span.content_cache)
     self.assertIsNone(block.content_cache)
     self.assertJSONEqual(
         json.dumps(span.content),
         json.dumps({
             'type': "span-regular",
             'id': str(span.pk),
             'text': "cached text"
         }))
     self.assertJSONEqual(
         json.dumps(block.content),
         json.dumps({
             'type':
             "block-paragraph",
             'id':
             str(block.pk),
             'spans': [{
                 'type': "span-regular",
                 'id': str(span.pk),
                 'text': "cached text"
             }]
         }))
     span = Asset.objects.get(pk=span.pk)
     block = Asset.objects.get(pk=block.pk)
     self.assertIsNotNone(span.content_cache)
     self.assertIsNotNone(block.content_cache)
     span.clear_cache()
     span = Asset.objects.get(pk=span.pk)
     block = Asset.objects.get(pk=block.pk)
     self.assertIsNone(span.content_cache)
     self.assertIsNone(block.content_cache)
Exemplo n.º 30
0
 def test_no_type_in_existing_sub_asset(self):
     text = Text(text="Foo")
     text.save()
     span = Asset(t=AssetType.objects.get(type_name="span-regular"),
                  content_ids={"text": text.pk})
     span.save()
     response = self.client.post(reverse('save_asset'),
                                 data={
                                     "type":
                                     "block-paragraph",
                                     "spans": [{
                                         "id": str(span.pk),
                                         "text": "This is not 'Foo'"
                                     }]
                                 },
                                 content_type="application/json")
     self.assertEqual(response.status_code, 200)
     block = Asset.objects.filter(content_ids__spans=[str(span.pk)])[0]
     self.assertJSONEqual(response.content, {
         "success": True,
         "id": str(block.pk)
     })
Exemplo n.º 31
0
def modify_password(request):
    if request.method == 'POST':
        host_ip = request.POST.get('ip')
        password = request.POST.get('password')
        print host_ip, password
        try:
            a = Server.objects.filter(ssh_host=host_ip)
            if a:
                a.update(ssh_password=password)
            else:
                print "没有此ip:%s,开始创建数据" % host_ip
                adata = Asset(asset_type='virtual', purpose="nothing")
                adata.save()
                vdata = Server(asset=adata,
                               ssh_host=host_ip,
                               ssh_port="22992",
                               ssh_user="******",
                               ssh_password=password)
                vdata.save()
        except:
            print "没有此ip:%s" % host_ip
    return HttpResponse("OK")
Exemplo n.º 32
0
 def test_load(self):
     code = Text(text="print(1)")
     code.save()
     lang_python = Enum(t=EnumType.objects.get(pk=2), item="python")
     lang_python.save()
     listing_block = Asset(
         t=AssetType.objects.get(type_name="block-listing"),
         content_ids={
             "code": code.pk,
             "language": lang_python.pk
         })
     listing_block.save()
     response = self.client.get(reverse('turnout_request'),
                                {'id': str(listing_block.pk)})
     self.assertEqual(response.status_code, 200)
     self.assertJSONEqual(
         response.content,
         json.dumps({
             "id": str(listing_block.pk),
             "type": "block-listing",
             "code": "print(1)",
             "language": "python"
         }))
Exemplo n.º 33
0
def bill_cashless_add(request):
    # def what_to_people_friendly(a):
    #     b=list(set(a.split(';')))
    #     c = ''
    #     for word in b:
    #         count=a.split(';').count(word)
    #         c = c + word + ' - ' + str(count) + u' шт; '
    #     return c
    lang,user,fio,method = get_info(request)
    # Получаем настройки из файла:
    import ConfigParser
    config=ConfigParser.RawConfigParser()
    config.read(config_file)
    # stages = ";".join([a[1] for a in config.items("cashless_stages")])
    from user_settings.functions import get_stages
    stages = get_stages(";")

    if request.method == 'POST':
        # Порядок действия таков:
        # 1) Создаём Cashless c этапами из файла настройки
        # 2) Создаём Payment с этим Cash
        # 3) Создаём Garanty - если её ещё нет. Если есть - добавляем к имеющейся
        # 4) Итерируем по элементам в форме от 1 до макс добавляя активы в список активов
        # 5) Если всё прошло хорошо - активы из списка сохраняем
        bill_date = request.POST.get('date','')
        if bill_date:
            a=[int(a) for a in bill_date.split(bill_date[2])]
            a.reverse()
            bill_date=datetime.datetime(*a)
        else:
            bill_date = datetime.datetime.now()
        cashless = Cashless(date_of_invoice = bill_date,
                stages=stages,
                # нужно для более простой обработки в дальнейшем
                dates = ';'.join(map(lambda x: '',range(len(stages.split(';'))))),
                contractor = Contractor.objects.get(id=request.POST.get('contractor_id')),
                bill_number = request.POST.get('bill_number'),
                )
        cashless.save()
        payment = Payment(cashless = cashless,
                )
        payment.save()
        try:
            garanty = Garanty.objects.get(number = request.POST.get('garanty'))
        except Garanty.DoesNotExist:
            garanty = Garanty(number = request.POST.get('garanty'))
            garanty.save()
        # Для записки сопровождения счёта
        places = ''
        what = ''
        price = 0
        for item_number in range(1,int(request.POST.get('max_asset_form_number'))+1):
            sitem_number = str(item_number)
            if sitem_number+'_model' in request.POST:
                for count in range(0,int(request.POST.get('count_of_asset'+sitem_number))):
                    a=Asset(asset_type = Asset_type.objects.get(id=request.POST.get(sitem_number+'_asset_type')),
                        payment = payment,
                        garanty = garanty,
                        model = request.POST.get(sitem_number+'_model'),
                        status = Status.objects.get(id=request.POST.get(sitem_number+'_status')),
                        guarantee_period = request.POST.get(sitem_number+'_guarantee_period'),
                        note = request.POST.get(sitem_number+'_note'),
                        price = request.POST.get(sitem_number+'_price'),
                        )
                    a.save()
                    cur_place=Place_Asset(installation_date = bill_date,
                        asset = a,
                        place = Place.objects.get(id=request.POST.get(sitem_number+'_current_place')),
                        )
                    cur_place.save()
                    # a_TMP = cur_place.place.place
                    if cur_place.place.place + u';' not in places:
                        places = places+ cur_place.place.place + u';'
                    # if a.model + u';' not in what:    
                        # what = what + a.model + u';'
                    what = what + a.model + u';'
                    price += float(a.price)
        places = places[:-1]
        # Приводим к человеческому виду "кот - 5шт"
        what = what_to_people_friendly(what[:-1])
        # Теперь надо выдать штуку для распечатки сопровождения счёта
        text = config.get('cashless','text')
        text=text.decode('utf8').format({'number':cashless.bill_number,'where':places,'date':str(cashless.date_of_invoice),'price':price,'what':what,'who':fio.fio,'phones':fio.tel,'date2':str(datetime.datetime.now()).split('.')[0]}).replace('\n','<p>')
        # window.open("http://mylink.net", "windowName");
        # window.localStorage.setItem('text',text)
        # document.body.innerHTML=window.localStorage.getItem('text')        
        # return (False,HttpResponseRedirect('/all_bills/'))
        # Открывается окно с сопровождающей запиской, из него уже открывается окно списка счетов
        show_cashless_maintain = config.get('cashless','show_text')
        if show_cashless_maintain=='True':
            return (True,('cashless_redirect.html', {},{'text':text,'cashless':cashless},request,app))
        return (False,HttpResponseRedirect('/all_bills/'))
    # Создаём новый счёт, значит теперь надо номер новой гарантии
    try:
        garanty_number = int(Garanty.objects.all().order_by('-number')[0].number)+1
    except IndexError:
        # значит, гарантий ещё в базе нет
        garanty_number = 0

    contractors_list = assets.api.get_contractors_list(request,internal=True)
    asset_types_list = assets.api.get_asset_type_list(request,internal=True)
    return (True,
            ('new_bill.html',
             {'NewCashBillForm':{'garanty':garanty_number}},
             {'stages':stages,'contractors_list':contractors_list,
              'asset_types_list':asset_types_list,
              'method':method},
             request,
             app))
Exemplo n.º 34
0
def bill_cash_add(request):
    lang,user,fio,method = get_info(request)
    if request.method == 'POST':
        # Порядок действия таков:
        # 1) Создаём Cash
        # 2) Создаём Payment с этим Cash
        # 3) Создаём Garanty - если её ещё нет. Если есть - добавляем к имеющейся
        # 4) Итерируем по элементам в форме от 1 до макс добавляя активы в список активов
        # 5) Если всё прошло хорошо - активы из списка сохраняем

        bill_date = request.POST.get('date','')
        if bill_date:
            a=[int(a) for a in bill_date.split('.')]
            a.reverse()
            bill_date=datetime.datetime(*a)
        else:
            bill_date = datetime.datetime.now()
        # print bill_date
        # raise ImportError
        cash = Cash(date = bill_date,
               contractor = Contractor.objects.get(id=request.POST.get('contractor_id')),
               bill_number = request.POST.get('bill_number'),
               )
        cash.save()
        payment = Payment(cash = cash,
                )
        payment.save()
        try:
            garanty = Garanty.objects.get(number = request.POST.get('garanty'))
        except Garanty.DoesNotExist:
            garanty = Garanty(number = request.POST.get('garanty'))
            garanty.save()
        for item_number in range(1,int(request.POST.get('max_asset_form_number'))+1):
            sitem_number = str(item_number)
            if sitem_number+'_model' in request.POST:
                for count in range(0,int(request.POST.get('count_of_asset'+sitem_number))):
                    a=Asset(asset_type = Asset_type.objects.get(id=request.POST.get(sitem_number+'_asset_type')),
                        payment = payment,
                        garanty = garanty,
                        model = request.POST.get(sitem_number+'_model'),
                        status = Status.objects.get(id=request.POST.get(sitem_number+'_status')),
                        guarantee_period = request.POST.get(sitem_number+'_guarantee_period'),
                        note = request.POST.get(sitem_number+'_note'),
                        price = request.POST.get(sitem_number+'_price'),
                        )
                    a.save()
                    cur_place=Place_Asset(installation_date = bill_date,
                        asset = a,
                        place = Place.objects.get(id=request.POST.get(sitem_number+'_current_place')),
                        )
                    cur_place.save()
        return (False,HttpResponseRedirect('/all_bills/'))
    # Создаём новый счёт, значит теперь надо номер новой гарантии
    try:
        garanty_number = int(Garanty.objects.all().order_by('-number')[0].number)+1
    except IndexError:
        # значит, гарантий ещё в базе нет
        garanty_number = 0
    contractors_list = assets.api.get_contractors_list(request,internal=True)
    asset_types_list = assets.api.get_asset_type_list(request,internal=True)
    return (True,('new_bill.html', {'NewCashBillForm':{'garanty':garanty_number}},{'contractors_list':contractors_list,'asset_types_list':asset_types_list, 'method':method},request,app))
Exemplo n.º 35
0
def new_asset(class_label, path):
    relative_path = path.partition(ASSET_BASEDIR)[-1]
    a = Asset(class_label=class_label, relative_file_path=relative_path)
    a.is_original = True
    a.save()
Exemplo n.º 36
0
def add_mola():
    a = Asset(class_label="mola basemap")
    a.relative_path = MOLA_BASEMAP_PATH.partition(ASSET_BASEDIR)[-1]
    a.is_original = True
    a.save()
Exemplo n.º 37
0
def bill_add(request):
    lang,user,fio,method = get_info(request)
    if request.method == 'POST':
        # Порядок действия таков:
        # 1) Создаём Cash
        # 2) Создаём Payment с этим Cash
        # 3) Создаём Garanty - если её ещё нет. Если есть - добавляем к имеющейся
        # 4) Итерируем по элементам в форме от 1 до макс добавляя активы в список активов
        # 5) Если всё прошло хорошо - активы из списка сохраняем

        bill_date = request.POST.get('date','')
        if bill_date:
            a=[int(a) for a in bill_date.split('.')]
            a.reverse()
            bill_date=datetime.datetime(*a)
        else:
            bill_date = datetime.datetime.now()
        # print bill_date
        # raise ImportError
        cash = Cash(date = bill_date,
               contractor = Contractor.objects.get(id=request.POST.get('contractor_id')),
               bill_number = request.POST.get('bill_number'),
               )
        cash.save()
        payment = Payment(cash = cash,
                )
        payment.save()
        try:
            garanty = Garanty.objects.get(number = request.POST.get('garanty'))
        except Garanty.DoesNotExist:
            garanty = Garanty(number = request.POST.get('garanty'))
            garanty.save()
        for item_number in range(1,int(request.POST.get('max_asset_form_number'))+1):
            sitem_number = str(item_number)
            if sitem_number+'_model' in request.POST:
                for count in range(0,int(request.POST.get('count_of_asset'+sitem_number))):
                    a=Asset(asset_type = Asset_type.objects.get(id=request.POST.get(sitem_number+'_asset_type')),
                        payment = payment,
                        garanty = garanty,
                        model = request.POST.get(sitem_number+'_model'),
                        status = Status.objects.get(id=request.POST.get(sitem_number+'_status')),
                        guarantee_period = request.POST.get(sitem_number+'_guarantee_period'),
                        note = request.POST.get(sitem_number+'_note'),
                        price = request.POST.get(sitem_number+'_price'),
                        )
                    a.save()
                    cur_place=Place_Asset(installation_date = bill_date,
                        asset = a,
                        place = Place.objects.get(id=request.POST.get(sitem_number+'_current_place')),
                        )
                    cur_place.save()
        return (False,HttpResponseRedirect('/tasks/'))
        # else:
            # print "FOrm is not valid??"
    contractors_list = assets.api.get_contractors_list(request,internal=True)
    asset_types_list = assets.api.get_asset_type_list(request,internal=True)
    # Translators: This message appears on the home page only
    message=_('Message')
    print message
    print request.LANGUAGE_CODE
    return (True,('new_bill.html', {'NewCashBillForm':{}},{'contractors_list':contractors_list,'asset_types_list':asset_types_list, 'method':method,'message':message},request,app))