Adding check to ensure that tests are running in test db.

This commit is contained in:
Roland 2022-01-07 13:59:43 -07:00
parent 512fb532d8
commit b9606c1b31
No known key found for this signature in database
GPG key ID: 9D6DBD3ACF11AB93
5 changed files with 111 additions and 97 deletions

View file

@ -4,7 +4,8 @@ from http import HTTPStatus
from sanic import response, Blueprint
from sanic.request import Request
from wrolpi.common import logger, wrol_mode_check, get_relative_to_media_directory, make_media_directory
from wrolpi.common import logger, wrol_mode_check, get_relative_to_media_directory, make_media_directory, \
get_media_directory
from wrolpi.errors import UnknownDirectory
from wrolpi.root_api import json_response
from wrolpi.schema import validate_doc, JSONErrorResponse
@ -53,13 +54,15 @@ def channel_get(_: Request, link: str):
@wrol_mode_check
def channel_post(_: Request, data: dict):
try:
data['directory'] = get_relative_to_media_directory(data['directory'])
# Channel directory is relative to the media directory. Channel directory may not be in "videos" directory!
data['directory'] = get_media_directory() / data['directory']
except UnknownDirectory:
if data['mkdir']:
make_media_directory(data['directory'])
data['directory'] = get_relative_to_media_directory(data['directory'])
else:
raise
print(data['directory'])
if download_frequency := data.get('download_frequency'):
try:

View file

