Ejemplo n.º 1
0
    def test_auth_missing_auth_users_parameter(self):
        class AuthTestingConfig(TestingConfig):
            AUTH_ENABLED = True

        with pytest.raises(PyodheanServerConfigError,
                           match="Missing AUTH_USERS parameter."):
            create_app(AuthTestingConfig)
Ejemplo n.º 2
0
    def test_auth_missing_auth_users_db_file(self, tmp_path):
        users_db_file = tmp_path / 'users.db'

        class AuthTestingConfig(TestingConfig):
            AUTH_ENABLED = True
            AUTH_USERS = str(users_db_file)

        with pytest.raises(PyodheanServerConfigError,
                           match="Missing users DB file."):
            create_app(AuthTestingConfig)
Ejemplo n.º 3
0
    def test_request_response_logging(
        self, json_input, tmp_path, celery_worker
    ):

        # Pass io files directory to Flask app config
        class IOLoggerTestingConfig(TestingConfig):
            IO_FILES_DIR = str(tmp_path)

        app = create_app(IOLoggerTestingConfig)
        client = app.test_client()

        # Pass io files directory to Celery app config
        celery_worker.app.conf['io_files_dir'] = str(tmp_path)

        # Post task
        response = client.post('/solver/tasks/', json=json_input)
        task_id = response.json['task_id']

        # Check request is logged
        log_files = list(tmp_path.iterdir())
        assert len(log_files) == 1
        request_file = log_files[0]
        assert request_file.name == f"{task_id}-request.json"
        assert json.load(request_file.open()) == json_input

        # Wait until task is completed
        while client.get(
                '/solver/tasks/{}/status'.format(task_id)
        ).json['status'] in ('waiting', 'ongoing'):
            time.sleep(0.1)

        # Query task result
        response = client.get('/solver/tasks/{}/result'.format(task_id))
        assert response.status_code == 200
        result = response.json
        assert result['status'] == 'ok'
        assert 'solution' in result

        # Check response is logged
        log_files = list(tmp_path.iterdir())
        assert len(log_files) == 2
        response_file = next(
            f for f in log_files if f.name == f"{task_id}-response.json"
        )
        # We can't test that response_file == response.json because the
        # response is modified by API schemas.
        assert 'solution' in json.load(response_file.open())
Ejemplo n.º 4
0
    def test_auth_resource(self, tmp_path):
        """Test authentication feature

        Only "status" route is tested. The point is only to test the feature.
        """

        # Create users database file
        users_db_file = tmp_path / 'users.db'
        with open(users_db_file, 'w') as users_db:
            users_db.write(','.join(('test', generate_password_hash('test'))))

        class AuthTestingConfig(TestingConfig):
            AUTH_ENABLED = True
            AUTH_USERS = str(users_db_file)

        app = create_app(AuthTestingConfig)
        client = app.test_client()

        # Missing credentials
        response = client.get('/solver/tasks/{}/status'.format(DUMMY_TASK_ID))
        assert response.status_code == 401
        assert response.json["message"] == "Authentication error"

        # Wrong credentials
        creds = base64.b64encode('test:wrong'.encode()).decode()
        response = client.get(
            '/solver/tasks/{}/status'.format(DUMMY_TASK_ID),
            headers={'Authorization': 'Basic ' + creds},
        )
        assert response.status_code == 401
        assert response.json["message"] == "Authentication error"

        # Right credentials
        creds = base64.b64encode('test:test'.encode()).decode()
        response = client.get(
            '/solver/tasks/{}/status'.format(DUMMY_TASK_ID),
            headers={'Authorization': 'Basic ' + creds},
        )
        assert response.status_code == 404
Ejemplo n.º 5
0
def init_app(request):
    """Initialize test application"""
    request.cls.app = create_app(request.param)
    request.cls.client = request.cls.app.test_client()
Ejemplo n.º 6
0
"""PyODHeaN solver API example"""
# pylint: disable=invalid-name

import time
from pprint import pprint

from pyodhean_server.app import create_app


app = create_app()

json_input = {
    'nodes': {
        'production': [
            # P1
            {
                'id': [0.0, 0.0],
                'technologies': {
                    'k1': {
                        'efficiency': 0.9,
                        't_out_max': 100,
                        't_in_min': 30,
                        'production_unitary_cost': 800,
                        'energy_unitary_cost': 0.08,
                        'energy_cost_inflation_rate': 0.04,
                        'coverage_rate': 0.80,
                    },
                    'k2': {
                        'efficiency': 0.9,
                        't_out_max': 100,
                        't_in_min': 30,