def test_create_asset_with_duplicate_tag(
            self,
            client,
            init_db,  #pylint: disable=C0103,W0613
            auth_header,
            new_asset_category):
        """
        Test creation of assets with duplicate tag.
        """
        new_asset_category.save()
        ASSET_FIVE["asset_category_id"] = new_asset_category.id
        del ASSET_FIVE["assetCategoryId"]
        asset_object = Asset(**ASSET_FIVE)
        asset_object.save()
        del ASSET_FIVE["asset_category_id"]
        ASSET_FIVE["assetCategoryId"] = new_asset_category.id
        data = json.dumps(ASSET_FIVE)
        response = client.post(
            f'{API_BASE_URL_V1}/assets', headers=auth_header, data=data)
        response_json = json.loads(response.data.decode(CHARSET))

        assert response.status_code == 409
        assert response_json["status"] == "error"
        assert response_json["message"] == "Asset with the tag Kinngg Macbook"\
            " already exists"
    def test_assets(self, new_asset_category):
        asset = Asset(tag='AND/345/EWR', serial='GRGR334TG')

        new_asset_category.assets.append(asset)
        asset.save()
        new_asset_category.save()
        assert new_asset_category.assets[0] == asset
Exemplo n.º 3
0
def asset_with_attrs():  #pylint: disable=C0103
    """Test asset with no custom attributes."""
    category = AssetCategory(name="Test Category")
    category = category.save()

    attributes = [{
        '_key': 'waranty',
        'label': 'waranty',
        'is_required': True,
        'asset_category_id': category.id,
        'input_control': 'Text'
    }, {
        '_key': 'length',
        'label': 'length',
        'input_control': 'Text',
        'asset_category_id': category.id,
        'is_required': False
    }]

    for attribute in attributes:
        db.session.add(Attribute(**attribute))  #pylint: disable=E1101
    db.session.commit()  #pylint: disable=E1101

    ASSET_VALID_CUSTOM_ATTRS['asset_category_id'] = category.id
    asset = Asset(**ASSET_VALID_CUSTOM_ATTRS)
    return asset.save()
Exemplo n.º 4
0
def asset_no_attrs(new_asset_category_with_non_deleted_asset):  #pylint: disable=C0103
    """Test asset with no custom attributes."""
    asset = dict(**ASSET_NO_CUSTOM_ATTRS)
    del asset['assetCategoryId']
    del asset['customAttributes']
    asset['asset_category_id'] = new_asset_category_with_non_deleted_asset.id
    asset = Asset(**asset)
    return asset.save()
Exemplo n.º 5
0
    def test_card_6(self):
        """ Przeprowadź remont generalny wszystkich swoich nieruchomości: Zapłać za każdy dom M 250. Zapłać za każdy hotel M 1000 """
        budget = self.dice_roll_view.user.budget
        Asset(isPledged=False, field_id=2, playingUser_id=self.dice_roll_view.user.id, estateNumber=4).save()
        Asset(isPledged=False, field_id=12, playingUser_id=self.dice_roll_view.user.id, estateNumber=2).save()
        Asset(isPledged=False, field_id=3, playingUser_id=self.dice_roll_view.user.id, estateNumber=5).save()
        response = self.dice_roll_view.card(6)

        self.assertEqual(self.dice_roll_view.user.budget, budget-4*250-2*250-1000)
        self.assertEqual(response['pay'], 4*250+2*250+1000)
