Merge pull request #156 from eReuse/feature/#155_decode_snapshots

Feature/#155 decode snapshot json
This commit is contained in:
cayop 2021-07-06 12:47:02 +02:00 committed by GitHub
commit 705b86cb99
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
17 changed files with 235 additions and 155 deletions

View File

@ -76,3 +76,4 @@ class DevicehubConfig(Config):
"""Definition of path where save the documents of customers""" """Definition of path where save the documents of customers"""
PATH_DOCUMENTS_STORAGE = config('PATH_DOCUMENTS_STORAGE', '/tmp/') PATH_DOCUMENTS_STORAGE = config('PATH_DOCUMENTS_STORAGE', '/tmp/')
JWT_PASS = config('JWT_PASS', '')

View File

@ -1,5 +1,6 @@
import itertools import itertools
import json import json
import jwt
from pathlib import Path from pathlib import Path
from typing import Set from typing import Set
@ -94,7 +95,7 @@ class Dummy:
for path in bar: for path in bar:
with path.open() as f: with path.open() as f:
snapshot = yaml.load(f) snapshot = yaml.load(f)
s, _ = user1.post(res=m.Snapshot, data=snapshot) s, _ = user1.post(res=m.Snapshot, data=self.json_encode(snapshot))
if s.get('uuid', None) == 'ec23c11b-80b6-42cd-ac5c-73ba7acddbc4': if s.get('uuid', None) == 'ec23c11b-80b6-42cd-ac5c-73ba7acddbc4':
sample_pc = s['device']['id'] sample_pc = s['device']['id']
sample_pc_devicehub_id = s['device']['devicehubID'] sample_pc_devicehub_id = s['device']['devicehubID']
@ -206,3 +207,15 @@ class Dummy:
response_wrapper=self.app.response_class) response_wrapper=self.app.response_class)
client.login() client.login()
return client return client
def json_encode(self, dev: str) -> dict:
"""Encode json."""
data = {"type": "Snapshot"}
data['data'] = jwt.encode(dev,
self.app.config['JWT_PASS'],
algorithm="HS256",
json_encoder=ereuse_utils.JSONEncoder
)
return data

View File

@ -59,7 +59,6 @@ def move_json(tmp_snapshots, path_name, user, live=False):
os.remove(path_name) os.remove(path_name)
class SnapshotView(): class SnapshotView():
"""Performs a Snapshot. """Performs a Snapshot.
@ -70,8 +69,8 @@ class SnapshotView():
# snapshot, and we want to wait to flush snapshot at the end # snapshot, and we want to wait to flush snapshot at the end
def __init__(self, snapshot_json: dict, resource_def, schema): def __init__(self, snapshot_json: dict, resource_def, schema):
# import pdb; pdb.set_trace()
self.schema = schema self.schema = schema
self.snapshot_json = snapshot_json
self.resource_def = resource_def self.resource_def = resource_def
self.tmp_snapshots = app.config['TMP_SNAPSHOTS'] self.tmp_snapshots = app.config['TMP_SNAPSHOTS']
self.path_snapshot = save_json(snapshot_json, self.tmp_snapshots, g.user.email) self.path_snapshot = save_json(snapshot_json, self.tmp_snapshots, g.user.email)

View File

@ -1,26 +1,29 @@
""" This is the view for Snapshots """ """ This is the view for Snapshots """
import jwt
import ereuse_utils
from datetime import timedelta from datetime import timedelta
from distutils.version import StrictVersion from distutils.version import StrictVersion
from uuid import UUID from uuid import UUID
from flask import current_app as app, request, g from flask import current_app as app, request, g
from teal.db import ResourceNotFound
from teal.marshmallow import ValidationError from teal.marshmallow import ValidationError
from teal.resource import View from teal.resource import View
from teal.db import ResourceNotFound
from ereuse_devicehub.db import db from ereuse_devicehub.db import db
from ereuse_devicehub.query import things_response from ereuse_devicehub.query import things_response
from ereuse_devicehub.resources.action.models import (Action, Snapshot, VisualTest, from ereuse_devicehub.resources.action.models import (Action, Snapshot, VisualTest,
InitTransfer, Live, Allocate, Deallocate, InitTransfer, Live, Allocate, Deallocate,
Trade, Confirm, ConfirmRevoke, Revoke) Trade, Confirm, ConfirmRevoke, Revoke)
from ereuse_devicehub.resources.device.models import Device, Computer, DataStorage
from ereuse_devicehub.resources.enums import Severity
from ereuse_devicehub.resources.action.views import trade as trade_view from ereuse_devicehub.resources.action.views import trade as trade_view
from ereuse_devicehub.resources.action.views.snapshot import SnapshotView, save_json, move_json from ereuse_devicehub.resources.action.views.snapshot import SnapshotView, save_json, move_json
from ereuse_devicehub.resources.device.models import Device, Computer, DataStorage
from ereuse_devicehub.resources.enums import Severity
SUPPORTED_WORKBENCH = StrictVersion('11.0') SUPPORTED_WORKBENCH = StrictVersion('11.0')
class AllocateMix(): class AllocateMix():
model = None model = None
@ -121,11 +124,11 @@ class LiveView(View):
"""If the device.allocated == True, then this snapshot create an action live.""" """If the device.allocated == True, then this snapshot create an action live."""
hid = self.get_hid(snapshot) hid = self.get_hid(snapshot)
if not hid or not Device.query.filter( if not hid or not Device.query.filter(
Device.hid==hid).count(): Device.hid == hid).count():
raise ValidationError('Device not exist.') raise ValidationError('Device not exist.')
device = Device.query.filter( device = Device.query.filter(
Device.hid==hid, Device.allocated==True).one() Device.hid == hid, Device.allocated == True).one()
# Is not necessary # Is not necessary
if not device: if not device:
raise ValidationError('Device not exist.') raise ValidationError('Device not exist.')
@ -166,19 +169,47 @@ class LiveView(View):
return live return live
def decode_snapshot(data):
try:
return jwt.decode(data['data'], app.config['JWT_PASS'], algorithms="HS256", json_encoder=ereuse_utils.JSONEncoder)
except jwt.exceptions.InvalidSignatureError as err:
txt = 'Invalid snapshot'
raise ValidationError(txt)
class ActionView(View): class ActionView(View):
def post(self): def post(self):
"""Posts an action.""" """Posts an action."""
json = request.get_json(validate=False) json = request.get_json(validate=False)
if not json or 'type' not in json: if not json or 'type' not in json:
raise ValidationError('Resource needs a type.') raise ValidationError('Post request needs a json.')
# todo there should be a way to better get subclassess resource # todo there should be a way to better get subclassess resource
# defs # defs
resource_def = app.resources[json['type']] resource_def = app.resources[json['type']]
if json['type'] == Snapshot.t: if json['type'] == Snapshot.t:
if json.get('software') == 'Web' and json['device'] == 'Computer':
txt = 'Invalid snapshot'
raise ValidationError(txt)
if json.get('software') == 'Web':
snapshot = SnapshotView(json, resource_def, self.schema) snapshot = SnapshotView(json, resource_def, self.schema)
return snapshot.post() return snapshot.post()
if not 'data' in json:
txt = 'Invalid snapshot'
raise ValidationError(txt)
snapshot_data = decode_snapshot(json)
if not snapshot_data:
txt = 'Invalid snapshot'
raise ValidationError(txt)
snapshot = SnapshotView(snapshot_data, resource_def, self.schema)
return snapshot.post()
if json['type'] == VisualTest.t: if json['type'] == VisualTest.t:
pass pass
# TODO JN add compute rate with new visual test and old components device # TODO JN add compute rate with new visual test and old components device
@ -233,4 +264,3 @@ class ActionView(View):
def transfer_ownership(self): def transfer_ownership(self):
"""Perform a InitTransfer action to change author_id of device""" """Perform a InitTransfer action to change author_id of device"""
pass pass

View File

@ -625,10 +625,10 @@ class Computer(Device):
It is a subset of the Linux definition of DMI / DMI decode. It is a subset of the Linux definition of DMI / DMI decode.
""" """
amount = Column(Integer, check_range('amount', min=0, max=100), default=0) amount = Column(Integer, check_range('amount', min=0, max=100), default=0)
# owner_id = db.Column(UUID(as_uuid=True), owner_id = db.Column(UUID(as_uuid=True),
# db.ForeignKey(User.id), db.ForeignKey(User.id),
# nullable=False, nullable=False,
# default=lambda: g.user.id) default=lambda: g.user.id)
# author = db.relationship(User, primaryjoin=owner_id == User.id) # author = db.relationship(User, primaryjoin=owner_id == User.id)
transfer_state = db.Column(IntEnum(TransferState), default=TransferState.Initial, nullable=False) transfer_state = db.Column(IntEnum(TransferState), default=TransferState.Initial, nullable=False)
transfer_state.comment = TransferState.__doc__ transfer_state.comment = TransferState.__doc__

View File

@ -36,3 +36,4 @@ sortedcontainers==2.1.0
tqdm==4.32.2 tqdm==4.32.2
python-decouple==3.3 python-decouple==3.3
python-dotenv==0.14.0 python-dotenv==0.14.0
pyjwt==2.0.0a1

View File

@ -1,8 +1,11 @@
import io import io
import uuid import uuid
import jwt
import ereuse_utils
from contextlib import redirect_stdout from contextlib import redirect_stdout
from datetime import datetime from datetime import datetime
from pathlib import Path from pathlib import Path
from decouple import config
import boltons.urlutils import boltons.urlutils
import pytest import pytest
@ -26,6 +29,7 @@ ENDT = datetime(year=2000, month=1, day=1, hour=2)
"""A dummy ending time to use in tests.""" """A dummy ending time to use in tests."""
T = {'start_time': STARTT, 'end_time': ENDT} T = {'start_time': STARTT, 'end_time': ENDT}
"""A dummy start_time/end_time to use as function keywords.""" """A dummy start_time/end_time to use as function keywords."""
P = config('JWT_PASS', '')
class TestConfig(DevicehubConfig): class TestConfig(DevicehubConfig):
@ -36,6 +40,7 @@ class TestConfig(DevicehubConfig):
TMP_LIVES = '/tmp/lives' TMP_LIVES = '/tmp/lives'
EMAIL_ADMIN = 'foo@foo.com' EMAIL_ADMIN = 'foo@foo.com'
PATH_DOCUMENTS_STORAGE = '/tmp/trade_documents' PATH_DOCUMENTS_STORAGE = '/tmp/trade_documents'
JWT_PASS = config('JWT_PASS', '')
@pytest.fixture(scope='session') @pytest.fixture(scope='session')
@ -137,12 +142,30 @@ def auth_app_context(app: Devicehub):
yield app yield app
def file(name: str) -> dict: def json_encode(dev: str) -> dict:
"""Encode json."""
data = {"type": "Snapshot"}
data['data'] = jwt.encode(dev,
P,
algorithm="HS256",
json_encoder=ereuse_utils.JSONEncoder
)
return data
def yaml2json(name: str) -> dict:
"""Opens and parses a YAML file from the ``files`` subdir.""" """Opens and parses a YAML file from the ``files`` subdir."""
with Path(__file__).parent.joinpath('files').joinpath(name + '.yaml').open() as f: with Path(__file__).parent.joinpath('files').joinpath(name + '.yaml').open() as f:
return yaml.load(f) return yaml.load(f)
def file(name: str) -> dict:
"""Opens and parses a YAML file from the ``files`` subdir. And decode"""
return json_encode(yaml2json(name))
def file_workbench(name: str) -> dict: def file_workbench(name: str) -> dict:
"""Opens and parses a YAML file from the ``files`` subdir.""" """Opens and parses a YAML file from the ``files`` subdir."""
with Path(__file__).parent.joinpath('workbench_files').joinpath(name + '.json').open() as f: with Path(__file__).parent.joinpath('workbench_files').joinpath(name + '.json').open() as f:

