Exemple #1
0
def database_mock(request, mocker):
    """Mock database for testing."""

    from snippy.storage.database import Database as Db

    Config.init(['snippy', '-q'] + Database.get_cli_params()
                )  # Prevent unnecessary CLI help output with quiet option.
    mocker.patch.object(Config,
                        'storage_file',
                        Database.get_storage(),
                        create=True)
    mocker.patch.object(Config,
                        'storage_schema',
                        Database.get_schema(),
                        create=True)

    database = Db()
    database.init()

    def fin():
        """Clear the resources at the end."""

        database.disconnect()
        Database.delete_all_contents()
        Database.delete_storage()

    request.addfinalizer(fin)

    return database
Exemple #2
0
def _create_snippy(mocker, request, params, database):
    """Create snippy with mocks.

    Args:
        params (list): Command line arguments to start the Snippy.
        database (str): Database used with the tests.

    Returns:
        obj: Snippy object.
    """

    if request.config.getoption("--snippy-logs"):
        params.append('--debug')

    # Mock only objects from the Snippy package. If system calls like os.open
    # are mocked from here, it will mock all the third party packages that are
    # imported when the Snippy object is created. System calls must be mocked
    # after the Snippy object is in a such state that it can accept test case
    # input.
    mocker.patch.object(Config,
                        '_storage_file',
                        return_value=Database.get_storage())
    if database == Database.DB_POSTGRESQL:
        params = params + Database.get_cli_params()

    snippy = Snippy(params)

    return snippy
Exemple #3
0
    def store(content):
        """Store content into database.

        Args:
            content (dict): Content in a dictionary.
        """

        Database.store(content)
Exemple #4
0
    def assert_storage_size(cls, size):
        """Compare content count stored in database."""

        try:
            assert size == len(Database.get_collection())
        except AssertionError:
            print('database contains {} contents when expected size was {}'.
                  format(len(Database.get_collection()), size))
            raise AssertionError
    def test_database_insert_001(database, cause):
        """Test database basic insert.

        Insert one Snippet resource into the database.
        """

        collection = Content.get_collection(Snippet.REMOVE)
        database.insert(collection)
        cause.assert_called_once_with('201 Created', 'content created')
        assert collection == TDatabase.get_snippets()
        assert len(TDatabase.get_snippets()) == 1
Exemple #6
0
def pytest_sessionstart(session):
    """Pytest hook called when session is started.

    This hook is called before the Pytest report header hook is called
    and after the Pytest command line arguments have been parsed.

    Args:
        session (obj): Pytest Session() object.
    """

    database = session.config.getoption("--snippy-db")
    Database.set_database(database)
    Database.delete_all_contents()
    def test_database_insert_002(database, cause):
        """Test SqliteDb basic insert.

        Insert four Snippet resources into the database. This verifies with
        multiple items in tag and link lists.
        """

        collection = Content.get_collection(Snippet.REMOVE)
        collection.migrate(Content.get_collection(Snippet.FORCED))
        collection.migrate(Content.get_collection(Snippet.EXITED))
        collection.migrate(Content.get_collection(Snippet.NETCAT))
        database.insert(collection)
        cause.assert_called_once_with('201 Created', 'content created')
        assert collection == TDatabase.get_snippets()
        assert len(TDatabase.get_snippets()) == 4
Exemple #8
0
    def test_database_delete_001(database, cause, mocker):
        """Test database basic delete.

        Delete one row from database with long digest.
        """

        collection = Content.get_collection(Snippet.REMOVE)
        collection.migrate(Content.get_collection(Snippet.FORCED))
        database.insert(collection)
        database.delete('53908d68425c61dc310c9ce49d530bd858c5be197990491ca20dbe888e6deac5')
        results = []
        results.append(mocker.call('201 Created', 'content created'))
        results.append(mocker.call('204 No Content', 'content deleted successfully'))
        cause.assert_has_calls(results)
        assert TDatabase.get_snippets() == Content.get_collection(Snippet.REMOVE)
        assert len(TDatabase.get_snippets()) == 1
Exemple #9
0
def _import_content_mkdn(snippy, mocker, contents, timestamps):
    """Import requested Markdown content."""

    mocker.patch.object(Config, 'utcnow', side_effect=timestamps)
    start = len(Database.get_collection()) + 1
    with mock.patch('snippy.content.migrate.os.path.isfile',
                    return_value=True):
        for idx, content in enumerate(contents, start=start):
            file_content = mocker.mock_open(
                read_data=_get_template_mkdn(content))
            mocker.patch('snippy.content.migrate.open',
                         file_content,
                         create=True)
            cause = snippy.run(['snippy', 'import', '-f', 'content.mkdn'])
            assert cause == Cause.ALL_OK
            assert len(Database.get_collection()) == idx
Exemple #10
0
def pytest_report_header(config):  # pylint: disable=unused-argument
    """Pytest hook to set report header.

    Args:
        config (obj): Pytest Config() object.
    """

    return 'database: {}{}{}'.format(Helper.COLOR_OK, Database.get_database(),
                                     Helper.COLOR_END)
Exemple #11
0
    def assert_storage(cls, content):
        """Compare content stored in database.

        The assert comparisons use equality implemented for collection data
        class. This quarantees that the count and content of resources are
        the same in database and expected content.

        If the result and expected content are compared only as collections,
        there are cases that are not noticed. A content fields in collection
        are for example sorted and trimmed in some cases. The given content
        dictionary format from test cases must be set correctly in order to
        keep the content definitions in test correct. Because of this, the
        content must be compared also in dictionary format.

        The original content must not be changed because it is in most cases
        default content shared between all tests.

        Args:
            content (dict): Excepted content compared against database.
        """

        if not content:
            assert not Database.get_collection()

            return

        result_collection = Database.get_collection()
        result_dictionary = cls._get_db_dictionary(result_collection)
        expect_collection = cls._get_expect_collection(content)
        expect_dictionary = content
        try:
            assert result_collection == expect_collection
            assert result_dictionary == expect_dictionary
        except AssertionError:
            Content._print_assert(result_collection, expect_collection)
            Content._print_assert(result_dictionary, expect_dictionary)
            raise AssertionError
Exemple #12
0
    def db_cli_params():
        """Return required CLI parameters for database."""

        return Database.get_cli_params()
Exemple #13
0
    def output():
        """Print all content stored in database."""

        Database.print_contents()
Exemple #14
0
    def delete():
        """Delete all existing content and the database."""

        Database.delete_all_contents()
        Database.delete_storage()
Exemple #15
0
    def fin():
        """Clear the resources at the end."""

        database.disconnect()
        Database.delete_all_contents()
        Database.delete_storage()
Exemple #16
0
    def fin():
        """Clear the resources at the end."""

        snippy.release()
        Database.delete_storage()