Exemplo n.º 6
0
def new_asset_category_with_deleted_asset(app, request_ctx,
                                          mock_request_obj_decoded_token):
    """Fixture for asset category with a deleted child asset."""
    asset_category = AssetCategory(name='Laptop1')
    asset_category = asset_category.save()

    asset = Asset(tag='abd', serial='def', asset_category_id=asset_category.id)

    asset = asset.save()
    asset.delete()

    return asset_category
    def test_search_asset_endpoint(
            self,
            client,
            init_db,
            auth_header,  #pylint: disable=W0613
            new_asset_category):
        """
         Test that a list of asset is returned when a search query is provided
        """
        asset1 = Asset(
            tag='AND/345/EWH',
            serial='GFGR634TG',
            custom_attributes={'warranty': '2017-11-09'})
        asset2 = Asset(
            tag='AND/245/EkL',
            serial='GFGR633TG',
            custom_attributes={'warranty': '2018-11-09'})
        new_asset_category.assets.append(asset1)
        new_asset_category.assets.append(asset2)
        new_asset_category.save()
        asset1.save()
        asset2.save()

        response = client.get(
            f'''{API_BASE_URL_V1}/assets/search?start={(asset1.created_at).date()}&\
end={(asset2.created_at).date()}&warranty_start={asset1.custom_attributes['warranty']}&\
warranty_end={asset1.custom_attributes['warranty']}''',
            headers=auth_header)

        response_json = json.loads(response.data.decode(CHARSET))

        assert response.status_code == 200
        assert response_json['status'] == 'success'
        assert len(response_json['data']) > 0  #pylint: disable=C1801
        assert type(response_json['data']) == list  #pylint: disable=C0123
Exemplo n.º 8
0
def new_asset_category_with_non_deleted_asset(app):
    """
    The module scope is used here to prevent a test module data leaking into
    another.

    Fixture for asset category with a non deleted child asset.
    """

    asset_category = AssetCategory(name='Laptop0')
    asset_category = asset_category.save()

    asset = Asset(tag='abc', serial='def', asset_category_id=asset_category.id)

    asset = asset.save()

    return asset_category
Exemplo n.º 9
0
    def test_search_asset_endpoint(self, client, init_db, auth_header,
                                   new_asset_category):
        """
         Test that a list of asset is returned when a search query is provided
        """
        assets_data = [
            dict(tag='AND/345/EWH',
                 serial='GFGR634TG',
                 custom_attributes={'warranty': '2017-11-09'}),
            dict(tag='AND/245/EkL',
                 serial='GFGR633TG',
                 custom_attributes={'warranty': '2018-11-09'})
        ]
        assets = []

        for asset in assets_data:
            new_asset = Asset(**asset)
            new_asset_category.assets.append(new_asset)
            assets.append(new_asset)
        new_asset_category.save()

        url = f'''{api_v1_base_url}/assets/search?start=\
{(assets[0].created_at).date()}&end={(assets[1].created_at).date()}&\
warranty_start={assets[0].custom_attributes['warranty']}&\
warranty_end={assets[0].custom_attributes['warranty']}'''

        response = client.get(url, headers=auth_header)
        response_json = json.loads(response.data.decode(CHARSET))

        assert response.status_code == 200
        assert response_json['status'] == 'success'
        assert len(response_json['data']) > 0
        assert type(response_json['data']) == list
Exemplo n.º 10
0
def asset_service(request, asset_id):
    if request.method == 'GET':
        if asset_id is not None:
            obj = Asset.objects.get(id=asset_id)
            if obj is not None:
                data = serializers.serialize('json', {obj, })
                return HttpResponse(data, content_type=APPLICATION_JSON)
            else:
                return HttpResponse("Object could not be found", status=404)
        else:
            return HttpResponse("ID required", status=405)
    elif request.method == 'POST':
        form = AssetForm(request.POST)
        asset = Asset()
        asset.name = form.name
        asset.description = form.description
        asset.assetType = form.assetType
        asset.componentSet = ComponentSet.get(id=form.componentSet)
        asset.save()
        return HttpResponse('{"status":"created", "id":' + str(asset.id) + '}', content_type=APPLICATION_JSON)
    else:
        return HttpResponse("Invalid Method", status=405)
Exemplo n.º 11
0
 def test_new_asset(self, new_asset_category, init_db):
     asset = Asset(tag='AND/345/EWR', serial='GRGR334TG')
     new_asset_category.assets.append(asset)
     new_asset_category.save()
     assert asset == asset.save()
Exemplo n.º 12
0
 def test_get(self, new_asset_category):
     asset = Asset(tag='AND/345/EWH', serial='GFGR634TG')
     new_asset_category.assets.append(asset)
     new_asset_category.save()
     asset.save()
     assert Asset.get(asset.id) == asset
Exemplo n.º 13
0
 def test_query(self):
     asset_query = Asset._query()
     assert asset_query.count() == 1
     assert isinstance(asset_query.all(), list)