View File

@ -29,7 +29,7 @@ from ereuse_devicehub.resources.device.models import Desktop, Device, GraphicCar
RamModule, SolidStateDrive RamModule, SolidStateDrive
from ereuse_devicehub.resources.enums import ComputerChassis, Severity, TestDataStorageLength from ereuse_devicehub.resources.enums import ComputerChassis, Severity, TestDataStorageLength
from tests import conftest from tests import conftest
from tests.conftest import create_user, file from tests.conftest import create_user, file, yaml2json, json_encode
@pytest.mark.mvp @pytest.mark.mvp
@ -260,6 +260,7 @@ def test_live(user: UserClient, client: Client, app: Devicehub):
"""Tests inserting a Live into the database and GETting it.""" """Tests inserting a Live into the database and GETting it."""
acer = file('acer.happy.battery.snapshot') acer = file('acer.happy.battery.snapshot')
snapshot, _ = user.post(acer, res=models.Snapshot) snapshot, _ = user.post(acer, res=models.Snapshot)
acer = yaml2json('acer.happy.battery.snapshot')
device_id = snapshot['device']['id'] device_id = snapshot['device']['id']
post_request = {"transaction": "ccc", "name": "John", "endUsers": 1, post_request = {"transaction": "ccc", "name": "John", "endUsers": 1,
"devices": [device_id], "description": "aaa", "devices": [device_id], "description": "aaa",
@ -292,6 +293,7 @@ def test_live(user: UserClient, client: Client, app: Devicehub):
@pytest.mark.usefixtures(conftest.app_context.__name__) @pytest.mark.usefixtures(conftest.app_context.__name__)
def test_live_example(user: UserClient, client: Client, app: Devicehub): def test_live_example(user: UserClient, client: Client, app: Devicehub):
"""Tests inserting a Live into the database and GETting it.""" """Tests inserting a Live into the database and GETting it."""
# import pdb; pdb.set_trace()
acer = file('snapshotLive') acer = file('snapshotLive')
snapshot, _ = user.post(acer, res=models.Snapshot) snapshot, _ = user.post(acer, res=models.Snapshot)
device_id = snapshot['device']['id'] device_id = snapshot['device']['id']
@ -304,7 +306,7 @@ def test_live_example(user: UserClient, client: Client, app: Devicehub):
user.post(res=models.Allocate, data=post_request) user.post(res=models.Allocate, data=post_request)
acer = file('live') acer = yaml2json('live')
live, _ = client.post(acer, res=models.Live) live, _ = client.post(acer, res=models.Live)
db_device = Device.query.filter_by(id=device_id).one() db_device = Device.query.filter_by(id=device_id).one()
action_live = [a for a in db_device.actions if a.type == 'Live'] action_live = [a for a in db_device.actions if a.type == 'Live']
@ -320,9 +322,9 @@ def test_live_two_users(user: UserClient, user2: UserClient, client: Client, app
"""Tests inserting a Live into the database and GETting it.""" """Tests inserting a Live into the database and GETting it."""
acer = file('snapshotLive') acer = file('snapshotLive')
snapshot, _ = user.post(acer, res=models.Snapshot) snapshot, _ = user.post(acer, res=models.Snapshot)
acer2 = file('snapshotLive') acer2 = yaml2json('snapshotLive')
acer2['uuid'] = '3b6a9288-0ba6-4bdd-862a-2b1f660e7115' acer2['uuid'] = '3b6a9288-0ba6-4bdd-862a-2b1f660e7115'
snapshot2, _ = user2.post(acer2, res=models.Snapshot) snapshot2, _ = user2.post(json_encode(acer2), res=models.Snapshot)
device_id = snapshot['device']['id'] device_id = snapshot['device']['id']
post_request = {"transaction": "ccc", "name": "John", "endUsers": 1, post_request = {"transaction": "ccc", "name": "John", "endUsers": 1,
"devices": [device_id], "description": "aaa", "devices": [device_id], "description": "aaa",
@ -333,7 +335,7 @@ def test_live_two_users(user: UserClient, user2: UserClient, client: Client, app
user.post(res=models.Allocate, data=post_request) user.post(res=models.Allocate, data=post_request)
acer = file('live') acer = yaml2json('live')
live, _ = client.post(acer, res=models.Live) live, _ = client.post(acer, res=models.Live)
db_device = Device.query.filter_by(id=device_id).one() db_device = Device.query.filter_by(id=device_id).one()
action_live = [a for a in db_device.actions if a.type == 'Live'] action_live = [a for a in db_device.actions if a.type == 'Live']
@ -349,9 +351,9 @@ def test_live_two_allocated(user: UserClient, user2: UserClient, client: Client,
"""Tests inserting a Live into the database and GETting it.""" """Tests inserting a Live into the database and GETting it."""
acer = file('snapshotLive') acer = file('snapshotLive')
snapshot, _ = user.post(acer, res=models.Snapshot) snapshot, _ = user.post(acer, res=models.Snapshot)
acer2 = file('snapshotLive') acer2 = yaml2json('snapshotLive')
acer2['uuid'] = '3b6a9288-0ba6-4bdd-862a-2b1f660e7115' acer2['uuid'] = '3b6a9288-0ba6-4bdd-862a-2b1f660e7115'
snapshot2, _ = user2.post(acer2, res=models.Snapshot) snapshot2, _ = user2.post(json_encode(acer2), res=models.Snapshot)
device_id = snapshot['device']['id'] device_id = snapshot['device']['id']
device_id2 = snapshot2['device']['id'] device_id2 = snapshot2['device']['id']
post_request = {"transaction": "ccc", "name": "John", "endUsers": 1, post_request = {"transaction": "ccc", "name": "John", "endUsers": 1,
@ -370,7 +372,7 @@ def test_live_two_allocated(user: UserClient, user2: UserClient, client: Client,
user.post(res=models.Allocate, data=post_request) user.post(res=models.Allocate, data=post_request)
user2.post(res=models.Allocate, data=post_request2) user2.post(res=models.Allocate, data=post_request2)
acer = file('live') acer = yaml2json('live')
live, _ = client.post(acer, res=models.Live, status=422) live, _ = client.post(acer, res=models.Live, status=422)
message = 'Expected only one Device but multiple where found' message = 'Expected only one Device but multiple where found'
assert live['message'] == message assert live['message'] == message
@ -396,6 +398,7 @@ def test_live_without_TestDataStorage(user: UserClient, client: Client, app: Dev
} }
user.post(res=models.Allocate, data=post_request) user.post(res=models.Allocate, data=post_request)
acer = yaml2json('acer.happy.battery.snapshot')
acer['uuid'] = "490fb8c0-81a1-42e9-95e0-5e7db7038ec3" acer['uuid'] = "490fb8c0-81a1-42e9-95e0-5e7db7038ec3"
actions = [a for a in acer['components'][7]['actions'] if a['type'] != 'TestDataStorage'] actions = [a for a in acer['components'][7]['actions'] if a['type'] != 'TestDataStorage']
acer['components'][7]['actions'] = actions acer['components'][7]['actions'] = actions
@ -429,6 +432,7 @@ def test_live_without_hdd_1(user: UserClient, client: Client, app: Devicehub):
} }
user.post(res=models.Allocate, data=post_request) user.post(res=models.Allocate, data=post_request)
acer = yaml2json('acer.happy.battery.snapshot')
acer['uuid'] = "490fb8c0-81a1-42e9-95e0-5e7db7038ec3" acer['uuid'] = "490fb8c0-81a1-42e9-95e0-5e7db7038ec3"
components = [a for a in acer['components'] if a['type'] != 'HardDrive'] components = [a for a in acer['components'] if a['type'] != 'HardDrive']
acer['components'] = components acer['components'] = components
@ -446,10 +450,10 @@ def test_live_without_hdd_2(user: UserClient, client: Client, app: Devicehub):
"""Tests inserting a Live into the database and GETting it. """Tests inserting a Live into the database and GETting it.
The snapshot haven't hdd and the live neither, and response 404 The snapshot haven't hdd and the live neither, and response 404
""" """
acer = file('acer.happy.battery.snapshot') acer = yaml2json('acer.happy.battery.snapshot')
components = [a for a in acer['components'] if a['type'] != 'HardDrive'] components = [a for a in acer['components'] if a['type'] != 'HardDrive']
acer['components'] = components acer['components'] = components
snapshot, _ = user.post(acer, res=models.Snapshot) snapshot, _ = user.post(json_encode(acer), res=models.Snapshot)
device_id = snapshot['device']['id'] device_id = snapshot['device']['id']
db_device = Device.query.filter_by(id=device_id).one() db_device = Device.query.filter_by(id=device_id).one()
post_request = {"transaction": "ccc", "name": "John", "endUsers": 1, post_request = {"transaction": "ccc", "name": "John", "endUsers": 1,
@ -476,11 +480,11 @@ def test_live_without_hdd_3(user: UserClient, client: Client, app: Devicehub):
The snapshot haven't hdd and the live have, and save the live The snapshot haven't hdd and the live have, and save the live
with usage_time_allocate == 0 with usage_time_allocate == 0
""" """
acer = file('acer.happy.battery.snapshot') acer = yaml2json('acer.happy.battery.snapshot')
acer['uuid'] = "490fb8c0-81a1-42e9-95e0-5e7db7038ec3" acer['uuid'] = "490fb8c0-81a1-42e9-95e0-5e7db7038ec3"
components = [a for a in acer['components'] if a['type'] != 'HardDrive'] components = [a for a in acer['components'] if a['type'] != 'HardDrive']
acer['components'] = components acer['components'] = components
snapshot, _ = user.post(acer, res=models.Snapshot) snapshot, _ = user.post(json_encode(acer), res=models.Snapshot)
device_id = snapshot['device']['id'] device_id = snapshot['device']['id']
db_device = Device.query.filter_by(id=device_id).one() db_device = Device.query.filter_by(id=device_id).one()
post_request = {"transaction": "ccc", "name": "John", "endUsers": 1, post_request = {"transaction": "ccc", "name": "John", "endUsers": 1,
@ -491,7 +495,7 @@ def test_live_without_hdd_3(user: UserClient, client: Client, app: Devicehub):
} }
user.post(res=models.Allocate, data=post_request) user.post(res=models.Allocate, data=post_request)
acer = file('acer.happy.battery.snapshot') acer = yaml2json('acer.happy.battery.snapshot')
acer.pop('elapsed') acer.pop('elapsed')
acer['licence_version'] = '1.0.0' acer['licence_version'] = '1.0.0'
live, _ = client.post(acer, res=models.Live) live, _ = client.post(acer, res=models.Live)
@ -524,7 +528,7 @@ def test_live_with_hdd_with_old_time(user: UserClient, client: Client, app: Devi
} }
user.post(res=models.Allocate, data=post_request) user.post(res=models.Allocate, data=post_request)
acer = file('acer.happy.battery.snapshot') acer = yaml2json('acer.happy.battery.snapshot')
acer['uuid'] = "490fb8c0-81a1-42e9-95e0-5e7db7038ec3" acer['uuid'] = "490fb8c0-81a1-42e9-95e0-5e7db7038ec3"
action = [a for a in acer['components'][7]['actions'] if a['type'] == 'TestDataStorage'] action = [a for a in acer['components'][7]['actions'] if a['type'] == 'TestDataStorage']
action[0]['lifetime'] -= 100 action[0]['lifetime'] -= 100
@ -557,6 +561,7 @@ def test_live_search_last_allocate(user: UserClient, client: Client, app: Device
} }
user.post(res=models.Allocate, data=post_request) user.post(res=models.Allocate, data=post_request)
acer = yaml2json('acer.happy.battery.snapshot')
acer['uuid'] = "490fb8c0-81a1-42e9-95e0-5e7db7038ec3" acer['uuid'] = "490fb8c0-81a1-42e9-95e0-5e7db7038ec3"
hdd = [c for c in acer['components'] if c['type'] == 'HardDrive'][0] 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 = [a for a in hdd['actions'] if a['type'] == 'TestDataStorage'][0]
@ -576,8 +581,8 @@ def test_live_search_last_allocate(user: UserClient, client: Client, app: Device
@pytest.mark.mvp @pytest.mark.mvp
def test_save_live_json(app: Devicehub, user: UserClient, client: Client): def test_save_live_json(app: Devicehub, user: UserClient, client: Client):
""" This test check if works the function save_snapshot_in_file """ """ This test check if works the function save_snapshot_in_file """
acer = file('acer.happy.battery.snapshot') acer = yaml2json('acer.happy.battery.snapshot')
snapshot, _ = user.post(acer, res=models.Snapshot) snapshot, _ = user.post(json_encode(acer), res=models.Snapshot)
debug = 'AAA' debug = 'AAA'
acer['debug'] = debug acer['debug'] = debug
device_id = snapshot['device']['id'] device_id = snapshot['device']['id']

View File

@ -29,7 +29,7 @@ from ereuse_devicehub.resources.enums import ComputerChassis, DisplayTech, Sever
from ereuse_devicehub.resources.tag.model import Tag from ereuse_devicehub.resources.tag.model import Tag
from ereuse_devicehub.resources.user import User from ereuse_devicehub.resources.user import User
from tests import conftest from tests import conftest
from tests.conftest import file from tests.conftest import file, yaml2json, json_encode
@pytest.mark.mvp @pytest.mark.mvp
@ -138,7 +138,7 @@ def test_physical_properties():
@pytest.mark.usefixtures(conftest.auth_app_context.__name__) @pytest.mark.usefixtures(conftest.auth_app_context.__name__)
def test_component_similar_one(): def test_component_similar_one():
user = User.query.filter().first() user = User.query.filter().first()
snapshot = conftest.file('pc-components.db') snapshot = yaml2json('pc-components.db')
pc = snapshot['device'] pc = snapshot['device']
snapshot['components'][0]['serial_number'] = snapshot['components'][1]['serial_number'] = None snapshot['components'][0]['serial_number'] = snapshot['components'][1]['serial_number'] = None
pc = d.Desktop(**pc, components=OrderedSet(d.Component(**c) for c in snapshot['components'])) pc = d.Desktop(**pc, components=OrderedSet(d.Component(**c) for c in snapshot['components']))
@ -167,7 +167,7 @@ def test_add_remove():
# pc2 has c3 # pc2 has c3
# c4 is not with any pc # c4 is not with any pc
user = User.query.filter().first() user = User.query.filter().first()
values = conftest.file('pc-components.db') values = yaml2json('pc-components.db')
pc = values['device'] pc = values['device']
c1, c2 = (d.Component(**c) for c in values['components']) c1, c2 = (d.Component(**c) for c in values['components'])
pc = d.Desktop(**pc, components=OrderedSet([c1, c2])) pc = d.Desktop(**pc, components=OrderedSet([c1, c2]))
@ -198,7 +198,7 @@ def test_sync_run_components_empty():
"""Syncs a device that has an empty components list. The system should """Syncs a device that has an empty components list. The system should
remove all the components from the device. remove all the components from the device.
""" """
s = conftest.file('pc-components.db') s = yaml2json('pc-components.db')
pc = d.Desktop(**s['device'], components=OrderedSet(d.Component(**c) for c in s['components'])) pc = d.Desktop(**s['device'], components=OrderedSet(d.Component(**c) for c in s['components']))
db.session.add(pc) db.session.add(pc)
db.session.commit() db.session.commit()
@ -216,7 +216,7 @@ def test_sync_run_components_none():
"""Syncs a device that has a None components. The system should """Syncs a device that has a None components. The system should
keep all the components from the device. keep all the components from the device.
""" """
s = conftest.file('pc-components.db') s = yaml2json('pc-components.db')
pc = d.Desktop(**s['device'], components=OrderedSet(d.Component(**c) for c in s['components'])) pc = d.Desktop(**s['device'], components=OrderedSet(d.Component(**c) for c in s['components']))
db.session.add(pc) db.session.add(pc)
db.session.commit() db.session.commit()
@ -233,7 +233,7 @@ def test_sync_run_components_none():
def test_sync_execute_register_desktop_new_desktop_no_tag(): def test_sync_execute_register_desktop_new_desktop_no_tag():
"""Syncs a new d.Desktop with HID and without a tag, creating it.""" """Syncs a new d.Desktop with HID and without a tag, creating it."""
# Case 1: device does not exist on DB # Case 1: device does not exist on DB
pc = d.Desktop(**conftest.file('pc-components.db')['device']) pc = d.Desktop(**yaml2json('pc-components.db')['device'])
db_pc = Sync().execute_register(pc) db_pc = Sync().execute_register(pc)
assert pc.physical_properties == db_pc.physical_properties assert pc.physical_properties == db_pc.physical_properties
@ -242,12 +242,12 @@ def test_sync_execute_register_desktop_new_desktop_no_tag():
@pytest.mark.usefixtures(conftest.auth_app_context.__name__) @pytest.mark.usefixtures(conftest.auth_app_context.__name__)
def test_sync_execute_register_desktop_existing_no_tag(): def test_sync_execute_register_desktop_existing_no_tag():
"""Syncs an existing d.Desktop with HID and without a tag.""" """Syncs an existing d.Desktop with HID and without a tag."""
pc = d.Desktop(**conftest.file('pc-components.db')['device']) pc = d.Desktop(**yaml2json('pc-components.db')['device'])
db.session.add(pc) db.session.add(pc)
db.session.commit() db.session.commit()
pc = d.Desktop( pc = d.Desktop(
**conftest.file('pc-components.db')['device']) # Create a new transient non-db object **yaml2json('pc-components.db')['device']) # Create a new transient non-db object
# 1: device exists on DB # 1: device exists on DB
db_pc = Sync().execute_register(pc) db_pc = Sync().execute_register(pc)
pc.amount = 0 pc.amount = 0
@ -262,7 +262,7 @@ def test_sync_execute_register_desktop_no_hid_no_tag(user: UserClient):
"""Syncs a d.Desktop without HID and no tag. """Syncs a d.Desktop without HID and no tag.
This should not fail as we don't have a way to identify it. This should not fail as we don't have a way to identify it.
""" """
device = conftest.file('pc-components.db')['device'] device = yaml2json('pc-components.db')['device']
device['owner_id'] = user.user['id'] device['owner_id'] = user.user['id']
pc = d.Desktop(**device) pc = d.Desktop(**device)
# 1: device has no HID # 1: device has no HID
@ -283,7 +283,7 @@ def test_sync_execute_register_desktop_tag_not_linked():
db.session.commit() db.session.commit()
# Create a new transient non-db object # Create a new transient non-db object
pc = d.Desktop(**conftest.file('pc-components.db')['device'], tags=OrderedSet([Tag(id='foo')])) pc = d.Desktop(**yaml2json('pc-components.db')['device'], tags=OrderedSet([Tag(id='foo')]))
returned_pc = Sync().execute_register(pc) returned_pc = Sync().execute_register(pc)
assert returned_pc == pc assert returned_pc == pc
assert tag.device == pc, 'Tag has to be linked' assert tag.device == pc, 'Tag has to be linked'
@ -300,7 +300,7 @@ def test_sync_execute_register_no_hid_tag_not_linked(tag_id: str):
be linked), and thus it creates a new d.Desktop. be linked), and thus it creates a new d.Desktop.
""" """
tag = Tag(id=tag_id) tag = Tag(id=tag_id)
pc = d.Desktop(**conftest.file('pc-components.db')['device'], tags=OrderedSet([tag])) pc = d.Desktop(**yaml2json('pc-components.db')['device'], tags=OrderedSet([tag]))
db.session.add(g.user) db.session.add(g.user)
returned_pc = Sync().execute_register(pc) returned_pc = Sync().execute_register(pc)
db.session.commit() db.session.commit()
@ -323,7 +323,7 @@ def test_sync_execute_register_tag_does_not_exist():
Tags have to be created before trying to link them through a Snapshot. Tags have to be created before trying to link them through a Snapshot.
""" """
user = User.query.filter().first() user = User.query.filter().first()
pc = d.Desktop(**conftest.file('pc-components.db')['device'], tags=OrderedSet([Tag('foo')])) pc = d.Desktop(**yaml2json('pc-components.db')['device'], tags=OrderedSet([Tag('foo')]))
pc.owner_id = user.id pc.owner_id = user.id
with raises(ResourceNotFound): with raises(ResourceNotFound):
Sync().execute_register(pc) Sync().execute_register(pc)
@ -337,12 +337,12 @@ def test_sync_execute_register_tag_linked_same_device():
(If it has HID it validates both HID and tag point at the same (If it has HID it validates both HID and tag point at the same
device, this his checked in ). device, this his checked in ).
""" """
orig_pc = d.Desktop(**conftest.file('pc-components.db')['device']) orig_pc = d.Desktop(**yaml2json('pc-components.db')['device'])
db.session.add(Tag(id='foo', device=orig_pc)) db.session.add(Tag(id='foo', device=orig_pc))
db.session.commit() db.session.commit()
pc = d.Desktop( pc = d.Desktop(
**conftest.file('pc-components.db')['device']) # Create a new transient non-db object **yaml2json('pc-components.db')['device']) # Create a new transient non-db object
pc.tags.add(Tag(id='foo')) pc.tags.add(Tag(id='foo'))
db_pc = Sync().execute_register(pc) db_pc = Sync().execute_register(pc)
assert db_pc.id == orig_pc.id assert db_pc.id == orig_pc.id
@ -356,16 +356,16 @@ def test_sync_execute_register_tag_linked_other_device_mismatch_between_tags():
"""Checks that sync raises an error if finds that at least two passed-in """Checks that sync raises an error if finds that at least two passed-in
tags are not linked to the same device. tags are not linked to the same device.
""" """
pc1 = d.Desktop(**conftest.file('pc-components.db')['device']) pc1 = d.Desktop(**yaml2json('pc-components.db')['device'])
db.session.add(Tag(id='foo-1', device=pc1)) db.session.add(Tag(id='foo-1', device=pc1))
pc2 = d.Desktop(**conftest.file('pc-components.db')['device']) pc2 = d.Desktop(**yaml2json('pc-components.db')['device'])
pc2.serial_number = 'pc2-serial' pc2.serial_number = 'pc2-serial'
pc2.hid = Naming.hid(pc2.type, pc2.manufacturer, pc2.model, pc2.serial_number) pc2.hid = Naming.hid(pc2.type, pc2.manufacturer, pc2.model, pc2.serial_number)
db.session.add(Tag(id='foo-2', device=pc2)) db.session.add(Tag(id='foo-2', device=pc2))
db.session.commit() db.session.commit()
pc1 = d.Desktop( pc1 = d.Desktop(
**conftest.file('pc-components.db')['device']) # Create a new transient non-db object **yaml2json('pc-components.db')['device']) # Create a new transient non-db object
pc1.tags.add(Tag(id='foo-1')) pc1.tags.add(Tag(id='foo-1'))
pc1.tags.add(Tag(id='foo-2')) pc1.tags.add(Tag(id='foo-2'))
with raises(MismatchBetweenTags): with raises(MismatchBetweenTags):
@ -380,16 +380,16 @@ def test_sync_execute_register_mismatch_between_tags_and_hid():
In this case we set HID -> pc1 but tag -> pc2 In this case we set HID -> pc1 but tag -> pc2
""" """
pc1 = d.Desktop(**conftest.file('pc-components.db')['device']) pc1 = d.Desktop(**yaml2json('pc-components.db')['device'])
db.session.add(Tag(id='foo-1', device=pc1)) db.session.add(Tag(id='foo-1', device=pc1))
pc2 = d.Desktop(**conftest.file('pc-components.db')['device']) pc2 = d.Desktop(**yaml2json('pc-components.db')['device'])
pc2.serial_number = 'pc2-serial' pc2.serial_number = 'pc2-serial'
pc2.hid = Naming.hid(pc2.type, pc2.manufacturer, pc2.model, pc2.serial_number) pc2.hid = Naming.hid(pc2.type, pc2.manufacturer, pc2.model, pc2.serial_number)
db.session.add(Tag(id='foo-2', device=pc2)) db.session.add(Tag(id='foo-2', device=pc2))
db.session.commit() db.session.commit()
pc1 = d.Desktop( pc1 = d.Desktop(
**conftest.file('pc-components.db')['device']) # Create a new transient non-db object **yaml2json('pc-components.db')['device']) # Create a new transient non-db object
pc1.tags.add(Tag(id='foo-2')) pc1.tags.add(Tag(id='foo-2'))
with raises(MismatchBetweenTagsAndHid): with raises(MismatchBetweenTagsAndHid):
Sync().execute_register(pc1) Sync().execute_register(pc1)
@ -623,9 +623,9 @@ def test_hid_with_mac(app: Devicehub, user: UserClient):
@pytest.mark.mvp @pytest.mark.mvp
def test_hid_without_mac(app: Devicehub, user: UserClient): def test_hid_without_mac(app: Devicehub, user: UserClient):
"""Checks hid without mac.""" """Checks hid without mac."""
snapshot = file('asus-eee-1000h.snapshot.11') snapshot = yaml2json('asus-eee-1000h.snapshot.11')
snapshot['components'] = [c for c in snapshot['components'] if c['type'] != 'NetworkAdapter'] snapshot['components'] = [c for c in snapshot['components'] if c['type'] != 'NetworkAdapter']
snap, _ = user.post(snapshot, res=m.Snapshot) snap, _ = user.post(json_encode(snapshot), res=m.Snapshot)
pc, _ = user.get(res=d.Device, item=snap['device']['devicehubID']) pc, _ = user.get(res=d.Device, item=snap['device']['devicehubID'])
assert pc['hid'] == 'laptop-asustek_computer_inc-1000h-94oaaq021116' assert pc['hid'] == 'laptop-asustek_computer_inc-1000h-94oaaq021116'
@ -633,10 +633,10 @@ def test_hid_without_mac(app: Devicehub, user: UserClient):
@pytest.mark.mvp @pytest.mark.mvp
def test_hid_with_mac_none(app: Devicehub, user: UserClient): def test_hid_with_mac_none(app: Devicehub, user: UserClient):
"""Checks hid with mac = None.""" """Checks hid with mac = None."""
snapshot = file('asus-eee-1000h.snapshot.11') snapshot = yaml2json('asus-eee-1000h.snapshot.11')
network = [c for c in snapshot['components'] if c['type'] == 'NetworkAdapter'][0] network = [c for c in snapshot['components'] if c['type'] == 'NetworkAdapter'][0]
network['serialNumber'] = None network['serialNumber'] = None
snap, _ = user.post(snapshot, res=m.Snapshot) snap, _ = user.post(json_encode(snapshot), res=m.Snapshot)
pc, _ = user.get(res=d.Device, item=snap['device']['devicehubID']) pc, _ = user.get(res=d.Device, item=snap['device']['devicehubID'])
assert pc['hid'] == 'laptop-asustek_computer_inc-1000h-94oaaq021116' assert pc['hid'] == 'laptop-asustek_computer_inc-1000h-94oaaq021116'
@ -644,12 +644,12 @@ def test_hid_with_mac_none(app: Devicehub, user: UserClient):
@pytest.mark.mvp @pytest.mark.mvp
def test_hid_with_2networkadapters(app: Devicehub, user: UserClient): def test_hid_with_2networkadapters(app: Devicehub, user: UserClient):
"""Checks hid with 2 networks adapters""" """Checks hid with 2 networks adapters"""
snapshot = file('asus-eee-1000h.snapshot.11') snapshot = yaml2json('asus-eee-1000h.snapshot.11')
network = [c for c in snapshot['components'] if c['type'] == 'NetworkAdapter'][0] network = [c for c in snapshot['components'] if c['type'] == 'NetworkAdapter'][0]
network2 = copy.copy(network) network2 = copy.copy(network)
snapshot['components'].append(network2) snapshot['components'].append(network2)
network['serialNumber'] = 'a0:24:8c:7f:cf:2d' network['serialNumber'] = 'a0:24:8c:7f:cf:2d'
user.post(snapshot, res=m.Snapshot) user.post(json_encode(snapshot), res=m.Snapshot)
devices, _ = user.get(res=d.Device) devices, _ = user.get(res=d.Device)
laptop = devices['items'][0] laptop = devices['items'][0]
@ -660,18 +660,18 @@ def test_hid_with_2networkadapters(app: Devicehub, user: UserClient):
@pytest.mark.mvp @pytest.mark.mvp
def test_hid_with_2network_and_drop_no_mac_in_hid(app: Devicehub, user: UserClient): 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""" """Checks hid with 2 networks adapters and next drop the network is not used in hid"""
snapshot = file('asus-eee-1000h.snapshot.11') snapshot = yaml2json('asus-eee-1000h.snapshot.11')
network = [c for c in snapshot['components'] if c['type'] == 'NetworkAdapter'][0] network = [c for c in snapshot['components'] if c['type'] == 'NetworkAdapter'][0]
network2 = copy.copy(network) network2 = copy.copy(network)
snapshot['components'].append(network2) snapshot['components'].append(network2)
network['serialNumber'] = 'a0:24:8c:7f:cf:2d' network['serialNumber'] = 'a0:24:8c:7f:cf:2d'
snap, _ = user.post(snapshot, res=m.Snapshot) snap, _ = user.post(json_encode(snapshot), res=m.Snapshot)
pc, _ = user.get(res=d.Device, item=snap['device']['devicehubID']) 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' assert pc['hid'] == 'laptop-asustek_computer_inc-1000h-94oaaq021116-00:24:8c:7f:cf:2d'
snapshot['uuid'] = 'd1b70cb8-8929-4f36-99b7-fe052cec0abb' snapshot['uuid'] = 'd1b70cb8-8929-4f36-99b7-fe052cec0abb'
snapshot['components'] = [c for c in snapshot['components'] if c != network] snapshot['components'] = [c for c in snapshot['components'] if c != network]
user.post(snapshot, res=m.Snapshot) user.post(json_encode(snapshot), res=m.Snapshot)
devices, _ = user.get(res=d.Device) devices, _ = user.get(res=d.Device)
laptop = devices['items'][0] laptop = devices['items'][0]
assert laptop['hid'] == 'laptop-asustek_computer_inc-1000h-94oaaq021116-00:24:8c:7f:cf:2d' assert laptop['hid'] == 'laptop-asustek_computer_inc-1000h-94oaaq021116-00:24:8c:7f:cf:2d'
@ -683,19 +683,19 @@ def test_hid_with_2network_and_drop_no_mac_in_hid(app: Devicehub, user: UserClie
def test_hid_with_2network_and_drop_mac_in_hid(app: Devicehub, user: UserClient): 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""" """Checks hid with 2 networks adapters and next drop the network is used in hid"""
# One tipical snapshot with 2 network cards # One tipical snapshot with 2 network cards
snapshot = file('asus-eee-1000h.snapshot.11') snapshot = yaml2json('asus-eee-1000h.snapshot.11')
network = [c for c in snapshot['components'] if c['type'] == 'NetworkAdapter'][0] network = [c for c in snapshot['components'] if c['type'] == 'NetworkAdapter'][0]
network2 = copy.copy(network) network2 = copy.copy(network)
snapshot['components'].append(network2) snapshot['components'].append(network2)
network['serialNumber'] = 'a0:24:8c:7f:cf:2d' network['serialNumber'] = 'a0:24:8c:7f:cf:2d'
snap, _ = user.post(snapshot, res=m.Snapshot) snap, _ = user.post(json_encode(snapshot), res=m.Snapshot)
pc, _ = user.get(res=d.Device, item=snap['device']['devicehubID']) 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' 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 # we drop the network card then is used for to build the hid
snapshot['uuid'] = 'd1b70cb8-8929-4f36-99b7-fe052cec0abb' snapshot['uuid'] = 'd1b70cb8-8929-4f36-99b7-fe052cec0abb'
snapshot['components'] = [c for c in snapshot['components'] if c != network2] snapshot['components'] = [c for c in snapshot['components'] if c != network2]
user.post(snapshot, res=m.Snapshot) user.post(json_encode(snapshot), res=m.Snapshot)
devices, _ = user.get(res=d.Device) devices, _ = user.get(res=d.Device)
laptops = [c for c in devices['items'] if c['type'] == 'Laptop'] laptops = [c for c in devices['items'] if c['type'] == 'Laptop']
assert len(laptops) == 2 assert len(laptops) == 2
@ -707,7 +707,7 @@ def test_hid_with_2network_and_drop_mac_in_hid(app: Devicehub, user: UserClient)
# we drop all network cards # we drop all network cards
snapshot['uuid'] = 'd1b70cb8-8929-4f36-99b7-fe052cec0abc' snapshot['uuid'] = 'd1b70cb8-8929-4f36-99b7-fe052cec0abc'
snapshot['components'] = [c for c in snapshot['components'] if not c in [network, network2]] snapshot['components'] = [c for c in snapshot['components'] if not c in [network, network2]]
user.post(snapshot, res=m.Snapshot) user.post(json_encode(snapshot), res=m.Snapshot)
devices, _ = user.get(res=d.Device) devices, _ = user.get(res=d.Device)
laptops = [c for c in devices['items'] if c['type'] == 'Laptop'] laptops = [c for c in devices['items'] if c['type'] == 'Laptop']
assert len(laptops) == 3 assert len(laptops) == 3

View File

@ -13,7 +13,7 @@ from ereuse_devicehub.resources.device.views import Filters, Sorting
from ereuse_devicehub.resources.enums import ComputerChassis from ereuse_devicehub.resources.enums import ComputerChassis
from ereuse_devicehub.resources.lot.models import Lot from ereuse_devicehub.resources.lot.models import Lot
from tests import conftest from tests import conftest
from tests.conftest import file from tests.conftest import file, yaml2json, json_encode
@pytest.mark.mvp @pytest.mark.mvp
@ -196,9 +196,9 @@ def test_device_query_permitions(user: UserClient, user2: UserClient):
i2, _ = user2.get(res=Device) i2, _ = user2.get(res=Device)
assert i2['items'] == [] assert i2['items'] == []
basic_snapshot = file('basic.snapshot') basic_snapshot = yaml2json('basic.snapshot')
basic_snapshot['uuid'] = f"{uuid.uuid4()}" basic_snapshot['uuid'] = f"{uuid.uuid4()}"
user2.post(basic_snapshot, res=Snapshot) user2.post(json_encode(basic_snapshot), res=Snapshot)
i2, _ = user2.get(res=Device) i2, _ = user2.get(res=Device)
pc2 = next(d for d in i2['items'] if d['type'] == 'Desktop') pc2 = next(d for d in i2['items'] if d['type'] == 'Desktop')
@ -265,9 +265,9 @@ def test_device_query_search_synonyms_asus(user: UserClient):
@pytest.mark.mvp @pytest.mark.mvp
def test_device_query_search_synonyms_intel(user: UserClient): def test_device_query_search_synonyms_intel(user: UserClient):
s = file('real-hp.snapshot.11') s = yaml2json('real-hp.snapshot.11')
s['device']['model'] = 'foo' # The model had the word 'HP' in it s['device']['model'] = 'foo' # The model had the word 'HP' in it
user.post(s, res=Snapshot) user.post(json_encode(s), res=Snapshot)
i, _ = user.get(res=Device, query=[('search', 'hewlett packard')]) i, _ = user.get(res=Device, query=[('search', 'hewlett packard')])
assert 1 == len(i['items']) assert 1 == len(i['items'])
i, _ = user.get(res=Device, query=[('search', 'hewlett')]) i, _ = user.get(res=Device, query=[('search', 'hewlett')])

View File

@ -23,7 +23,7 @@ from ereuse_devicehub.resources.hash_reports import ReportHash
from ereuse_devicehub.resources.enums import SessionType from ereuse_devicehub.resources.enums import SessionType
from ereuse_devicehub.db import db from ereuse_devicehub.db import db
from tests import conftest from tests import conftest
from tests.conftest import file from tests.conftest import file, yaml2json, json_encode
@pytest.mark.mvp @pytest.mark.mvp
@ -114,8 +114,8 @@ def test_export_csv_permitions(user: UserClient, user2: UserClient, client: Clie
@pytest.mark.mvp @pytest.mark.mvp
def test_export_csv_actions(user: UserClient, user2: UserClient, client: Client): def test_export_csv_actions(user: UserClient, user2: UserClient, client: Client):
"""Test export device information in a csv file with others users.""" """Test export device information in a csv file with others users."""
acer = file('acer.happy.battery.snapshot') acer = yaml2json('acer.happy.battery.snapshot')
snapshot, _ = user.post(acer, res=Snapshot) snapshot, _ = user.post(json_encode(acer), res=Snapshot)
device_id = snapshot['device']['id'] device_id = snapshot['device']['id']
post_request = {"transaction": "ccc", "name": "John", "endUsers": 1, post_request = {"transaction": "ccc", "name": "John", "endUsers": 1,
"devices": [device_id], "description": "aaa", "devices": [device_id], "description": "aaa",
@ -156,8 +156,8 @@ def test_export_csv_actions(user: UserClient, user2: UserClient, client: Client)
@pytest.mark.usefixtures(conftest.app_context.__name__) @pytest.mark.usefixtures(conftest.app_context.__name__)
def test_live_export_csv2(user: UserClient, client: Client, app: Devicehub): def test_live_export_csv2(user: UserClient, client: Client, app: Devicehub):
"""Tests inserting a Live into the database and GETting it.""" """Tests inserting a Live into the database and GETting it."""
acer = file('acer-happy.snapshot-test1') acer = yaml2json('acer-happy.snapshot-test1')
snapshot, _ = user.post(acer, res=Snapshot) snapshot, _ = user.post(json_encode(acer), res=Snapshot)
device_id = snapshot['device']['id'] device_id = snapshot['device']['id']
post_request = {"transaction": "ccc", "name": "John", "endUsers": 1, post_request = {"transaction": "ccc", "name": "John", "endUsers": 1,
"devices": [device_id], "description": "aaa", "devices": [device_id], "description": "aaa",
@ -168,7 +168,7 @@ def test_live_export_csv2(user: UserClient, client: Client, app: Devicehub):
user.post(res=Allocate, data=post_request) user.post(res=Allocate, data=post_request)
acer = file('acer-happy.live-test1') acer = yaml2json('acer-happy.live-test1')
live, _ = client.post(acer, res=Live) live, _ = client.post(acer, res=Live)
csv_user, _ = user.get(res=documents.DocumentDef.t, csv_user, _ = user.get(res=documents.DocumentDef.t,
item='actions/', item='actions/',
@ -183,8 +183,8 @@ def test_live_export_csv2(user: UserClient, client: Client, app: Devicehub):
@pytest.mark.usefixtures(conftest.app_context.__name__) @pytest.mark.usefixtures(conftest.app_context.__name__)
def test_live_example2(user: UserClient, client: Client, app: Devicehub): def test_live_example2(user: UserClient, client: Client, app: Devicehub):
"""Tests inserting a Live into the database and GETting it.""" """Tests inserting a Live into the database and GETting it."""
acer = file('acer-happy.snapshot-test1') acer = yaml2json('acer-happy.snapshot-test1')
snapshot, _ = user.post(acer, res=Snapshot) snapshot, _ = user.post(json_encode(acer), res=Snapshot)
device_id = snapshot['device']['id'] device_id = snapshot['device']['id']
post_request = {"transaction": "ccc", "name": "John", "endUsers": 1, post_request = {"transaction": "ccc", "name": "John", "endUsers": 1,
"devices": [device_id], "description": "aaa", "devices": [device_id], "description": "aaa",
@ -195,7 +195,7 @@ def test_live_example2(user: UserClient, client: Client, app: Devicehub):
user.post(res=Allocate, data=post_request) user.post(res=Allocate, data=post_request)
acer = file('acer-happy.live-test1') acer = yaml2json('acer-happy.live-test1')
live, _ = client.post(acer, res=Live) live, _ = client.post(acer, res=Live)
db_device = d.Device.query.filter_by(id=device_id).one() db_device = d.Device.query.filter_by(id=device_id).one()
action_live = [a for a in db_device.actions if a.type == 'Live'] action_live = [a for a in db_device.actions if a.type == 'Live']
@ -553,8 +553,8 @@ def test_verify_stamp_devices_stock(user: UserClient, client: Client):
@pytest.mark.mvp @pytest.mark.mvp
def test_verify_stamp_csv_actions(user: UserClient, client: Client): def test_verify_stamp_csv_actions(user: UserClient, client: Client):
"""Test verify stamp of one export device information in a csv file with others users.""" """Test verify stamp of one export device information in a csv file with others users."""
acer = file('acer.happy.battery.snapshot') acer = yaml2json('acer.happy.battery.snapshot')
snapshot, _ = user.post(acer, res=Snapshot) snapshot, _ = user.post(json_encode(acer), res=Snapshot)
device_id = snapshot['device']['id'] device_id = snapshot['device']['id']
post_request = {"transaction": "ccc", "name": "John", "endUsers": 1, post_request = {"transaction": "ccc", "name": "John", "endUsers": 1,
"devices": [device_id], "description": "aaa", "devices": [device_id], "description": "aaa",

View File

@ -3,7 +3,7 @@ import pytest
from ereuse_devicehub.client import UserClient from ereuse_devicehub.client import UserClient
from ereuse_devicehub.resources.action import models as ma from ereuse_devicehub.resources.action import models as ma
from tests import conftest from tests import conftest
from tests.conftest import file from tests.conftest import file, yaml2json, json_encode
@pytest.mark.mvp @pytest.mark.mvp
@ -11,10 +11,10 @@ from tests.conftest import file
def test_simple_metrics(user: UserClient): def test_simple_metrics(user: UserClient):
""" Checks one standard query of metrics """ """ Checks one standard query of metrics """
# Insert computer # Insert computer
lenovo = file('desktop-9644w8n-lenovo-0169622.snapshot') lenovo = yaml2json('desktop-9644w8n-lenovo-0169622.snapshot')
acer = file('acer.happy.battery.snapshot') acer = yaml2json('acer.happy.battery.snapshot')
user.post(lenovo, res=ma.Snapshot) user.post(json_encode(lenovo), res=ma.Snapshot)
snapshot, _ = user.post(acer, res=ma.Snapshot) snapshot, _ = user.post(json_encode(acer), res=ma.Snapshot)
device_id = snapshot['device']['id'] device_id = snapshot['device']['id']
post_request = {"transaction": "ccc", "name": "John", "endUsers": 1, post_request = {"transaction": "ccc", "name": "John", "endUsers": 1,
"finalUserCode": "abcdefjhi", "finalUserCode": "abcdefjhi",
@ -58,8 +58,8 @@ def test_simple_metrics(user: UserClient):
def test_second_hdd_metrics(user: UserClient): def test_second_hdd_metrics(user: UserClient):
""" Checks one standard query of metrics """ """ Checks one standard query of metrics """
# Insert computer # Insert computer
acer = file('acer.happy.battery.snapshot') acer = yaml2json('acer.happy.battery.snapshot')
snapshot, _ = user.post(acer, res=ma.Snapshot) snapshot, _ = user.post(json_encode(acer), res=ma.Snapshot)
device_id = snapshot['device']['id'] device_id = snapshot['device']['id']
post_request = {"transaction": "ccc", "name": "John", "endUsers": 1, post_request = {"transaction": "ccc", "name": "John", "endUsers": 1,
"finalUserCode": "abcdefjhi", "finalUserCode": "abcdefjhi",

View File

@ -12,7 +12,7 @@ from ereuse_devicehub.resources.device.models import Computer, Desktop, Device,
from ereuse_devicehub.resources.enums import AppearanceRange, ComputerChassis, \ from ereuse_devicehub.resources.enums import AppearanceRange, ComputerChassis, \
FunctionalityRange FunctionalityRange
from tests import conftest from tests import conftest
from tests.conftest import file from tests.conftest import file, yaml2json, json_encode
@pytest.mark.mvp @pytest.mark.mvp
@ -104,16 +104,16 @@ def test_when_rate_must_not_compute(user: UserClient):
... ...
""" """
# Checking case 1 # Checking case 1
s = file('basic.snapshot') s = yaml2json('basic.snapshot')
# Delete snapshot device actions to delete VisualTest # Delete snapshot device actions to delete VisualTest
del s['device']['actions'] del s['device']['actions']
# Post to compute rate and check to didn't do it # Post to compute rate and check to didn't do it
snapshot, _ = user.post(s, res=Snapshot) snapshot, _ = user.post(json_encode(s), res=Snapshot)
assert 'rate' not in snapshot['device'] assert 'rate' not in snapshot['device']
# Checking case 2 # Checking case 2
s = file('basic.snapshot') s = yaml2json('basic.snapshot')
# Change snapshot software source # Change snapshot software source
s['software'] = 'Web' s['software'] = 'Web'
del s['uuid'] del s['uuid']
@ -121,14 +121,14 @@ def test_when_rate_must_not_compute(user: UserClient):
del s['components'] del s['components']
# Post to compute rate and check to didn't do it # Post to compute rate and check to didn't do it
snapshot, _ = user.post(s, res=Snapshot) snapshot, _ = user.post(json_encode(s), res=Snapshot)
assert 'rate' not in snapshot['device'] assert 'rate' not in snapshot['device']
# Checking case 3 # Checking case 3
s = file('keyboard.snapshot') s = yaml2json('keyboard.snapshot')
# Post to compute rate and check to didn't do it # Post to compute rate and check to didn't do it
snapshot, _ = user.post(s, res=Snapshot) snapshot, _ = user.post(json_encode(s), res=Snapshot)
assert 'rate' not in snapshot['device'] assert 'rate' not in snapshot['device']

View File

@ -31,7 +31,7 @@ from ereuse_devicehub.resources.tag import Tag
from ereuse_devicehub.resources.user.models import User from ereuse_devicehub.resources.user.models import User
from ereuse_devicehub.resources.action.views.snapshot import save_json from ereuse_devicehub.resources.action.views.snapshot import save_json
from ereuse_devicehub.resources.documents import documents from ereuse_devicehub.resources.documents import documents
from tests.conftest import file from tests.conftest import file, yaml2json, json_encode
from tests import conftest from tests import conftest
@ -70,7 +70,7 @@ def test_snapshot_model():
@pytest.mark.mvp @pytest.mark.mvp
def test_snapshot_schema(app: Devicehub): def test_snapshot_schema(app: Devicehub):
with app.app_context(): with app.app_context():
s = file('basic.snapshot') s = yaml2json('basic.snapshot')
app.resources['Snapshot'].schema.load(s) app.resources['Snapshot'].schema.load(s)
@ -79,7 +79,7 @@ def test_snapshot_post(user: UserClient):
"""Tests the post snapshot endpoint (validation, etc), data correctness, """Tests the post snapshot endpoint (validation, etc), data correctness,
and relationship correctness. and relationship correctness.
""" """
snapshot = snapshot_and_check(user, file('basic.snapshot'), snapshot = snapshot_and_check(user, yaml2json('basic.snapshot'),
action_types=( action_types=(
BenchmarkProcessor.t, BenchmarkProcessor.t,
VisualTest.t, VisualTest.t,
@ -112,6 +112,7 @@ def test_snapshot_post(user: UserClient):
@pytest.mark.mvp @pytest.mark.mvp
def test_same_device_tow_users(user: UserClient, user2: UserClient): def test_same_device_tow_users(user: UserClient, user2: UserClient):
"""Two users can up the same snapshot and the system save 2 computers""" """Two users can up the same snapshot and the system save 2 computers"""
# import pdb; pdb.set_trace()
user.post(file('basic.snapshot'), res=Snapshot) user.post(file('basic.snapshot'), res=Snapshot)
i, _ = user.get(res=m.Device) i, _ = user.get(res=m.Device)
pc = next(d for d in i['items'] if d['type'] == 'Desktop') pc = next(d for d in i['items'] if d['type'] == 'Desktop')
@ -119,9 +120,9 @@ def test_same_device_tow_users(user: UserClient, user2: UserClient):
devicehub_id = pc['devicehubID'] devicehub_id = pc['devicehubID']
assert i['items'][0]['url'] == f'/devices/{devicehub_id}' assert i['items'][0]['url'] == f'/devices/{devicehub_id}'
basic_snapshot = file('basic.snapshot') basic_snapshot = yaml2json('basic.snapshot')
basic_snapshot['uuid'] = f"{uuid.uuid4()}" basic_snapshot['uuid'] = f"{uuid.uuid4()}"
user2.post(basic_snapshot, res=Snapshot) user2.post(json_encode(basic_snapshot), res=Snapshot)
i2, _ = user2.get(res=m.Device) i2, _ = user2.get(res=m.Device)
pc2 = next(d for d in i2['items'] if d['type'] == 'Desktop') pc2 = next(d for d in i2['items'] if d['type'] == 'Desktop')
assert pc['id'] != pc2['id'] assert pc['id'] != pc2['id']
@ -133,13 +134,13 @@ 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 Tests for check if one computer have the time mark updated when one component of it is updated
""" """
computer1 = file('1-device-with-components.snapshot') computer1 = yaml2json('1-device-with-components.snapshot')
snapshot = snapshot_and_check(user, snapshot = snapshot_and_check(user,
computer1, computer1,
action_types=(BenchmarkProcessor.t, action_types=(BenchmarkProcessor.t,
RateComputer.t), RateComputer.t),
perform_second_snapshot=False) perform_second_snapshot=False)
computer2 = file('2-second-device-with-components-of-first.snapshot') computer2 = yaml2json('2-second-device-with-components-of-first.snapshot')
snapshot_and_check(user, computer2, action_types=('Remove', 'RateComputer'), snapshot_and_check(user, computer2, action_types=('Remove', 'RateComputer'),
perform_second_snapshot=False) perform_second_snapshot=False)
pc1_devicehub_id = snapshot['device']['devicehubID'] pc1_devicehub_id = snapshot['device']['devicehubID']
@ -165,7 +166,7 @@ def test_snapshot_component_add_remove(user: UserClient):
# We add the first device (2 times). The distribution of components # We add the first device (2 times). The distribution of components
# (represented with their S/N) should be: # (represented with their S/N) should be:
# PC 1: p1c1s, p1c2s, p1c3s. PC 2: ø # PC 1: p1c1s, p1c2s, p1c3s. PC 2: ø
s1 = file('1-device-with-components.snapshot') s1 = yaml2json('1-device-with-components.snapshot')
snapshot1 = snapshot_and_check(user, snapshot1 = snapshot_and_check(user,
s1, s1,
action_types=(BenchmarkProcessor.t, action_types=(BenchmarkProcessor.t,
@ -190,7 +191,7 @@ def test_snapshot_component_add_remove(user: UserClient):
# It has the processor of the first one (p1c2s) # It has the processor of the first one (p1c2s)
# PC 1: p1c1s, p1c3s. PC 2: p2c1s, p1c2s # PC 1: p1c1s, p1c3s. PC 2: p2c1s, p1c2s
# Actions PC1: Snapshot, Remove. PC2: Snapshot # Actions PC1: Snapshot, Remove. PC2: Snapshot
s2 = file('2-second-device-with-components-of-first.snapshot') s2 = yaml2json('2-second-device-with-components-of-first.snapshot')
# num_actions = 2 = Remove, Add # num_actions = 2 = Remove, Add
snapshot2 = snapshot_and_check(user, s2, action_types=('Remove', 'RateComputer'), snapshot2 = snapshot_and_check(user, s2, action_types=('Remove', 'RateComputer'),
perform_second_snapshot=False) perform_second_snapshot=False)
@ -220,7 +221,7 @@ def test_snapshot_component_add_remove(user: UserClient):
# and moving processor from the second device to the first. # and moving processor from the second device to the first.
# We have created 1 Remove (from PC2's processor back to PC1) # We have created 1 Remove (from PC2's processor back to PC1)
# PC 0: p1c2s, p1c3s. PC 1: p2c1s # PC 0: p1c2s, p1c3s. PC 1: p2c1s
s3 = file('3-first-device-but-removing-motherboard-and-adding-processor-from-2.snapshot') s3 = yaml2json('3-first-device-but-removing-motherboard-and-adding-processor-from-2.snapshot')
snapshot_and_check(user, s3, ('Remove', 'RateComputer'), perform_second_snapshot=False) snapshot_and_check(user, s3, ('Remove', 'RateComputer'), perform_second_snapshot=False)
pc1, _ = user.get(res=m.Device, item=pc1_devicehub_id) pc1, _ = user.get(res=m.Device, item=pc1_devicehub_id)
pc2, _ = user.get(res=m.Device, item=pc2_devicehub_id) pc2, _ = user.get(res=m.Device, item=pc2_devicehub_id)
@ -266,7 +267,7 @@ def test_snapshot_component_add_remove(user: UserClient):
# We register the first device but without the processor, # We register the first device but without the processor,
# adding a graphic card and adding a new component # adding a graphic card and adding a new component
s4 = file('4-first-device-but-removing-processor.snapshot-and-adding-graphic-card') s4 = yaml2json('4-first-device-but-removing-processor.snapshot-and-adding-graphic-card')
snapshot4 = snapshot_and_check(user, s4, ('RateComputer',), perform_second_snapshot=False) snapshot4 = snapshot_and_check(user, s4, ('RateComputer',), perform_second_snapshot=False)
pc1, _ = user.get(res=m.Device, item=pc1_devicehub_id) pc1, _ = user.get(res=m.Device, item=pc1_devicehub_id)
pc2, _ = user.get(res=m.Device, item=pc2_devicehub_id) pc2, _ = user.get(res=m.Device, item=pc2_devicehub_id)
@ -312,7 +313,7 @@ def test_snapshot_mismatch_id():
@pytest.mark.mvp @pytest.mark.mvp
def test_snapshot_tag_inner_tag(user: UserClient, tag_id: str, app: Devicehub): def test_snapshot_tag_inner_tag(user: UserClient, tag_id: str, app: Devicehub):
"""Tests a posting Snapshot with a local tag.""" """Tests a posting Snapshot with a local tag."""
b = file('basic.snapshot') b = yaml2json('basic.snapshot')
b['device']['tags'] = [{'type': 'Tag', 'id': tag_id}] b['device']['tags'] = [{'type': 'Tag', 'id': tag_id}]
snapshot_and_check(user, b, snapshot_and_check(user, b,
@ -325,13 +326,13 @@ def test_snapshot_tag_inner_tag(user: UserClient, tag_id: str, app: Devicehub):
@pytest.mark.mvp @pytest.mark.mvp
def test_snapshot_tag_inner_tag_mismatch_between_tags_and_hid(user: UserClient, tag_id: str): 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.""" """Ensures one device cannot 'steal' the tag from another one."""
pc1 = file('basic.snapshot') pc1 = yaml2json('basic.snapshot')
pc1['device']['tags'] = [{'type': 'Tag', 'id': tag_id}] pc1['device']['tags'] = [{'type': 'Tag', 'id': tag_id}]
user.post(pc1, res=Snapshot) user.post(json_encode(pc1), res=Snapshot)
pc2 = file('1-device-with-components.snapshot') pc2 = yaml2json('1-device-with-components.snapshot')
user.post(pc2, res=Snapshot) # PC2 uploads well user.post(json_encode(pc2), res=Snapshot) # PC2 uploads well
pc2['device']['tags'] = [{'type': 'Tag', 'id': tag_id}] # Set tag from pc1 to pc2 pc2['device']['tags'] = [{'type': 'Tag', 'id': tag_id}] # Set tag from pc1 to pc2
user.post(pc2, res=Snapshot, status=MismatchBetweenTagsAndHid) user.post(json_encode(pc2), res=Snapshot, status=MismatchBetweenTagsAndHid)
@pytest.mark.mvp @pytest.mark.mvp
@ -341,17 +342,17 @@ def test_snapshot_different_properties_same_tags(user: UserClient, tag_id: str):
Devicehub must fail the Snapshot. Devicehub must fail the Snapshot.
""" """
# 1. Upload PC1 without hid but with tag # 1. Upload PC1 without hid but with tag
pc1 = file('basic.snapshot') pc1 = yaml2json('basic.snapshot')
pc1['device']['tags'] = [{'type': 'Tag', 'id': tag_id}] pc1['device']['tags'] = [{'type': 'Tag', 'id': tag_id}]
del pc1['device']['serialNumber'] del pc1['device']['serialNumber']
user.post(pc1, res=Snapshot) user.post(json_encode(pc1), res=Snapshot)
# 2. Upload PC2 without hid, a different characteristic than PC1, but with same tag # 2. Upload PC2 without hid, a different characteristic than PC1, but with same tag
pc2 = file('basic.snapshot') pc2 = yaml2json('basic.snapshot')
pc2['uuid'] = uuid4() pc2['uuid'] = uuid4()
pc2['device']['tags'] = pc1['device']['tags'] pc2['device']['tags'] = pc1['device']['tags']
# pc2 model is unknown but pc1 model is set = different property # pc2 model is unknown but pc1 model is set = different property
del pc2['device']['model'] del pc2['device']['model']
user.post(pc2, res=Snapshot, status=MismatchBetweenProperties) user.post(json_encode(pc2), res=Snapshot, status=MismatchBetweenProperties)
@pytest.mark.mvp @pytest.mark.mvp
@ -368,14 +369,14 @@ def test_snapshot_component_containing_components(user: UserClient):
This test avoids this until an appropriate use-case is presented. This test avoids this until an appropriate use-case is presented.
""" """
s = file('basic.snapshot') s = yaml2json('basic.snapshot')
s['device'] = { s['device'] = {
'type': 'Processor', 'type': 'Processor',
'serialNumber': 'foo', 'serialNumber': 'foo',
'manufacturer': 'bar', 'manufacturer': 'bar',
'model': 'baz' 'model': 'baz'
} }
user.post(s, res=Snapshot, status=ValidationError) user.post(json_encode(s), res=Snapshot, status=ValidationError)
@pytest.mark.mvp @pytest.mark.mvp
@ -386,7 +387,7 @@ def test_ereuse_price(user: UserClient):
This tests ensures that only the last erasure is picked up, as This tests ensures that only the last erasure is picked up, as
erasures have always custom endTime value set. erasures have always custom endTime value set.
""" """
s = file('erase-sectors.snapshot') s = yaml2json('erase-sectors.snapshot')
assert s['components'][0]['actions'][0]['endTime'] == '2018-06-01T09:12:06+02:00' assert s['components'][0]['actions'][0]['endTime'] == '2018-06-01T09:12:06+02:00'
s['device']['type'] = 'Server' s['device']['type'] = 'Server'
snapshot = snapshot_and_check(user, s, action_types=( snapshot = snapshot_and_check(user, s, action_types=(
@ -408,7 +409,7 @@ def test_erase_privacy_standards_endtime_sort(user: UserClient):
This tests ensures that only the last erasure is picked up, as This tests ensures that only the last erasure is picked up, as
erasures have always custom endTime value set. erasures have always custom endTime value set.
""" """
s = file('erase-sectors.snapshot') s = yaml2json('erase-sectors.snapshot')
assert s['components'][0]['actions'][0]['endTime'] == '2018-06-01T09:12:06+02:00' assert s['components'][0]['actions'][0]['endTime'] == '2018-06-01T09:12:06+02:00'
snapshot = snapshot_and_check(user, s, action_types=( snapshot = snapshot_and_check(user, s, action_types=(
EraseSectors.t, EraseSectors.t,
@ -465,7 +466,7 @@ def test_erase_privacy_standards_endtime_sort(user: UserClient):
# Let's try a second erasure with an error # Let's try a second erasure with an error
s['uuid'] = uuid4() s['uuid'] = uuid4()
s['components'][0]['actions'][0]['severity'] = 'Error' s['components'][0]['actions'][0]['severity'] = 'Error'
snapshot, _ = user.post(s, res=Snapshot) snapshot, _ = user.post(json_encode(s), res=Snapshot)
storage, _ = user.get(res=m.Device, item=storage['devicehubID']) storage, _ = user.get(res=m.Device, item=storage['devicehubID'])
assert storage['hid'] == 'solidstatedrive-c1mr-c1ml-c1s' assert storage['hid'] == 'solidstatedrive-c1mr-c1ml-c1s'
assert storage['privacy']['type'] == 'EraseSectors' assert storage['privacy']['type'] == 'EraseSectors'
@ -524,7 +525,7 @@ def snapshot_and_check(user: UserClient,
:return: The last resulting snapshot. :return: The last resulting snapshot.
""" """
snapshot, _ = user.post(res=Snapshot, data=input_snapshot) snapshot, _ = user.post(res=Snapshot, data=json_encode(input_snapshot))
assert all(e['type'] in action_types for e in snapshot['actions']) assert all(e['type'] in action_types for e in snapshot['actions'])
assert len(snapshot['actions']) == len(action_types) assert len(snapshot['actions']) == len(action_types)
# Ensure there is no Remove action after the first Add # Ensure there is no Remove action after the first Add
@ -594,7 +595,7 @@ def test_pc_2(user: UserClient):
@pytest.mark.mvp @pytest.mark.mvp
def test_save_snapshot_in_file(app: Devicehub, user: UserClient): def test_save_snapshot_in_file(app: Devicehub, user: UserClient):
""" This test check if works the function save_snapshot_in_file """ """ This test check if works the function save_snapshot_in_file """
snapshot_no_hid = file('basic.snapshot.nohid') snapshot_no_hid = yaml2json('basic.snapshot.nohid')
tmp_snapshots = app.config['TMP_SNAPSHOTS'] tmp_snapshots = app.config['TMP_SNAPSHOTS']
path_dir_base = os.path.join(tmp_snapshots, user.user['email'], 'errors') path_dir_base = os.path.join(tmp_snapshots, user.user['email'], 'errors')
@ -638,9 +639,9 @@ def test_action_no_snapshot_without_save_file(app: Devicehub, user: UserClient):
@pytest.mark.mvp @pytest.mark.mvp
def test_save_snapshot_with_debug(app: Devicehub, user: UserClient): def test_save_snapshot_with_debug(app: Devicehub, user: UserClient):
""" This test check if works the function save_snapshot_in_file """ """ This test check if works the function save_snapshot_in_file """
snapshot_file = file('basic.snapshot.with_debug') snapshot_file = yaml2json('basic.snapshot.with_debug')
debug = snapshot_file['debug'] debug = snapshot_file['debug']
user.post(res=Snapshot, data=snapshot_file) user.post(res=Snapshot, data=json_encode(snapshot_file))
tmp_snapshots = app.config['TMP_SNAPSHOTS'] tmp_snapshots = app.config['TMP_SNAPSHOTS']
path_dir_base = os.path.join(tmp_snapshots, user.user['email']) path_dir_base = os.path.join(tmp_snapshots, user.user['email'])
@ -664,12 +665,12 @@ def test_backup_snapshot_with_errors(app: Devicehub, user: UserClient):
""" This test check if the file snapshot is create when some snapshot is wrong """ """ This test check if the file snapshot is create when some snapshot is wrong """
tmp_snapshots = app.config['TMP_SNAPSHOTS'] tmp_snapshots = app.config['TMP_SNAPSHOTS']
path_dir_base = os.path.join(tmp_snapshots, user.user['email'], 'errors') path_dir_base = os.path.join(tmp_snapshots, user.user['email'], 'errors')
snapshot_no_hid = file('basic.snapshot.badly_formed') snapshot_no_hid = yaml2json('basic.snapshot.badly_formed')
uuid = snapshot_no_hid['uuid'] uuid = snapshot_no_hid['uuid']
snapshot = {'software': '', 'version': '', 'uuid': ''} snapshot = {'software': '', 'version': '', 'uuid': ''}
with pytest.raises(KeyError): with pytest.raises(KeyError):
response = user.post(res=Snapshot, data=snapshot_no_hid) 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] files = [x for x in os.listdir(path_dir_base) if uuid in x]
if files: if files:
@ -689,12 +690,12 @@ def test_snapshot_failed_missing_cpu_benchmark(app: Devicehub, user: UserClient)
""" This test check if the file snapshot is create when some snapshot is wrong """ """ This test check if the file snapshot is create when some snapshot is wrong """
tmp_snapshots = app.config['TMP_SNAPSHOTS'] tmp_snapshots = app.config['TMP_SNAPSHOTS']
path_dir_base = os.path.join(tmp_snapshots, user.user['email'], 'errors') path_dir_base = os.path.join(tmp_snapshots, user.user['email'], 'errors')
snapshot_error = file('failed.snapshot.500.missing-cpu-benchmark') snapshot_error = yaml2json('failed.snapshot.500.missing-cpu-benchmark')
uuid = snapshot_error['uuid'] uuid = snapshot_error['uuid']
snapshot = {'software': '', 'version': '', 'uuid': ''} snapshot = {'software': '', 'version': '', 'uuid': ''}
with pytest.raises(TypeError): with pytest.raises(TypeError):
user.post(res=Snapshot, data=snapshot_error) user.post(res=Snapshot, data=json_encode(snapshot_error))
files = [x for x in os.listdir(path_dir_base) if uuid in x] files = [x for x in os.listdir(path_dir_base) if uuid in x]
if files: if files:
@ -714,12 +715,12 @@ def test_snapshot_failed_missing_hdd_benchmark(app: Devicehub, user: UserClient)
""" This test check if the file snapshot is create when some snapshot is wrong """ """ This test check if the file snapshot is create when some snapshot is wrong """
tmp_snapshots = app.config['TMP_SNAPSHOTS'] tmp_snapshots = app.config['TMP_SNAPSHOTS']
path_dir_base = os.path.join(tmp_snapshots, user.user['email'], 'errors') path_dir_base = os.path.join(tmp_snapshots, user.user['email'], 'errors')
snapshot_error = file('failed.snapshot.500.missing-hdd-benchmark') snapshot_error = yaml2json('failed.snapshot.500.missing-hdd-benchmark')
uuid = snapshot_error['uuid'] uuid = snapshot_error['uuid']
snapshot = {'software': '', 'version': '', 'uuid': ''} snapshot = {'software': '', 'version': '', 'uuid': ''}
with pytest.raises(TypeError): with pytest.raises(TypeError):
user.post(res=Snapshot, data=snapshot_error) user.post(res=Snapshot, data=json_encode(snapshot_error))
files = [x for x in os.listdir(path_dir_base) if uuid in x] files = [x for x in os.listdir(path_dir_base) if uuid in x]
if files: if files:
@ -739,11 +740,11 @@ 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 """ """ This test check if the file snapshot is create when some snapshot is wrong """
tmp_snapshots = app.config['TMP_SNAPSHOTS'] tmp_snapshots = app.config['TMP_SNAPSHOTS']
path_dir_base = os.path.join(tmp_snapshots, user.user['email'], 'errors') path_dir_base = os.path.join(tmp_snapshots, user.user['email'], 'errors')
snapshot_error = file('desktop-9644w8n-lenovo-0169622.snapshot') snapshot_error = yaml2json('desktop-9644w8n-lenovo-0169622.snapshot')
snapshot_error['device']['chassis'] = None snapshot_error['device']['chassis'] = None
uuid = snapshot_error['uuid'] uuid = snapshot_error['uuid']
snapshot, res = user.post(res=Snapshot, data=snapshot_error) snapshot, res = user.post(res=Snapshot, data=json_encode(snapshot_error))
shutil.rmtree(tmp_snapshots) shutil.rmtree(tmp_snapshots)
@ -757,12 +758,12 @@ def test_snapshot_failed_missing_chassis(app: Devicehub, user: UserClient):
""" This test check if the file snapshot is create when some snapshot is wrong """ """ This test check if the file snapshot is create when some snapshot is wrong """
tmp_snapshots = app.config['TMP_SNAPSHOTS'] tmp_snapshots = app.config['TMP_SNAPSHOTS']
path_dir_base = os.path.join(tmp_snapshots, user.user['email'], 'errors') path_dir_base = os.path.join(tmp_snapshots, user.user['email'], 'errors')
snapshot_error = file('failed.snapshot.422.missing-chassis') snapshot_error = yaml2json('failed.snapshot.422.missing-chassis')
uuid = snapshot_error['uuid'] uuid = snapshot_error['uuid']
snapshot = {'software': '', 'version': '', 'uuid': ''} snapshot = {'software': '', 'version': '', 'uuid': ''}
with pytest.raises(TypeError): with pytest.raises(TypeError):
user.post(res=Snapshot, data=snapshot_error) user.post(res=Snapshot, data=json_encode(snapshot_error))
files = [x for x in os.listdir(path_dir_base) if uuid in x] files = [x for x in os.listdir(path_dir_base) if uuid in x]
if files: if files:
@ -798,9 +799,9 @@ 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 """ 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 and then we get a /devices, this create a crash
""" """
snapshot_file = file('asus-end_time_bug88.snapshot') snapshot_file = yaml2json('asus-end_time_bug88.snapshot')
snapshot_file['endTime'] = '2001-01-01 00:00:00+00:00' snapshot_file['endTime'] = '2001-01-01 00:00:00+00:00'
snapshot, _ = user.post(res=Snapshot, data=snapshot_file) snapshot, _ = user.post(res=Snapshot, data=json_encode(snapshot_file))
device, _ = user.get(res=m.Device, item=snapshot['device']['devicehubID']) device, _ = user.get(res=m.Device, item=snapshot['device']['devicehubID'])
end_times = [x['endTime'] for x in device['actions']] end_times = [x['endTime'] for x in device['actions']]
@ -847,4 +848,5 @@ def test_bug_141(user: UserClient):
with a big number in the parameter command_timeout of the DataStorage with a big number in the parameter command_timeout of the DataStorage
""" """
user.post(file('2021-5-4-13-41_time_out_test_datastorage'), res=Snapshot) dev = file('2021-5-4-13-41_time_out_test_datastorage')
user.post(dev, res=Snapshot)

View File

@ -19,7 +19,7 @@ from ereuse_devicehub.resources.tag import Tag
from ereuse_devicehub.resources.tag.view import CannotCreateETag, LinkedToAnotherDevice, \ from ereuse_devicehub.resources.tag.view import CannotCreateETag, LinkedToAnotherDevice, \
TagNotLinked TagNotLinked
from tests import conftest from tests import conftest
from tests.conftest import file from tests.conftest import file, yaml2json, json_encode
@pytest.mark.mvp @pytest.mark.mvp
@ -319,9 +319,9 @@ def test_tag_secondary_workbench_link_find(user: UserClient):
with pytest.raises(ResourceNotFound): with pytest.raises(ResourceNotFound):
Tag.from_an_id('nope').one() Tag.from_an_id('nope').one()
s = file('basic.snapshot') s = yaml2json('basic.snapshot')
s['device']['tags'] = [{'id': 'foo', 'secondary': 'bar', 'type': 'Tag'}] s['device']['tags'] = [{'id': 'foo', 'secondary': 'bar', 'type': 'Tag'}]
snapshot, _ = user.post(s, res=Snapshot) snapshot, _ = user.post(json_encode(s), res=Snapshot)
device, _ = user.get(res=Device, item=snapshot['device']['devicehubID']) device, _ = user.get(res=Device, item=snapshot['device']['devicehubID'])
assert device['tags'][0]['id'] == 'foo' assert device['tags'][0]['id'] == 'foo'
assert device['tags'][0]['secondary'] == 'bar' assert device['tags'][0]['secondary'] == 'bar'

View File

@ -11,7 +11,7 @@ from ereuse_devicehub.resources.action.models import RateComputer, BenchmarkProc
from ereuse_devicehub.resources.device.exceptions import NeedsId from ereuse_devicehub.resources.device.exceptions import NeedsId
from ereuse_devicehub.resources.device.models import Device from ereuse_devicehub.resources.device.models import Device
from ereuse_devicehub.resources.tag.model import Tag from ereuse_devicehub.resources.tag.model import Tag
from tests.conftest import file, file_workbench from tests.conftest import file, file_workbench, yaml2json, json_encode
@pytest.mark.mvp @pytest.mark.mvp
@ -20,18 +20,18 @@ def test_workbench_server_condensed(user: UserClient):
condensed in only one big ``Snapshot`` file, as described condensed in only one big ``Snapshot`` file, as described
in the docs. in the docs.
""" """
s = file('workbench-server-1.snapshot') s = yaml2json('workbench-server-1.snapshot')
s['device']['actions'].append(file('workbench-server-2.stress-test')) s['device']['actions'].append(yaml2json('workbench-server-2.stress-test'))
s['components'][4]['actions'].extend(( s['components'][4]['actions'].extend((
file('workbench-server-3.erase'), yaml2json('workbench-server-3.erase'),
file('workbench-server-4.install') yaml2json('workbench-server-4.install')
)) ))
s['components'][5]['actions'].append(file('workbench-server-3.erase')) s['components'][5]['actions'].append(yaml2json('workbench-server-3.erase'))
# Create tags # Create tags
for t in s['device']['tags']: for t in s['device']['tags']:
user.post({'id': t['id']}, res=Tag) user.post({'id': t['id']}, res=Tag)
snapshot, _ = user.post(res=em.Snapshot, data=s) snapshot, _ = user.post(res=em.Snapshot, data=json_encode(s))
pc_id = snapshot['device']['id'] pc_id = snapshot['device']['id']
cpu_id = snapshot['components'][3]['id'] cpu_id = snapshot['components'][3]['id']
ssd_id= snapshot['components'][4]['id'] ssd_id= snapshot['components'][4]['id']
@ -77,28 +77,28 @@ def test_workbench_server_phases(user: UserClient):
actions.html#snapshots-from-workbench>`_. actions.html#snapshots-from-workbench>`_.
""" """
# 1. Snapshot with sync / rate / benchmarks / test data storage # 1. Snapshot with sync / rate / benchmarks / test data storage
s = file('workbench-server-1.snapshot') s = yaml2json('workbench-server-1.snapshot')
snapshot, _ = user.post(res=em.Snapshot, data=s) snapshot, _ = user.post(res=em.Snapshot, data=json_encode(s))
assert not snapshot['closed'], 'Snapshot must be waiting for the new actions' assert not snapshot['closed'], 'Snapshot must be waiting for the new actions'
# 2. stress test # 2. stress test
st = file('workbench-server-2.stress-test') st = yaml2json('workbench-server-2.stress-test')
st['snapshot'] = snapshot['id'] st['snapshot'] = snapshot['id']
stress_test, _ = user.post(res=em.StressTest, data=st) stress_test, _ = user.post(res=em.StressTest, data=st)
# 3. erase # 3. erase
ssd_id, hdd_id = snapshot['components'][4]['id'], snapshot['components'][5]['id'] ssd_id, hdd_id = snapshot['components'][4]['id'], snapshot['components'][5]['id']
e = file('workbench-server-3.erase') e = yaml2json('workbench-server-3.erase')
e['snapshot'], e['device'] = snapshot['id'], ssd_id e['snapshot'], e['device'] = snapshot['id'], ssd_id
erase1, _ = user.post(res=em.EraseSectors, data=e) erase1, _ = user.post(res=em.EraseSectors, data=e)
# 3 bis. a second erase # 3 bis. a second erase
e = file('workbench-server-3.erase') e = yaml2json('workbench-server-3.erase')
e['snapshot'], e['device'] = snapshot['id'], hdd_id e['snapshot'], e['device'] = snapshot['id'], hdd_id
erase2, _ = user.post(res=em.EraseSectors, data=e) erase2, _ = user.post(res=em.EraseSectors, data=e)
# 4. Install # 4. Install
i = file('workbench-server-4.install') i = yaml2json('workbench-server-4.install')
i['snapshot'], i['device'] = snapshot['id'], ssd_id i['snapshot'], i['device'] = snapshot['id'], ssd_id
install, _ = user.post(res=em.Install, data=i) install, _ = user.post(res=em.Install, data=i)
@ -317,7 +317,7 @@ def test_workbench_fixtures(file: pathlib.Path, user: UserClient):
""" """
s = json.load(file.open()) s = json.load(file.open())
user.post(res=em.Snapshot, user.post(res=em.Snapshot,
data=s, data=json_encode(s),
status=201) status=201)
@ -337,3 +337,8 @@ def test_david(user: UserClient):
def test_eresueprice_computer_type(user: UserClient): def test_eresueprice_computer_type(user: UserClient):
s = file_workbench('computer-type.snapshot') s = file_workbench('computer-type.snapshot')
snapshot, _ = user.post(res=em.Snapshot, data=s) snapshot, _ = user.post(res=em.Snapshot, data=s)
def test_workbench_encoded_snapshot(user: UserClient):
s = file_workbench('encoded.snapshot')
snapshot, _ = user.post(res=em.Snapshot, data=s)

File diff suppressed because one or more lines are too long