Esempio n. 1
0
def generate_database_entries(entries_to_generate=1,
                              base_port=8000,
                              base_issuer="issuer",
                              base_instance_id="id",
                              base_config_file_dict_value="value",
                              static_port_value=None,
                              static_issuer_value=None,
                              static_instance_id_value=None,
                              static_port_type_value=None):
    index = 0
    database = PortDatabase(is_port_used_func=is_port_used_func)
    while index < entries_to_generate:
        port = set_base_attribute(base_port, static_port_value, index)
        issuer = set_base_attribute(base_issuer, static_issuer_value,
                                    str(index))
        instance_id = set_base_attribute(base_instance_id,
                                         static_instance_id_value, str(index))
        port_type = set_port_type(index, static_port_type_value)
        config_file = {"key": base_config_file_dict_value + str(index)}

        database.upsert(port=port,
                        issuer=issuer,
                        instance_id=instance_id,
                        port_type=port_type,
                        config_file=config_file)
        index = index + 1
    return database
Esempio n. 2
0
 def _allocate_next_free_port(self):
     port_db = PortDatabase(is_port_used_func=is_port_used_by_another_process)
     return port_db.allocate_port("issuer",
                                  "instance_id",
                                  PortDatabase.STATIC_PORT_TYPE,
                                  8000,
                                  8100)
 def test_get_next_unused_port(self):
     is_port_used_func = Mock()
     is_port_used_func.side_effect = [True, True,
                                      False]  # Inicates that the two first ports are used
     database = PortDatabase(is_port_used_func=is_port_used_func)
     port = database._get_next_free_port(min_port=8000, max_port=8005)
     assert port == 8002
Esempio n. 4
0
def uses_dynamic_client_reg(issuer, instance_id):
    port_database = PortDatabase(CONF.PORT_DATABASE_FILE)
    port = port_database.get_existing_port(
        issuer=issuer,
        instance_id=instance_id,
        port_type=PortDatabase.DYNAMIC_PORT_TYPE)
    return port
Esempio n. 5
0
def handle_load_existing_contact_info(response_encoder, parameters):
    if ISSUER_QUERY_KEY in parameters:
        port_db = PortDatabase(CONF.PORT_DATABASE_FILE)
        email = port_db.identify_existing_contact_info(parameters[ISSUER_QUERY_KEY])
        if email:
            response_info = {"existing_email": email}
            return response_encoder.return_json(json.dumps(response_info))
        return response_encoder.return_json("{}")
    return response_encoder.bad_request()
Esempio n. 6
0
def handle_load_existing_contact_info(response_encoder, parameters):
    if ISSUER_QUERY_KEY in parameters:
        port_db = PortDatabase(CONF.PORT_DATABASE_FILE)
        email = port_db.identify_existing_contact_info(
            parameters[ISSUER_QUERY_KEY])
        if email:
            response_info = {"existing_email": email}
            return response_encoder.return_json(json.dumps(response_info))
        return response_encoder.return_json("{}")
    return response_encoder.bad_request()
    def test_create_multiple_in_memory_database(self):
        db1 = PortDatabase(is_port_used_func=is_port_used_func)
        db1.upsert(8001, "issuer1", "id1", PortDatabase.STATIC_PORT_TYPE)

        db2 = PortDatabase(is_port_used_func=is_port_used_func)
        db2.upsert(8002, "issuer2", "id2", PortDatabase.STATIC_PORT_TYPE)

        assert not os.path.isfile(":memory:")
        assert db1.get_all_ports() == [8001]
        assert db2.get_all_ports() == [8002]
Esempio n. 8
0
def handle_submit_contact_info(response_encoder, parameters):
    if 'issuer' not in parameters or 'email' not in parameters:
        return response_encoder.bad_request()

    issuer = parameters['issuer']
    email = parameters['email']

    port_db = PortDatabase(CONF.PORT_DATABASE_FILE)
    port_db.set_email_info(issuer, email)

    ports = port_db.get_ports(issuer)
    set_email_to_file(ports, email, CONF)

    return_info = {'issuer': issuer, 'existing_email': email}
    return response_encoder.return_json(json.dumps(return_info))
