def test_workbench_server_condensed(user: UserClient):
    """
    As :def:`.test_workbench_server_phases` but all the events
    condensed in only one big ``Snapshot`` file, as described
    in the docs.
    """
    s = file('workbench-server-1.snapshot')
    del s['expectedEvents']
    s['device']['events'].append(file('workbench-server-2.stress-test'))
    s['components'][4]['events'].extend(
        (file('workbench-server-3.erase'), file('workbench-server-4.install')))
    s['components'][5]['events'].append(file('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=s)
    events = snapshot['events']
    assert {(event['type'], event['device'])
            for event in events} == {('AggregateRate', 1),
                                     ('WorkbenchRate', 1),
                                     ('BenchmarkProcessorSysbench', 5),
                                     ('StressTest', 1), ('EraseSectors', 6),
                                     ('BenchmarkRamSysbench', 1),
                                     ('BenchmarkProcessor', 5), ('Install', 6),
                                     ('EraseSectors', 7),
                                     ('BenchmarkDataStorage', 6),
                                     ('BenchmarkDataStorage', 7),
                                     ('TestDataStorage', 6)}
    assert snapshot['closed']
    assert snapshot['severity'] == 'Info'
    device, _ = user.get(res=Device, item=snapshot['device']['id'])
    assert device['dataStorageSize'] == 1100
    assert device['chassis'] == 'Tower'
    assert device['hid'] == 'desktop-d1mr-d1ml-d1s'
    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'] == 0
    assert device['rate']['workbench']
    assert device['rate']['appearanceRange'] == 'A'
    assert device['rate']['functionalityRange'] == 'B'
    assert device['tags'][0]['id'] == 'tag1'
Exemple #2
0
def test_lot_post_add_children_view_ui_tree_normal(user: UserClient):
    """Tests adding children lots to a lot through the view and
    GETting the results.
    """
    parent, _ = user.post(({'name': 'Parent'}), res=Lot)
    child, _ = user.post(({'name': 'Child'}), res=Lot)
    parent, _ = user.post({},
                          res=Lot,
                          item='{}/children'.format(parent['id']),
                          query=[('id', child['id'])])
    assert parent['children'][0]['id'] == child['id']
    child, _ = user.get(res=Lot, item=child['id'])
    assert child['parents'][0]['id'] == parent['id']

    # Format UiTree
    r = user.get(res=Lot, query=[('format', 'UiTree')])[0]
    lots, nodes = r['items'], r['tree']
    assert 1 == len(nodes)
    assert nodes[0]['id'] == parent['id']
    assert len(nodes[0]['nodes']) == 1
    assert nodes[0]['nodes'][0]['id'] == child['id']
    assert 2 == len(lots)
    assert 'Parent' == lots[parent['id']]['name']
    assert 'Child' == lots[child['id']]['name']
    assert lots[child['id']]['parents'][0]['name'] == 'Parent'

    # Normal list format
    lots = user.get(res=Lot)[0]['items']
    assert 2 == len(lots)
    assert lots[0]['name'] == 'Parent'
    assert lots[1]['name'] == 'Child'

    # List format with a filter
    lots = user.get(res=Lot, query=[('search', 'pa')])[0]['items']
    assert 1 == len(lots)
    assert lots[0]['name'] == 'Parent'
Exemple #3
0
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')
Exemple #4
0
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
Exemple #5
0
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)
Exemple #6
0
def test_snapshot_update_timefield_updated(user: UserClient):
    """
    Tests for check if one computer have the time mark updated when one component of it is updated
    """
    computer1 = yaml2json('1-device-with-components.snapshot')
    snapshot = snapshot_and_check(user,
                                  computer1,
                                  action_types=(BenchmarkProcessor.t,
                                                RateComputer.t),
                                  perform_second_snapshot=False)
    computer2 = yaml2json('2-second-device-with-components-of-first.snapshot')
    snapshot_and_check(user, computer2, action_types=('Remove', 'RateComputer'),
                       perform_second_snapshot=False)
    pc1_devicehub_id = snapshot['device']['devicehubID']
    pc1, _ = user.get(res=m.Device, item=pc1_devicehub_id)
    assert pc1['updated'] != snapshot['device']['updated']
Exemple #7
0
def test_price_custom_client(user: UserClient):
    """As test_price_custom but creating the price through the API."""
    s = file('basic.snapshot')
    snapshot, _ = user.post(s, res=models.Snapshot)
    price, _ = user.post(
        {
            'type': 'Price',
            'price': 25,
            'currency': Currency.EUR.name,
            'device': snapshot['device']['id']
        },
        res=models.Event)
    assert 25 == price['price']
    assert Currency.EUR.name == price['currency']

    device, _ = user.get(res=Device, item=price['device']['id'])
    assert 25 == device['price']['price']
Exemple #8
0
def test_second_hdd_metrics(user: UserClient):
    """ Checks one standard query of metrics """
    # Insert computer
    acer = yaml2json('acer.happy.battery.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 a second device
    acer['uuid'] = "490fb8c0-81a1-42e9-95e0-5e7db7038ec5"
    hdd = [c for c in acer['components'] if c['type'] == 'HardDrive'][0]
    hdd['serialNumber'] = 'WD-WX11A80W7440'
    user.post(acer, res=ma.Live)

    # Check metrics if we change the hdd we need a result of one device
    metrics = {'allocateds': 1, 'live': 1}
    res, _ = user.get("/metrics/")
    assert res == metrics
Exemple #9
0
def test_cooking_mixer_api(user: UserClient):
    snapshot, _ = user.post(
        {
            'type': 'Snapshot',
            'device': {
                'serialNumber': 'foo',
                'model': 'bar',
                'manufacturer': 'foobar',
                'type': 'Mixer'
            },
            'version': '11.0',
            'software': SnapshotSoftware.Web.name
        },
        res=m.Snapshot)
    mixer, _ = user.get(res=d.Device, item=snapshot['device']['id'])
    assert mixer['type'] == 'Mixer'
    assert mixer['serialNumber'] == 'foo'
Exemple #10
0
def test_trade(event_model_state: Tuple[models.Event, states.Trading],
               user: UserClient):
    """Tests POSTing all Trade events."""
    event_model, state = event_model_state
    snapshot, _ = user.post(file('basic.snapshot'), res=models.Snapshot)
    event = {
        'type': event_model.t,
        'devices': [snapshot['device']['id']],
        'to': user.user['individuals'][0]['id'],
        'shippingDate': '2018-06-29T12:28:54',
        'invoiceNumber': 'ABC'
    }
    event, _ = user.post(event, res=models.Event)
    assert event['devices'][0]['id'] == snapshot['device']['id']
    device, _ = user.get(res=Device, item=snapshot['device']['id'])
    assert device['events'][-1]['id'] == event['id']
    assert device['trading'] == state.name
Exemple #11
0
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
Exemple #12
0
def test_get_device(user: UserClient):
    """Checks GETting a d.Desktop with its components."""
    g.user = User.query.one()
    pc = d.Desktop(model='p1mo',
                   manufacturer='p1ma',
                   serial_number='p1s',
                   chassis=ComputerChassis.Tower,
                   owner_id=user.user['id'])
    pc.components = OrderedSet([
        d.NetworkAdapter(model='c1mo',
                         manufacturer='c1ma',
                         serial_number='c1s',
                         owner_id=user.user['id']),
        d.GraphicCard(model='c2mo',
                      manufacturer='c2ma',
                      memory=1500,
                      owner_id=user.user['id'])
    ])
    db.session.add(pc)
    # todo test is an abstract class. replace with another one
    db.session.add(
        TestConnectivity(device=pc,
                         severity=Severity.Info,
                         agent=Person(name='Timmy'),
                         author=User(email='*****@*****.**')))
    db.session.commit()
    pc_api, _ = user.get(res=d.Device, item=pc.devicehub_id)
    assert len(pc_api['actions']) == 1
    assert pc_api['actions'][0]['type'] == 'TestConnectivity'
    assert pc_api['actions'][0]['device'] == pc.id
    assert pc_api['actions'][0]['severity'] == 'Info'
    assert UUID(pc_api['actions'][0]['author'])
    assert 'actions_components' not in pc_api, 'actions_components are internal use only'
    assert 'actions_one' not in pc_api, 'they are internal use only'
    assert 'author' not in pc_api
    assert tuple(c['id'] for c in pc_api['components']) == tuple(
        c.id for c in pc.components)
    assert pc_api['hid'] == 'desktop-p1ma-p1mo-p1s'
    assert pc_api['model'] == 'p1mo'
    assert pc_api['manufacturer'] == 'p1ma'
    assert pc_api['serialNumber'] == 'p1s'
    assert pc_api['type'] == d.Desktop.t
def test_erase_privacy_standards(user: UserClient):
    """Tests a Snapshot with EraseSectors and the resulting
    privacy properties.
    """
    s = file('erase-sectors.snapshot')
    assert '2018-06-01T09:12:06+02:00' == s['components'][0]['events'][0]['endTime']
    snapshot = snapshot_and_check(user, s, (EraseSectors.t,), perform_second_snapshot=True)
    assert '2018-06-01T07:12:06+00:00' == snapshot['events'][0]['endTime']
    storage, *_ = snapshot['components']
    assert storage['type'] == 'SolidStateDrive', 'Components must be ordered by input order'
    storage, _ = user.get(res=m.Device, item=storage['id'])  # Let's get storage events too
    # order: creation time descending
    erasure1, _snapshot1, erasure2, _snapshot2 = storage['events']
    assert erasure1['type'] == erasure2['type'] == 'EraseSectors'
    assert _snapshot1['type'] == _snapshot2['type'] == 'Snapshot'
    get_snapshot, _ = user.get(res=Event, item=_snapshot2['id'])
    assert get_snapshot['events'][0]['endTime'] == '2018-06-01T07:12:06+00:00'
    assert snapshot == get_snapshot
    erasure, _ = user.get(res=Event, 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']['id'])
    assert pc['privacy'] == [storage['privacy']]

    # Let's try a second erasure with an error
    s['uuid'] = uuid4()
    s['components'][0]['events'][0]['severity'] = 'Error'
    snapshot, _ = user.post(s, res=Snapshot)
    storage, _ = user.get(res=m.Device, item=storage['id'])
    assert storage['hid'] == 'solidstatedrive-c1mr-c1ml-c1s'
    assert storage['privacy']['type'] == 'EraseSectors'
    pc, _ = user.get(res=m.Device, item=snapshot['device']['id'])
    assert pc['privacy'] == [storage['privacy']]
def test_export_keyboard(user: UserClient):
    """
    Test a export device type keyboard
    """
    snapshot, _ = user.post(file('keyboard.snapshot'), res=Snapshot)
    csv_str, _ = user.get(res=documents.DocumentDef.t,
                          item='devices/',
                          accept='text/csv',
                          query=[('filter', {'type': ['Keyboard']})])
    f = StringIO(csv_str)
    obj_csv = csv.reader(f, f)
    export_csv = list(obj_csv)
    # Open fixture csv and transform to list
    with Path(__file__).parent.joinpath('files').joinpath('keyboard.csv').open() as csv_file:
        obj_csv = csv.reader(csv_file)
        fixture_csv = list(obj_csv)

    # Pop dates fields from csv lists to compare them
    fixture_csv[1] = fixture_csv[1][:8]
    export_csv[1] = export_csv[1][:8]

    assert fixture_csv[0] == export_csv[0], 'Headers are not equal'
    assert fixture_csv[1] == export_csv[1], 'Component information are not equal'
Exemple #15
0
def test_get_devices(app: Devicehub, user: UserClient):
    """Checks GETting multiple devices."""
    g.user = User.query.one()
    pc = d.Desktop(model='p1mo',
                   manufacturer='p1ma',
                   serial_number='p1s',
                   chassis=ComputerChassis.Tower,
                   owner_id=user.user['id'])
    pc.components = OrderedSet([
        d.NetworkAdapter(model='c1mo',
                         manufacturer='c1ma',
                         serial_number='c1s',
                         owner_id=user.user['id']),
        d.GraphicCard(model='c2mo',
                      manufacturer='c2ma',
                      memory=1500,
                      owner_id=user.user['id'])
    ])
    pc1 = d.Desktop(model='p2mo',
                    manufacturer='p2ma',
                    serial_number='p2s',
                    chassis=ComputerChassis.Tower,
                    owner_id=user.user['id'])
    pc2 = d.Laptop(model='p3mo',
                   manufacturer='p3ma',
                   serial_number='p3s',
                   chassis=ComputerChassis.Netbook,
                   owner_id=user.user['id'])
    db.session.add_all((pc, pc1, pc2))
    db.session.commit()
    devices, _ = user.get(res=d.Device)
    ids = (pc.id, pc1.id, pc2.id, pc.components[0].id, pc.components[1].id)
    assert tuple(dev['id'] for dev in devices['items']) == ids
    assert tuple(
        dev['type']
        for dev in devices['items']) == (d.Desktop.t, d.Desktop.t, d.Laptop.t,
                                         d.NetworkAdapter.t, d.GraphicCard.t)
Exemple #16
0
def test_get_device(app: Devicehub, user: UserClient):
    """Checks GETting a d.Desktop with its components."""
    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)
        ])
        db.session.add(pc)
        db.session.add(
            Test(device=pc,
                 elapsed=timedelta(seconds=4),
                 severity=Severity.Info,
                 agent=Person(name='Timmy'),
                 author=User(email='*****@*****.**')))
        db.session.commit()
    pc, _ = user.get(res=d.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 pc['events'][0]['severity'] == 'Info'
    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'] == 'desktop-p1ma-p1mo-p1s'
    assert pc['model'] == 'p1mo'
    assert pc['manufacturer'] == 'p1ma'
    assert pc['serialNumber'] == 'p1s'
    assert pc['type'] == d.Desktop.t
Exemple #17
0
def test_metrics_with_live_null(user: UserClient):
    """ Checks one standard query of metrics """
    # Insert computer
    acer = file('acer.happy.battery.snapshot')
    snapshot, _ = user.post(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)

    # Check metrics if we change the hdd we need a result of one device
    metrics = {'allocateds': 1, 'live': 0}
    res, _ = user.get("/metrics/")
    assert res == metrics
def test_workbench_server_phases(user: UserClient):
    """
    Tests the phases described in the docs section `Snapshots from
    Workbench <http://devicehub.ereuse.org/
    events.html#snapshots-from-workbench>`_.
    """
    # 1. Snapshot with sync / rate / benchmarks / test data storage
    s = file('workbench-server-1.snapshot')
    snapshot, _ = user.post(res=Snapshot, data=s)
    assert not snapshot['closed'], 'Snapshot must be waiting for the new events'

    # 2. stress test
    st = file('workbench-server-2.stress-test')
    st['snapshot'] = snapshot['id']
    stress_test, _ = user.post(res=StressTest, data=st)

    # 3. erase
    ssd_id, hdd_id = snapshot['components'][4]['id'], snapshot['components'][
        5]['id']
    e = file('workbench-server-3.erase')
    e['snapshot'], e['device'] = snapshot['id'], ssd_id
    erase1, _ = user.post(res=EraseSectors, data=e)

    # 3 bis. a second erase
    e = file('workbench-server-3.erase')
    e['snapshot'], e['device'] = snapshot['id'], hdd_id
    erase2, _ = user.post(res=EraseSectors, data=e)

    # 4. Install
    i = file('workbench-server-4.install')
    i['snapshot'], i['device'] = snapshot['id'], ssd_id
    install, _ = user.post(res=Install, data=i)

    # Check events have been appended in Snapshot and devices
    # and that Snapshot is closed
    snapshot, _ = user.get(res=Snapshot, item=snapshot['id'])
    events = snapshot['events']
    assert len(events) == 9
    assert events[0]['type'] == 'Rate'
    assert events[0]['device'] == 1
    assert events[0]['closed']
    assert events[0]['type'] == 'WorkbenchRate'
    assert events[0]['device'] == 1
    assert events[1]['type'] == 'BenchmarkProcessor'
    assert events[1]['device'] == 5
    assert events[2]['type'] == 'BenchmarkProcessorSysbench'
    assert events[2]['device'] == 5
    assert events[3]['type'] == 'BenchmarkDataStorage'
    assert events[3]['device'] == 6
    assert events[4]['type'] == 'TestDataStorage'
    assert events[4]['device'] == 6
    assert events[4]['type'] == 'BenchmarkDataStorage'
    assert events[4]['device'] == 7
    assert events[5]['type'] == 'StressTest'
    assert events[5]['device'] == 1
    assert events[6]['type'] == 'EraseSectors'
    assert events[6]['device'] == 6
    assert events[7]['type'] == 'EraseSectors'
    assert events[7]['device'] == 7
    assert events[8]['type'] == 'Install'
    assert events[8]['device'] == 6
    assert snapshot['closed']
    assert not snapshot['error']

    pc, _ = user.get(res=Device, item=snapshot['id'])
    assert len(pc['events']) == 10  # todo shall I add child events?
def test_snapshot_component_add_remove(user: UserClient):
    """
    Tests adding and removing components and some don't generate HID.
    All computers generate HID.
    """
    def get_events_info(events: List[dict]) -> tuple:
        return tuple(
            (e['type'], [c['serialNumber'] for c in e['components']])
            for e in user.get_many(res=Event, resources=events, key='id'))

    # We add the first device (2 times). The distribution of components
    # (represented with their S/N) should be:
    # PC 1: p1c1s, p1c2s, p1c3s. PC 2: ø
    s1 = file('1-device-with-components.snapshot')
    snapshot1 = snapshot_and_check(user, s1, perform_second_snapshot=False)
    pc1_id = snapshot1['device']['id']
    pc1, _ = user.get(res=Device, item=pc1_id)
    # Parent contains components
    assert tuple(c['serialNumber']
                 for c in pc1['components']) == ('p1c1s', 'p1c2s', 'p1c3s')
    # Components contain parent
    assert all(c['parent'] == pc1_id for c in pc1['components'])
    # pc has Snapshot as event
    assert len(pc1['events']) == 1
    assert pc1['events'][0]['type'] == Snapshot.t
    # p1c1s has Snapshot
    p1c1s, _ = user.get(res=Device, item=pc1['components'][0]['id'])
    assert tuple(e['type'] for e in p1c1s['events']) == ('Snapshot', )

    # We register a new device
    # It has the processor of the first one (p1c2s)
    # PC 1: p1c1s, p1c3s. PC 2: p2c1s, p1c2s
    # Events PC1: Snapshot, Remove. PC2: Snapshot
    s2 = file('2-second-device-with-components-of-first.snapshot')
    # num_events = 2 = Remove, Add
    snapshot2 = snapshot_and_check(user,
                                   s2,
                                   event_types=('Remove', ),
                                   perform_second_snapshot=False)
    pc2_id = snapshot2['device']['id']
    pc1, _ = user.get(res=Device, item=pc1_id)
    pc2, _ = user.get(res=Device, item=pc2_id)
    # PC1
    assert tuple(c['serialNumber']
                 for c in pc1['components']) == ('p1c1s', 'p1c3s')
    assert all(c['parent'] == pc1_id for c in pc1['components'])
    assert tuple(e['type'] for e in pc1['events']) == ('Snapshot', 'Remove')
    # PC2
    assert tuple(c['serialNumber']
                 for c in pc2['components']) == ('p1c2s', 'p2c1s')
    assert all(c['parent'] == pc2_id for c in pc2['components'])
    assert tuple(e['type'] for e in pc2['events']) == ('Snapshot', )
    # p1c2s has two Snapshots, a Remove and an Add
    p1c2s, _ = user.get(res=Device, item=pc2['components'][0]['id'])
    assert tuple(e['type'] for e in p1c2s['events']) == ('Snapshot',
                                                         'Snapshot', 'Remove')

    # We register the first device again, but removing motherboard
    # and moving processor from the second device to the first.
    # We have created 1 Remove (from PC2's processor back to PC1)
    # PC 0: p1c2s, p1c3s. PC 1: p2c1s
    s3 = file(
        '3-first-device-but-removing-motherboard-and-adding-processor-from-2.snapshot'
    )
    snapshot_and_check(user, s3, ('Remove', ), perform_second_snapshot=False)
    pc1, _ = user.get(res=Device, item=pc1_id)
    pc2, _ = user.get(res=Device, item=pc2_id)
    # PC1
    assert {c['serialNumber'] for c in pc1['components']} == {'p1c2s', 'p1c3s'}
    assert all(c['parent'] == pc1_id for c in pc1['components'])
    assert tuple(get_events_info(pc1['events'])) == (
        # id, type, components, snapshot
        ('Snapshot', ['p1c1s', 'p1c2s', 'p1c3s']),  # first Snapshot1
        ('Remove', ['p1c2s']),  # Remove Processor in Snapshot2
        ('Snapshot', ['p1c2s', 'p1c3s'])  # This Snapshot3
    )
    # PC2
    assert tuple(c['serialNumber'] for c in pc2['components']) == ('p2c1s', )
    assert all(c['parent'] == pc2_id for c in pc2['components'])
    assert tuple(e['type'] for e in pc2['events']) == (
        'Snapshot',  # Second Snapshot
        'Remove'  # the processor we added in 2.
    )
    # p1c2s has Snapshot, Remove and Add
    p1c2s, _ = user.get(res=Device, item=pc1['components'][0]['id'])
    assert tuple(get_events_info(p1c2s['events'])) == (
        ('Snapshot', ['p1c1s', 'p1c2s', 'p1c3s']),  # First Snapshot to PC1
        ('Snapshot', ['p1c2s', 'p2c1s']),  # Second Snapshot to PC2
        ('Remove', ['p1c2s']),  # ...which caused p1c2s to be removed form PC1
        ('Snapshot', ['p1c2s', 'p1c3s']),  # The third Snapshot to PC1
        ('Remove', ['p1c2s'])  # ...which caused p1c2 to be removed from PC2
    )

    # We register the first device but without the processor,
    # adding a graphic card and adding a new component
    s4 = file(
        '4-first-device-but-removing-processor.snapshot-and-adding-graphic-card'
    )
    snapshot_and_check(user, s4, perform_second_snapshot=False)
    pc1, _ = user.get(res=Device, item=pc1_id)
    pc2, _ = user.get(res=Device, item=pc2_id)
    # PC 0: p1c3s, p1c4s. PC1: p2c1s
    assert {c['serialNumber'] for c in pc1['components']} == {'p1c3s', 'p1c4s'}
    assert all(c['parent'] == pc1_id for c in pc1['components'])
    # This last Snapshot only
    assert get_events_info(pc1['events'])[-1] == ('Snapshot',
                                                  ['p1c3s', 'p1c4s'])
    # PC2
    # We haven't changed PC2
    assert tuple(c['serialNumber'] for c in pc2['components']) == ('p2c1s', )
    assert all(c['parent'] == pc2_id for c in pc2['components'])
Exemple #20
0
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', owner_id=user.user['id']))
        db.session.commit()
    user.get(res=Tag, item='foo-bar/device', status=TagNotLinked)
Exemple #21
0
def test_tag_get_device_from_tag_endpoint_no_tag(user: UserClient):
    """As above, but when there is no tag with such ID."""
    user.get(res=Tag, item='foo-bar/device', status=ResourceNotFound)
def test_snapshot_mobile_smartphone_imei_manual_rate(user: UserClient):
    s = file('smartphone.snapshot')
    snapshot = snapshot_and_check(user, s, event_types=('ManualRate',))
    mobile, _ = user.get(res=m.Device, item=snapshot['device']['id'])
    assert mobile['imei'] == 3568680000414120
def test_snapshot_real_eee_1001pxd(user: UserClient):
    """
    Checks the values of the device, components,
    events and their relationships of a real pc.
    """
    s = file('real-eee-1001pxd.snapshot.11')
    snapshot, _ = user.post(res=em.Snapshot, data=s)
    pc, _ = user.get(res=Device, item=snapshot['device']['id'])
    assert pc['type'] == 'Laptop'
    assert pc['chassis'] == 'Netbook'
    assert pc['model'] == '1001pxd'
    assert pc['serialNumber'] == 'b8oaas048286'
    assert pc['manufacturer'] == 'asustek computer inc.'
    assert pc['hid'] == 'laptop-asustek_computer_inc-1001pxd-b8oaas048286'
    assert pc['tags'] == []
    assert pc['networkSpeeds'] == [
        100, 0
    ], 'Although it has WiFi we do not know the speed'
    assert pc['rate']
    rate = pc['rate']
    assert rate['appearanceRange'] == 'B'
    assert rate['functionalityRange'] == 'A'
    assert rate['processorRange'] == 'VERY_LOW'
    assert rate['ramRange'] == 'VERY_LOW'
    assert rate['ratingRange'] == 'VERY_LOW'
    assert rate['ram'] == 1.53
    assert rate['data_storage'] == 3.76
    assert rate['type'] == 'AggregateRate'
    assert rate['biosRange'] == 'C'
    assert rate['appearance'] == 0, 'appearance B equals 0 points'
    # todo fix gets correctly functionality rates values not equals to 0.
    assert rate['functionality'] == 0, 'functionality A equals 0.4 points'
    # why this assert?? -2 < rating < 4.7
    # assert rate['rating'] > 0 and rate['rating'] != 1
    components = snapshot['components']
    wifi = components[0]
    assert wifi['hid'] == 'networkadapter-qualcomm_atheros-' \
                          'ar9285_wireless_network_adapter-74_2f_68_8b_fd_c8'
    assert wifi['serialNumber'] == '74:2f:68:8b:fd:c8'
    assert wifi['wireless']
    eth = components[1]
    assert eth['hid'] == 'networkadapter-qualcomm_atheros-' \
                         'ar8152_v2_0_fast_ethernet-14_da_e9_42_f6_7c'
    assert eth['speed'] == 100
    assert not eth['wireless']
    cpu = components[2]
    assert cpu['address'] == 64
    assert cpu['cores'] == 1
    assert cpu['threads'] == 1
    assert cpu['speed'] == 1.667
    assert 'hid' not in cpu
    assert pc['processorModel'] == cpu[
        'model'] == 'intel atom cpu n455 @ 1.66ghz'
    cpu, _ = user.get(res=Device, item=cpu['id'])
    events = cpu['events']
    sysbench = next(e for e in events
                    if e['type'] == em.BenchmarkProcessorSysbench.t)
    assert sysbench['elapsed'] == 164
    assert math.isclose(sysbench['rate'], 164, rel_tol=0.001)
    assert sysbench['snapshot'] == snapshot['id']
    assert sysbench['device'] == cpu['id']
    assert sysbench['parent'] == pc['id']
    benchmark_cpu = next(e for e in events
                         if e['type'] == em.BenchmarkProcessor.t)
    assert math.isclose(benchmark_cpu['rate'], 6666, rel_tol=0.001)
    assert benchmark_cpu['elapsed'] == 0
    event_types = tuple(e['type'] for e in events)
    assert em.BenchmarkRamSysbench.t in event_types
    assert em.StressTest.t in event_types
    assert em.Snapshot.t in event_types
    assert len(events) == 7
    gpu = components[3]
    assert gpu[
        'model'] == 'atom processor d4xx/d5xx/n4xx/n5xx integrated graphics controller'
    assert gpu['manufacturer'] == 'intel corporation'
    assert gpu['memory'] == 256
    gpu, _ = user.get(res=Device, item=gpu['id'])
    event_types = tuple(e['type'] for e in gpu['events'])
    assert em.BenchmarkRamSysbench.t in event_types
    assert em.StressTest.t in event_types
    assert em.Snapshot.t in event_types
    # todo why?? change event types 3 to 5
    assert len(event_types) == 5
    sound = components[4]
    assert sound[
        'model'] == 'nm10/ich7 family high definition audio controller'
    sound = components[5]
    assert sound['model'] == 'usb 2.0 uvc vga webcam'
    ram = components[6]
    assert ram['interface'] == 'DDR2'
    assert ram['speed'] == 667
    assert pc['ramSize'] == ram['size'] == 1024
    hdd = components[7]
    assert hdd['type'] == 'HardDrive'
    assert hdd['hid'] == 'harddrive-hitachi-hts54322-e2024242cv86hj'
    assert hdd['interface'] == 'ATA'
    assert hdd['size'] == 238475
    hdd, _ = user.get(res=Device, item=hdd['id'])
    event_types = tuple(e['type'] for e in hdd['events'])
    assert em.BenchmarkRamSysbench.t in event_types
    assert em.StressTest.t in event_types
    assert em.BenchmarkDataStorage.t in event_types
    assert em.TestDataStorage.t in event_types
    assert em.EraseBasic.t in event_types
    assert em.Snapshot.t in event_types
    # todo why?? change event types 6 to 8
    assert len(event_types) == 8
    erase = next(e for e in hdd['events'] if e['type'] == em.EraseBasic.t)
    assert erase['endTime']
    assert erase['startTime']
    assert erase['severity'] == 'Info'
    assert hdd['privacy']['type'] == 'EraseBasic'
    mother = components[8]
    assert mother[
        'hid'] == 'motherboard-asustek_computer_inc-1001pxd-eee0123456789'
Exemple #24
0
def test_device_query_filter_lots(user: UserClient):
    parent, _ = user.post({'name': 'Parent'}, res=Lot)
    child, _ = user.post({'name': 'Child'}, res=Lot)

    i, _ = user.get(res=Device,
                    query=[('filter', {
                        'lot': {
                            'id': [parent['id']]
                        }
                    })])
    assert not i['items'], 'No devices in lot'

    parent, _ = user.post({},
                          res=Lot,
                          item='{}/children'.format(parent['id']),
                          query=[('id', child['id'])])
    i, _ = user.get(res=Device, query=[('filter', {'type': ['Computer']})])
    assert ('1', '2', '3', '4') == tuple(d['serialNumber'] for d in i['items'])
    parent, _ = user.post({},
                          res=Lot,
                          item='{}/devices'.format(parent['id']),
                          query=[('id', d['id']) for d in i['items'][:2]])
    child, _ = user.post({},
                         res=Lot,
                         item='{}/devices'.format(child['id']),
                         query=[('id', d['id']) for d in i['items'][2:]])
    i, _ = user.get(res=Device,
                    query=[('filter', {
                        'lot': {
                            'id': [parent['id']]
                        }
                    })])
    assert ('1', '2', '3', '4', '1-gc', '2-ssd', '4-ssd') == tuple(
        x['serialNumber'] for x in i['items']
    ), 'The parent lot contains 2 items plus indirectly the other ' \
       '2 from the child lot, with all their 2 components'

    i, _ = user.get(res=Device,
                    query=[
                        ('filter', {
                            'type': ['Computer'],
                            'lot': {
                                'id': [parent['id']]
                            }
                        }),
                    ])
    assert ('1', '2', '3', '4') == tuple(x['serialNumber'] for x in i['items'])
    s, _ = user.get(res=Device,
                    query=[('filter', {
                        'lot': {
                            'id': [child['id']]
                        }
                    })])
    assert ('3', '4', '4-ssd') == tuple(x['serialNumber'] for x in s['items'])
    s, _ = user.get(res=Device,
                    query=[('filter', {
                        'lot': {
                            'id': [child['id'], parent['id']]
                        }
                    })])
    assert ('1', '2', '3', '4', '1-gc', '2-ssd', '4-ssd') == tuple(
        x['serialNumber'] for x in s['items']
    ), 'Adding both lots is redundant in this case and we have the 4 elements.'
Exemple #25
0
def test_device_query_no_filters(user: UserClient):
    i, _ = user.get(res=Device)
    assert ('1', '2', '3', '4', '1-gc', '2-ssd',
            '4-ssd') == tuple(d['serialNumber'] for d in i['items'])
Exemple #26
0
def test_post_get_lot(user: UserClient):
    """Tests submitting and retreiving a basic lot."""
    l, _ = user.post({'name': 'Foo'}, res=Lot)
    assert l['name'] == 'Foo'
    l, _ = user.get(res=Lot, item=l['id'])
    assert l['name'] == 'Foo'
Exemple #27
0
def test_device_query_filter_type(user: UserClient):
    i, _ = user.get(res=Device,
                    query=[('filter', {
                        'type': ['Desktop', 'Laptop']
                    })])
    assert ('1', '2', '3') == tuple(d['serialNumber'] for d in i['items'])
Exemple #28
0
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
Exemple #29
0
def test_device_query_search_synonyms_asus(user: UserClient):
    user.post(file('real-eee-1001pxd.snapshot.11'), res=Snapshot)
    i, _ = user.get(res=Device, query=[('search', 'asustek')])
    assert 1 == len(i['items'])
    i, _ = user.get(res=Device, query=[('search', 'asus')])
    assert 1 == len(i['items'])
Exemple #30
0
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]