Пример #1
0
def test_create_tag_no_slash():
    """Checks that no tags can be created that contain a slash."""
    with raises(ValidationError):
        Tag('/')

    with raises(ValidationError):
        Tag('bar', secondary='/')
Пример #2
0
def test_merge_two_device_with_differents_tags(app: Devicehub, user: UserClient):
    """ Check if is correct to do a manual merge of 2 diferents devices with diferents tags """
    snapshot1, _ = user.post(import_snap('real-custom.snapshot.11'), res=m.Snapshot)
    snapshot2, _ = user.post(import_snap('real-hp.snapshot.11'), res=m.Snapshot)
    pc1_id = snapshot1['device']['id']
    pc2_id = snapshot2['device']['id']

    with app.app_context():
        pc1 = d.Device.query.filter_by(id=pc1_id).one()
        pc2 = d.Device.query.filter_by(id=pc2_id).one()

        tag1 = Tag(id='fii-bor', owner_id=user.user['id'])
        tag2 = Tag(id='foo-bar', owner_id=user.user['id'])
        pc1.tags.add(tag1)
        pc2.tags.add(tag2)
        db.session.add(pc1)
        db.session.add(pc2)
        db.session.commit()

        uri = '/devices/%d/merge/%d' % (pc1_id, pc2_id)
        result, _ = user.post({'id': 1}, uri=uri, status=201)

        assert pc1.hid == pc2.hid
        assert tag1 in pc1.tags
        assert tag2 in pc1.tags
Пример #3
0
def test_tag_get_device_from_tag_endpoint_multiple_tags(app: Devicehub, user: UserClient, user2: UserClient, client: Client):
    """As above, but when there are two tags with the secondary ID, the
    system should not return any of both (to be deterministic) so
    it should raise an exception.
    """
    g.user = User.query.all()[0]
    db.session.add(Tag(id='foo', secondary='bar', owner_id=user.user['id']))
    db.session.commit()

    db.session.add(Tag(id='foo', secondary='bar', owner_id=user2.user['id']))
    db.session.commit()

    db.session.add(Tag(id='foo2', secondary='bar', owner_id=user.user['id']))
    with raises(DBError):
        db.session.commit()
    db.session.rollback()

    tag1 = Tag.from_an_id('foo').filter_by(owner_id=user.user['id']).one()
    tag2 = Tag.from_an_id('foo').filter_by(owner_id=user2.user['id']).one()
    pc1 = Desktop(serial_number='sn1', chassis=ComputerChassis.Tower, owner_id=user.user['id'])
    pc2 = Desktop(serial_number='sn2', chassis=ComputerChassis.Tower, owner_id=user2.user['id'])
    pc1.tags.add(tag1)
    pc2.tags.add(tag2)
    db.session.add(pc1)
    db.session.add(pc2)
    db.session.commit()
    computer, _ = user.get(res=Tag, item='foo/device')
    assert computer['serialNumber'] == 'sn1'
    computer, _ = user2.get(res=Tag, item='foo/device')
    assert computer['serialNumber'] == 'sn2'

    _, status = client.get(res=Tag, item='foo/device', status=MultipleResourcesFound)
    assert status.status_code == 422
Пример #4
0
def test_create_same_tag_default_org_two_users(user: UserClient, user2: UserClient):
    """Creates a tag using the default organization."""
    tag = Tag(id='foo-1', owner_id=user.user['id'])
    tag2 = Tag(id='foo-1', owner_id=user2.user['id'])
    db.session.add(tag)
    db.session.add(tag2)
    db.session.commit()
    assert tag.org.name == 'FooOrg'  # as defined in the settings
    assert tag2.org.name == 'FooOrg'  # as defined in the settings
Пример #5
0
 def _post_one(self):
     t = request.get_json()
     tag = Tag(**t)
     if tag.like_etag():
         raise CannotCreateETag(tag.id)
     db.session.add(tag)
     db.session().final_flush()
     db.session.commit()
     return Response(status=201)
Пример #6
0
def test_tag_create_tags_cli_csv(app: Devicehub, user: UserClient):
    """Checks creating tags with the CLI endpoint using a CSV."""
    owner_id = user.user['id']
    csv = pathlib.Path(__file__).parent / 'files' / 'tags-cli.csv'
    runner = app.test_cli_runner()
    runner.invoke('tag', 'add-csv', str(csv), '-u', owner_id)
    with app.app_context():
        t1 = Tag.from_an_id('id1').one()
        t2 = Tag.from_an_id('sec1').one()
        assert t1 == t2