Esempio n. 9
0
def handle_submit_contact_info(response_encoder, parameters):
    if 'issuer' not in parameters or 'email' not in parameters:
        return response_encoder.bad_request()

    issuer = parameters['issuer']
    email = parameters['email']

    port_db = PortDatabase(CONF.PORT_DATABASE_FILE)
    port_db.set_email_info(issuer, email)

    ports = port_db.get_ports(issuer)
    set_email_to_file(ports, email, CONF)

    return_info = {'issuer': issuer, 'existing_email': email}
    return response_encoder.return_json(json.dumps(return_info))
Esempio n. 10
0
def handle_restart_test_instance(response_encoder, parameters):
    if ISSUER_QUERY_KEY in parameters and INSTANCE_ID_QUERY_KEY in parameters:
        issuer = remove_last_slash(parameters[ISSUER_QUERY_KEY])
        instance_id = parameters[INSTANCE_ID_QUERY_KEY]
        port_database = PortDatabase(CONF.PORT_DATABASE_FILE)
        configurations = port_database.get_configuration(issuer, instance_id)
        if not configurations:
            raise MissingConfigurations(
                "Failed to load the configuration for the given test instance",
                log_info="No configuration from test instance issuer: "
                         "%s instance_id: %s" % (issuer, instance_id),
                show_trace=False)
        port = port_database.get_port(issuer, instance_id)
        profile = configurations['behaviour']['profile']
        return restart_test_instance(instance_id, port, profile, response_encoder, configurations)
    return response_encoder.bad_request()
Esempio n. 11
0
def handle_restart_test_instance(response_encoder, parameters):
    if ISSUER_QUERY_KEY in parameters and INSTANCE_ID_QUERY_KEY in parameters:
        issuer = remove_last_slash(parameters[ISSUER_QUERY_KEY])
        instance_id = parameters[INSTANCE_ID_QUERY_KEY]
        port_database = PortDatabase(CONF.PORT_DATABASE_FILE)
        configurations = port_database.get_configuration(issuer, instance_id)
        if not configurations:
            raise MissingConfigurations(
                "Failed to load the configuration for the given test instance",
                log_info="No configuration from test instance issuer: "
                         "%s instance_id: %s" % (issuer, instance_id),
                show_trace=False)
        port = port_database.get_port(issuer, instance_id)
        profile = configurations['behaviour']['profile']
        return restart_test_instance(instance_id, port, profile, response_encoder, configurations)
    return response_encoder.bad_request()
Esempio n. 12
0
def handle_get_redirect_url(session, response_encoder, parameters):
    if INSTANCE_ID_QUERY_KEY not in session:
        raise MissingSessionInformation(
            "No ID for the current test instance "
            "configuration where found in the session",
            show_trace=False)
    if 'issuer' not in parameters:
        return response_encoder.bad_request()

    if IS_RECONFIGURING not in session:
        raise MissingSessionInformation(
            "Could not find a required attribute in the session",
            show_trace=False)
    instance_id = session[INSTANCE_ID_QUERY_KEY]
    issuer = parameters['issuer']
    response = {}

    if session[IS_RECONFIGURING]:
        if uses_dynamic_client_reg(issuer, instance_id):
            response['info'] = "While reconfiguring a test instance it is not possible to " \
                               "change whether your openID provider supports 'client " \
                               "registration' or not. In order to change this feature please " \
                               "create a new test instance"
        port_database = PortDatabase(CONF.PORT_DATABASE_FILE)
        port = port_database.get_port(issuer, instance_id)
    else:
        try:
            port = allocate_static_port(issuer, instance_id)
        except NoPortAvailable:
            raise NoStaticClientRegPortAvailable(
                "No ports for test instances using static client "
                "registration is available at the moment, "
                "please try "
                "again later.",
                log_info="Failed to allocate a port used for "
                "static "
                "client registration since no port "
                "where available.",
                show_trace=False)
    session['port'] = port
    redirect_url = get_base_url(port) + "authz_cb"
    response['redirect_url'] = redirect_url
    return response_encoder.return_json(json.dumps(response))