Exemplo n.º 14
0
 def test_count(self):
     assert Asset.count() == 1
Exemplo n.º 15
0
def seed_asset():
    # Apple tv assets
    apple_tv_category = AssetCategory._query().filter_by(
        name='Apple TV').first()
    custom_attributes = {
        'color': 'red',
        'warranty': '2019-02-08',
        'size': '13.3inches'
    }
    apple_tv_assets_data = [{
        'tag': 'AND/345/EWRD',
        'serial': 'GRGR334TGD',
        'asset_category_id': apple_tv_category.id,
        'custom_attributes': custom_attributes
    }, {
        'tag': 'AND/654/FWED',
        'serial': 'SDW435OOJD',
        'asset_category_id': apple_tv_category.id,
        'custom_attributes': custom_attributes
    }, {
        'tag': 'AND/234/FJAD',
        'serial': 'JHDHG23JJD',
        'asset_category_id': apple_tv_category.id,
        'custom_attributes': custom_attributes
    }, {
        'tag': 'AND/345/AFWD',
        'serial': 'AFWEF34OFD',
        'asset_category_id': apple_tv_category.id,
        'custom_attributes': custom_attributes
    }]

    apple_tv_assets = [
        Asset(tag=data['tag'],
              serial=data.get('serial'),
              asset_category_id=data['asset_category_id'],
              custom_attributes=data['custom_attributes'])
        for data in apple_tv_assets_data
    ]

    for asset in apple_tv_assets:
        asset.save()

    # Chromebooks assets
    chromebooks_category = AssetCategory._query().filter_by(
        name='ChromeBooks').first()
    chromebooks_assets_data = [{
        'tag': 'AND/3235/ERR',
        'serial': 'NBA220FWE',
        'asset_category_id': chromebooks_category.id,
        'custom_attributes': {
            'warranty': '2019-02-08'
        }
    }, {
        'tag': 'AND/634/FHE',
        'serial': 'NTW456RGR',
        'asset_category_id': chromebooks_category.id,
        'custom_attributes': {
            'warranty': '2019-02-08'
        }
    }, {
        'tag': 'AND/246/TRA',
        'serial': 'JAA556EGR',
        'asset_category_id': chromebooks_category.id,
        'custom_attributes': {
            'warranty': '2019-02-08'
        }
    }, {
        'tag': 'AND/875/HJR',
        'serial': 'AWF232EGG',
        'asset_category_id': chromebooks_category.id,
        'custom_attributes': {
            'warranty': '2019-02-08'
        }
    }]

    chromebooks_assets = [
        Asset(tag=data['tag'],
              serial=data.get('serial'),
              custom_attributes=data['custom_attributes'],
              asset_category_id=data['asset_category_id'])
        for data in chromebooks_assets_data
    ]

    for asset in chromebooks_assets:
        asset.save()

    # Laptops assets
    laptops_category = AssetCategory._query().filter_by(name='Laptops').first()
    laptops_asset_data = [{
        'tag': 'AND/K32/001',
        'serial': 'KDJS43JN432LP',
        'asset_category_id': laptops_category.id,
        'custom_attributes': {
            'warranty': '2019-02-08'
        }
    }, {
        'tag': 'AND/K32/002',
        'serial': 'KDJS43JN432LP',
        'asset_category_id': laptops_category.id,
        'custom_attributes': {
            'warranty': '2019-02-08'
        }
    }, {
        'tag': 'AND/K32/003',
        'serial': 'KDJS43JN432LP',
        'asset_category_id': laptops_category.id,
        'custom_attributes': {
            'warranty': '2019-02-08'
        }
    }, {
        'tag': 'AND/K32/004',
        'serial': 'KDJS43JN432LP',
        'asset_category_id': laptops_category.id,
        'custom_attributes': {
            'warranty': '2019-02-08'
        }
    }, {
        'tag': 'AND/K32/005',
        'serial': 'KDJS43JN432LP',
        'asset_category_id': laptops_category.id,
        'custom_attributes': {
            'warranty': '2019-02-08'
        }
    }]

    laptops_asset = [
        Asset(tag=data['tag'],
              serial=data.get('serial'),
              custom_attributes=data['custom_attributes'],
              asset_category_id=data['asset_category_id'])
        for data in laptops_asset_data
    ]

    for asset in laptops_asset:
        asset.save()