Пример #7
0
def test_create_two_same_tags():
    """Ensures there cannot be two tags with the same ID and organization."""
    db.session.add(Tag(id='foo-bar'))
    db.session.add(Tag(id='foo-bar'))
    with raises(IntegrityError):
        db.session.commit()
    db.session.rollback()
    # And it works if tags are in different organizations
    db.session.add(Tag(id='foo-bar'))
    org2 = Organization(name='org 2', tax_id='tax id org 2')
    db.session.add(Tag(id='foo-bar', org=org2))
    db.session.commit()
Пример #8
0
def test_tag_get_device_from_tag_endpoint_multiple_tags(
        app: Devicehub, user: UserClient):
    """
    As above, but when there are two tags with the same ID, the
    system should not return any of both (to be deterministic) so
    it should raise an exception.
    """
    with app.app_context():
        db.session.add(Tag(id='foo-bar'))
        org2 = Organization(name='org 2', tax_id='tax id org 2')
        db.session.add(Tag(id='foo-bar', org=org2))
        db.session.commit()
    user.get(res=Tag, item='foo-bar/device', status=MultipleResourcesFound)
Пример #9
0
def test_create_two_same_tags(user: UserClient):
    """Ensures there cannot be two tags with the same ID and organization."""

    db.session.add(Tag(id='foo-bar', owner_id=user.user['id']))
    db.session.add(Tag(id='foo-bar', owner_id=user.user['id']))

    with raises(DBError):
        db.session.commit()
    db.session.rollback()
    # And it works if tags are in different organizations
    db.session.add(Tag(id='foo-bar', owner_id=user.user['id']))
    org2 = Organization(name='org 2', tax_id='tax id org 2')
    db.session.add(Tag(id='foo-bar', org=org2, owner_id=user.user['id']))
    with raises(DBError):
        db.session.commit()
Пример #10
0
def test_tag_manual_link_search(app: Devicehub, user: UserClient):
    """Tests linking manually a tag through PUT /tags/<id>/device/<id>

    Checks search has the term.
    """
    with app.app_context():
        g.user = User.query.one()
        db.session.add(Tag('foo-bar', secondary='foo-sec', owner_id=user.user['id']))
        desktop = Desktop(serial_number='foo', chassis=ComputerChassis.AllInOne, owner_id=user.user['id'])
        db.session.add(desktop)
        db.session.commit()
        desktop_id = desktop.id
        devicehub_id = desktop.devicehub_id
    user.put({}, res=Tag, item='foo-bar/device/{}'.format(desktop_id), status=204)
    device, _ = user.get(res=Device, item=devicehub_id)
    assert 'foo-bar' in [x['id'] for x in device['tags']]

    # Device already linked
    # Just returns an OK to conform to PUT as anything changes

    user.put({}, res=Tag, item='foo-sec/device/{}'.format(desktop_id), status=204)

    # Secondary IDs are case insensitive
    user.put({}, res=Tag, item='FOO-BAR/device/{}'.format(desktop_id), status=204)
    user.put({}, res=Tag, item='FOO-SEC/device/{}'.format(desktop_id), status=204)

    # cannot link to another device when already linked
    user.put({}, res=Tag, item='foo-bar/device/99', status=LinkedToAnotherDevice)

    i, _ = user.get(res=Device, query=[('search', 'foo-bar')])
    assert i['items']
    i, _ = user.get(res=Device, query=[('search', 'foo-sec')])
    assert i['items']
    i, _ = user.get(res=Device, query=[('search', 'foo')])
    assert i['items']
Пример #11
0
def test_get_tags_endpoint(user: UserClient, app: Devicehub,
                           requests_mock: requests_mock.mocker.Mocker):
    """Performs GET /tags after creating 3 tags, 2 printable and one
    not. Only the printable ones are returned.
    """
    # Prepare test
    with app.app_context():
        org = Organization(name='bar', tax_id='bartax')
        tag = Tag(id='bar-1', org=org, provider=URL('http://foo.bar'), owner_id=user.user['id'])
        db.session.add(tag)
        db.session.commit()
        assert not tag.printable

    requests_mock.post('https://example.com/',
                       # request
                       request_headers={
                           'Authorization': 'Basic {}'.format(DevicehubClient.encode_token(
                               '52dacef0-6bcb-4919-bfed-f10d2c96ecee'))
                       },
                       # response
                       json=['tag1id', 'tag2id'],
                       status_code=201)
    user.post({}, res=Tag, query=[('num', 2)])

    # Test itself
    data, _ = user.get(res=Tag)
    assert len(data['items']) == 2, 'Only 2 tags are printable, thus retreived'
    # Order is created descending
    assert data['items'][0]['id'] == 'tag2id'
    assert data['items'][0]['printable']
    assert data['items'][1]['id'] == 'tag1id'
    assert data['items'][1]['printable'], 'Tags made this way are printable'