Esempio n. 13
0
def handle_request_instance_ids(response_encoder, parameters):
    if 'issuer' not in parameters:
        return response_encoder.bad_request()

    issuer = parameters['issuer']
    port_db = PortDatabase(CONF.PORT_DATABASE_FILE)
    instance_ids = port_db.get_instance_ids(issuer)

    return_info = {}
    for instance_id in instance_ids:
        port = port_db.get_port(issuer=issuer, instance_id=instance_id)
        contains_config = does_configuration_exists(port_db,
                                                    issuer=issuer,
                                                    instance_id=instance_id,
                                                    conf=CONF)
        return_info[instance_id] = {"url": get_base_url(port),
                                    "port": port,
                                    "contains_config": contains_config}

    return response_encoder.return_json(json.dumps(return_info))
Esempio n. 14
0
def generate_database_entries(entries_to_generate=1, base_port=BASE_PORT, base_issuer=BASE_ISSUER,
                              base_instance_id="id", base_config_file_dict_value="value",
                              static_port_value=None, static_issuer_value=None,
                              static_instance_id_value=None, static_port_type_value=None):
    index = 0
    database = PortDatabase(is_port_used_func=is_port_used_func)
    while index < entries_to_generate:
        port = set_base_attribute(base_port, static_port_value, index)
        issuer = set_base_attribute(base_issuer, static_issuer_value, str(index))
        instance_id = set_base_attribute(base_instance_id, static_instance_id_value, str(index))
        port_type = set_port_type(index, static_port_type_value)
        config_file = {"key": base_config_file_dict_value + str(index)}

        database.upsert(port=port,
                        issuer=issuer,
                        instance_id=instance_id,
                        port_type=port_type,
                        config_file=config_file)
        index = index + 1
    return database
Esempio n. 15
0
def handle_request_instance_ids(response_encoder, parameters):
    if 'issuer' not in parameters:
        return response_encoder.bad_request()

    issuer = parameters['issuer']
    port_db = PortDatabase(CONF.PORT_DATABASE_FILE)
    instance_ids = port_db.get_instance_ids(issuer)

    return_info = {}
    for instance_id in instance_ids:
        port = port_db.get_port(issuer=issuer, instance_id=instance_id)
        contains_config = does_configuration_exists(port_db,
                                                    issuer=issuer,
                                                    instance_id=instance_id,
                                                    conf=CONF)
        return_info[instance_id] = {"url": get_base_url(port),
                                    "port": port,
                                    "contains_config": contains_config}

    return response_encoder.return_json(json.dumps(return_info))
Esempio n. 16
0
def handle_get_redirect_url(session, response_encoder, parameters):
    if INSTANCE_ID_QUERY_KEY not in session:
        raise MissingSessionInformation("No ID for the current test instance "
                                        "configuration where found in the session",
                                        show_trace=False)
    if 'issuer' not in parameters:
        return response_encoder.bad_request()

    if IS_RECONFIGURING not in session:
        raise MissingSessionInformation("Could not find a required attribute in the session",
                                        show_trace=False)
    instance_id = session[INSTANCE_ID_QUERY_KEY]
    issuer = parameters['issuer']
    response = {}

    if session[IS_RECONFIGURING]:
        if uses_dynamic_client_reg(issuer, instance_id):
            response['info'] = "While reconfiguring a test instance it is not possible to " \
                               "change whether your openID provider supports 'client " \
                               "registration' or not. In order to change this feature please " \
                               "create a new test instance"
        port_database = PortDatabase(CONF.PORT_DATABASE_FILE)
        port = port_database.get_port(issuer, instance_id)
    else:
        try:
            port = allocate_static_port(issuer, instance_id)
        except NoPortAvailable:
            raise NoStaticClientRegPortAvailable("No ports for test instances using static client "
                                                 "registration is available at the moment, "
                                                 "please try "
                                                 "again later.",
                                                 log_info="Failed to allocate a port used for "
                                                          "static "
                                                          "client registration since no port "
                                                          "where available.",
                                                 show_trace=False)
    session['port'] = port
    redirect_url = get_base_url(port) + "authz_cb"
    response['redirect_url'] = redirect_url
    return response_encoder.return_json(json.dumps(response))
