Fix not creating tags with providers; check if default org is created

This commit is contained in:
Xavier Bustamante Talavera 2018-09-29 19:39:38 +02:00
parent f80e6a0764
commit 517c21789d
6 changed files with 34 additions and 14 deletions

View File

@ -9,9 +9,9 @@ from sqlalchemy.ext.declarative import declared_attr
from sqlalchemy.orm import backref, relationship, validates from sqlalchemy.orm import backref, relationship, validates
from sqlalchemy_utils import EmailType, PhoneNumberType from sqlalchemy_utils import EmailType, PhoneNumberType
from teal import enums from teal import enums
from teal.db import INHERIT_COND, POLYMORPHIC_ID, \ from teal.db import DBError, INHERIT_COND, POLYMORPHIC_ID, POLYMORPHIC_ON
POLYMORPHIC_ON
from teal.marshmallow import ValidationError from teal.marshmallow import ValidationError
from werkzeug.exceptions import NotImplemented, UnprocessableEntity
from ereuse_devicehub.resources.models import STR_SIZE, STR_SM_SIZE, Thing from ereuse_devicehub.resources.models import STR_SIZE, STR_SM_SIZE, Thing
from ereuse_devicehub.resources.user.models import User from ereuse_devicehub.resources.user.models import User
@ -85,10 +85,15 @@ class Organization(JoinedTableMixin, Agent):
@classmethod @classmethod
def get_default_org_id(cls) -> UUID: def get_default_org_id(cls) -> UUID:
"""Retrieves the default organization.""" """Retrieves the default organization."""
try:
return g.setdefault('org_id', return g.setdefault('org_id',
Organization.query.filter_by( Organization.query.filter_by(
**app.config.get_namespace('ORGANIZATION_') **app.config.get_namespace('ORGANIZATION_')
).one().id) ).one().id)
except (DBError, UnprocessableEntity):
# todo test how well this works
raise NotImplemented('Error in getting the default organization. '
'Is the DB initialized?')
class Individual(JoinedTableMixin, Agent): class Individual(JoinedTableMixin, Agent):

View File

@ -19,7 +19,7 @@ class TagDef(Resource):
ORG_H = 'The name of an existing organization in the DB. ' ORG_H = 'The name of an existing organization in the DB. '
'By default the organization operating this Devicehub.' 'By default the organization operating this Devicehub.'
PROV_H = 'The Base URL of the provider. ' PROV_H = 'The Base URL of the provider; scheme + domain. Ex: "https://foo.com". '
'By default set to the actual Devicehub.' 'By default set to the actual Devicehub.'
CLI_SCHEMA = schema.Tag(only=('id', 'provider', 'org', 'secondary')) CLI_SCHEMA = schema.Tag(only=('id', 'provider', 'org', 'secondary'))
@ -56,7 +56,7 @@ class TagDef(Resource):
org: str = None, org: str = None,
sec: str = None, sec: str = None,
provider: str = None): provider: str = None):
"""Create TAGS and associates them to a specific PROVIDER.""" """Create a tag with the given ID."""
db.session.add(Tag(**self.schema.load( db.session.add(Tag(**self.schema.load(
dict(id=id, org=org, secondary=sec, provider=provider) dict(id=id, org=org, secondary=sec, provider=provider)
))) )))

View File

@ -40,9 +40,7 @@ class Tag(Thing):
secondary = Column(Unicode()) secondary = Column(Unicode())
secondary.comment = """ secondary.comment = """
A secondary identifier for this tag. It has the same A secondary identifier for this tag. It has the same
constraints as the main one. constraints as the main one. Only needed in special cases.
Only needed in special cases.
""" """
def __init__(self, id: str, **kwargs) -> None: def __init__(self, id: str, **kwargs) -> None:

View File

@ -26,6 +26,6 @@ requests==2.19.1
requests-mock==1.5.2 requests-mock==1.5.2
SQLAlchemy==1.2.11 SQLAlchemy==1.2.11
SQLAlchemy-Utils==0.33.3 SQLAlchemy-Utils==0.33.3
teal==0.2.0a16 teal==0.2.0a19
webargs==4.0.0 webargs==4.0.0
Werkzeug==0.14.1 Werkzeug==0.14.1

View File

@ -34,7 +34,7 @@ setup(
long_description=long_description, long_description=long_description,
long_description_content_type='text/markdown', long_description_content_type='text/markdown',
install_requires=[ install_requires=[
'teal>=0.2.0a18', # teal always first 'teal>=0.2.0a19', # teal always first
'click', 'click',
'click-spinner', 'click-spinner',
'ereuse-rate==0.0.2', 'ereuse-rate==0.0.2',

View File

@ -1,6 +1,7 @@
import pathlib import pathlib
import pytest import pytest
from boltons.urlutils import URL
from pytest import raises from pytest import raises
from teal.db import MultipleResourcesFound, ResourceNotFound, UniqueViolation from teal.db import MultipleResourcesFound, ResourceNotFound, UniqueViolation
from teal.marshmallow import ValidationError from teal.marshmallow import ValidationError
@ -21,9 +22,12 @@ from tests import conftest
def test_create_tag(): def test_create_tag():
"""Creates a tag specifying a custom organization.""" """Creates a tag specifying a custom organization."""
org = Organization(name='Bar', tax_id='BarTax') org = Organization(name='Bar', tax_id='BarTax')
tag = Tag(id='bar-1', org=org) tag = Tag(id='bar-1', org=org, provider=URL('http://foo.bar'))
db.session.add(tag) db.session.add(tag)
db.session.commit() db.session.commit()
tag = Tag.query.one()
assert tag.id == 'bar-1'
assert tag.provider == URL('http://foo.bar')
@pytest.mark.usefixtures(conftest.app_context.__name__) @pytest.mark.usefixtures(conftest.app_context.__name__)
@ -136,6 +140,19 @@ def test_tag_create_tags_cli(app: Devicehub, user: UserClient):
assert tag.org.id == Organization.get_default_org_id() assert tag.org.id == Organization.get_default_org_id()
def test_tag_create_etags_cli(app: Devicehub, user: UserClient):
"""Creates an eTag through the CLI."""
# todo what happens to organization?
runner = app.test_cli_runner()
runner.invoke(args=['create-tag', '-p', 'https://t.ereuse.org', '-s', 'foo', 'DT-BARBAR'],
catch_exceptions=False)
with app.app_context():
tag = Tag.query.one() # type: Tag
assert tag.id == 'DT-BARBAR'
assert tag.secondary == 'foo'
assert tag.provider == URL('https://t.ereuse.org')
def test_tag_manual_link(app: Devicehub, user: UserClient): def test_tag_manual_link(app: Devicehub, user: UserClient):
"""Tests linking manually a tag through PUT /tags/<id>/device/<id>""" """Tests linking manually a tag through PUT /tags/<id>/device/<id>"""
with app.app_context(): with app.app_context():