Пример #12
0
def test_deactivate_merge(app: Devicehub, user: UserClient):
    """ Check if is correct to do a manual merge """
    snapshot1, _ = user.post(import_snap('real-custom.snapshot.11'), res=m.Snapshot)
    snapshot2, _ = user.post(import_snap('real-hp.snapshot.11'), res=m.Snapshot)
    pc1_id = snapshot1['device']['id']
    pc2_id = snapshot2['device']['id']

    with app.app_context():
        pc1 = d.Device.query.filter_by(id=pc1_id).one()
        pc2 = d.Device.query.filter_by(id=pc2_id).one()
        n_actions1 = len(pc1.actions)
        n_actions2 = len(pc2.actions)
        action1 = pc1.actions[0]
        action2 = pc2.actions[0]
        assert not action2 in pc1.actions

        tag = Tag(id='foo-bar', owner_id=user.user['id'])
        pc2.tags.add(tag)
        db.session.add(pc2)
        db.session.commit()

        components1 = [com for com in pc1.components]
        components2 = [com for com in pc2.components]
        components1_excluded = [com for com in pc1.components if not com in components2]
        assert pc1.hid != pc2.hid
        assert not tag in pc1.tags

        uri = '/devices/%d/merge/%d' % (pc1_id, pc2_id)
        _, code = user.post({'id': 1}, uri=uri, status=404)
        assert code.status == '404 NOT FOUND'
Пример #13
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'))
        db.session.commit()
    user.get(res=Tag, item='foo-bar/device', status=TagNotLinked)
Пример #14
0
def tag_id(app: Devicehub) -> str:
    """Creates a tag and returns its id."""
    with app.app_context():
        t = Tag(id='foo')
        db.session.add(t)
        db.session.commit()
        return t.id
Пример #15
0
 def find(self, args: dict):
     tags = Tag.query.filter(Tag.is_printable_q()) \
         .order_by(Tag.created.desc()) \
         .paginate(per_page=200)  # type: Pagination
     return things_response(
         self.schema.dump(tags.items, many=True, nested=0), tags.page,
         tags.per_page, tags.total, tags.prev_num, tags.next_num)
Пример #16
0
 def one(self, id):
     """Gets the device from the tag."""
     tag = Tag.from_an_id(id).one()  # type: Tag
     if not tag.device:
         raise TagNotLinked(tag.id)
     if not request.authorization:
         return redirect(location=url_for_resource(Device, tag.device.id))
     return app.resources[Device.t].schema.jsonify(tag.device)
Пример #17
0
def test_create_tag_default_org():
    """Creates a tag using the default organization."""
    tag = Tag(id='foo-1')
    assert not tag.org_id, 'org-id is set as default value so it should only load on flush'
    # We don't want the organization to load, or it would make this
    # object, from transient to new (added to session)
    assert 'org' not in vars(tag), 'Organization should not have been loaded'
    db.session.add(tag)
    db.session.commit()
    assert tag.org.name == 'FooOrg'  # as defined in the settings
Пример #18
0
def test_tag_get_device_from_tag_endpoint(app: Devicehub, user: UserClient):
    """Checks getting a linked device from a tag endpoint"""
    with app.app_context():
        # Create a pc with a tag
        tag = Tag(id='foo-bar')
        pc = Computer(serial_number='sn1')
        pc.tags.add(tag)
        db.session.add(pc)
        db.session.commit()
    computer, _ = user.get(res=Tag, item='foo-bar/device')
    assert computer['serialNumber'] == 'sn1'
Пример #19
0
def tag_id(app: Devicehub) -> str:
    """Creates a tag and returns its id."""
    with app.app_context():
        if User.query.count():
            user = User.query.one()
        else:
            user = create_user()
        t = Tag(id='foo', owner_id=user.id)
        db.session.add(t)
        db.session.commit()
        return t.id