Esempio n. 17
0
def handle_load_existing_config(response_encoder, session, parameters):
    if ISSUER_QUERY_KEY in parameters and INSTANCE_ID_QUERY_KEY in parameters:
        configurations = load_configuration_from_database(parameters)

        if not configurations:
            issuer = remove_last_slash(parameters[ISSUER_QUERY_KEY])
            instance_id = parameters[INSTANCE_ID_QUERY_KEY]
            port_db = PortDatabase(CONF.PORT_DATABASE_FILE)
            port = port_db.get_port(issuer, instance_id)
            configurations = identify_existing_config_file(port, CONF.OPRP_DIR_PATH)

        store_query_parameter(parameters, session, ISSUER_QUERY_KEY)
        store_query_parameter(parameters, session, INSTANCE_ID_QUERY_KEY)

        if configurations:
            session[OP_CONFIG] = configurations
        else:
            session[OP_CONFIG] = get_default_client()

        session[IS_RECONFIGURING] = True
        return response_encoder.return_json("{}")
    return response_encoder.bad_request()
Esempio n. 18
0
def handle_load_existing_config(response_encoder, session, parameters):
    if ISSUER_QUERY_KEY in parameters and INSTANCE_ID_QUERY_KEY in parameters:
        configurations = load_configuration_from_database(parameters)

        if not configurations:
            issuer = remove_last_slash(parameters[ISSUER_QUERY_KEY])
            instance_id = parameters[INSTANCE_ID_QUERY_KEY]
            port_db = PortDatabase(CONF.PORT_DATABASE_FILE)
            port = port_db.get_port(issuer, instance_id)
            configurations = identify_existing_config_file(port, CONF.OPRP_DIR_PATH)

        store_query_parameter(parameters, session, ISSUER_QUERY_KEY)
        store_query_parameter(parameters, session, INSTANCE_ID_QUERY_KEY)

        if configurations:
            session[OP_CONFIG] = configurations
        else:
            session[OP_CONFIG] = get_default_client()

        session[IS_RECONFIGURING] = True
        return response_encoder.return_json("{}")
    return response_encoder.bad_request()
Esempio n. 19
0
def save_config_info_in_database(_port, configurations):
    port_db = PortDatabase(CONF.PORT_DATABASE_FILE)
    row = port_db.get_row_by_port(_port)
    port_db.upsert_row(row, configurations)
 def test_create_database_file(self):
     database_file = "./test.db"
     PortDatabase(database_file, is_port_used_func=is_port_used_func)
     assert os.path.isfile(database_file)
     os.remove(database_file)
Esempio n. 21
0
def is_port_in_database(_port):
    port_db = PortDatabase(CONF.PORT_DATABASE_FILE)
    return port_db.get_row_by_port(_port) is None
def setup_empty_database():
    return PortDatabase(is_port_used_func=is_port_used_func)
 def port_db_editor(self):
     self.port_db_editor = PortDatabaseEditor()
     self.database = PortDatabase()
