Ejemplo n.º 1
0
def test_db_url(db: SQLAlchemy):
    class Foo(db.Model):
        id = db.Column(db.Integer, primary_key=True)
        bar = db.Column(URL)

    db.create_all()
    foo = Foo(id=1, bar=urlutils.URL('http://foo.com/bar'))
    assert foo.bar == urlutils.URL('http://foo.com/bar')
    db.session.add(foo)
    db.session.commit()
Ejemplo n.º 2
0
def test_marshmallow_url():
    class Foo(Schema):
        foo = marshmallow.URL()

    foo = Foo()
    foo.load({'foo': 'https://foo.com/bar'})
    foo.load({'foo': 'https://foo.com/'})
    with pytest.raises(ValueError):
        foo.load({'foo': 'this is not an url'})
    with pytest.raises(ValueError):
        foo.load({'foo': 'foo.com/'})

    serialized = foo.dump({'foo': urlutils.URL('https://foo.com/bar')})
    assert serialized == {'foo': 'https://foo.com/bar'}

    serialized = foo.dump({'foo': None})
    assert serialized == {'foo': None}

    class Bar(Schema):
        bar = marshmallow.URL(require_path=True)

    bar = Bar()
    bar.load({'bar': 'https://foo.com/bar'})
    with pytest.raises(ValueError):
        bar.load({'bar': 'https://foo.com'})
    with pytest.raises(ValueError):
        bar.load({'bar': 'https://foo.com/'})
Ejemplo n.º 3
0
def test_snapshot_model():
    """
    Tests creating a Snapshot with its relationships ensuring correct
    DB mapping.
    """
    device = m.Desktop(serial_number='a1', chassis=ComputerChassis.Tower)
    # noinspection PyArgumentList
    snapshot = Snapshot(uuid=uuid4(),
                        end_time=datetime.now(timezone.utc),
                        version='1.0',
                        software=SnapshotSoftware.DesktopApp,
                        elapsed=timedelta(seconds=25))
    snapshot.device = device
    snapshot.request = SnapshotRequest(request={'foo': 'bar'})
    db.session.add(snapshot)
    db.session.commit()
    device = m.Desktop.query.one()  # type: m.Desktop
    e1 = device.events[0]
    assert isinstance(e1, Snapshot), 'Creation order must be preserved: 1. snapshot, 2. WR'
    db.session.delete(device)
    db.session.commit()
    assert Snapshot.query.one_or_none() is None
    assert SnapshotRequest.query.one_or_none() is None
    assert User.query.one() is not None
    assert m.Desktop.query.one_or_none() is None
    assert m.Device.query.one_or_none() is None
    # Check properties
    assert device.url == urlutils.URL('http://localhost/devices/1')
Ejemplo n.º 4
0
 def _deserialize(self, value, attr, data):
     url = urlutils.URL(value)
     if url.scheme or url.host:
         if self.require_path:
             if url.path and url.path != '/':
                 return url
         else:
             return url
     raise ValueError('Not a valid URL.')
Ejemplo n.º 5
0
    def get(self, id):
        """Get a collection of resources or a specific one.
        ---
        parameters:
        - name: id
          in: path
          description: The identifier of the resource.
          type: string
          required: false
        responses:
          200:
            description: Return the collection or the specific one.
        """
        args = self.QUERY_PARSER.parse(self.find_args,
                                       flask.request,
                                       locations=('querystring', ))
        if id:
            # todo we assume we can pass both device id and event id
            # for certificates... how is it going to end up being?
            try:
                id = uuid.UUID(id)
            except ValueError:
                try:
                    id = int(id)
                except ValueError:
                    raise teal.marshmallow.ValidationError(
                        'Document must be an ID or UUID.')
                else:
                    query = devs.Device.query.filter_by(id=id)
            else:
                query = evs.Event.query.filter_by(id=id)
        else:
            flask.current_app.auth.requires_auth(
                lambda: None)()  # todo not nice
            query = self.query(args)

        type = urlutils.URL(flask.request.url).path_parts[-2]
        if type == 'erasures':
            template = self.erasure(query)
        if args.get('format') == Format.PDF:
            res = flask_weasyprint.render_pdf(
                flask_weasyprint.HTML(string=template),
                download_filename='{}.pdf'.format(type))
        else:
            res = flask.make_response(template)
        return res
Ejemplo n.º 6
0
 def url(self) -> urlutils.URL:
     """The URL where to GET this device."""
     # todo this url only works for printable internal tags
     return urlutils.URL(url_for_resource(Tag, item_id=self.id))
Ejemplo n.º 7
0
 def url(self) -> urlutils.URL:
     """The URL where to GET this event."""
     return urlutils.URL(url_for_resource(Lot, item_id=self.id))
Ejemplo n.º 8
0
 def get_url_path(self):
     url = urlutils.URL(request.url)
     url.normalize()
     url.path_parts = url.path_parts[:-2] + ['check', '']
     return url.to_text()
Ejemplo n.º 9
0
 def url(self) -> urlutils.URL:
     """The URL where to GET this action."""
     return urlutils.URL(url_for_resource(Deliverynote, item_id=self.id))
Ejemplo n.º 10
0
 def url(self) -> urlutils.URL:
     """The URL where to GET this device."""
     return urlutils.URL(url_for_resource(Device, item_id=self.id))
Ejemplo n.º 11
0
 def __attrs_post_init__(self) -> None:
     """Initialize parsed url object."""
     self.parse = urlparse(self.url)
     self.bolton = urlutils.URL(self.url)