@ -120,99 +120,6 @@ class TestVideoAPI(TestAPI):
request, response = api_app.test_client.delete(location)
assert response.status_code == HTTPStatus.NOT_FOUND
@wrap_test_db
def test_channel_conflicts(self):
with tempfile.TemporaryDirectory() as media_dir, \
mock.patch('wrolpi.common.get_media_directory', lambda: pathlib.Path(media_dir)):
channel_directory = tempfile.TemporaryDirectory(dir=media_dir).name
pathlib.Path(channel_directory).mkdir()
new_channel = dict(
directory=channel_directory,
match_regex='asdf',
name='Example Channel 1',
url='https://example.com/channel1',
)
def _post_channel(channel):
return api_app.test_client.post('/api/videos/channels', content=json.dumps(channel))
# Create it
request, response = _post_channel(new_channel)
assert response.status_code == HTTPStatus.CREATED
# Name is an exact match
channel_directory2 = tempfile.TemporaryDirectory(dir=media_dir).name
pathlib.Path(channel_directory2).mkdir()
new_channel = dict(
directory=channel_directory2,
name='Example Channel 1',
)
request, response = _post_channel(new_channel)
assert response.status_code == HTTPStatus.BAD_REQUEST
assert response.json == {'error': 'Could not validate the contents of the request', 'code': 10,
'cause': {'error': 'The channel name is already taken.', 'code': 5}}
# Name matches when converted to link
channel_directory2 = tempfile.TemporaryDirectory(dir=media_dir).name
pathlib.Path(channel_directory2).mkdir()
new_channel = dict(
directory=channel_directory2,
name='Example channel 1',
)
request, response = _post_channel(new_channel)
assert response.status_code == HTTPStatus.BAD_REQUEST
assert response.json == {'error': 'Could not validate the contents of the request', 'code': 10,
'cause': {'code': 11, 'error': 'Channel link already used by another channel'}}
# Directory was already used
new_channel = dict(
directory=channel_directory,
name='name is fine',
)
request, response = _post_channel(new_channel)
assert response.status_code == HTTPStatus.BAD_REQUEST
assert response.json == {'error': 'Could not validate the contents of the request', 'code': 10,
'cause': {'code': 7, 'error': 'The directory is already used by another channel.'}}
# URL is already used
channel_directory3 = tempfile.TemporaryDirectory(dir=media_dir).name
pathlib.Path(channel_directory3).mkdir()
new_channel = dict(
directory=channel_directory3,
name='name is fine',
url='https://example.com/channel1',
)
request, response = _post_channel(new_channel)
assert response.status_code == HTTPStatus.BAD_REQUEST
assert response.json == {'error': 'Could not validate the contents of the request', 'code': 10,
'cause': {'code': 6, 'error': 'The URL is already used by another channel.'}}
@wrap_test_db
def test_channel_empty_url_doesnt_conflict(self):
"""Two channels with empty URLs shouldn't conflict"""
with tempfile.TemporaryDirectory() as media_dir, \
mock.patch('wrolpi.common.get_media_directory', lambda: pathlib.Path(media_dir)):
channel_directory = tempfile.TemporaryDirectory(dir=media_dir).name
pathlib.Path(channel_directory).mkdir()
new_channel = {
'name': 'Fooz',
'directory': channel_directory,
}
request, response = api_app.test_client.post('/api/videos/channels', content=json.dumps(new_channel))
assert response.status_code == HTTPStatus.CREATED, response.json
location = response.headers['Location']
channel_directory2 = tempfile.TemporaryDirectory(dir=media_dir).name
pathlib.Path(channel_directory2).mkdir()
new_channel = {
'name': 'Barz',
'directory': channel_directory2,
}
request, response = api_app.test_client.post('/api/videos/channels', content=json.dumps(new_channel))
assert response.status_code == HTTPStatus.CREATED, response.json
assert location != response.headers['Location']
@wrap_test_db
def test_refresh_no_channel(self):
with get_db_session() as session:
@ -611,3 +518,92 @@ def test_video_file_name(test_session, simple_video, test_client):
assert resp.status_code == HTTPStatus.OK
assert resp.json['video']['video_path'] == 'simple_video.mp4'
assert resp.json['video'].get('stem') == 'simple_video'
def test_channel_conflicts(test_session, test_directory):
channel_directory = tempfile.TemporaryDirectory(dir=test_directory).name
pathlib.Path(channel_directory).mkdir()
new_channel = dict(
directory=channel_directory,
match_regex='asdf',
name='Example Channel 1',
url='https://example.com/channel1',
)
def _post_channel(channel):
return api_app.test_client.post('/api/videos/channels', content=json.dumps(channel))
# Create it
request, response = _post_channel(new_channel)
assert response.status_code == HTTPStatus.CREATED
# Name is an exact match
channel_directory2 = tempfile.TemporaryDirectory(dir=test_directory).name
pathlib.Path(channel_directory2).mkdir()
new_channel = dict(
directory=channel_directory2,
name='Example Channel 1',
)
request, response = _post_channel(new_channel)
assert response.status_code == HTTPStatus.BAD_REQUEST
assert response.json == {'error': 'Could not validate the contents of the request', 'code': 10,
'cause': {'error': 'The channel name is already taken.', 'code': 5}}
# Name matches when converted to link
channel_directory2 = tempfile.TemporaryDirectory(dir=test_directory).name
pathlib.Path(channel_directory2).mkdir()
new_channel = dict(
directory=channel_directory2,
name='Example channel 1',
)
request, response = _post_channel(new_channel)
assert response.status_code == HTTPStatus.BAD_REQUEST
assert response.json == {'error': 'Could not validate the contents of the request', 'code': 10,
'cause': {'code': 11, 'error': 'Channel link already used by another channel'}}
# Directory was already used
new_channel = dict(
directory=channel_directory,
name='name is fine',
)
request, response = _post_channel(new_channel)
assert response.status_code == HTTPStatus.BAD_REQUEST
assert response.json == {'error': 'Could not validate the contents of the request', 'code': 10,
'cause': {'code': 7, 'error': 'The directory is already used by another channel.'}}
# URL is already used
channel_directory3 = tempfile.TemporaryDirectory(dir=test_directory).name
pathlib.Path(channel_directory3).mkdir()
new_channel = dict(
directory=channel_directory3,
name='name is fine',
url='https://example.com/channel1',
)
request, response = _post_channel(new_channel)
assert response.status_code == HTTPStatus.BAD_REQUEST
assert response.json == {'error': 'Could not validate the contents of the request', 'code': 10,
'cause': {'code': 6, 'error': 'The URL is already used by another channel.'}}
def test_channel_empty_url_doesnt_conflict(test_session, test_directory):
"""Two channels with empty URLs shouldn't conflict"""
channel_directory = tempfile.TemporaryDirectory(dir=test_directory).name
pathlib.Path(channel_directory).mkdir()
new_channel = {
'name': 'Fooz',
'directory': channel_directory,
}
request, response = api_app.test_client.post('/api/videos/channels', content=json.dumps(new_channel))
assert response.status_code == HTTPStatus.CREATED, response.json
location = response.headers['Location']
channel_directory2 = tempfile.TemporaryDirectory(dir=test_directory).name
pathlib.Path(channel_directory2).mkdir()
new_channel = {
'name': 'Barz',
'directory': channel_directory2,
}
request, response = api_app.test_client.post('/api/videos/channels', content=json.dumps(new_channel))
assert response.status_code == HTTPStatus.CREATED, response.json
assert location != response.headers['Location']

View file

@ -71,7 +71,10 @@ def get_db_context() -> Tuple[create_engine, Session]:
"""
Get a DB engine and session.
"""
return _get_db_session()
local_engine, session = _get_db_session()
if PYTEST and 'wrolpi_testing' not in str(local_engine.url):
raise ValueError(f'Running tests, but a test database is not being used!! {local_engine.url=}')
return local_engine, session
@contextmanager

View file

@ -1,6 +1,6 @@
from sqlalchemy.orm import Session
from wrolpi.db import optional_session
from wrolpi.db import optional_session, get_db_session
def test_optional_session(test_session):
@ -34,3 +34,14 @@ def test_optional_session(test_session):
func()
func(session=test_session)
func(test_session)
def test_test_session_is_required():
"""
fixture `test_session` must be used in all tests to avoid using the real database.
"""
try:
with get_db_session() as session:
raise Exception('test engine was not used!!')
except ValueError as e:
assert 'test database' in str(e)

View file

@ -11,6 +11,7 @@ PUBLIC_HOST = os.environ.get('PUBLIC_HOST')
PUBLIC_PORT = os.environ.get('PUBLIC_PORT')
DOCKERIZED = True if os.environ.get('DOCKER', '').lower().startswith('t') else False
# tests are running
PYTEST = 'pytest' in sys.modules
DEFAULT_TIMEZONE_STR = 'America/Boise'