Esempio n. 24
0
def get_port_from_database(issuer, instance_id, min_port, max_port, port_type):
    is_port_unused_func = is_port_used_by_another_process
    port_db = PortDatabase(CONF.PORT_DATABASE_FILE, is_port_unused_func)
    return port_db.allocate_port(issuer, instance_id, port_type, min_port,
                                 max_port)
Esempio n. 25
0
def save_config_info_in_database(_port, configurations):
    port_db = PortDatabase(CONF.PORT_DATABASE_FILE)
    row = port_db.get_row_by_port(_port)
    port_db.upsert_row(row, configurations)
Esempio n. 26
0
def get_port_from_database(issuer, instance_id, min_port, max_port, port_type):
    is_port_unused_func = is_port_used_by_another_process
    port_db = PortDatabase(CONF.PORT_DATABASE_FILE, is_port_unused_func)
    return port_db.allocate_port(issuer, instance_id, port_type, min_port, max_port)
 def port_db_editor(self):
     self.port_db_editor = PortDatabaseEditor()
     self.database = PortDatabase()
Esempio n. 28
0
def load_configuration_from_database(parameters):
    issuer = remove_last_slash(parameters[ISSUER_QUERY_KEY])
    instance_id = parameters[INSTANCE_ID_QUERY_KEY]
    port_database = PortDatabase(CONF.PORT_DATABASE_FILE)
    configurations = port_database.get_configuration(issuer, instance_id)
    return configurations
class TestPortDatabaseEditor:
    port_db_editor = None
    database = None

    @pytest.fixture(autouse=True)
    def port_db_editor(self):
        self.port_db_editor = PortDatabaseEditor()
        self.database = PortDatabase()

    def test_get_instance_id_from_config_with_instance_id(self):
        _instance_id = "ID_1"
        config_file_dict = {CONFIG_DICT_INSTANCE_ID_KEY: _instance_id}
        returned_instance_id = self.port_db_editor.get_instance_id(config_file_dict, 8000)
        assert _instance_id == returned_instance_id

    def _remove_config_files(self, folder, ports):
        for port in ports:
            config_file_name = get_config_file_path(port, folder)
            os.remove(config_file_name)

    def _create_config_files(self, folder, ports, file_content=""):
        for port in ports:
            config_file_name = get_config_file_path(port, folder)
            with open(config_file_name, "w") as _file:
                _file.write(file_content)

    def test_port_is_returned_when_no_instance_id_exists(self):
        port = 8000
        config_file_dict = {}
        returned_instance_id = self.port_db_editor.get_instance_id(config_file_dict, port)
        assert port == int(returned_instance_id)

    def test_get_port_from_module(self, port_db_editor):
        port = self.port_db_editor.get_port("rp_conf_8001")
        assert port == 8001

    def test_get_config_file_dict_from_module(self):
        folder = "."
        ports = [0]
        file_content = "CLIENT = {'first_key': 'public',\n 'second_key': 'public'}"
        self._create_config_files(folder, ports, file_content=file_content)
        client = self.port_db_editor.get_config_file_dict("rp_conf_%s" % ports[0])
        assert client
        self._remove_config_files(folder, ports)

    def test_get_config_file_dict_from_module_without_client_attibute(self):
        folder = "."
        ports = [2]
        file_content = "NON_CLIENT = {'first_key': 'public'}"
        self._create_config_files(folder, ports, file_content=file_content)
        with pytest.raises(AttributeError):
            self.port_db_editor.get_config_file_dict("rp_conf_%s" % ports[0])
        self._remove_config_files(folder, ports)

    def _setup_database_entries(self, database_ports=[8001, 8002, 8003]):
        for port in database_ports:
            self.database.upsert(
                issuer="google", port=port, instance_id="test" + str(port), port_type=PortDatabase.DYNAMIC_PORT_TYPE
            )

    def test_identify_removed_config_files(self):
        database_ports = [8001, 8002, 8003]
        self._setup_database_entries(database_ports)
        ports = self.port_db_editor.identify_ports_for_removed_config_files(
            self.database, ["rp_conf_8001.py", "rp_conf_8003.py"]
        )
        assert ports == [8002]

    def test_restore_removed_config_file(self):
        database_ports = [8001, 8002]
        self._setup_database_entries(database_ports)
        self.port_db_editor._restore_config_file = MagicMock(return_value=None)

        with mock.patch("__builtin__.raw_input", return_value="y"):
            self.port_db_editor.prompt_user_for_config_file_restoration(self.database, [8002])
        assert self.port_db_editor._restore_config_file.called

    def test_remove_unwanted_config_file_info_from_database(self):
        database_ports = [8001, 8002]
        self._setup_database_entries(database_ports)

        with mock.patch("__builtin__.raw_input", return_value="n"):
            self.port_db_editor.prompt_user_for_config_file_restoration(self.database, [8002])
        assert self.database.get_all_ports() == [8001]

    def test_add_config_info_to_existing_entry_if_not_existing(self):
        database_ports = [8001]
        self._setup_database_entries(database_ports)
        instance_id = self.database.get_row(8001)[CONFIG_DICT_INSTANCE_ID_KEY]
        config_file_dict = {"srv_discovery_url": "https://test.com", CONFIG_DICT_INSTANCE_ID_KEY: instance_id}
        self.port_db_editor.get_config_file_dict = MagicMock(return_value=config_file_dict)
        assert self.database.get_row(8001)[CONFIG_FILE_COLUMN] == None

        self.port_db_editor.sync_database_information(self.database, "rp_conf_8001.py")
        config_file_in_db = self.database.get_row(8001)[CONFIG_FILE_COLUMN]
        assert config_file_dict == config_file_in_db

    def test_non_existing_entry_in_database(self):
        config_file_dict = {"srv_discovery_url": "https://test.com", CONFIG_DICT_INSTANCE_ID_KEY: "test_id"}
        self.port_db_editor.get_config_file_dict = MagicMock(return_value=config_file_dict)
        with pytest.raises(TypeError):
            self.database.get_row(8001)[CONFIG_FILE_COLUMN]

        self.port_db_editor.sync_database_information(self.database, "rp_conf_8001.py")
        config_file_in_db = self.database.get_row(8001)[CONFIG_FILE_COLUMN]
        assert config_file_dict == config_file_in_db
