Increasing test coverage.

This commit is contained in:
Roland 2022-10-15 10:37:49 -06:00
parent 287edad9e6
commit acf4453a52
No known key found for this signature in database
GPG key ID: 9D6DBD3ACF11AB93
4 changed files with 71 additions and 60 deletions

View file

@ -1,5 +1,7 @@
from unittest import mock
import pytest
from modules.map import lib
@ -19,3 +21,38 @@ def test_get_map_paths(test_directory):
with mock.patch('modules.map.lib.subprocess.check_output') as mock_check_output:
mock_check_output.return_value = b'PostgreSQL custom database dump'
assert lib.get_map_paths() == [dump, ]
@pytest.mark.asyncio
async def test_import_file(test_directory, mock_create_subprocess_shell):
"""
Import map files. Files to import are checked for validity before importing. Any errors returned by
asyncio.create_subprocess_shell are caught and reported.
"""
pbf_file = test_directory / 'foo.osm.pbf'
with pytest.raises(ValueError):
await lib.import_file(pbf_file)
pbf_file.touch()
with pytest.raises(ValueError):
await lib.import_file(pbf_file)
with mock.patch('modules.map.lib.asyncio') as mock_asyncio, \
mock.patch('modules.map.lib.is_pbf_file') as mock_is_pbf_file:
# Run the import, it succeeds.
mock_asyncio.create_subprocess_shell = mock_create_subprocess_shell(
communicate_return=(b'out', b'error')
)
mock_is_pbf_file.return_value = True
await lib.import_file(pbf_file)
with mock.patch('modules.map.lib.asyncio') as mock_asyncio, \
mock.patch('modules.map.lib.is_pbf_file') as mock_is_pbf_file:
# Run the import, it fails.
mock_asyncio.create_subprocess_shell = mock_create_subprocess_shell(
communicate_return=(b'out', b'error'),
return_code=1,
)
mock_is_pbf_file.return_value = True
with pytest.raises(ValueError):
await lib.import_file(pbf_file)

View file

@ -1,12 +1,10 @@
import asyncio
import contextlib
import inspect
import json
import logging
import multiprocessing
import os
import pathlib
import queue
import re
import string
import sys
@ -16,15 +14,13 @@ from datetime import datetime, date
from decimal import Decimal
from functools import wraps
from itertools import islice, filterfalse, tee
from multiprocessing import Event, Queue, Lock, Manager
from multiprocessing import Lock, Manager
from pathlib import Path
from typing import Union, Callable, Tuple, Dict, List, Iterable, Optional, Generator, Any
from urllib.parse import urlparse
import aiohttp
import yaml
from sanic import Blueprint
from sanic.request import Request
from sqlalchemy import types
from sqlalchemy.ext.compiler import compiles
from sqlalchemy.ext.declarative import declarative_base
@ -93,60 +89,6 @@ def sanitize_link(link: str) -> str:
return new_link
DEFAULT_QUEUE_SIZE = 1000
QUEUE_TIMEOUT = 10
feed_logger = logger.getChild('ws_feed')
EVENTS = []
QUEUES = []
def create_websocket_feed(name: str, uri: str, blueprint: Blueprint, maxsize: int = DEFAULT_QUEUE_SIZE):
"""
Build the objects needed to run a websocket which will pass on messages from a multiprocessing.Queue.
:param name: the name that will be reported in the global event feeds
:param uri: the Sanic URI that the websocket will listen on
:param blueprint: the Sanic Blueprint to attach the websocket to
:param maxsize: the maximum size of the Queue
:return:
"""
q = Queue(maxsize=maxsize)
QUEUES.append(q)
event = Event()
EVENTS.append((name, event))
@blueprint.websocket(uri)
async def local_websocket(_: Request, ws):
feed_logger.info(f'client connected to {ws}')
feed_logger.debug(f'event.is_set: {event.is_set()}')
any_messages = False
while q.qsize() or event.is_set():
# Pass along messages from the queue until its empty, or the event is cleared. Give up after 1 second so
# the worker can take another request.
try:
msg = q.get(timeout=QUEUE_TIMEOUT)
any_messages = True
dump = json.dumps(msg)
await ws.send(dump)
# yield back to the event loop
await asyncio.sleep(0)
except queue.Empty: # pragma: no cover
# No messages yet, try again while event is set
pass
feed_logger.info(f'loop complete')
if any_messages is False:
await ws.send(json.dumps({'code': 'no-messages'}))
# No messages left, stream is complete
await ws.send(json.dumps({'code': 'stream-complete'}))
return q, event
class ConfigFile:
"""
This class keeps track of the contents of a config file. You can update the config by calling

View file

@ -8,6 +8,7 @@ import tempfile
from typing import List, Callable, Union, Dict
from typing import Tuple, Set
from unittest import mock
from unittest.mock import MagicMock
from uuid import uuid1, uuid4
import pytest
@ -83,6 +84,7 @@ def test_directory() -> pathlib.Path:
"""
with tempfile.TemporaryDirectory() as tmp_dir:
tmp_path = pathlib.Path(tmp_dir)
tmp_path.chmod(0o40755)
assert tmp_path.is_dir()
set_test_media_directory(tmp_path)
yield tmp_path
@ -246,3 +248,20 @@ def wrol_mode_fixture(test_config, test_download_manager):
disable_wrol_mode(test_download_manager)
return set_wrol_mode
@pytest.fixture
def mock_create_subprocess_shell():
def mocker(communicate_return=None, return_code=None):
async def communicate(*a, **kw):
return communicate_return or (None, None)
async def create_subprocess_shell(*a, **kw):
proc = MagicMock()
proc.communicate = communicate
proc.returncode = return_code if return_code is not None else 0
return proc
return create_subprocess_shell
return mocker

View file

@ -4,11 +4,12 @@ import tempfile
import unittest
from datetime import date, datetime
from decimal import Decimal
from unittest import mock
import pytest
from wrolpi.common import insert_parameter, date_range, api_param_limiter, chdir, zig_zag, \
escape_file_name, match_paths_to_suffixes, truncate_object_bytes
escape_file_name, match_paths_to_suffixes, truncate_object_bytes, check_media_directory
from wrolpi.dates import set_timezone, now
from wrolpi.errors import InvalidTimezone
from wrolpi.test.common import build_test_directories
@ -340,3 +341,15 @@ def test_truncate_object_bytes():
assert truncate_object_bytes('foo' * 100, 51) == 'f'
assert truncate_object_bytes('foo' * 100, 50) == ''
assert truncate_object_bytes('foo' * 100, 0) == ''
def test_check_media_directory(test_directory):
"""The directory provided by the test_directory fixture is a valid media directory."""
assert check_media_directory() is True
def test_bad_check_media_directory():
"""/dev/full is not a valid media directory, warnings are issued and the check fails."""
with mock.patch('wrolpi.common.get_media_directory') as mock_get_media_directory:
mock_get_media_directory.return_value = pathlib.Path('/dev/full')
assert check_media_directory() is False