def test_service_factory(): config = Config() event_bus = build_eventbus(MagicMock(), config, autostart=False) assert event_bus.backend.__class__.__name__ == "LocalEventBus" config = Config( eventbus=EventBusConfig(redis=RedisConfig(host="localhost")) ) with pytest.raises(redis.exceptions.ConnectionError): # this error implies that this is the redis one... build_eventbus(MagicMock(), config, autostart=False)
def test_users(): engine = create_engine("sqlite:///:memory:", echo=True) session = scoped_session( sessionmaker(autocommit=False, autoflush=False, bind=engine)) Base.metadata.create_all(engine) repo = UserRepository( config=Config(security=SecurityConfig(admin_pwd="admin")), session=session, ) a = User( name="a", password=Password("a"), ) b = User(name="b", password=Password("b")) a = repo.save(a) b = repo.save(b) assert b.id c = repo.get(a.id) assert a == c assert a.password.check("a") assert b == repo.get_by_name("b") repo.delete(a.id) assert repo.get(a.id) is None
def build_storage_service( study_factory=Mock(), exporter=Mock(), session=Mock(), path_studies=Path(), path_resources=Path(), user_service=Mock(), ) -> StorageService: config = Config( resources_path=path_resources, security=SecurityConfig(disabled=True), storage=StorageConfig( workspaces={ DEFAULT_WORKSPACE_NAME: WorkspaceConfig(path=path_studies) }), ) return build_storage( application=Mock(), config=config, session=session, user_service=user_service, study_factory=study_factory, exporter=exporter, )
def test_exporter_file(tmp_path: Path, sta_mini_zip_path: Path): path_studies = tmp_path / "studies" with ZipFile(sta_mini_zip_path) as zip_output: zip_output.extractall(path=path_studies) config = Config( resources_path=Path(), security=SecurityConfig(disabled=True), storage=StorageConfig( workspaces={ DEFAULT_WORKSPACE_NAME: WorkspaceConfig(path=path_studies) } ), ) md = RawStudy( id="STA-mini", workspace=DEFAULT_WORKSPACE_NAME, path=str(path_studies / "STA-mini"), ) repo = Mock() repo.get.return_value = md service = build_storage( application=Mock(), config=config, session=Mock(), user_service=Mock(), metadata_repository=repo, ) data = assert_url_content(service, url="/studies/STA-mini/export") assert_data(data)
def test_get_yaml(project_path: Path): config = Config.from_yaml_file(file=project_path / "resources/application.yaml") assert config.security.admin_pwd == "admin" assert config.storage.workspaces["default"].path == Path( "examples/studies/") assert config.logging.level == "INFO"
def build_config(root: Path) -> Config: return Config(storage=StorageConfig( workspaces={ DEFAULT_WORKSPACE_NAME: WorkspaceConfig(path=root / DEFAULT_WORKSPACE_NAME, groups=["toto"]), "diese": WorkspaceConfig(path=root / "diese", groups=["tata"]), }))
def create_app(service: Mock) -> Flask: app = Flask(__name__) build_launcher( app, service_launcher=service, config=Config(security=SecurityConfig(disabled=True)), db_session=Mock(), ) return app
def test_lifecycle(): event_bus = build_eventbus(MagicMock(), Config(), autostart=True) test_bucket = [] lid = event_bus.add_listener(lambda event: test_bucket.append(event)) event = Event("test", "foo") event_bus.push(event) autoretry(lambda: len(test_bucket) == 1, 2) event_bus.remove_listener(lid) test_bucket.clear() event_bus.push(event) autoretry(lambda: len(test_bucket) == 0, 2)
def create_app(service: Mock, auth_disabled=False) -> Flask: app = Flask(__name__) app.config["SECRET_KEY"] = "super-secret" app.config["JWT_TOKEN_LOCATION"] = ["cookies", "headers"] build_login( app, service=service, config=Config( resources_path=Path(), security=SecurityConfig(disabled=auth_disabled), ), db_session=Mock(), ) return app
def test_ldap(): config = Config(security=SecurityConfig(ldap_url="http://localhost:8869")) repo = Mock() repo.get_by_name.return_value = None repo.save.side_effect = lambda x: x ldap = LdapService(config=config, users=repo) # Start server httpd = HTTPServer(("localhost", 8869), MockServerHandler) server = threading.Thread(None, httpd.handle_request) server.start() res = ldap.login(name="John", password="******") assert res assert "John" == res.name repo.save.assert_called_once_with(UserLdap(name="John"))
def test_version() -> None: mock_storage_service = Mock() mock_storage_service.study_service.path_resources = Path("/") app = Flask(__name__) build_storage( app, storage_service=mock_storage_service, session=Mock(), config=Config(), user_service=Mock(), ) client = app.test_client() path = "/version" result = client.get(path) assert result.status_code == HTTPStatus.OK.value assert json.loads(result.data)["version"] == __version__
def test_compute(): local_launcher = LocalLauncher(Config()) uuid = uuid4() expected_execution_result = JobResult( id=str(uuid), job_status=JobStatus.SUCCESS, msg="Hello, World!", exit_code=0, ) callback = Mock() local_launcher.add_callback(callback) local_launcher._compute(antares_solver_path="echo", study_path="Hello, World!", uuid=uuid) callback.assert_called_once_with(expected_execution_result)
def storage_service(tmp_path: str, project_path: Path, sta_mini_zip_path: Path) -> StorageService: path_studies = Path(tmp_path) / "studies" path_resources = project_path / "resources" with ZipFile(sta_mini_zip_path) as zip_output: zip_output.extractall(path=path_studies) md = RawStudy( id="STA-mini", workspace=DEFAULT_WORKSPACE_NAME, path=str(path_studies / "STA-mini"), ) repo = Mock() repo.get.side_effect = lambda name: RawStudy( id=name, workspace=DEFAULT_WORKSPACE_NAME, path=str(path_studies / name), ) repo.get_all.return_value = [md] config = Config( resources_path=path_resources, security=SecurityConfig(disabled=True), storage=StorageConfig( workspaces={ DEFAULT_WORKSPACE_NAME: WorkspaceConfig(path=path_studies) }), ) storage_service = build_storage( application=Mock(), session=Mock(), user_service=Mock(), config=config, metadata_repository=repo, ) return storage_service
def build_config(study_path: Path): return Config(storage=StorageConfig( workspaces={DEFAULT_WORKSPACE_NAME: WorkspaceConfig(path=study_path)}))
from antarest import __version__ from antarest.common.config import ( Config, SecurityConfig, StorageConfig, WorkspaceConfig, ) from antarest.storage.main import build_storage from antarest.storage.model import DEFAULT_WORKSPACE_NAME CONFIG = Config( resources_path=Path(), security=SecurityConfig(disabled=True), storage=StorageConfig( workspaces={DEFAULT_WORKSPACE_NAME: WorkspaceConfig(path=Path())} ), ) @pytest.mark.unit_test def test_version() -> None: mock_storage_service = Mock() mock_storage_service.study_service.path_resources = Path("/") app = Flask(__name__) build_storage( app, storage_service=mock_storage_service,
def flask_app(config_file: Path, resource_path: Optional[Path] = None) -> Flask: res = resource_path or get_local_path() / "resources" config = Config.from_yaml_file(res=res, file=config_file) configure_logger(config) # Database engine = create_engine(config.db_url, echo=config.debug) Base.metadata.create_all(engine) db_session = scoped_session( sessionmaker(autocommit=False, autoflush=False, bind=engine)) application = Flask(__name__, static_url_path="/static", static_folder=str(res / "webapp")) application.wsgi_app = ReverseProxyMiddleware( application.wsgi_app) # type: ignore application.config["SECRET_KEY"] = config.security.jwt_key application.config["JWT_ACCESS_TOKEN_EXPIRES"] = Auth.ACCESS_TOKEN_DURATION application.config[ "JWT_REFRESH_TOKEN_EXPIRES"] = Auth.REFRESH_TOKEN_DURATION application.config["JWT_TOKEN_LOCATION"] = ["headers", "cookies"] @application.route("/", methods=["GET"]) def home() -> Any: """ Home ui --- responses: '200': content: application/html: {} description: html home page tags: - UI """ return render_template("index.html") @application.teardown_appcontext def shutdown_session(exception: Any = None) -> None: Auth.invalidate() db_session.remove() @application.errorhandler(HTTPException) def handle_exception(e: Any) -> Tuple[Any, Number]: """Return JSON instead of HTML for HTTP errors.""" # start with the correct headers and status code from the error response = e.get_response() # replace the body with JSON response.data = json.dumps({ "name": e.name, "description": e.description, }) response.content_type = "application/json" return response, e.code event_bus = build_eventbus(application, config) user_service = build_login(application, config, db_session, event_bus=event_bus) storage = build_storage( application, config, db_session, user_service=user_service, event_bus=event_bus, ) build_launcher( application, config, db_session, service_storage=storage, event_bus=event_bus, ) build_swagger(application) return application