Esempio n. 30
0
def load_configuration_from_database(parameters):
    issuer = remove_last_slash(parameters[ISSUER_QUERY_KEY])
    instance_id = parameters[INSTANCE_ID_QUERY_KEY]
    port_database = PortDatabase(CONF.PORT_DATABASE_FILE)
    configurations = port_database.get_configuration(issuer, instance_id)
    return configurations
Esempio n. 31
0
def uses_dynamic_client_reg(issuer, instance_id):
    port_database = PortDatabase(CONF.PORT_DATABASE_FILE)
    port = port_database.get_existing_port(issuer=issuer,
                                           instance_id=instance_id,
                                           port_type=PortDatabase.DYNAMIC_PORT_TYPE)
    return port
Esempio n. 32
0
def is_port_in_database(_port):
    port_db = PortDatabase(CONF.PORT_DATABASE_FILE)
    return port_db.get_row_by_port(_port) is None
Esempio n. 33
0
    PARSER.add_argument("-r", dest="port_to_remove", help="Remove port")

    PARSER.add_argument(
        "-g",
        dest="generate_database",
        action="store_true",
        help="Generate database from configuration files in current folder",
    )

    PARSER.add_argument("-p", dest="oprp_config_file_path", help="Path to where the oprp config files are located")

    PARSER.add_argument(dest="database")
    ARGS = PARSER.parse_args()

    DATABASE = PortDatabase(ARGS.database)

    if ARGS.port_to_remove:
        DATABASE.remove_row(ARGS.port_to_remove)

    if ARGS.oprp_config_file_path:
        CONFIG_EDITOR = PortDatabaseEditor(ARGS.oprp_config_file_path)
    else:
        CONFIG_EDITOR = PortDatabaseEditor()

    if ARGS.generate_database:
        CONFIG_EDITOR.extract_database_info_from_config_file(DATABASE)

    if ARGS.show_database_content:
        DATABASE.print_table()
