def test_group_id() -> None: service = Mock() service.get_group.return_value = Group(id="my-group", name="group") app = create_app(service) client = app.test_client() res = client.get("/groups/1", headers=create_auth_token(app)) assert res.status_code == 200 assert res.json == Group(id="my-group", name="group").to_dict()
def test_is_group_admin(): jwt = JWTUser( id=0, impersonator=0, type="users", groups=[JWTGroup(id="group", name="group", role=RoleType.ADMIN)], ) assert jwt.is_group_admin(Group(id="group")) assert not JWTUser( id=0, impersonator=0, type="users", ).is_group_admin(Group(id="group"))
def test_group_create() -> None: group = Group(id="my-group", name="group") service = Mock() service.save_group.return_value = group app = create_app(service) client = app.test_client() res = client.post( "/groups", headers=create_auth_token(app), json={"name": "group"}, ) assert res.status_code == 200 assert res.json == group.to_dict()
def test_get_user(): user = User(id=3) users = Mock() users.get.return_value = user ldap = Mock() ldap.get.return_value = None role = Role(type=RoleType.READER, identity=user, group=Group(id="group")) roles = Mock() roles.get_all_by_user.return_value = [role] service = LoginService( user_repo=users, bot_repo=Mock(), group_repo=Mock(), role_repo=roles, ldap=ldap, event_bus=Mock(), ) assert_permission( test=lambda x: service.get_user(3, x), values=[(SADMIN, True), (GADMIN, True), (USER3, True)], error=UserNotFoundError, )
def test_authenticate(): users = Mock() users.get_by_name.return_value = User(id=0, password=Password("pwd")) users.get.return_value = User(id=0, name="linus") ldap = Mock() ldap.login.return_value = None ldap.get.return_value = None roles = Mock() roles.get_all_by_user.return_value = [ Role(type=RoleType.READER, group=Group(id="group", name="group")) ] exp = JWTUser( id=0, impersonator=0, type="users", groups=[JWTGroup(id="group", name="group", role=RoleType.READER)], ) service = LoginService( user_repo=users, bot_repo=Mock(), group_repo=Mock(), role_repo=roles, ldap=ldap, event_bus=Mock(), ) assert exp == service.authenticate("dupond", "pwd") users.get_by_name.assert_called_once_with("dupond") roles.get_all_by_user.assert_called_once_with(0)
def _scan(self) -> None: def rec_scan(path: Path, workspace: str, groups: List[Group]) -> List[StudyFolder]: try: if (path / "study.antares").exists(): logger.debug(f"Study {path.name} found in {workspace}") return [StudyFolder(path, workspace, groups)] else: folders: List[StudyFolder] = list() if path.is_dir(): for child in path.iterdir(): folders = folders + rec_scan( child, workspace, groups) return folders except Exception as e: logger.error(f"Failed to scan dir {path}", exc_info=e) return [] studies: List[StudyFolder] = list() for name, workspace in self.config.storage.workspaces.items(): if name != DEFAULT_WORKSPACE_NAME: path = Path(workspace.path) groups = [Group(id=g) for g in workspace.groups] studies = studies + rec_scan(path, name, groups) self.service.sync_studies_on_disk(studies)
def test_scan(tmp_path: Path): clean_files() default = tmp_path / "default" default.mkdir() a = default / "studyA" a.mkdir() (a / "study.antares").touch() diese = tmp_path / "diese" diese.mkdir() c = diese / "folder/studyC" c.mkdir(parents=True) (c / "study.antares").touch() d = diese / "folder/trash" d.mkdir(parents=True) (d / "trash").touch() service = Mock() watcher = Watcher(build_config(tmp_path), service) watcher._scan() service.sync_studies_on_disk.assert_called_once_with([ StudyFolder(c, "diese", [Group(id="tata")]), ])
def test_study_inheritance(): engine = create_engine("sqlite:///:memory:", echo=True) sess = scoped_session( sessionmaker(autocommit=False, autoflush=False, bind=engine)) user = User(id=0, name="admin") group = Group(id="my-group", name="group") Base.metadata.create_all(engine) repo = StudyMetadataRepository(session=sess) a = RawStudy( name="a", version="42", author="John Smith", created_at=datetime.now(), updated_at=datetime.now(), public_mode=PublicMode.FULL, owner=user, groups=[group], workspace=DEFAULT_WORKSPACE_NAME, path="study", content_status=StudyContentStatus.WARNING, ) repo.save(a) b = repo.get(a.id) assert isinstance(b, RawStudy) assert b.path == "study"
def _save_study( self, study: RawStudy, owner: Optional[JWTUser] = None, group_ids: List[str] = list(), content_status: StudyContentStatus = StudyContentStatus.VALID, ) -> None: if not owner: raise UserHasNotPermissionError info = self.study_service.get_study_information(study)["antares"] study.name = info["caption"] study.version = info["version"] study.author = info["author"] study.created_at = datetime.fromtimestamp(info["created"]) study.updated_at = datetime.fromtimestamp(info["lastsave"]) study.content_status = content_status if owner: study.owner = User(id=owner.impersonator) groups = [] for gid in group_ids: group = next(filter(lambda g: g.id == gid, owner.groups), None) if group is None or not group.role.is_higher_or_equals( RoleType.WRITER): raise UserHasNotPermissionError() groups.append(Group(id=group.id, name=group.name)) study.groups = groups self.repository.save(study)
def delete_group(self, id: str, params: RequestParameters) -> None: if params.user and any(( params.user.is_site_admin(), params.user.is_group_admin(Group(id=id)), )): return self.groups.delete(id) else: raise UserHasNotPermissionError()
def __init__(self, session: Session): self.session = session if self.get(1, "admin") is None: self.save( Role( type=RoleType.ADMIN, identity=User(id=1), group=Group(id="admin"), ))
def delete_role(self, user: int, group: str, params: RequestParameters) -> None: if params.user and any(( params.user.is_site_admin(), params.user.is_group_admin(Group(id=group)), )): return self.roles.delete(user, group) else: raise UserHasNotPermissionError()
def test_save_group(): groups = Mock() groups.save.return_value = Group(id="group", name="group") service = LoginService( user_repo=Mock(), bot_repo=Mock(), group_repo=groups, role_repo=Mock(), ldap=Mock(), event_bus=Mock(), ) group = Group(id="group", name="group") assert_permission( test=lambda x: service.save_group(group, x), values=[(SADMIN, True), (GADMIN, True), (USER3, False)], )
def get_all_roles_in_group(self, group: str, params: RequestParameters) -> List[Role]: if params.user and any(( params.user.is_site_admin(), params.user.is_group_admin(Group(id=group)), )): return self.roles.get_all_by_group(group) else: raise UserHasNotPermissionError()
def test_save_metadata() -> None: # Mock repository = Mock() uuid = str(uuid4()) study_service = Mock() study_service.get_study_information.return_value = { "antares": { "caption": "CAPTION", "version": "VERSION", "author": "AUTHOR", "created": 1234, "lastsave": 9876, } } # Input jwt = JWTUser( id=0, impersonator=0, type="users", groups=[JWTGroup(id="my-group", name="group", role=RoleType.ADMIN)], ) user = User(id=0, name="user") group = Group(id="my-group", name="group") # Expected study = RawStudy( id=uuid, name="CAPTION", version="VERSION", author="AUTHOR", created_at=datetime.fromtimestamp(1234), updated_at=datetime.fromtimestamp(9876), content_status=StudyContentStatus.VALID, workspace=DEFAULT_WORKSPACE_NAME, owner=user, groups=[group], ) service = StorageService( study_service=study_service, importer_service=Mock(), exporter_service=Mock(), user_service=Mock(), repository=repository, event_bus=Mock(), ) service._save_study( RawStudy(id=uuid, workspace=DEFAULT_WORKSPACE_NAME), owner=jwt, ) repository.save.assert_called_once_with(study)
def test_role() -> None: role = Role( identity=User(id=0, name="n"), group=Group(id="g", name="n"), type=RoleType.ADMIN, ) service = Mock() service.get_all_roles_in_group.return_value = [role] app = create_app(service) client = app.test_client() res = client.get("/roles/group/g", headers=create_auth_token(app)) assert res.status_code == 200 assert res.json == [role.to_dict()]
def test_groups(): engine = create_engine("sqlite:///:memory:", echo=True) session = scoped_session( sessionmaker(autocommit=False, autoflush=False, bind=engine)) Base.metadata.create_all(engine) repo = GroupRepository(session=session) a = Group(name="a") a = repo.save(a) assert a.id assert a == repo.get(a.id) repo.delete(a.id) assert repo.get(a.id) is None
def test_delete_group(): groups = Mock() groups.delete.return_value = Group() service = LoginService( user_repo=Mock(), bot_repo=Mock(), group_repo=groups, role_repo=Mock(), ldap=Mock(), event_bus=Mock(), ) assert_permission( test=lambda x: service.delete_group("group", x), values=[(SADMIN, True), (GADMIN, True), (USER3, False)], )
def save_bot(self, bot: BotCreateDTO, params: RequestParameters) -> Bot: if params.user: role = self.roles.get(params.user.id, bot.group) if role and role.type.is_higher_or_equals(bot.role): b = self.bots.save( Bot( name=bot.name, is_author=bot.is_author, owner=params.user.id, )) self.roles.save( Role(group=Group(id=bot.group), type=bot.role, identity=b)) return b else: raise UserHasNotPermissionError() else: raise UserHasNotPermissionError()
def test_get_all_groups(): group = Group(id="my-group") groups = Mock() groups.get_all.return_value = [group] service = LoginService( user_repo=Mock(), bot_repo=Mock(), group_repo=groups, role_repo=Mock(), ldap=Mock(), event_bus=Mock(), ) assert_permission( test=lambda x: service.get_all_groups(x), values=[(SADMIN, True), (GADMIN, False), (USER3, False)], )
def test_bot_create() -> None: bot = Bot(id=2, owner=3, name="bot", is_author=False) create = BotCreateDTO(name="bot", group="group", role=RoleType.ADMIN) service = Mock() service.save_bot.return_value = bot service.get_group.return_value = Group(id="group", name="group") app = create_app(service) client = app.test_client() res = client.post( "/bots", headers=create_auth_token(app), json=create.to_dict(), ) assert res.status_code == 200 assert len(res.data.decode().split(".")) == 3
def test_roles(): engine = create_engine("sqlite:///:memory:", echo=True) session = scoped_session( sessionmaker(autocommit=False, autoflush=False, bind=engine)) Base.metadata.create_all(engine) repo = RoleRepository(session=session) a = Role(type=RoleType.ADMIN, identity=User(id=0), group=Group(id="group")) a = repo.save(a) assert a == repo.get(user=0, group="group") assert [a] == repo.get_all_by_user(user=0) assert [a] == repo.get_all_by_group(group="group") repo.delete(user=0, group="group") assert repo.get(user=0, group="group") is None
def test_get_group(): group = Group(id="group", name="group") groups = Mock() groups.get.return_value = group service = LoginService( user_repo=Mock(), bot_repo=Mock(), group_repo=groups, role_repo=Mock(), ldap=Mock(), event_bus=Mock(), ) assert_permission( test=lambda x: service.get_group("group", x), values=[(SADMIN, True), (GADMIN, True), (USER3, False)], error=GroupNotFoundError, )
def test_save_bot(): bot_create = BotCreateDTO(name="bot", group="group", role=RoleType.READER) bots = Mock() bots.save.side_effect = lambda b: b roles = Mock() roles.get.return_value = Role( identity=Identity(id=3), group=Group(id="group"), type=RoleType.WRITER ) service = LoginService( user_repo=Mock(), bot_repo=bots, group_repo=Mock(), role_repo=roles, ldap=Mock(), event_bus=Mock(), ) res = service.save_bot(bot_create, USER3) assert res == Bot(name="bot", is_author=True, owner=3)
def test_cyclelife(): engine = create_engine("sqlite:///:memory:", echo=True) sess = scoped_session( sessionmaker(autocommit=False, autoflush=False, bind=engine)) user = User(id=0, name="admin") group = Group(id="my-group", name="group") Base.metadata.create_all(engine) repo = StudyMetadataRepository(session=sess) a = Study( name="a", version="42", author="John Smith", created_at=datetime.now(), updated_at=datetime.now(), public_mode=PublicMode.FULL, owner=user, groups=[group], ) b = Study( name="b", version="43", author="Morpheus", created_at=datetime.now(), updated_at=datetime.now(), public_mode=PublicMode.FULL, owner=user, groups=[group], ) a = repo.save(a) b = repo.save(b) assert b.id c = repo.get(a.id) assert a == c repo.delete(a.id) assert repo.get(a.id) is None
def test_role_create() -> None: role = Role( identity=User(id=0, name="n"), group=Group(id="g", name="n"), type=RoleType.ADMIN, ) service = Mock() service.save_role.return_value = role app = create_app(service) client = app.test_client() res = client.post( "/roles", headers=create_auth_token(app), json={ "type": RoleType.ADMIN.value, "identity_id": 0, "group_id": "g" }, ) assert res.status_code == 200 assert res.json == role.to_dict()
def test_save_bot_wrong_role(): bot_create = BotCreateDTO(name="bot", group="group", role=RoleType.ADMIN) bots = Mock() bots.save.side_effect = lambda b: b roles = Mock() roles.get.return_value = Role( identity=Identity(id=3), group=Group(id="group"), type=RoleType.READER ) service = LoginService( user_repo=Mock(), bot_repo=bots, group_repo=Mock(), role_repo=roles, ldap=Mock(), event_bus=Mock(), ) assert_permission( test=lambda x: service.save_bot(bot_create, x), values=[(USER3, False)], )
def test_save_role(): role = RoleCreationDTO( type=RoleType.ADMIN, identity_id=0, group_id="group" ) users = Mock() users.get.return_value = User(id=0, name="admin") groups = Mock() groups.get.return_value = Group(id="group", name="some group") roles = Mock() roles.save.return_value = role service = LoginService( user_repo=users, bot_repo=Mock(), group_repo=groups, role_repo=roles, ldap=Mock(), event_bus=Mock(), ) assert_permission( test=lambda x: service.save_role(role, x), values=[(SADMIN, True), (GADMIN, True), (USER3, False)], )
def test_create_study() -> None: # Mock repository = Mock() # Input user = User(id=0, name="user") group = Group(id="my-group", name="group") expected = RawStudy( id=str(uuid4()), name="new-study", version="VERSION", author="AUTHOR", created_at=datetime.fromtimestamp(1234), updated_at=datetime.fromtimestamp(9876), content_status=StudyContentStatus.VALID, workspace=DEFAULT_WORKSPACE_NAME, owner=user, groups=[group], ) study_service = Mock() study_service.get_default_workspace_path.return_value = Path("") study_service.get_study_information.return_value = { "antares": { "caption": "CAPTION", "version": "VERSION", "author": "AUTHOR", "created": 1234, "lastsave": 9876, } } study_service.create_study.return_value = expected service = StorageService( study_service=study_service, importer_service=Mock(), exporter_service=Mock(), user_service=Mock(), repository=repository, event_bus=Mock(), ) with pytest.raises(UserHasNotPermissionError): service.create_study( "new-study", ["my-group"], RequestParameters(JWTUser(id=0, impersonator=0, type="users")), ) service.create_study( "new-study", ["my-group"], RequestParameters( JWTUser( id=0, impersonator=0, type="users", groups=[ JWTGroup(id="my-group", name="group", role=RoleType.WRITER) ], )), ) study_service.create_study.assert_called() repository.save.assert_called_once_with(expected)
def __init__(self, session: Session): self.session = session self.save(Group(id="admin", name="admin"))