def test_device_search_all_devices_token_if_empty(app: Devicehub, user: UserClient): """Ensures DeviceSearch can regenerate itself when the table is empty.""" user.post(file('basic.snapshot'), res=Snapshot) with app.app_context(): app.db.session.execute('TRUNCATE TABLE {}'.format( DeviceSearch.__table__.name)) app.db.session.commit() i, _ = user.get(res=Device, query=[('search', 'Desktop')]) assert not len(i['items']) with app.app_context(): DeviceSearch.set_all_devices_tokens_if_empty(app.db.session) app.db.session.commit() i, _ = user.get(res=Device, query=[('search', 'Desktop')]) assert i['items']
def test_lot_post_add_remove_device_view(app: Devicehub, user: UserClient): """Tests adding a device to a lot using POST and removing it with DELETE.""" # todo check with components with app.app_context(): device = Desktop(serial_number='foo', model='bar', manufacturer='foobar', chassis=ComputerChassis.Lunchbox) db.session.add(device) db.session.commit() device_id = device.id parent, _ = user.post(({'name': 'lot'}), res=Lot) lot, _ = user.post({}, res=Lot, item='{}/devices'.format(parent['id']), query=[('id', device_id)]) assert lot['devices'][0]['id'] == device_id, 'Lot contains device' device, _ = user.get(res=Device, item=device_id) assert len(device['lots']) == 1 assert device['lots'][0]['id'] == lot['id'], 'Device is inside lot' # Remove the device lot, _ = user.delete(res=Lot, item='{}/devices'.format(parent['id']), query=[('id', device_id)], status=200) assert not len(lot['devices'])
def tag_id(app: Devicehub) -> str: """Creates a tag and returns its id.""" with app.app_context(): t = Tag(id='foo') db.session.add(t) db.session.commit() return t.id
def test_deactivate_merge(app: Devicehub, user: UserClient): """ Check if is correct to do a manual merge """ snapshot1, _ = user.post(import_snap('real-custom.snapshot.11'), res=m.Snapshot) snapshot2, _ = user.post(import_snap('real-hp.snapshot.11'), res=m.Snapshot) pc1_id = snapshot1['device']['id'] pc2_id = snapshot2['device']['id'] with app.app_context(): pc1 = d.Device.query.filter_by(id=pc1_id).one() pc2 = d.Device.query.filter_by(id=pc2_id).one() n_actions1 = len(pc1.actions) n_actions2 = len(pc2.actions) action1 = pc1.actions[0] action2 = pc2.actions[0] assert not action2 in pc1.actions tag = Tag(id='foo-bar', owner_id=user.user['id']) pc2.tags.add(tag) db.session.add(pc2) db.session.commit() components1 = [com for com in pc1.components] components2 = [com for com in pc2.components] components1_excluded = [com for com in pc1.components if not com in components2] assert pc1.hid != pc2.hid assert not tag in pc1.tags uri = '/devices/%d/merge/%d' % (pc1_id, pc2_id) _, code = user.post({'id': 1}, uri=uri, status=404) assert code.status == '404 NOT FOUND'
def test_merge_two_device_with_differents_tags(app: Devicehub, user: UserClient): """ Check if is correct to do a manual merge of 2 diferents devices with diferents tags """ snapshot1, _ = user.post(import_snap('real-custom.snapshot.11'), res=m.Snapshot) snapshot2, _ = user.post(import_snap('real-hp.snapshot.11'), res=m.Snapshot) pc1_id = snapshot1['device']['id'] pc2_id = snapshot2['device']['id'] with app.app_context(): pc1 = d.Device.query.filter_by(id=pc1_id).one() pc2 = d.Device.query.filter_by(id=pc2_id).one() tag1 = Tag(id='fii-bor', owner_id=user.user['id']) tag2 = Tag(id='foo-bar', owner_id=user.user['id']) pc1.tags.add(tag1) pc2.tags.add(tag2) db.session.add(pc1) db.session.add(pc2) db.session.commit() uri = '/devices/%d/merge/%d' % (pc1_id, pc2_id) result, _ = user.post({'id': 1}, uri=uri, status=201) assert pc1.hid == pc2.hid assert tag1 in pc1.tags assert tag2 in pc1.tags
def test_get_devices(app: Devicehub, user: UserClient): """Checks GETting multiple devices.""" with app.app_context(): pc = d.Desktop(model='p1mo', manufacturer='p1ma', serial_number='p1s', chassis=ComputerChassis.Tower) pc.components = OrderedSet([ d.NetworkAdapter(model='c1mo', manufacturer='c1ma', serial_number='c1s'), d.GraphicCard(model='c2mo', manufacturer='c2ma', memory=1500) ]) pc1 = d.Desktop(model='p2mo', manufacturer='p2ma', serial_number='p2s', chassis=ComputerChassis.Tower) pc2 = d.Laptop(model='p3mo', manufacturer='p3ma', serial_number='p3s', chassis=ComputerChassis.Netbook) db.session.add_all((pc, pc1, pc2)) db.session.commit() devices, _ = user.get(res=d.Device) assert tuple(dev['id'] for dev in devices['items']) == (1, 2, 3, 4, 5) assert tuple( dev['type'] for dev in devices['items']) == (d.Desktop.t, d.Desktop.t, d.Laptop.t, d.NetworkAdapter.t, d.GraphicCard.t)
def test_get_device(app: Devicehub, user: UserClient): """Checks GETting a Desktop with its components.""" with app.app_context(): pc = Desktop(model='p1mo', manufacturer='p1ma', serial_number='p1s') pc.components = OrderedSet([ NetworkAdapter(model='c1mo', manufacturer='c1ma', serial_number='c1s'), GraphicCard(model='c2mo', manufacturer='c2ma', memory=1500) ]) db.session.add(pc) db.session.add(Test(device=pc, elapsed=timedelta(seconds=4), error=False, author=User(email='*****@*****.**'))) db.session.commit() pc, _ = user.get(res=Device, item=1) assert len(pc['events']) == 1 assert pc['events'][0]['type'] == 'Test' assert pc['events'][0]['device'] == 1 assert pc['events'][0]['elapsed'] == 4 assert not pc['events'][0]['error'] assert UUID(pc['events'][0]['author']) assert 'events_components' not in pc, 'events_components are internal use only' assert 'events_one' not in pc, 'they are internal use only' assert 'author' not in pc assert tuple(c['id'] for c in pc['components']) == (2, 3) assert pc['hid'] == 'p1ma-p1s-p1mo' assert pc['model'] == 'p1mo' assert pc['manufacturer'] == 'p1ma' assert pc['serialNumber'] == 'p1s' assert pc['type'] == 'Desktop'
def test_get_tags_endpoint(user: UserClient, app: Devicehub, requests_mock: requests_mock.mocker.Mocker): """Performs GET /tags after creating 3 tags, 2 printable and one not. Only the printable ones are returned. """ # Prepare test with app.app_context(): org = Organization(name='bar', tax_id='bartax') tag = Tag(id='bar-1', org=org, provider=URL('http://foo.bar'), owner_id=user.user['id']) db.session.add(tag) db.session.commit() assert not tag.printable requests_mock.post('https://example.com/', # request request_headers={ 'Authorization': 'Basic {}'.format(DevicehubClient.encode_token( '52dacef0-6bcb-4919-bfed-f10d2c96ecee')) }, # response json=['tag1id', 'tag2id'], status_code=201) user.post({}, res=Tag, query=[('num', 2)]) # Test itself data, _ = user.get(res=Tag) assert len(data['items']) == 2, 'Only 2 tags are printable, thus retreived' # Order is created descending assert data['items'][0]['id'] == 'tag2id' assert data['items'][0]['printable'] assert data['items'][1]['id'] == 'tag1id' assert data['items'][1]['printable'], 'Tags made this way are printable'
def test_tag_get_device_from_tag_endpoint_no_linked(app: Devicehub, user: UserClient): """As above, but when the tag is not linked.""" with app.app_context(): db.session.add(Tag(id='foo-bar')) db.session.commit() user.get(res=Tag, item='foo-bar/device', status=TagNotLinked)
def app(request, _app: Devicehub) -> Devicehub: # More robust than 'yield' def _drop(*args, **kwargs): with _app.app_context(): db.drop_all() def _init(): _app.init_db(name='Test Inventory', org_name='FooOrg', org_id='foo-org-id', tag_url=boltons.urlutils.URL('https://example.com'), tag_token=uuid.UUID('52dacef0-6bcb-4919-bfed-f10d2c96ecee'), erase=False, common=True) with _app.app_context(): try: with redirect_stdout(io.StringIO()): _init() except (ProgrammingError, IntegrityError, AssertionError): print('Database was not correctly emptied. Re-empty and re-installing...') _drop() _init() request.addfinalizer(_drop) return _app
def test_tag_manual_link_search(app: Devicehub, user: UserClient): """Tests linking manually a tag through PUT /tags/<id>/device/<id> Checks search has the term. """ with app.app_context(): g.user = User.query.one() db.session.add(Tag('foo-bar', secondary='foo-sec', owner_id=user.user['id'])) desktop = Desktop(serial_number='foo', chassis=ComputerChassis.AllInOne, owner_id=user.user['id']) db.session.add(desktop) db.session.commit() desktop_id = desktop.id devicehub_id = desktop.devicehub_id user.put({}, res=Tag, item='foo-bar/device/{}'.format(desktop_id), status=204) device, _ = user.get(res=Device, item=devicehub_id) assert 'foo-bar' in [x['id'] for x in device['tags']] # Device already linked # Just returns an OK to conform to PUT as anything changes user.put({}, res=Tag, item='foo-sec/device/{}'.format(desktop_id), status=204) # Secondary IDs are case insensitive user.put({}, res=Tag, item='FOO-BAR/device/{}'.format(desktop_id), status=204) user.put({}, res=Tag, item='FOO-SEC/device/{}'.format(desktop_id), status=204) # cannot link to another device when already linked user.put({}, res=Tag, item='foo-bar/device/99', status=LinkedToAnotherDevice) i, _ = user.get(res=Device, query=[('search', 'foo-bar')]) assert i['items'] i, _ = user.get(res=Device, query=[('search', 'foo-sec')]) assert i['items'] i, _ = user.get(res=Device, query=[('search', 'foo')]) assert i['items']
def test_snapshot_tag_inner_tag(tag_id: str, user: UserClient, app: Devicehub): """Tests a posting Snapshot with a local tag.""" b = file('basic.snapshot') b['device']['tags'] = [{'type': 'Tag', 'id': tag_id}] snapshot_and_check(user, b, event_types=('WorkbenchRate', )) with app.app_context(): tag, *_ = Tag.query.all() # type: Tag assert tag.device_id == 1, 'Tag should be linked to the first device'
def user(app: Devicehub) -> UserClient: """Gets a client with a logged-in dummy user.""" with app.app_context(): password = '******' user = create_user(password=password) client = UserClient(app, user.email, password, response_wrapper=app.response_class) client.login() return client
def test_tag_create_tags_cli(app: Devicehub, user: UserClient): """Checks creating tags with the CLI endpoint.""" owner_id = user.user['id'] runner = app.test_cli_runner() runner.invoke('tag', 'add', 'id1', '-u', owner_id) with app.app_context(): tag = Tag.query.one() # type: Tag assert tag.id == 'id1' assert tag.org.id == Organization.get_default_org_id()
def test_snapshot_tag_inner_tag(user: UserClient, tag_id: str, app: Devicehub): """Tests a posting Snapshot with a local tag.""" b = yaml2json('basic.snapshot') b['device']['tags'] = [{'type': 'Tag', 'id': tag_id}] snapshot_and_check(user, b, action_types=(RateComputer.t, BenchmarkProcessor.t, VisualTest.t)) with app.app_context(): tag = Tag.query.all()[0] # type: Tag assert tag.device_id == 3, 'Tag should be linked to the first device'
def test_tag_create_tags_cli_csv(app: Devicehub, user: UserClient): """Checks creating tags with the CLI endpoint using a CSV.""" owner_id = user.user['id'] csv = pathlib.Path(__file__).parent / 'files' / 'tags-cli.csv' runner = app.test_cli_runner() runner.invoke('tag', 'add-csv', str(csv), '-u', owner_id) with app.app_context(): t1 = Tag.from_an_id('id1').one() t2 = Tag.from_an_id('sec1').one() assert t1 == t2
def test_create_user_email_insensitive(app: Devicehub): """Ensures email is case insensitive.""" with app.app_context(): user = User(email='*****@*****.**') db.session.add(user) db.session.commit() # We search in case insensitive manner u1 = User.query.filter_by(email='*****@*****.**').one() assert u1 == user assert u1.email == '*****@*****.**'
def inventory_query_dummy(app: Devicehub): with app.app_context(): db.session.add_all(( # The order matters ;-) Desktop(serial_number='s1', model='ml1', manufacturer='mr1'), Laptop(serial_number='s3', model='ml3', manufacturer='mr3'), Microtower(serial_number='s2', model='ml2', manufacturer='mr2'), SolidStateDrive(serial_number='s4', model='ml4', manufacturer='mr4'))) db.session.commit()
def user(app: Devicehub) -> UserClient: """Gets a client with a logged-in dummy user.""" with app.app_context(): user = create_user() client = UserClient(application=app, response_wrapper=app.response_class, email=user.email, password='******') client.user, _ = client.login(client.email, client.password) return client
def auth_app_context(app: Devicehub): """Creates an app context with a set user.""" with app.app_context(): user = create_user() class Auth: # Mock username = user.token password = '' app.auth.perform_auth(Auth()) yield
def test_authenticate_error(app: Devicehub): """Tests the authenticate method with wrong token values.""" with app.app_context(): MESSAGE = 'Provide a suitable token.' create_user() # Token doesn't exist with pytest.raises(Unauthorized, message=MESSAGE): app.auth.authenticate(token=str(uuid4())) # Wrong token format with pytest.raises(Unauthorized, message=MESSAGE): app.auth.authenticate(token='this is a wrong uuid')
def tag_id(app: Devicehub) -> str: """Creates a tag and returns its id.""" with app.app_context(): if User.query.count(): user = User.query.one() else: user = create_user() t = Tag(id='foo', owner_id=user.id) db.session.add(t) db.session.commit() return t.id
def test_tag_get_device_from_tag_endpoint(app: Devicehub, user: UserClient): """Checks getting a linked device from a tag endpoint""" with app.app_context(): # Create a pc with a tag tag = Tag(id='foo-bar') pc = Computer(serial_number='sn1') pc.tags.add(tag) db.session.add(pc) db.session.commit() computer, _ = user.get(res=Tag, item='foo-bar/device') assert computer['serialNumber'] == 'sn1'
def test_tag_get_device_from_tag_endpoint(app: Devicehub, user: UserClient): """Checks getting a linked device from a tag endpoint""" with app.app_context(): # Create a pc with a tag g.user = User.query.one() tag = Tag(id='foo-bar', owner_id=user.user['id']) pc = Desktop(serial_number='sn1', chassis=ComputerChassis.Tower, owner_id=user.user['id']) pc.tags.add(tag) db.session.add(pc) db.session.commit() computer, _ = user.get(res=Tag, item='foo-bar/device') assert computer['serialNumber'] == 'sn1'
def test_tag_create_etags_cli(app: Devicehub, user: UserClient): """Creates an eTag through the CLI.""" # todo what happens to organization? owner_id = user.user['id'] runner = app.test_cli_runner() args = ('tag', 'add', '-p', 'https://t.ereuse.org', '-s', 'foo', 'DT-BARBAR', '-u', owner_id) runner.invoke(*args) with app.app_context(): tag = Tag.query.one() # type: Tag assert tag.id == 'dt-barbar' assert tag.secondary == 'foo' assert tag.provider == URL('https://t.ereuse.org')
def test_create_user_method(app: Devicehub): """ Tests creating an user through the main method. This method checks that the token is correct, too. """ with app.app_context(): user_def = app.resources['User'] # type: UserDef u = user_def.create_user(email='*****@*****.**', password='******') user = User.query.filter_by(id=u['id']).one() # type: User assert user.email == '*****@*****.**' assert isinstance(user.token, UUID) assert User.query.filter_by(email='*****@*****.**').one() == user
def test_tag_get_device_from_tag_endpoint_multiple_tags( app: Devicehub, user: UserClient): """ As above, but when there are two tags with the same ID, the system should not return any of both (to be deterministic) so it should raise an exception. """ with app.app_context(): db.session.add(Tag(id='foo-bar')) org2 = Organization(name='org 2', tax_id='tax id org 2') db.session.add(Tag(id='foo-bar', org=org2)) db.session.commit() user.get(res=Tag, item='foo-bar/device', status=MultipleResourcesFound)
def test_get_devices(app: Devicehub, user: UserClient): """Checks GETting multiple devices.""" with app.app_context(): pc = Desktop(model='p1mo', manufacturer='p1ma', serial_number='p1s') pc.components = OrderedSet([ NetworkAdapter(model='c1mo', manufacturer='c1ma', serial_number='c1s'), GraphicCard(model='c2mo', manufacturer='c2ma', memory=1500) ]) pc1 = Microtower(model='p2mo', manufacturer='p2ma', serial_number='p2s') pc2 = Laptop(model='p3mo', manufacturer='p3ma', serial_number='p3s') db.session.add_all((pc, pc1, pc2)) db.session.commit() devices, _ = user.get(res=Device) assert tuple(d['id'] for d in devices) == (1, 2, 3, 4, 5) assert tuple(d['type'] for d in devices) == ('Desktop', 'Microtower', 'Laptop', 'NetworkAdapter', 'GraphicCard')
def device_query_dummy(app: Devicehub): """ 3 computers, where: 1. s1 Desktop with a Processor 2. s2 Desktop with an SSD 3. s3 Laptop 4. s4 Server with another SSD :param app: :return: """ with app.app_context(): devices = ( # The order matters ;-) Desktop(serial_number='1', model='ml1', manufacturer='mr1', chassis=ComputerChassis.Tower), Desktop(serial_number='2', model='ml2', manufacturer='mr2', chassis=ComputerChassis.Microtower), Laptop(serial_number='3', model='ml3', manufacturer='mr3', chassis=ComputerChassis.Detachable), Server(serial_number='4', model='ml4', manufacturer='mr4', chassis=ComputerChassis.Tower), ) devices[0].components.add( GraphicCard(serial_number='1-gc', model='s1ml', manufacturer='s1mr')) devices[1].components.add( SolidStateDrive(serial_number='2-ssd', model='s2ml', manufacturer='s2mr')) devices[-1].components.add( SolidStateDrive(serial_number='4-ssd', model='s4ml', manufacturer='s4mr')) db.session.add_all(devices) db.session.commit()
def test_get_tag_permissions(app: Devicehub, user: UserClient, user2: UserClient): """Creates a tag specifying a custom organization.""" with app.app_context(): # Create a pc with a tag g.user = User.query.all()[0] tag = Tag(id='foo-bar', owner_id=user.user['id']) pc = Desktop(serial_number='sn1', chassis=ComputerChassis.Tower, owner_id=user.user['id']) pc.tags.add(tag) db.session.add(pc) db.session.commit() computer, res = user.get(res=Tag, item='foo-bar/device') url = "/tags/?foo-bar/device" computer, res = user.get(url, None) computer2, res2 = user2.get(url, None) assert res.status_code == 200 assert res2.status_code == 200 assert len(computer['items']) == 2 assert len(computer2['items']) == 0