def test_not_remove_ram_in_same_computer(user: UserClient): """Tests a Snapshot We want check than all components is not duplicate in a second snapshot of the same device. """ s = yaml2json('erase-sectors.snapshot') s['device']['type'] = 'Server' snap1, _ = user.post(json_encode(s), res=Snapshot) s['uuid'] = '74caa7eb-2bad-4333-94f6-6f1b031d0774' s['components'].append({ "actions": [], "manufacturer": "Intel Corporation", "model": "NM10/ICH7 Family High Definition Audio Controller", "serialNumber": "mp2pc", "type": "SoundCard" }) dev1 = m.Device.query.filter_by(id=snap1['device']['id']).one() ram1 = [x.id for x in dev1.components if x.type == 'RamModule'][0] snap2, _ = user.post(json_encode(s), res=Snapshot) dev2 = m.Device.query.filter_by(id=snap2['device']['id']).one() ram2 = [x.id for x in dev2.components if x.type == 'RamModule'][0] assert ram1 != ram2 assert len(dev1.components) == 4 assert len(dev2.components) == 4 assert dev1.id == dev2.id assert dev1.components == dev2.components
def test_hid_with_2network_and_drop_no_mac_in_hid(app: Devicehub, user: UserClient): """Checks hid with 2 networks adapters and next drop the network is not used in hid""" snapshot = yaml2json('asus-eee-1000h.snapshot.11') network = [ c for c in snapshot['components'] if c['type'] == 'NetworkAdapter' ][0] network2 = copy.copy(network) snapshot['components'].append(network2) network['serialNumber'] = 'a0:24:8c:7f:cf:2d' snap, _ = user.post(json_encode(snapshot), res=m.Snapshot) pc, _ = user.get(res=d.Device, item=snap['device']['devicehubID']) assert pc[ 'hid'] == 'laptop-asustek_computer_inc-1000h-94oaaq021116-00:24:8c:7f:cf:2d' snapshot['uuid'] = 'd1b70cb8-8929-4f36-99b7-fe052cec0abb' snapshot['components'] = [ c for c in snapshot['components'] if c != network ] user.post(json_encode(snapshot), res=m.Snapshot) devices, _ = user.get(res=d.Device) laptop = devices['items'][0] assert laptop[ 'hid'] == 'laptop-asustek_computer_inc-1000h-94oaaq021116-00:24:8c:7f:cf:2d' assert len([c for c in devices['items'] if c['type'] == 'Laptop']) == 1 assert len([ c for c in laptop['components'] if c['type'] == 'NetworkAdapter' ]) == 1
def test_when_rate_must_not_compute(user: UserClient): """Test to check if rate is computed in case of should not be calculated: 1. Snapshot haven't visual test 2. Snapshot software aren't Workbench 3. Device type are not Computer ... """ # Checking case 1 s = yaml2json('basic.snapshot') # Delete snapshot device actions to delete VisualTest del s['device']['actions'] # Post to compute rate and check to didn't do it snapshot, _ = user.post(json_encode(s), res=Snapshot) assert 'rate' not in snapshot['device'] # Checking case 2 s = yaml2json('basic.snapshot') # Change snapshot software source s['software'] = 'Web' del s['uuid'] del s['elapsed'] del s['components'] # Post to compute rate and check to didn't do it snapshot, _ = user.post(json_encode(s), res=Snapshot) assert 'rate' not in snapshot['device'] # Checking case 3 s = yaml2json('keyboard.snapshot') # Post to compute rate and check to didn't do it snapshot, _ = user.post(json_encode(s), res=Snapshot) assert 'rate' not in snapshot['device']
def test_snapshot_tag_inner_tag_mismatch_between_tags_and_hid(user: UserClient, tag_id: str): """Ensures one device cannot 'steal' the tag from another one.""" pc1 = yaml2json('basic.snapshot') pc1['device']['tags'] = [{'type': 'Tag', 'id': tag_id}] user.post(json_encode(pc1), res=Snapshot) pc2 = yaml2json('1-device-with-components.snapshot') user.post(json_encode(pc2), res=Snapshot) # PC2 uploads well pc2['device']['tags'] = [{'type': 'Tag', 'id': tag_id}] # Set tag from pc1 to pc2 user.post(json_encode(pc2), res=Snapshot, status=MismatchBetweenTagsAndHid)
def test_simple_metrics(user: UserClient): """ Checks one standard query of metrics """ # Insert computer lenovo = yaml2json('desktop-9644w8n-lenovo-0169622.snapshot') acer = yaml2json('acer.happy.battery.snapshot') user.post(json_encode(lenovo), res=ma.Snapshot) snapshot, _ = user.post(json_encode(acer), res=ma.Snapshot) device_id = snapshot['device']['id'] post_request = { "transaction": "ccc", "name": "John", "endUsers": 1, "finalUserCode": "abcdefjhi", "devices": [device_id], "description": "aaa", "startTime": "2020-11-01T02:00:00+00:00", "endTime": "2020-12-01T02:00:00+00:00" } # Create Allocate user.post(res=ma.Allocate, data=post_request) acer['uuid'] = "490fb8c0-81a1-42e9-95e0-5e7db7038ec3" hdd = [c for c in acer['components'] if c['type'] == 'HardDrive'][0] hdd_action = [a for a in hdd['actions'] if a['type'] == 'TestDataStorage'][0] hdd_action['powerCycleCount'] += 1000 acer.pop('elapsed') acer['licence_version'] = '1.0.0' user.post(acer, res=ma.Live) # Create a live acer['uuid'] = "490fb8c0-81a1-42e9-95e0-5e7db7038ec4" hdd = [c for c in acer['components'] if c['type'] == 'HardDrive'][0] hdd_action = [a for a in hdd['actions'] if a['type'] == 'TestDataStorage'][0] hdd_action['powerCycleCount'] += 1000 user.post(acer, res=ma.Live) # Create an other live acer['uuid'] = "490fb8c0-81a1-42e9-95e0-5e7db7038ec5" hdd = [c for c in acer['components'] if c['type'] == 'HardDrive'][0] hdd_action = [a for a in hdd['actions'] if a['type'] == 'TestDataStorage'][0] hdd_action['powerCycleCount'] += 1000 user.post(acer, res=ma.Live) # Check metrics metrics = {'allocateds': 1, 'live': 1} res, _ = user.get("/metrics/") assert res == metrics
def test_hid_with_2network_and_drop_mac_in_hid(app: Devicehub, user: UserClient): """Checks hid with 2 networks adapters and next drop the network is used in hid""" # One tipical snapshot with 2 network cards snapshot = yaml2json('asus-eee-1000h.snapshot.11') network = [ c for c in snapshot['components'] if c['type'] == 'NetworkAdapter' ][0] network2 = copy.copy(network) snapshot['components'].append(network2) network['serialNumber'] = 'a0:24:8c:7f:cf:2d' snap, _ = user.post(json_encode(snapshot), res=m.Snapshot) pc, _ = user.get(res=d.Device, item=snap['device']['devicehubID']) assert pc[ 'hid'] == 'laptop-asustek_computer_inc-1000h-94oaaq021116-00:24:8c:7f:cf:2d' # we drop the network card then is used for to build the hid snapshot['uuid'] = 'd1b70cb8-8929-4f36-99b7-fe052cec0abb' snapshot['components'] = [ c for c in snapshot['components'] if c != network2 ] user.post(json_encode(snapshot), res=m.Snapshot) devices, _ = user.get(res=d.Device) laptops = [c for c in devices['items'] if c['type'] == 'Laptop'] assert len(laptops) == 2 hids = [h['hid'] for h in laptops] proof_hid = [ 'laptop-asustek_computer_inc-1000h-94oaaq021116-a0:24:8c:7f:cf:2d', 'laptop-asustek_computer_inc-1000h-94oaaq021116-00:24:8c:7f:cf:2d' ] assert all([h in proof_hid for h in hids]) # we drop all network cards snapshot['uuid'] = 'd1b70cb8-8929-4f36-99b7-fe052cec0abc' snapshot['components'] = [ c for c in snapshot['components'] if not c in [network, network2] ] user.post(json_encode(snapshot), res=m.Snapshot) devices, _ = user.get(res=d.Device) laptops = [c for c in devices['items'] if c['type'] == 'Laptop'] assert len(laptops) == 3 hids = [h['hid'] for h in laptops] proof_hid = [ 'laptop-asustek_computer_inc-1000h-94oaaq021116-a0:24:8c:7f:cf:2d', 'laptop-asustek_computer_inc-1000h-94oaaq021116-00:24:8c:7f:cf:2d', 'laptop-asustek_computer_inc-1000h-94oaaq021116' ] assert all([h in proof_hid for h in hids])
def test_workbench_fixtures(file: pathlib.Path, user: UserClient): """Uploads the Snapshot files Workbench tests generate. Keep this files up to date with the Workbench version. """ s = json.load(file.open()) user.post(res=em.Snapshot, data=json_encode(s), status=201)
def test_snapshot_different_properties_same_tags(user: UserClient, tag_id: str): """Tests a snapshot performed to device 1 with tag A and then to device 2 with tag B. Both don't have HID but are different type. Devicehub must fail the Snapshot. """ # 1. Upload PC1 without hid but with tag pc1 = yaml2json('basic.snapshot') pc1['device']['tags'] = [{'type': 'Tag', 'id': tag_id}] del pc1['device']['serialNumber'] user.post(json_encode(pc1), res=Snapshot) # 2. Upload PC2 without hid, a different characteristic than PC1, but with same tag pc2 = yaml2json('basic.snapshot') pc2['uuid'] = uuid4() pc2['device']['tags'] = pc1['device']['tags'] # pc2 model is unknown but pc1 model is set = different property del pc2['device']['model'] user.post(json_encode(pc2), res=Snapshot, status=MismatchBetweenProperties)
def test_workbench_server_condensed(user: UserClient): """As :def:`.test_workbench_server_phases` but all the actions condensed in only one big ``Snapshot`` file, as described in the docs. """ s = yaml2json('workbench-server-1.snapshot') s['device']['actions'].append(yaml2json('workbench-server-2.stress-test')) s['components'][4]['actions'].extend( (yaml2json('workbench-server-3.erase'), yaml2json('workbench-server-4.install'))) s['components'][5]['actions'].append(yaml2json('workbench-server-3.erase')) # Create tags for t in s['device']['tags']: user.post({'id': t['id']}, res=Tag) snapshot, _ = user.post(res=em.Snapshot, data=json_encode(s)) pc_id = snapshot['device']['id'] cpu_id = snapshot['components'][3]['id'] ssd_id = snapshot['components'][4]['id'] hdd_id = snapshot['components'][5]['id'] actions = snapshot['actions'] assert {(action['type'], action['device']) for action in actions} == {('BenchmarkProcessorSysbench', cpu_id), ('StressTest', pc_id), ('EraseSectors', ssd_id), ('EreusePrice', pc_id), ('BenchmarkRamSysbench', pc_id), ('BenchmarkProcessor', cpu_id), ('Install', ssd_id), ('EraseSectors', hdd_id), ('BenchmarkDataStorage', ssd_id), ('BenchmarkDataStorage', hdd_id), ('TestDataStorage', ssd_id), ('RateComputer', pc_id)} assert snapshot['closed'] assert snapshot['severity'] == 'Info' device, _ = user.get(res=Device, item=snapshot['device']['devicehubID']) assert device['dataStorageSize'] == 1100 assert device['chassis'] == 'Tower' assert device['hid'] == 'desktop-d1mr-d1ml-d1s-na1-s' assert device['graphicCardModel'] == device['components'][0][ 'model'] == 'gc1-1ml' assert device['networkSpeeds'] == [1000, 58] assert device['processorModel'] == device['components'][3][ 'model'] == 'p1-1ml' assert device[ 'ramSize'] == 2048, 'There are 3 RAM: 2 x 1024 and 1 None sizes' assert device['rate']['closed'] assert device['rate']['severity'] == 'Info' assert device['rate']['rating'] == 1 assert device['rate']['type'] == RateComputer.t # TODO JN why haven't same order in actions on each execution? assert any([ ac['type'] in [BenchmarkProcessor.t, BenchmarkRamSysbench.t] for ac in device['actions'] ]) assert 'tag1' in [x['id'] for x in device['tags']]
def test_hid_without_mac(app: Devicehub, user: UserClient): """Checks hid without mac.""" snapshot = yaml2json('asus-eee-1000h.snapshot.11') snapshot['components'] = [ c for c in snapshot['components'] if c['type'] != 'NetworkAdapter' ] snap, _ = user.post(json_encode(snapshot), res=m.Snapshot) pc, _ = user.get(res=d.Device, item=snap['device']['devicehubID']) assert pc['hid'] == 'laptop-asustek_computer_inc-1000h-94oaaq021116'
def test_ram_remove(user: UserClient): """Tests a Snapshot We want check than all components is duplicate less hard disk, than this is removed. """ s = yaml2json('erase-sectors.snapshot') s['device']['type'] = 'Server' snap1, _ = user.post(json_encode(s), res=Snapshot) s['uuid'] = '74caa7eb-2bad-4333-94f6-6f1b031d0774' s['device']['serialNumber'] = 'pc2s' snap2, _ = user.post(json_encode(s), res=Snapshot) dev1 = m.Device.query.filter_by(id=snap1['device']['id']).one() dev2 = m.Device.query.filter_by(id=snap2['device']['id']).one() assert len(dev1.components) == 1 assert len(dev2.components) == 3 ssd = [x for x in dev2.components if x.t == 'SolidStateDrive'][0] remove = [x for x in ssd.actions if x.t == 'Remove'][0] assert remove.t == 'Remove'
def test_device_query_search_synonyms_intel(user: UserClient): s = yaml2json('real-hp.snapshot.11') s['device']['model'] = 'foo' # The model had the word 'HP' in it user.post(json_encode(s), res=Snapshot) i, _ = user.get(res=Device, query=[('search', 'hewlett packard')]) assert 1 == len(i['items']) i, _ = user.get(res=Device, query=[('search', 'hewlett')]) assert 1 == len(i['items']) i, _ = user.get(res=Device, query=[('search', 'hp')]) assert 1 == len(i['items']) i, _ = user.get(res=Device, query=[('search', 'h.p')]) assert 1 == len(i['items'])
def test_visual_metrics_for_old_owners(user: UserClient, user2: UserClient): """ Checks if one old owner can see the metrics in a trade enviroment.""" # Insert computer lenovo = yaml2json('desktop-9644w8n-lenovo-0169622.snapshot') snap1, _ = user.post(json_encode(lenovo), res=ma.Snapshot) lot, _ = user.post({'name': 'MyLot'}, res=Lot) device_id = snap1['device']['id'] devices = [('id', device_id)] lot, _ = user.post({}, res=Lot, item='{}/devices'.format(lot['id']), query=devices) request_post = { 'type': 'Trade', 'devices': [device_id], 'userFromEmail': user.email, 'userToEmail': user2.email, 'price': 10, 'date': "2020-12-01T02:00:00+00:00", 'lot': lot['id'], 'confirms': True, } trade, _ = user.post(res=ma.Action, data=request_post) request_confirm = { 'type': 'Confirm', 'action': trade['id'], 'devices': [device_id] } user2.post(res=ma.Action, data=request_confirm) action = {'type': ma.Refurbish.t, 'devices': [device_id]} action_use, _ = user.post(action, res=ma.Action) csv_supplier, _ = user.get(res=documents.DocumentDef.t, item='actions/', accept='text/csv', query=[('filter', { 'type': ['Computer'], 'ids': [device_id] })]) csv_receiver, _ = user2.get(res=documents.DocumentDef.t, item='actions/', accept='text/csv', query=[('filter', { 'type': ['Computer'], 'ids': [device_id] })]) body = ';;0;0;Trade;0;0\n' assert body in csv_receiver assert body in csv_supplier assert csv_receiver == csv_supplier
def test_snapshot_component_containing_components(user: UserClient): """There is no reason for components to have components and when this happens it is always an error. This test avoids this until an appropriate use-case is presented. """ s = yaml2json('basic.snapshot') s['device'] = { 'type': 'Processor', 'serialNumber': 'foo', 'manufacturer': 'bar', 'model': 'baz' } user.post(json_encode(s), res=Snapshot, status=ValidationError)
def test_bug_trade_confirmed(user: UserClient, user2: UserClient): """When the receiber do a Trade, then the confirmation is wrong.""" lenovo = yaml2json('desktop-9644w8n-lenovo-0169622.snapshot') snap1, _ = user.post(json_encode(lenovo), res=ma.Snapshot) lot, _ = user.post({'name': 'MyLot'}, res=Lot) device_id = snap1['device']['id'] devices = [('id', device_id)] lot, _ = user.post({}, res=Lot, item='{}/devices'.format(lot['id']), query=devices) request_post = { 'type': 'Trade', 'devices': [device_id], 'userFromEmail': user2.email, 'userToEmail': user.email, 'price': 10, 'date': "2020-12-01T02:00:00+00:00", 'lot': lot['id'], 'confirms': True, } trade, _ = user.post(res=ma.Action, data=request_post) csv_not_confirmed, _ = user.get(res=documents.DocumentDef.t, item='actions/', accept='text/csv', query=[('filter', { 'type': ['Computer'], 'ids': [device_id] })]) request_confirm = { 'type': 'Confirm', 'action': trade['id'], 'devices': [device_id] } user2.post(res=ma.Action, data=request_confirm) csv_confirmed, _ = user2.get(res=documents.DocumentDef.t, item='actions/', accept='text/csv', query=[('filter', { 'type': ['Computer'], 'ids': [device_id] })]) body_not_confirmed = "Trade;[email protected];[email protected];Receiver;NeedConfirmation;" body_confirmed = "Trade;[email protected];[email protected];Receiver;TradeConfirmed;" assert body_not_confirmed in csv_not_confirmed assert body_confirmed in csv_confirmed
def test_snapshot_not_failed_null_chassis(app: Devicehub, user: UserClient): """ This test check if the file snapshot is create when some snapshot is wrong """ tmp_snapshots = app.config['TMP_SNAPSHOTS'] path_dir_base = os.path.join(tmp_snapshots, user.user['email'], 'errors') snapshot_error = yaml2json('desktop-9644w8n-lenovo-0169622.snapshot') snapshot_error['device']['chassis'] = None uuid = snapshot_error['uuid'] snapshot, res = user.post(res=Snapshot, data=json_encode(snapshot_error)) shutil.rmtree(tmp_snapshots) assert snapshot['software'] == snapshot_error['software'] assert snapshot['version'] == snapshot_error['version'] assert snapshot['uuid'] == uuid
def test_hid_with_2networkadapters(app: Devicehub, user: UserClient): """Checks hid with 2 networks adapters""" snapshot = yaml2json('asus-eee-1000h.snapshot.11') network = [ c for c in snapshot['components'] if c['type'] == 'NetworkAdapter' ][0] network2 = copy.copy(network) snapshot['components'].append(network2) network['serialNumber'] = 'a0:24:8c:7f:cf:2d' user.post(json_encode(snapshot), res=m.Snapshot) devices, _ = user.get(res=d.Device) laptop = devices['items'][0] assert laptop[ 'hid'] == 'laptop-asustek_computer_inc-1000h-94oaaq021116-00:24:8c:7f:cf:2d' assert len([c for c in devices['items'] if c['type'] == 'Laptop']) == 1
def test_snapshot_not_failed_end_time_bug(app: Devicehub, user: UserClient): """ This test check if the end_time != 0001-01-01 00:00:00+00:00 and then we get a /devices, this create a crash """ snapshot_file = yaml2json('asus-end_time_bug88.snapshot') snapshot_file['endTime'] = '2001-01-01 00:00:00+00:00' snapshot, _ = user.post(res=Snapshot, data=json_encode(snapshot_file)) device, _ = user.get(res=m.Device, item=snapshot['device']['devicehubID']) end_times = [x['endTime'] for x in device['actions']] assert not '1970-01-02T00:00:00+00:00' in end_times assert not '0001-01-01T00:00:00+00:00' in end_times assert '2001-01-01T00:00:00+00:00' in end_times tmp_snapshots = app.config['TMP_SNAPSHOTS'] shutil.rmtree(tmp_snapshots)
def test_same_device_tow_users(user: UserClient, user2: UserClient): """Two users can up the same snapshot and the system save 2 computers""" user.post(file('basic.snapshot'), res=Snapshot) i, _ = user.get(res=m.Device) pc = next(d for d in i['items'] if d['type'] == 'Desktop') pc_id = pc['id'] devicehub_id = pc['devicehubID'] assert i['items'][0]['url'] == f'/devices/{devicehub_id}' basic_snapshot = yaml2json('basic.snapshot') basic_snapshot['uuid'] = f"{uuid.uuid4()}" user2.post(json_encode(basic_snapshot), res=Snapshot) i2, _ = user2.get(res=m.Device) pc2 = next(d for d in i2['items'] if d['type'] == 'Desktop') assert pc['id'] != pc2['id'] assert pc['ownerID'] != pc2['ownerID'] assert pc['hid'] == pc2['hid']
def test_device_query_permitions(user: UserClient, user2: UserClient): """Checks result of inventory for two users""" user.post(file('basic.snapshot'), res=Snapshot) i, _ = user.get(res=Device) pc1 = next(d for d in i['items'] if d['type'] == 'Desktop') i2, _ = user2.get(res=Device) assert i2['items'] == [] basic_snapshot = yaml2json('basic.snapshot') basic_snapshot['uuid'] = f"{uuid.uuid4()}" user2.post(json_encode(basic_snapshot), res=Snapshot) i2, _ = user2.get(res=Device) pc2 = next(d for d in i2['items'] if d['type'] == 'Desktop') assert pc1['id'] != pc2['id'] assert pc1['hid'] == pc2['hid']
def test_metrics_action_status(user: UserClient, user2: UserClient): """ Checks one standard query of metrics.""" # Insert computer lenovo = yaml2json('desktop-9644w8n-lenovo-0169622.snapshot') snap, _ = user.post(json_encode(lenovo), res=ma.Snapshot) device_id = snap['device']['id'] action = {'type': ma.Use.t, 'devices': [device_id]} action_use, _ = user.post(action, res=ma.Action) csv_str, _ = user.get(res=documents.DocumentDef.t, item='actions/', accept='text/csv', query=[('filter', { 'type': ['Computer'], 'ids': [device_id] })]) head = 'DHID;Hid;Document-Name;Action-Type;Action-User-LastOwner-Supplier;Action-User-LastOwner-Receiver;Action-Create-By;Trade-Confirmed;Status-Created-By-Supplier-About-Reciber;Status-Receiver;Status Supplier – Created Date;Status Receiver – Created Date;Trade-Weight;Action-Create;Allocate-Start;Allocate-User-Code;Allocate-NumUsers;UsageTimeAllocate;Type;LiveCreate;UsageTimeHdd\n' body = 'O48N2;desktop-lenovo-9644w8n-0169622-00:1a:6b:5e:7f:10;;Status;;[email protected];Receiver;;;Use;;' assert head in csv_str assert body in csv_str
def test_save_snapshot_with_debug(app: Devicehub, user: UserClient): """ This test check if works the function save_snapshot_in_file """ snapshot_file = yaml2json('basic.snapshot.with_debug') debug = snapshot_file['debug'] user.post(res=Snapshot, data=json_encode(snapshot_file)) tmp_snapshots = app.config['TMP_SNAPSHOTS'] path_dir_base = os.path.join(tmp_snapshots, user.user['email']) uuid = snapshot_file['uuid'] files = [x for x in os.listdir(path_dir_base) if uuid in x] snapshot = {'debug': ''} if files: path_snapshot = os.path.join(path_dir_base, files[0]) with open(path_snapshot) as file_snapshot: snapshot = json.loads(file_snapshot.read()) shutil.rmtree(tmp_snapshots) assert snapshot['debug'] == debug
def snapshot_and_check(user: UserClient, input_snapshot: dict, action_types: Tuple[str, ...] = tuple(), perform_second_snapshot=True) -> dict: """Performs a Snapshot and then checks if the result is ok: - There have been performed the types of actions and in the same order as described in the passed-in ``action_types``. - The inputted devices are similar to the resulted ones. - There is no Remove action after the first Add. - All input components are now inside the parent device. Optionally, it can perform a second Snapshot which should perform an exact result, except for the actions. :return: The last resulting snapshot. """ snapshot, _ = user.post(res=Snapshot, data=json_encode(input_snapshot)) assert all(e['type'] in action_types for e in snapshot['actions']) assert len(snapshot['actions']) == len(action_types) # Ensure there is no Remove action after the first Add found_add = False for action in snapshot['actions']: if action['type'] == 'Add': found_add = True if found_add: assert action['type'] != 'Receive', 'All Remove actions must be before the Add ones' assert input_snapshot['device'] assert_similar_device(input_snapshot['device'], snapshot['device']) if input_snapshot.get('components', None): assert_similar_components(input_snapshot['components'], snapshot['components']) assert all(c['parent'] == snapshot['device']['id'] for c in snapshot['components']), \ 'Components must be in their parent' if perform_second_snapshot: if 'uuid' in input_snapshot: input_snapshot['uuid'] = uuid4() return snapshot_and_check(user, input_snapshot, action_types, perform_second_snapshot=False) else: return snapshot
def test_backup_snapshot_with_errors(app: Devicehub, user: UserClient): """ This test check if the file snapshot is create when some snapshot is wrong """ tmp_snapshots = app.config['TMP_SNAPSHOTS'] path_dir_base = os.path.join(tmp_snapshots, user.user['email'], 'errors') snapshot_no_hid = yaml2json('basic.snapshot.badly_formed') uuid = snapshot_no_hid['uuid'] snapshot = {'software': '', 'version': '', 'uuid': ''} with pytest.raises(KeyError): response = user.post(res=Snapshot, data=json_encode(snapshot_no_hid)) files = [x for x in os.listdir(path_dir_base) if uuid in x] if files: path_snapshot = os.path.join(path_dir_base, files[0]) with open(path_snapshot) as file_snapshot: snapshot = json.loads(file_snapshot.read()) shutil.rmtree(tmp_snapshots) assert snapshot['software'] == snapshot_no_hid['software'] assert snapshot['version'] == snapshot_no_hid['version'] assert snapshot['uuid'] == uuid
def test_snapshot_failed_missing_chassis(app: Devicehub, user: UserClient): """ This test check if the file snapshot is create when some snapshot is wrong """ tmp_snapshots = app.config['TMP_SNAPSHOTS'] path_dir_base = os.path.join(tmp_snapshots, user.user['email'], 'errors') snapshot_error = yaml2json('failed.snapshot.422.missing-chassis') uuid = snapshot_error['uuid'] snapshot = {'software': '', 'version': '', 'uuid': ''} with pytest.raises(TypeError): user.post(res=Snapshot, data=json_encode(snapshot_error)) files = [x for x in os.listdir(path_dir_base) if uuid in x] if files: path_snapshot = os.path.join(path_dir_base, files[0]) with open(path_snapshot) as file_snapshot: snapshot = json.loads(file_snapshot.read()) shutil.rmtree(tmp_snapshots) assert snapshot['software'] == snapshot_error['software'] assert snapshot['version'] == snapshot_error['version'] assert snapshot['uuid'] == uuid
def test_tag_secondary_workbench_link_find(user: UserClient): """Creates and consumes tags with a secondary id, linking them through Workbench to a device and getting them through search.""" t = Tag('foo', secondary='bar', owner_id=user.user['id']) db.session.add(t) db.session.flush() assert Tag.from_an_id('bar').one() == Tag.from_an_id('foo').one() with pytest.raises(ResourceNotFound): Tag.from_an_id('nope').one() s = yaml2json('basic.snapshot') s['device']['tags'] = [{'id': 'foo', 'secondary': 'bar', 'type': 'Tag'}] snapshot, _ = user.post(json_encode(s), res=Snapshot) device, _ = user.get(res=Device, item=snapshot['device']['devicehubID']) assert 'foo' in [x['id'] for x in device['tags']] assert 'bar' in [x.get('secondary') for x in device['tags']] r, _ = user.get(res=Device, query=[('search', 'foo'), ('filter', {'type': ['Computer']})]) assert len(r['items']) == 1 r, _ = user.get(res=Device, query=[('search', 'bar'), ('filter', {'type': ['Computer']})]) assert len(r['items']) == 1
def test_workbench_server_phases(user: UserClient): """Tests the phases described in the docs section `Snapshots from Workbench <http://devicehub.ereuse.org/ actions.html#snapshots-from-workbench>`_. """ # 1. Snapshot with sync / rate / benchmarks / test data storage s = yaml2json('workbench-server-1.snapshot') snapshot, _ = user.post(res=em.Snapshot, data=json_encode(s)) assert not snapshot[ 'closed'], 'Snapshot must be waiting for the new actions' # 2. stress test st = yaml2json('workbench-server-2.stress-test') st['snapshot'] = snapshot['id'] stress_test, _ = user.post(res=em.StressTest, data=st) # 3. erase ssd_id, hdd_id = snapshot['components'][4]['id'], snapshot['components'][ 5]['id'] e = yaml2json('workbench-server-3.erase') e['snapshot'], e['device'] = snapshot['id'], ssd_id erase1, _ = user.post(res=em.EraseSectors, data=e) # 3 bis. a second erase e = yaml2json('workbench-server-3.erase') e['snapshot'], e['device'] = snapshot['id'], hdd_id erase2, _ = user.post(res=em.EraseSectors, data=e) # 4. Install i = yaml2json('workbench-server-4.install') i['snapshot'], i['device'] = snapshot['id'], ssd_id install, _ = user.post(res=em.Install, data=i) # Check actions have been appended in Snapshot and devices # and that Snapshot is closed snapshot, _ = user.get(res=em.Snapshot, item=snapshot['id']) actions = snapshot['actions'] assert len(actions) == 9 assert actions[0]['type'] == 'Rate' assert actions[0]['device'] == 1 assert actions[0]['closed'] assert actions[0]['type'] == 'RateComputer' assert actions[0]['device'] == 1 assert actions[1]['type'] == 'BenchmarkProcessor' assert actions[1]['device'] == 5 assert actions[2]['type'] == 'BenchmarkProcessorSysbench' assert actions[2]['device'] == 5 assert actions[3]['type'] == 'BenchmarkDataStorage' assert actions[3]['device'] == 6 assert actions[4]['type'] == 'TestDataStorage' assert actions[4]['device'] == 6 assert actions[4]['type'] == 'BenchmarkDataStorage' assert actions[4]['device'] == 7 assert actions[5]['type'] == 'StressTest' assert actions[5]['device'] == 1 assert actions[6]['type'] == 'EraseSectors' assert actions[6]['device'] == 6 assert actions[7]['type'] == 'EraseSectors' assert actions[7]['device'] == 7 assert actions[8]['type'] == 'Install' assert actions[8]['device'] == 6 assert snapshot['closed'] assert snapshot['severity'] == 'Info' pc, _ = user.get(res=Device, item=snapshot['devicehubID']) assert len(pc['actions']) == 10 # todo shall I add child actions?
def test_erase_privacy_standards_endtime_sort(user: UserClient): """Tests a Snapshot with EraseSectors and the resulting privacy properties. This tests ensures that only the last erasure is picked up, as erasures have always custom endTime value set. """ s = yaml2json('erase-sectors.snapshot') assert s['components'][0]['actions'][0]['endTime'] == '2018-06-01T09:12:06+02:00' snapshot = snapshot_and_check(user, s, action_types=( EraseSectors.t, BenchmarkDataStorage.t, BenchmarkProcessor.t, RateComputer.t, EreusePrice.t ), perform_second_snapshot=False) # Perform a new snapshot changing the erasure time, as if # it is a new erasure performed after. erase = next(e for e in snapshot['actions'] if e['type'] == EraseSectors.t) assert erase['endTime'] == '2018-06-01T07:12:06+00:00' s['uuid'] = uuid4() s['components'][0]['actions'][0]['endTime'] = '2018-06-01T07:14:00+00:00' snapshot = snapshot_and_check(user, s, action_types=( EraseSectors.t, BenchmarkDataStorage.t, BenchmarkProcessor.t, RateComputer.t, EreusePrice.t ), perform_second_snapshot=False) # The actual test storage = next(e for e in snapshot['components'] if e['type'] == SolidStateDrive.t) storage, _ = user.get(res=m.Device, item=storage['devicehubID']) # Let's get storage actions too # order: endTime ascending # erasure1/2 have an user defined time and others actions endTime = created erasure1, erasure2, benchmark_hdd1, _snapshot1, _, _, benchmark_hdd2, _snapshot2 = storage['actions'][:8] assert erasure1['type'] == erasure2['type'] == 'EraseSectors' assert benchmark_hdd1['type'] == benchmark_hdd2['type'] == 'BenchmarkDataStorage' assert _snapshot1['type'] == _snapshot2['type'] == 'Snapshot' get_snapshot, _ = user.get(res=Action, item=_snapshot2['id']) assert get_snapshot['actions'][0]['endTime'] == '2018-06-01T07:14:00+00:00' assert snapshot == get_snapshot erasure, _ = user.get(res=Action, item=erasure1['id']) assert len(erasure['steps']) == 2 assert erasure['steps'][0]['startTime'] == '2018-06-01T06:15:00+00:00' assert erasure['steps'][0]['endTime'] == '2018-06-01T07:16:00+00:00' assert erasure['steps'][1]['startTime'] == '2018-06-01T06:16:00+00:00' assert erasure['steps'][1]['endTime'] == '2018-06-01T07:17:00+00:00' assert erasure['device']['id'] == storage['id'] step1, step2 = erasure['steps'] assert step1['type'] == 'StepZero' assert step1['severity'] == 'Info' assert 'num' not in step1 assert step2['type'] == 'StepRandom' assert step2['severity'] == 'Info' assert 'num' not in step2 assert ['HMG_IS5'] == erasure['standards'] assert storage['privacy']['type'] == 'EraseSectors' pc, _ = user.get(res=m.Device, item=snapshot['device']['devicehubID']) assert pc['privacy'] == [storage['privacy']] # Let's try a second erasure with an error s['uuid'] = uuid4() s['components'][0]['actions'][0]['severity'] = 'Error' snapshot, _ = user.post(json_encode(s), res=Snapshot) storage, _ = user.get(res=m.Device, item=storage['devicehubID']) assert storage['hid'] == 'solidstatedrive-c1mr-c1ml-c1s' assert storage['privacy']['type'] == 'EraseSectors' pc, _ = user.get(res=m.Device, item=snapshot['device']['devicehubID']) assert pc['privacy'] == [storage['privacy']]
def test_metrics_action_status_for_containers(user: UserClient, user2: UserClient): """ Checks one standard query of metrics for a container.""" # Insert computer lenovo = yaml2json('desktop-9644w8n-lenovo-0169622.snapshot') snap, _ = user.post(json_encode(lenovo), res=ma.Snapshot) lot, _ = user.post({'name': 'MyLot'}, res=Lot) devices = [('id', snap['device']['id'])] lot, _ = user.post({}, res=Lot, item='{}/devices'.format(lot['id']), query=devices) request_post = { 'type': 'Trade', 'devices': [snap['device']['id']], 'userFromEmail': user.email, 'userToEmail': user2.email, 'price': 10, 'date': "2020-12-01T02:00:00+00:00", 'lot': lot['id'], 'confirms': True, } user.post(res=ma.Action, data=request_post) request_post = { 'filename': 'test.pdf', 'hash': 'bbbbbbbb', 'url': 'http://www.ereuse.org/', 'weight': 150, 'lot': lot['id'] } tradedocument, _ = user.post(res=TradeDocument, data=request_post) action = { 'type': ma.Recycling.t, 'devices': [], 'documents': [tradedocument['id']] } action, _ = user.post(action, res=ma.Action) trade = TradeDocument.query.one() assert str(trade.actions[-1].id) == action['id'] # get metrics from botom in lot menu csv_str, _ = user.get(res=documents.DocumentDef.t, item='actions/', accept='text/csv', query=[('filter', { 'type': ['Computer'] }), ('lot', lot['id'])]) body1 = ';bbbbbbbb;test.pdf;Trade-Container;[email protected];[email protected];Supplier;False;Recycling;;' body2 = ';;150.0;' body3 = ';;0;0;Trade-Container;0;0' assert len(csv_str.split('\n')) == 3 assert body1 in csv_str.split('\n')[-2] assert body2 in csv_str.split('\n')[-2] assert body3 in csv_str.split('\n')[-2] # get metrics from botom in devices menu csv_str2, _ = user.get(res=documents.DocumentDef.t, item='actions/', accept='text/csv', query=[('filter', { 'type': ['Computer'], 'ids': [snap['device']['id']] })]) assert len(csv_str2.split('\n')) == 4 assert body1 in csv_str2.split('\n')[-2] assert body2 in csv_str2.split('\n')[-2] assert body3 in csv_str2.split('\n')[-2]
def test_complet_metrics_with_trade(user: UserClient, user2: UserClient): """ Checks one standard query of metrics in a trade enviroment.""" # Insert computer lenovo = yaml2json('desktop-9644w8n-lenovo-0169622.snapshot') acer = yaml2json('acer.happy.battery.snapshot') snap1, _ = user.post(json_encode(lenovo), res=ma.Snapshot) snap2, _ = user.post(json_encode(acer), res=ma.Snapshot) lot, _ = user.post({'name': 'MyLot'}, res=Lot) device1_id = snap1['device']['id'] device2_id = snap2['device']['id'] devices_id = [device1_id, device2_id] devices = [('id', device1_id), ('id', snap2['device']['id'])] lot, _ = user.post({}, res=Lot, item='{}/devices'.format(lot['id']), query=devices) action = {'type': ma.Refurbish.t, 'devices': [device1_id]} user.post(action, res=ma.Action) request_post = { 'type': 'Trade', 'devices': devices_id, 'userFromEmail': user.email, 'userToEmail': user2.email, 'price': 10, 'date': "2020-12-01T02:00:00+00:00", 'lot': lot['id'], 'confirms': True, } user.post(res=ma.Action, data=request_post) action = {'type': ma.Use.t, 'devices': [device1_id]} action_use, _ = user.post(action, res=ma.Action) csv_str, _ = user.get(res=documents.DocumentDef.t, item='actions/', accept='text/csv', query=[('filter', { 'type': ['Computer'], 'ids': devices_id })]) body1_lenovo = 'O48N2;desktop-lenovo-9644w8n-0169622-00:1a:6b:5e:7f:10;;Trade;[email protected];' body1_lenovo += '[email protected];Supplier;NeedConfirmation;Use;;' body2_lenovo = ';;0;0;Trade;0;0\n' body1_acer = 'J2MA2;laptop-acer-aohappy-lusea0d010038879a01601-00:26:c7:8e:cb:8c;;Trade;' body1_acer += '[email protected];[email protected];Supplier;NeedConfirmation;;;;;0;' body2_acer = ';;0;0;Trade;0;4692.0\n' assert body1_lenovo in csv_str assert body2_lenovo in csv_str assert body1_acer in csv_str assert body2_acer in csv_str # User2 mark this device as Refurbish action = {'type': ma.Use.t, 'devices': [device1_id]} action_use2, _ = user2.post(action, res=ma.Action) csv_str, _ = user.get(res=documents.DocumentDef.t, item='actions/', accept='text/csv', query=[('filter', { 'type': ['Computer'], 'ids': devices_id })]) body1_lenovo = 'O48N2;desktop-lenovo-9644w8n-0169622-00:1a:6b:5e:7f:10;;Trade;[email protected];' body1_lenovo += '[email protected];Supplier;NeedConfirmation;Use;Use;' body2_lenovo = ';;0;0;Trade;0;0\n' body2_acer = ';;0;0;Trade;0;4692.0\n' assert body1_lenovo in csv_str assert body2_lenovo in csv_str assert body2_acer in csv_str