Esempio n. 34
0
    PARSER.add_argument('-s', dest='show_database_content', action='store_true',
                        help="Print database")

    PARSER.add_argument('-r', dest='port_to_remove',
                        help="Remove port")

    PARSER.add_argument('-g', dest='generate_database', action='store_true',
                        help="Generate database from configuration files in current folder")

    PARSER.add_argument('-p', dest='oprp_config_file_path',
                        help="Path to where the oprp config files are located")

    PARSER.add_argument(dest="database")
    ARGS = PARSER.parse_args()

    DATABASE = PortDatabase(ARGS.database)

    if ARGS.port_to_remove:
        DATABASE.remove_row(ARGS.port_to_remove)

    if ARGS.oprp_config_file_path:
        CONFIG_EDITOR = PortDatabaseEditor(ARGS.oprp_config_file_path)
    else:
        CONFIG_EDITOR = PortDatabaseEditor()

    if ARGS.generate_database:
        CONFIG_EDITOR.extract_database_info_from_config_file(DATABASE)

    if ARGS.show_database_content:
        DATABASE.print_port_table()
        DATABASE.print_issuer_contact_table()
class TestPortDatabaseEditor:
    port_db_editor = None
    database = None

    @pytest.fixture(autouse=True)
    def port_db_editor(self):
        self.port_db_editor = PortDatabaseEditor()
        self.database = PortDatabase()

    def test_get_instance_id_from_config_with_instance_id(self):
        _instance_id = "ID_1"
        config_file_dict = {CONFIG_DICT_INSTANCE_ID_KEY: _instance_id}
        returned_instance_id = self.port_db_editor.get_instance_id(config_file_dict, 8000)
        assert _instance_id == returned_instance_id

    def _remove_config_files(self, folder, ports):
        for port in ports:
            config_file_name = get_config_file_path(port, folder)
            os.remove(config_file_name)

    def _create_config_files(self, folder, ports, file_content=""):
        for port in ports:
            config_file_name = get_config_file_path(port, folder)
            with open(config_file_name, "w") as _file:
                _file.write(file_content)

    def test_port_is_returned_when_no_instance_id_exists(self):
        port = 8000
        config_file_dict = {}
        returned_instance_id = self.port_db_editor.get_instance_id(config_file_dict, port)
        assert port == int(returned_instance_id)

    def test_get_port_from_module(self, port_db_editor):
        port = self.port_db_editor.get_port("rp_conf_8001")
        assert port == 8001

    def test_get_config_file_dict_from_module(self):
        folder = "."
        ports = [0]
        file_content = "CLIENT = {'first_key': 'public',\n 'second_key': 'public'}"
        self._create_config_files(folder, ports, file_content=file_content)
        client = self.port_db_editor.get_config_file_dict("rp_conf_%s" % ports[0])
        assert client
        self._remove_config_files(folder, ports)

    def test_get_config_file_dict_from_module_without_client_attibute(self):
        folder = "."
        ports = [2]
        file_content = "NON_CLIENT = {'first_key': 'public'}"
        self._create_config_files(folder, ports, file_content=file_content)
        with pytest.raises(AttributeError):
            self.port_db_editor.get_config_file_dict("rp_conf_%s" % ports[0])
        self._remove_config_files(folder, ports)

    def _setup_database_entries(self, database_ports=[8001, 8002, 8003]):
        for port in database_ports:
            self.database.upsert(issuer="google", port=port, instance_id="test" + str(port), port_type=PortDatabase.DYNAMIC_PORT_TYPE)

    def test_identify_removed_config_files(self):
        database_ports = [8001, 8002, 8003]
        self._setup_database_entries(database_ports)
        ports = self.port_db_editor.identify_ports_for_removed_config_files(self.database, ['rp_conf_8001.py', 'rp_conf_8003.py'])
        assert ports == [8002]

    def test_restore_removed_config_file(self):
        database_ports = [8001, 8002]
        self._setup_database_entries(database_ports)
        self.port_db_editor._restore_config_file = MagicMock(return_value=None)

        with mock.patch('__builtin__.raw_input', return_value='y'):
            self.port_db_editor.prompt_user_for_config_file_restoration(self.database, [8002])
        assert self.port_db_editor._restore_config_file.called

    def test_remove_unwanted_config_file_info_from_database(self):
        database_ports = [8001, 8002]
        self._setup_database_entries(database_ports)

        with mock.patch('__builtin__.raw_input', return_value='n'):
            self.port_db_editor.prompt_user_for_config_file_restoration(self.database, [8002])
        assert self.database.get_all_ports() == [8001]

    def test_add_config_info_to_existing_entry_if_not_existing(self):
        database_ports = [8001]
        self._setup_database_entries(database_ports)
        instance_id = self.database.get_row_by_port(8001)[CONFIG_DICT_INSTANCE_ID_KEY]
        config_file_dict = {'srv_discovery_url': "https://test.com", CONFIG_DICT_INSTANCE_ID_KEY: instance_id}
        self.port_db_editor.get_config_file_dict = MagicMock(return_value=config_file_dict)
        assert self.database.get_row_by_port(8001)[CONFIG_FILE_COLUMN] == None

        self.port_db_editor.sync_database_information(self.database, "rp_conf_8001.py")
        config_file_in_db = self.database.get_row_by_port(8001)[CONFIG_FILE_COLUMN]
        assert config_file_dict == config_file_in_db

    def test_non_existing_entry_in_database(self):
        config_file_dict = {'srv_discovery_url': "https://test.com", CONFIG_DICT_INSTANCE_ID_KEY: "test_id"}
        self.port_db_editor.get_config_file_dict = MagicMock(return_value=config_file_dict)
        with pytest.raises(TypeError):
            self.database.get_row_by_port(8001)[CONFIG_FILE_COLUMN]

        self.port_db_editor.sync_database_information(self.database, "rp_conf_8001.py")
        config_file_in_db = self.database.get_row_by_port(8001)[CONFIG_FILE_COLUMN]
        assert config_file_dict == config_file_in_db