Пример #20
0
def test_create_tag(user: UserClient):
    """Creates a tag specifying a custom organization."""
    org = Organization(name='bar', tax_id='bartax')
    tag = Tag(id='bar-1', org=org, provider=URL('http://foo.bar'), owner_id=user.user['id'])
    db.session.add(tag)
    db.session.commit()
    tag = Tag.query.one()
    assert tag.id == 'bar-1'
    assert tag.provider == URL('http://foo.bar')
    res, _ = user.get(res=Tag, item=tag.code, status=422)
    assert res['type'] == 'TagNotLinked'
Пример #21
0
 def _create_many_regular_tags(self, num: int):
     tags_id, _ = g.tag_provider.post('/', {}, query=[('num', num)])
     tags = [
         Tag(id=tag_id, provider=g.inventory.tag_provider)
         for tag_id in tags_id
     ]
     db.session.add_all(tags)
     db.session().final_flush()
     response = things_response(self.schema.dump(tags, many=True, nested=1),
                                code=201)
     db.session.commit()
     return response
Пример #22
0
def test_tag_get_device_from_tag_endpoint(app: Devicehub, user: UserClient):
    """Checks getting a linked device from a tag endpoint"""
    with app.app_context():
        # Create a pc with a tag
        g.user = User.query.one()
        tag = Tag(id='foo-bar', owner_id=user.user['id'])
        pc = Desktop(serial_number='sn1', chassis=ComputerChassis.Tower, owner_id=user.user['id'])
        pc.tags.add(tag)
        db.session.add(pc)
        db.session.commit()
    computer, _ = user.get(res=Tag, item='foo-bar/device')
    assert computer['serialNumber'] == 'sn1'
Пример #23
0
 def put(self, tag_id: str, device_id: str):
     """Links an existing tag with a device."""
     tag = Tag.from_an_id(tag_id).one()  # type: Tag
     if tag.device_id:
         if tag.device_id == device_id:
             return Response(status=204)
         else:
             raise LinkedToAnotherDevice(tag.device_id)
     else:
         tag.device_id = device_id
     db.session().final_flush()
     db.session.commit()
     return Response(status=204)
Пример #24
0
def test_erase_changing_hdd_between_pcs(user: UserClient):
    """Tests when we erase one device and next change the disk in other device we
    want see in the second device the disks erase."""
    s1 = file('erase-sectors-2-hdd.snapshot')
    s2 = file('erase-sectors-2-hdd.snapshot2')
    snapshot1, _ = user.post(res=Snapshot, data=s1)
    snapshot2, _ = user.post(res=Snapshot, data=s2)
    dev1 = m.Device.query.filter_by(id=snapshot1['device']['id']).one()
    dev2 = m.Device.query.filter_by(id=snapshot2['device']['id']).one()
    tag1 = Tag(id='dev1', device=dev1)
    tag2 = Tag(id='dev2', device=dev2)
    db.session.commit()

    assert dev2.components[1].actions[2].parent == dev1
    doc1, response = user.get(res=documents.DocumentDef.t,
                               item='erasures/{}'.format(dev1.id),
                               accept=ANY)
    doc2, response = user.get(res=documents.DocumentDef.t,
                               item='erasures/{}'.format(dev2.id),
                               accept=ANY)
    assert 'dev1' in doc2
    assert 'dev2' in doc2
Пример #25
0
def test_delete_tags(user: UserClient, client: Client):
    """Delete a named tag."""
    # Delete Tag Named
    g.user = User.query.one()
    pc = Desktop(serial_number='sn1', chassis=ComputerChassis.Tower, owner_id=user.user['id'])
    db.session.add(pc)
    db.session.commit()
    tag = Tag(id='bar', owner_id=user.user['id'], device_id=pc.id)
    db.session.add(tag)
    db.session.commit()
    tag = Tag.query.all()[-1]
    assert tag.id == 'bar'
    # Is not possible delete one tag linked to one device
    res, _ = user.delete(res=Tag, item=tag.id, status=422)
    msg = 'The tag bar is linked to device'
    assert msg in res['message'][0]

    tag.device_id = None
    db.session.add(tag)
    db.session.commit()
    # Is not possible delete one tag from an anonymous user
    client.delete(res=Tag, item=tag.id, status=401)

    # Is possible delete one normal tag
    user.delete(res=Tag, item=tag.id)
    user.get(res=Tag, item=tag.id, status=404)

    # Delete Tag UnNamed
    org = Organization(name='bar', tax_id='bartax')
    tag = Tag(id='bar-1', org=org, provider=URL('http://foo.bar'), owner_id=user.user['id'])
    db.session.add(tag)
    db.session.commit()
    tag = Tag.query.all()[-1]
    assert tag.id == 'bar-1'
    res, _ = user.delete(res=Tag, item=tag.id, status=422)
    msg = 'This tag {} is unnamed tag. It is imposible delete.'.format(tag.id)
    assert msg in res['message']
    tag = Tag.query.all()[-1]
    assert tag.id == 'bar-1'