Exemplo n.º 16
0
    def post(self, request):
        data = json.dumps(request.data)
        data = json.loads(data)

        if not 'image' in data:
            return Response({'error': 'no image in request.'},
                            status=status.HTTP_400_BAD_REQUEST)
        if not 'mime' in data:
            return Response({'error': 'no mime in request.'},
                            status=status.HTTP_400_BAD_REQUEST)

        mime = data['mime']
        if not mime in ['image/jpeg', 'image/png', 'image/gif', 'image/jpg']:
            return Response({'error': 'mime not accepted'},
                            status=status.HTTP_400_BAD_REQUEST)
        ext = mime[6:]
        salt = ''.join(
            random.choice(string.ascii_uppercase + string.digits)
            for _ in range(16))
        #data['image']=data['image']
        image_string = data['image']
        #image_string=image_string.replace('data:%s;base64,'% mime, '')

        # fh = open("public/static/admin/img/imageToSave.%s" % ext, "wb")
        # fh.write(base64.b64decode(image_string))
        # fh.close()

        from firebase import Firebase

        config = {
            'apiKey': "AIzaSyD7yT4lfcGx09w0WebnCMsGoNOW31dQm08",
            'authDomain': "group-proj-c8dd5.firebaseapp.com",
            'databaseURL': "https://group-proj-c8dd5.firebaseio.com",
            'projectId': "group-proj-c8dd5",
            'storageBucket': "group-proj-c8dd5.appspot.com",
            'messagingSenderId': "424365456354",
            'appId': "1:424365456354:web:27821c94665e5233"
        }

        firebase = Firebase(config)
        # storage=firebase.storage()
        # storage.child("storage/%s.%s"%(salt,ext)).put('public/static/admin/img/imageToSave.%s' % ext)

        asset_bundle = AssetBundle()
        asset_bundle.salt = salt
        asset_bundle.kind = 'image'
        #asset_bundle.base_url=storage.child("storage/%s.%s"%(salt,ext)).get_url(None)
        print(asset_bundle.base_url)
        asset_bundle.owner = request.user
        asset_bundle.save()

        for k in Asset.KIND_CHOICES:
            kind = k[0]

            asset = Asset()
            asset.asset_bundle = asset_bundle
            asset.kind = kind
            asset.extension = salt
            asset.processing = True
            asset.save()
            img = Image.open(BytesIO(base64.b64decode(image_string)))
            print(img)
            aspect = img.width / img.height

            width = 0
            height = 0
            resized_img = None
            if kind == 'original':
                print("ORIGINAL")
                width = img.width
                height = img.height
                resized_img = img.resize((width, height), PIL.Image.ANTIALIAS)

            elif kind == 'large':
                print("LARGE")
                width = 1024
                height = aspect * 1024
                resized_img = img.resize((int(width), int(height)),
                                         PIL.Image.ANTIALIAS)

            elif kind == 'small':
                print("SMALL")
                width = 128
                height = aspect * 128
                resized_img = img.resize((int(width), int(height)),
                                         PIL.Image.ANTIALIAS)

            else:
                print("ERROR - size not handled.")

            fh = open("public/static/admin/img/imageToSave.%s" % ext, "wb")
            fh.write(base64.b64decode(image_string))
            fh.close()

            storage = firebase.storage()

            storage.child("storage/%s-%s.%s" % (salt, kind, ext)).put(
                "public/static/admin/img/imageToSave.%s" % ext)
            asset.base_url = storage.child("storage/%s-%s.%s" %
                                           (salt, kind, ext)).get_url(None)
            #asset = Asset.objects.get(pk=asset_id)
            asset.width = width
            asset.height = height
            asset.processing = False
            asset.save()

        item = Item()
        item.asset__bundle = asset_bundle
        item.owner = request.user
        item.save()

        serializer = ItemDetailSerializer(item)
        return Response(serializer.data, status=status.HTTP_200_OK)