Esempio n. 36
0
    PARSER.add_argument('-r', dest='port_to_remove', help="Remove port")

    PARSER.add_argument(
        '-g',
        dest='generate_database',
        action='store_true',
        help="Generate database from configuration files in current folder")

    PARSER.add_argument('-p',
                        dest='oprp_config_file_path',
                        help="Path to where the oprp config files are located")

    PARSER.add_argument(dest="database")
    ARGS = PARSER.parse_args()

    DATABASE = PortDatabase(ARGS.database)

    if ARGS.port_to_remove:
        DATABASE.remove_row(ARGS.port_to_remove)

    if ARGS.oprp_config_file_path:
        CONFIG_EDITOR = PortDatabaseEditor(ARGS.oprp_config_file_path)
    else:
        CONFIG_EDITOR = PortDatabaseEditor()

    if ARGS.generate_database:
        CONFIG_EDITOR.extract_database_info_from_config_file(DATABASE)

    if ARGS.show_database_content:
        DATABASE.print_table()
Esempio n. 37
0
 def _allocate_next_free_port(self):
     port_db = PortDatabase(
         is_port_used_func=is_port_used_by_another_process)
     return port_db.allocate_port("issuer", "instance_id",
                                  PortDatabase.STATIC_PORT_TYPE, 8000, 8100)