Fix issue with tests + some cleaning.

This commit is contained in:
grossmj 2021-03-31 09:58:52 +10:30
parent fd844c309e
commit 91920e5a5b
7 changed files with 17 additions and 40 deletions

View File

@ -33,7 +33,6 @@ from gns3server import schemas
from gns3server.controller import Controller from gns3server.controller import Controller
from gns3server.db.repositories.templates import TemplatesRepository from gns3server.db.repositories.templates import TemplatesRepository
from gns3server.services.templates import TemplatesService from gns3server.services.templates import TemplatesService
from .dependencies.database import get_repository from .dependencies.database import get_repository
responses = { responses = {
@ -45,14 +44,14 @@ router = APIRouter(responses=responses)
@router.post("/templates", response_model=schemas.Template, status_code=status.HTTP_201_CREATED) @router.post("/templates", response_model=schemas.Template, status_code=status.HTTP_201_CREATED)
async def create_template( async def create_template(
template_data: schemas.TemplateCreate, template_create: schemas.TemplateCreate,
templates_repo: TemplatesRepository = Depends(get_repository(TemplatesRepository)) templates_repo: TemplatesRepository = Depends(get_repository(TemplatesRepository))
) -> dict: ) -> dict:
""" """
Create a new template. Create a new template.
""" """
return await TemplatesService(templates_repo).create_template(template_data) return await TemplatesService(templates_repo).create_template(template_create)
@router.get("/templates/{template_id}", @router.get("/templates/{template_id}",
@ -84,14 +83,14 @@ async def get_template(
response_model_exclude_unset=True) response_model_exclude_unset=True)
async def update_template( async def update_template(
template_id: UUID, template_id: UUID,
template_data: schemas.TemplateUpdate, template_update: schemas.TemplateUpdate,
templates_repo: TemplatesRepository = Depends(get_repository(TemplatesRepository)) templates_repo: TemplatesRepository = Depends(get_repository(TemplatesRepository))
) -> dict: ) -> dict:
""" """
Update a template. Update a template.
""" """
return await TemplatesService(templates_repo).update_template(template_id, template_data) return await TemplatesService(templates_repo).update_template(template_id, template_update)
@router.delete("/templates/{template_id}", @router.delete("/templates/{template_id}",

View File

@ -110,11 +110,6 @@ class Compute:
self._http_session = aiohttp.ClientSession(connector=connector) self._http_session = aiohttp.ClientSession(connector=connector)
return self._http_session return self._http_session
#def __del__(self):
#
# if self._http_session:
# self._http_session.close()
def _set_auth(self, user, password): def _set_auth(self, user, password):
""" """
Set authentication parameters Set authentication parameters

View File

@ -62,7 +62,7 @@ def _check_topology_schema(topo):
def project_to_topology(project): def project_to_topology(project):
""" """
:return: A dictionnary with the topology ready to dump to a .gns3 :return: A dictionary with the topology ready to dump to a .gns3
""" """
data = { data = {
"project_id": project.id, "project_id": project.id,

View File

@ -15,8 +15,7 @@
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
from sqlalchemy import Boolean, Column, ForeignKey, Integer, String, DateTime, func from sqlalchemy import Boolean, Column, String
from sqlalchemy.orm import relationship
from .base import BaseTable, generate_uuid, GUID from .base import BaseTable, generate_uuid, GUID
@ -32,17 +31,3 @@ class User(BaseTable):
hashed_password = Column(String) hashed_password = Column(String)
is_active = Column(Boolean, default=True) is_active = Column(Boolean, default=True)
is_superuser = Column(Boolean, default=False) is_superuser = Column(Boolean, default=False)
# items = relationship("Item", back_populates="owner")
#
#
# class Item(Base):
# __tablename__ = "items"
#
# id = Column(Integer, primary_key=True, index=True)
# title = Column(String, index=True)
# description = Column(String, index=True)
# owner_id = Column(Integer, ForeignKey("users.id"))
#
# owner = relationship("User", back_populates="items")

View File

@ -93,8 +93,6 @@ class UsersRepository(BaseRepository):
result = await self._db_session.execute(query) result = await self._db_session.execute(query)
await self._db_session.commit() await self._db_session.commit()
return result.rowcount > 0 return result.rowcount > 0
#except:
# await session.rollback()
async def authenticate_user(self, username: str, password: str) -> Optional[models.User]: async def authenticate_user(self, username: str, password: str) -> Optional[models.User]:

View File

@ -154,22 +154,22 @@ class TemplatesService:
templates.append(jsonable_encoder(builtin_template)) templates.append(jsonable_encoder(builtin_template))
return templates return templates
async def create_template(self, template_data: schemas.TemplateCreate) -> dict: async def create_template(self, template_create: schemas.TemplateCreate) -> dict:
try: try:
# get the default template settings # get the default template settings
template_settings = jsonable_encoder(template_data, exclude_unset=True) template_settings = jsonable_encoder(template_create, exclude_unset=True)
template_schema = TEMPLATE_TYPE_TO_SHEMA[template_data.template_type] template_schema = TEMPLATE_TYPE_TO_SHEMA[template_create.template_type]
template_settings_with_defaults = template_schema.parse_obj(template_settings) template_settings_with_defaults = template_schema.parse_obj(template_settings)
settings = template_settings_with_defaults.dict() settings = template_settings_with_defaults.dict()
if template_data.template_type == "dynamips": if template_create.template_type == "dynamips":
# special case for Dynamips to cover all platform types that contain specific settings # special case for Dynamips to cover all platform types that contain specific settings
dynamips_template_schema = DYNAMIPS_PLATFORM_TO_SHEMA[settings["platform"]] dynamips_template_schema = DYNAMIPS_PLATFORM_TO_SHEMA[settings["platform"]]
dynamips_template_settings_with_defaults = dynamips_template_schema.parse_obj(template_settings) dynamips_template_settings_with_defaults = dynamips_template_schema.parse_obj(template_settings)
settings = dynamips_template_settings_with_defaults.dict() settings = dynamips_template_settings_with_defaults.dict()
except pydantic.ValidationError as e: except pydantic.ValidationError as e:
raise ControllerBadRequestError(f"JSON schema error received while creating new template: {e}") raise ControllerBadRequestError(f"JSON schema error received while creating new template: {e}")
db_template = await self._templates_repo.create_template(template_data.template_type, settings) db_template = await self._templates_repo.create_template(template_create.template_type, settings)
template = db_template.asjson() template = db_template.asjson()
self._controller.notification.controller_emit("template.created", template) self._controller.notification.controller_emit("template.created", template)
return template return template
@ -185,14 +185,14 @@ class TemplatesService:
raise ControllerNotFoundError(f"Template '{template_id}' not found") raise ControllerNotFoundError(f"Template '{template_id}' not found")
return template return template
async def update_template(self, template_id: UUID, template_data: schemas.TemplateUpdate) -> dict: async def update_template(self, template_id: UUID, template_update: schemas.TemplateUpdate) -> dict:
if self.get_builtin_template(template_id): if self.get_builtin_template(template_id):
raise ControllerForbiddenError(f"Template '{template_id}' cannot be updated because it is built-in") raise ControllerForbiddenError(f"Template '{template_id}' cannot be updated because it is built-in")
template = await self._templates_repo.update_template(template_id, template_data) db_template = await self._templates_repo.update_template(template_id, template_update)
if not template: if not db_template:
raise ControllerNotFoundError(f"Template '{template_id}' not found") raise ControllerNotFoundError(f"Template '{template_id}' not found")
template = template.asjson() template = db_template.asjson()
self._controller.notification.controller_emit("template.updated", template) self._controller.notification.controller_emit("template.updated", template)
return template return template

View File

@ -62,12 +62,12 @@ async def app() -> FastAPI:
@pytest.fixture(scope="class") @pytest.fixture(scope="class")
def db_engine(): async def db_engine():
db_url = os.getenv("GNS3_TEST_DATABASE_URI", "sqlite+aiosqlite:///:memory:") # "sqlite:///./sql_test_app.db" db_url = os.getenv("GNS3_TEST_DATABASE_URI", "sqlite+aiosqlite:///:memory:") # "sqlite:///./sql_test_app.db"
engine = create_async_engine(db_url, connect_args={"check_same_thread": False}, future=True) engine = create_async_engine(db_url, connect_args={"check_same_thread": False}, future=True)
yield engine yield engine
engine.sync_engine.dispose() #await engine.sync_engine.dispose()
@pytest.fixture(scope="class") @pytest.fixture(scope="class")