Пример #26
0
    def delete(self, tag_id: str, device_id: str):
        tag = Tag.from_an_id(tag_id).filter_by(owner=g.user).one()  # type: Tag
        device = Device.query.filter_by(owner=g.user).filter_by(
            id=device_id).one()
        if tag.provider:
            # if is an unamed tag not do nothing
            return Response(status=204)

        if tag.device == device:
            tag.device_id = None
            db.session().final_flush()
            db.session.commit()
        return Response(status=204)
Пример #27
0
def test_tag_secondary_workbench_link_find(user: UserClient):
    """Creates and consumes tags with a secondary id, linking them
    through Workbench to a device
    and getting them through search."""
    t = Tag('foo', secondary='bar', owner_id=user.user['id'])
    db.session.add(t)
    db.session.flush()
    assert Tag.from_an_id('bar').one() == Tag.from_an_id('foo').one()
    with pytest.raises(ResourceNotFound):
        Tag.from_an_id('nope').one()

    s = yaml2json('basic.snapshot')
    s['device']['tags'] = [{'id': 'foo', 'secondary': 'bar', 'type': 'Tag'}]
    snapshot, _ = user.post(json_encode(s), res=Snapshot)
    device, _ = user.get(res=Device, item=snapshot['device']['devicehubID'])
    assert 'foo' in [x['id'] for x in device['tags']]
    assert 'bar' in [x.get('secondary') for x in device['tags']]

    r, _ = user.get(res=Device, query=[('search', 'foo'), ('filter', {'type': ['Computer']})])
    assert len(r['items']) == 1
    r, _ = user.get(res=Device, query=[('search', 'bar'), ('filter', {'type': ['Computer']})])
    assert len(r['items']) == 1
Пример #28
0
def test_create_tag_with_device(user: UserClient):
    """Creates a tag specifying linked with one device."""
    g.user = User.query.one()
    pc = Desktop(serial_number='sn1', chassis=ComputerChassis.Tower, owner_id=user.user['id'])
    db.session.add(pc)
    db.session.commit()
    tag = Tag(id='bar', owner_id=user.user['id'])
    db.session.add(tag)
    db.session.commit()
    data = '{tag_id}/device/{device_id}'.format(tag_id=tag.id, device_id=pc.id)
    user.put({}, res=Tag, item=data, status=204)
    user.get(res=Tag, item='{}/device'.format(tag.id))
    user.delete({}, res=Tag, item=data, status=204)
    res, _ = user.get(res=Tag, item='{}/device'.format(tag.id), status=422)
    assert res['type'] == 'TagNotLinked'
Пример #29
0
    def put(self, tag_id: str, device_id: int):
        """Links an existing tag with a device."""
        device_id = int(device_id)
        tag = Tag.from_an_id(tag_id).filter_by(owner=g.user).one()  # type: Tag
        if tag.device_id:
            if tag.device_id == device_id:
                return Response(status=204)
            else:
                raise LinkedToAnotherDevice(tag.device_id)
        else:
            # Check if this device exist for this owner
            Device.query.filter_by(owner=g.user).filter_by(id=device_id).one()
            tag.device_id = device_id

        db.session().final_flush()
        db.session.commit()
        return Response(status=204)
Пример #30
0
def test_get_tag_permissions(app: Devicehub, user: UserClient, user2: UserClient):
    """Creates a tag specifying a custom organization."""
    with app.app_context():
        # Create a pc with a tag
        g.user = User.query.all()[0]
        tag = Tag(id='foo-bar', owner_id=user.user['id'])
        pc = Desktop(serial_number='sn1', chassis=ComputerChassis.Tower, owner_id=user.user['id'])
        pc.tags.add(tag)
        db.session.add(pc)
        db.session.commit()
    computer, res = user.get(res=Tag, item='foo-bar/device')

    url = "/tags/?foo-bar/device"
    computer, res = user.get(url, None)
    computer2, res2 = user2.get(url, None)
    assert res.status_code == 200
    assert res2.status_code == 200
    assert len(computer['items']) == 2
    assert len(computer2['items']) == 0