Added a hack to make testing the filesystem adapter tests working

This commit is contained in:
Sumner Evans
2020-04-21 13:50:01 -06:00
parent 9d7218afd9
commit 2863570e5b
7 changed files with 81 additions and 18 deletions

View File

@@ -20,7 +20,7 @@ lint:
script: script:
- pipenv run python setup.py check -mrs - pipenv run python setup.py check -mrs
- pipenv run flake8 - pipenv run flake8
- pipenv run mypy sublime - pipenv run mypy sublime tests/**/*.py
- pipenv run cicd/custom_style_check.py - pipenv run cicd/custom_style_check.py
test: test:

View File

@@ -95,6 +95,14 @@ yourself with the following commands::
$ mypy sublime $ mypy sublime
$ ./cicd/custom_style_check.py $ ./cicd/custom_style_check.py
Testing
-------
This project uses ``pytest`` for testing. Tests can be added in the docstrings
of the methods that are being tested or in the ``tests`` directory. 100% test
coverage is **not** a goal of this project, and will never be. There is a lot of
code that just doesn't need tested, or is better if just tested manually.
CI/CD Pipeline CI/CD Pipeline
-------------- --------------

View File

@@ -36,6 +36,15 @@ ignore_missing_imports = True
[mypy-pychromecast] [mypy-pychromecast]
ignore_missing_imports = True ignore_missing_imports = True
[mypy-pytest]
ignore_missing_imports = True
[mypy-playhouse.sqliteq]
ignore_missing_imports = True
[mypy-peewee]
ignore_missing_imports = True
[yapf] [yapf]
based_on_style = pep8 based_on_style = pep8
split_before_bitwise_operator = true split_before_bitwise_operator = true

View File

@@ -2,12 +2,13 @@ import logging
from dataclasses import asdict from dataclasses import asdict
from pathlib import Path from pathlib import Path
from typing import Any, Dict, Sequence, Optional, Tuple from typing import Any, Dict, Sequence, Optional, Tuple
from time import sleep
from playhouse.sqliteq import SqliteQueueDatabase from playhouse.sqliteq import SqliteQueueDatabase
from sublime.adapters.api_objects import (Playlist, PlaylistDetails) from sublime.adapters.api_objects import (Playlist, PlaylistDetails)
from . import database from . import models
from .. import CacheMissError, CachingAdapter, ConfigParamDescriptor from .. import CacheMissError, CachingAdapter, ConfigParamDescriptor
@@ -36,13 +37,12 @@ class FilesystemAdapter(CachingAdapter):
self.data_directory = data_directory self.data_directory = data_directory
logging.info('Opening connection to the database.') logging.info('Opening connection to the database.')
database_filename = data_directory.joinpath('cache.db') database_filename = data_directory.joinpath('cache.db')
self.database = SqliteQueueDatabase( models.database.initialize(
database_filename, SqliteQueueDatabase(database_filename, autorollback=True))
autorollback=True, models.database.connect()
) models.database.create_tables(models.ALL_TABLES)
database.proxy.initialize(self.database) sleep(1)
self.database.connect() assert len(models.database.get_tables()) > 0
self.database.create_tables(database.ALL_TABLES)
def shutdown(self): def shutdown(self):
logging.info('Shutdown complete') logging.info('Shutdown complete')
@@ -61,7 +61,7 @@ class FilesystemAdapter(CachingAdapter):
can_get_playlists: bool = True can_get_playlists: bool = True
def get_playlists(self) -> Sequence[Playlist]: def get_playlists(self) -> Sequence[Playlist]:
playlists = list(database.Playlist.select()) playlists = list(models.Playlist.select())
if len(playlists) == 0: # TODO not necessarily a cache miss if len(playlists) == 0: # TODO not necessarily a cache miss
raise CacheMissError() raise CacheMissError()
return playlists return playlists
@@ -84,6 +84,6 @@ class FilesystemAdapter(CachingAdapter):
): ):
if function_name == 'get_playlists': if function_name == 'get_playlists':
( (
database.Playlist.insert_many( models.Playlist.insert_many(
map(lambda p: database.Playlist(**asdict(p)), map(lambda p: models.Playlist(**asdict(p)),
data)).on_conflict_replace()) data)).on_conflict_replace())

View File

@@ -3,8 +3,8 @@ from typing import Any, Optional
from peewee import ( from peewee import (
BooleanField, BooleanField,
DatabaseProxy,
DateTimeField, DateTimeField,
DatabaseProxy,
Field, Field,
ForeignKeyField, ForeignKeyField,
IntegerField, IntegerField,
@@ -12,12 +12,12 @@ from peewee import (
TextField, TextField,
) )
proxy = DatabaseProxy() database = DatabaseProxy()
class BaseModel(Model): class BaseModel(Model):
class Meta: class Meta:
database = proxy database = database
class DurationField(IntegerField): class DurationField(IntegerField):

View File

@@ -0,0 +1,47 @@
import json
import logging
import re
from datetime import datetime, timedelta, timezone
from pathlib import Path
from typing import Any, Dict, Generator, Optional, Tuple
import pytest
from sublime.adapters.filesystem import (
models,
FilesystemAdapter,
)
MOCK_DATA_FILES = Path(__file__).parent.joinpath('mock_data')
@pytest.fixture
def adapter(tmp_path: Path):
adapter = FilesystemAdapter({}, tmp_path)
yield adapter
adapter.shutdown()
@pytest.fixture
def cache_adapter(tmp_path: Path):
adapter = FilesystemAdapter({}, tmp_path, is_cache=True)
yield adapter
adapter.shutdown()
def mock_data_files(
request_name: str,
mode: str = 'r',
) -> Generator[Tuple[Path, Any], None, None]:
"""
Yields all of the files in the mock_data directory that start with
``request_name``.
"""
for file in MOCK_DATA_FILES.iterdir():
if file.name.split('-')[0] in request_name:
with open(file, mode) as f:
yield file, f.read()
def test_get_playlists(adapter: FilesystemAdapter, tmp_path: Path):
assert adapter.get_playlists() == []

View File

@@ -1,11 +1,10 @@
import importlib import importlib
import importlib.util
import json import json
import logging import logging
import re import re
from datetime import datetime, timedelta, timezone from datetime import datetime, timedelta, timezone
from pathlib import Path from pathlib import Path
from typing import Any, Dict, Generator, Optional, Tuple from typing import Any, Dict, Generator, Optional, Tuple, Union
import pytest import pytest
@@ -34,7 +33,7 @@ def adapter(tmp_path: Path):
def mock_data_files( def mock_data_files(
request_name: str, request_name: str,
mode: str = 'r', mode: str = 'r',
) -> Generator[str, None, None]: ) -> Generator[Tuple[Path, Any], None, None]:
""" """
Yields all of the files in the mock_data directory that start with Yields all of the files in the mock_data directory that start with
``request_name``. ``request_name``.