Migrate core and common

This commit is contained in:
Tim 2020-02-13 20:50:39 +00:00
parent 3bda907d4d
commit 2eb385c774
No known key found for this signature in database
GPG Key ID: 3D454289AF831A6D
6 changed files with 716 additions and 738 deletions

View File

@ -19,79 +19,82 @@
# along with this program. If not, see <https://www.gnu.org/licenses/>. # # along with this program. If not, see <https://www.gnu.org/licenses/>. #
########################################################################## ##########################################################################
""" """
Package to test the openlp.core.common package. Package to test the openlp.core.common.mixins package.
""" """
from unittest import TestCase import pytest
from unittest.mock import MagicMock, patch from unittest.mock import MagicMock, patch
from openlp.core.common.mixins import RegistryProperties from openlp.core.common.mixins import RegistryProperties
from openlp.core.common.registry import Registry from openlp.core.common.registry import Registry
class TestRegistryProperties(TestCase, RegistryProperties): @pytest.fixture
def registry_env():
"""An instance of the Registry"""
Registry.create()
class Test(RegistryProperties):
pass
return Test()
def test_no_application(registry_env):
""" """
Test the functions in the ThemeManager module Test property if no registry value assigned
""" """
def setUp(self): # GIVEN an Empty Registry
""" # WHEN there is no Application
Create the Register # THEN the application should be none
""" assert registry_env.application is None, 'The application value should be None'
Registry.create()
def test_no_application(self):
"""
Test property if no registry value assigned
"""
# GIVEN an Empty Registry
# WHEN there is no Application
# THEN the application should be none
assert self.application is None, 'The application value should be None'
def test_application(self): def test_application(registry_env):
""" """
Test property if registry value assigned Test property if registry value assigned
""" """
# GIVEN an Empty Registry # GIVEN an Empty Registry
application = MagicMock() application = MagicMock()
# WHEN the application is registered # WHEN the application is registered
Registry().register('application', application) Registry().register('application', application)
# THEN the application should be none # THEN the application should be none
assert self.application == application, 'The application value should match' assert registry_env.application == application, 'The application value should match'
@patch('openlp.core.common.mixins.is_win')
def test_application_on_windows(self, mocked_is_win):
"""
Test property if registry value assigned on Windows
"""
# GIVEN an Empty Registry and we're on Windows
application = MagicMock()
mocked_is_win.return_value = True
# WHEN the application is registered @patch('openlp.core.common.mixins.is_win')
Registry().register('application', application) def test_application_on_windows(mocked_is_win, registry_env):
"""
Test property if registry value assigned on Windows
"""
# GIVEN an Empty Registry and we're on Windows
application = MagicMock()
mocked_is_win.return_value = True
# THEN the application should be none # WHEN the application is registered
assert self.application == application, 'The application value should match' Registry().register('application', application)
@patch('openlp.core.common.mixins.is_win') # THEN the application should be none
def test_get_application_on_windows(self, mocked_is_win): assert registry_env.application == application, 'The application value should match'
"""
Set that getting the application object on Windows happens dynamically
"""
# GIVEN an Empty Registry and we're on Windows
mocked_is_win.return_value = True
mock_application = MagicMock()
reg_props = RegistryProperties()
registry = Registry()
# WHEN the application is accessed
with patch.object(registry, 'get') as mocked_get:
mocked_get.return_value = mock_application
actual_application = reg_props.application
# THEN the application should be the mock object, and the correct function should have been called @patch('openlp.core.common.mixins.is_win')
assert mock_application == actual_application, 'The application value should match' def test_get_application_on_windows(mocked_is_win):
mocked_is_win.assert_called_with() """
mocked_get.assert_called_with('application') Set that getting the application object on Windows happens dynamically
"""
# GIVEN an Empty Registry and we're on Windows
mocked_is_win.return_value = True
mock_application = MagicMock()
reg_props = RegistryProperties()
registry = Registry()
# WHEN the application is accessed
with patch.object(registry, 'get') as mocked_get:
mocked_get.return_value = mock_application
actual_application = reg_props.application
# THEN the application should be the mock object, and the correct function should have been called
assert mock_application == actual_application, 'The application value should match'
mocked_is_win.assert_called_with()
mocked_get.assert_called_with('application')

View File

@ -22,218 +22,223 @@
Package to test the openlp.core.common.path package. Package to test the openlp.core.common.path package.
""" """
import os import os
import pytest
from pathlib import Path from pathlib import Path
from unittest import TestCase
from unittest.mock import MagicMock, patch from unittest.mock import MagicMock, patch
from openlp.core.common.path import create_paths, files_to_paths, path_to_str, replace_params, str_to_path, which from openlp.core.common.path import create_paths, files_to_paths, path_to_str, replace_params, str_to_path, which
class TestShutil(TestCase): def test_replace_params_no_params():
""" """
Tests for the :mod:`openlp.core.common.path` module Test replace_params when called with and empty tuple instead of parameters to replace
""" """
def test_replace_params_no_params(self): # GIVEN: Some test data
""" test_args = (1, 2)
Test replace_params when called with and empty tuple instead of parameters to replace test_kwargs = {'arg3': 3, 'arg4': 4}
""" test_params = tuple()
# GIVEN: Some test data
test_args = (1, 2)
test_kwargs = {'arg3': 3, 'arg4': 4}
test_params = tuple()
# WHEN: Calling replace_params # WHEN: Calling replace_params
result_args, result_kwargs = replace_params(test_args, test_kwargs, test_params) result_args, result_kwargs = replace_params(test_args, test_kwargs, test_params)
# THEN: The positional and keyword args should not have changed # THEN: The positional and keyword args should not have changed
assert test_args == result_args assert test_args == result_args
assert test_kwargs == result_kwargs assert test_kwargs == result_kwargs
def test_replace_params_params(self):
"""
Test replace_params when given a positional and a keyword argument to change
"""
# GIVEN: Some test data
test_args = (1, 2)
test_kwargs = {'arg3': 3, 'arg4': 4}
test_params = ((1, 'arg2', str), (2, 'arg3', str))
# WHEN: Calling replace_params
result_args, result_kwargs = replace_params(test_args, test_kwargs, test_params)
# THEN: The positional and keyword args should have have changed
assert result_args == (1, '2')
assert result_kwargs == {'arg3': '3', 'arg4': 4}
def test_which_no_command(self):
"""
Test :func:`openlp.core.common.path.which` when the command is not found.
"""
# GIVEN: A mocked :func:`shutil.which` when the command is not found.
with patch('openlp.core.common.path.shutil.which', return_value=None) as mocked_shutil_which:
# WHEN: Calling :func:`openlp.core.common.path.which` with a command that does not exist.
result = which('no_command')
# THEN: :func:`shutil.which` should have been called with the command, and :func:`which` should return None.
mocked_shutil_which.assert_called_once_with('no_command')
assert result is None
def test_which_command(self):
"""
Test :func:`openlp.core.common.path.which` when a command has been found.
"""
# GIVEN: A mocked :func:`shutil.which` when the command is found.
with patch('openlp.core.common.path.shutil.which',
return_value=os.path.join('path', 'to', 'command')) as mocked_shutil_which:
# WHEN: Calling :func:`openlp.core.common.path.which` with a command that exists.
result = which('command')
# THEN: :func:`shutil.which` should have been called with the command, and :func:`which` should return a
# Path object equivalent of the command path.
mocked_shutil_which.assert_called_once_with('command')
assert result == Path('path', 'to', 'command')
class TestPath(TestCase): def test_replace_params_params():
""" """
Tests for the :mod:`openlp.core.common.path` module Test replace_params when given a positional and a keyword argument to change
""" """
# GIVEN: Some test data
test_args = (1, 2)
test_kwargs = {'arg3': 3, 'arg4': 4}
test_params = ((1, 'arg2', str), (2, 'arg3', str))
def test_path_to_str_type_error(self): # WHEN: Calling replace_params
""" result_args, result_kwargs = replace_params(test_args, test_kwargs, test_params)
Test that `path_to_str` raises a type error when called with an invalid type
"""
# GIVEN: The `path_to_str` function
# WHEN: Calling `path_to_str` with an invalid Type
# THEN: A TypeError should have been raised
with self.assertRaises(TypeError):
path_to_str(57)
def test_path_to_str_wth_str(self): # THEN: The positional and keyword args should have have changed
""" assert result_args == (1, '2')
Test that `path_to_str` just returns a str when given a str assert result_kwargs == {'arg3': '3', 'arg4': 4}
"""
# GIVEN: The `path_to_str` function
# WHEN: Calling `path_to_str` with a str
result = path_to_str('/usr/bin')
# THEN: The string should be returned
assert result == '/usr/bin'
def test_path_to_str_none(self): def test_which_no_command():
""" """
Test that `path_to_str` correctly converts the path parameter when passed with None Test :func:`openlp.core.common.path.which` when the command is not found.
""" """
# GIVEN: The `path_to_str` function # GIVEN: A mocked :func:`shutil.which` when the command is not found.
# WHEN: Calling the `path_to_str` function with None with patch('openlp.core.common.path.shutil.which', return_value=None) as mocked_shutil_which:
result = path_to_str(None)
# THEN: `path_to_str` should return an empty string # WHEN: Calling :func:`openlp.core.common.path.which` with a command that does not exist.
assert result == '' result = which('no_command')
def test_path_to_str_path_object(self): # THEN: :func:`shutil.which` should have been called with the command, and :func:`which` should return None.
""" mocked_shutil_which.assert_called_once_with('no_command')
Test that `path_to_str` correctly converts the path parameter when passed a Path object assert result is None
"""
# GIVEN: The `path_to_str` function
# WHEN: Calling the `path_to_str` function with a Path object
result = path_to_str(Path('test/path'))
# THEN: `path_to_str` should return a string representation of the Path object
assert result == os.path.join('test', 'path')
def test_str_to_path_type_error(self): def test_which_command():
""" """
Test that `str_to_path` returns None if called with invalid information Test :func:`openlp.core.common.path.which` when a command has been found.
""" """
# GIVEN: The `str_to_path` function # GIVEN: A mocked :func:`shutil.which` when the command is found.
# WHEN: Calling `str_to_path` with an invalid Type with patch('openlp.core.common.path.shutil.which',
# THEN: None is returned return_value=os.path.join('path', 'to', 'command')) as mocked_shutil_which:
assert str_to_path(Path()) is None
def test_str_to_path_empty_str(self): # WHEN: Calling :func:`openlp.core.common.path.which` with a command that exists.
""" result = which('command')
Test that `str_to_path` correctly converts the string parameter when passed with and empty string
"""
# GIVEN: The `str_to_path` function
# WHEN: Calling the `str_to_path` function with None
result = str_to_path('')
# THEN: `path_to_str` should return None # THEN: :func:`shutil.which` should have been called with the command, and :func:`which` should return a
assert result is None # Path object equivalent of the command path.
mocked_shutil_which.assert_called_once_with('command')
assert result == Path('path', 'to', 'command')
def test_create_paths_dir_exists(self):
"""
Test the create_paths() function when the path already exists
"""
# GIVEN: A `Path` to check with patched out mkdir and exists methods
mocked_path = MagicMock()
mocked_path.exists.return_value = True
# WHEN: `create_paths` is called and the path exists def test_path_to_str_type_error():
"""
Test that `path_to_str` raises a type error when called with an invalid type
"""
# GIVEN: The `path_to_str` function
# WHEN: Calling `path_to_str` with an invalid Type
# THEN: A TypeError should have been raised
with pytest.raises(TypeError):
path_to_str(57)
def test_path_to_str_wth_str():
"""
Test that `path_to_str` just returns a str when given a str
"""
# GIVEN: The `path_to_str` function
# WHEN: Calling `path_to_str` with a str
result = path_to_str('/usr/bin')
# THEN: The string should be returned
assert result == '/usr/bin'
def test_path_to_str_none():
"""
Test that `path_to_str` correctly converts the path parameter when passed with None
"""
# GIVEN: The `path_to_str` function
# WHEN: Calling the `path_to_str` function with None
result = path_to_str(None)
# THEN: `path_to_str` should return an empty string
assert result == ''
def test_path_to_str_path_object():
"""
Test that `path_to_str` correctly converts the path parameter when passed a Path object
"""
# GIVEN: The `path_to_str` function
# WHEN: Calling the `path_to_str` function with a Path object
result = path_to_str(Path('test/path'))
# THEN: `path_to_str` should return a string representation of the Path object
assert result == os.path.join('test', 'path')
def test_str_to_path_type_error():
"""
Test that `str_to_path` returns None if called with invalid information
"""
# GIVEN: The `str_to_path` function
# WHEN: Calling `str_to_path` with an invalid Type
# THEN: None is returned
assert str_to_path(Path()) is None
def test_str_to_path_empty_str():
"""
Test that `str_to_path` correctly converts the string parameter when passed with and empty string
"""
# GIVEN: The `str_to_path` function
# WHEN: Calling the `str_to_path` function with None
result = str_to_path('')
# THEN: `path_to_str` should return None
assert result is None
def test_create_paths_dir_exists():
"""
Test the create_paths() function when the path already exists
"""
# GIVEN: A `Path` to check with patched out mkdir and exists methods
mocked_path = MagicMock()
mocked_path.exists.return_value = True
# WHEN: `create_paths` is called and the path exists
create_paths(mocked_path)
# THEN: The function should not attempt to create the directory
mocked_path.exists.assert_called_once_with()
assert mocked_path.mkdir.call_count == 0, 'mkdir should not have been called'
def test_create_paths_dir_doesnt_exists():
"""
Test the create_paths() function when the path does not already exist
"""
# GIVEN: A `Path` to check with patched out mkdir and exists methods
mocked_path = MagicMock()
mocked_path.exists.return_value = False
# WHEN: `create_paths` is called and the path does not exist
create_paths(mocked_path)
# THEN: The directory should have been created
mocked_path.exists.assert_called_once_with()
mocked_path.mkdir.assert_called_once_with(parents=True)
@patch('openlp.core.common.path.log')
def test_create_paths_dir_io_error(mocked_logger):
"""
Test the create_paths() when an OSError is raised
"""
# GIVEN: A `Path` to check with patched out mkdir and exists methods
mocked_path = MagicMock()
mocked_path.exists.side_effect = OSError('Cannot make directory')
# WHEN: An OSError is raised when checking the if the path exists.
create_paths(mocked_path)
# THEN: The Error should have been logged
mocked_logger.exception.assert_called_once_with('failed to check if directory exists or create directory')
def test_create_paths_dir_value_error():
"""
Test the create_paths() when an error other than OSError is raised
"""
# GIVEN: A `Path` to check with patched out mkdir and exists methods
mocked_path = MagicMock()
mocked_path.exists.side_effect = ValueError('Some other error')
# WHEN: Some other exception is raised
try:
create_paths(mocked_path) create_paths(mocked_path)
assert False, 'create_paths should have thrown an exception'
except Exception:
# THEN: `create_paths` raises an exception
pass
# THEN: The function should not attempt to create the directory
mocked_path.exists.assert_called_once_with()
assert mocked_path.mkdir.call_count == 0, 'mkdir should not have been called'
def test_create_paths_dir_doesnt_exists(self): def test_files_to_paths():
""" """
Test the create_paths() function when the path does not already exist Test the files_to_paths() method
""" """
# GIVEN: A `Path` to check with patched out mkdir and exists methods # GIVEN: A list of string filenames
mocked_path = MagicMock() test_files = ['/tmp/openlp/file1.txt', '/tmp/openlp/file2.txt']
mocked_path.exists.return_value = False
# WHEN: `create_paths` is called and the path does not exist # WHEN: files_to_paths is called
create_paths(mocked_path) result = files_to_paths(test_files)
# THEN: The directory should have been created # THEN: The result should be a list of Paths
mocked_path.exists.assert_called_once_with() assert result == [Path('/tmp/openlp/file1.txt'), Path('/tmp/openlp/file2.txt')]
mocked_path.mkdir.assert_called_once_with(parents=True)
@patch('openlp.core.common.path.log')
def test_create_paths_dir_io_error(self, mocked_logger):
"""
Test the create_paths() when an OSError is raised
"""
# GIVEN: A `Path` to check with patched out mkdir and exists methods
mocked_path = MagicMock()
mocked_path.exists.side_effect = OSError('Cannot make directory')
# WHEN: An OSError is raised when checking the if the path exists.
create_paths(mocked_path)
# THEN: The Error should have been logged
mocked_logger.exception.assert_called_once_with('failed to check if directory exists or create directory')
def test_create_paths_dir_value_error(self):
"""
Test the create_paths() when an error other than OSError is raised
"""
# GIVEN: A `Path` to check with patched out mkdir and exists methods
mocked_path = MagicMock()
mocked_path.exists.side_effect = ValueError('Some other error')
# WHEN: Some other exception is raised
try:
create_paths(mocked_path)
assert False, 'create_paths should have thrown an exception'
except Exception:
# THEN: `create_paths` raises an exception
pass
def test_files_to_paths(self):
"""
Test the files_to_paths() method
"""
# GIVEN: A list of string filenames
test_files = ['/tmp/openlp/file1.txt', '/tmp/openlp/file2.txt']
# WHEN: files_to_paths is called
result = files_to_paths(test_files)
# THEN: The result should be a list of Paths
assert result == [Path('/tmp/openlp/file1.txt'), Path('/tmp/openlp/file2.txt')]

View File

@ -21,130 +21,127 @@
""" """
Package to test the openlp.core.lib package. Package to test the openlp.core.lib package.
""" """
from unittest import TestCase import pytest
from unittest.mock import MagicMock from unittest.mock import MagicMock
from openlp.core.common.registry import Registry, RegistryBase from openlp.core.common.registry import Registry, RegistryBase
class TestRegistry(TestCase): def dummy_function_1():
return "function_1"
def test_registry_service(self):
"""
Test the registry creation and its usage
"""
# GIVEN: A new registry
Registry.create()
# WHEN: I add a component it should save it def dummy_function_2():
mock_1 = MagicMock() return "function_2"
def test_registry_service(registry):
"""
Test the registry creation and its usage
"""
# GIVEN: A new registry
# WHEN: I add a component it should save it
mock_1 = MagicMock()
Registry().register('test1', mock_1)
# THEN: we should be able retrieve the saved component
assert Registry().get('test1') == mock_1, 'The saved service can be retrieved and matches'
# WHEN: I add a component for the second time I am mad.
# THEN and I will get an exception
with pytest.raises(KeyError) as context:
Registry().register('test1', mock_1) Registry().register('test1', mock_1)
assert context.value != KeyError('Duplicate service exception test1'), \
'KeyError exception should have been thrown for duplicate service'
# THEN: we should be able retrieve the saved component # WHEN I try to get back a non existent component
assert Registry().get('test1') == mock_1, 'The saved service can be retrieved and matches' # THEN I will get an exception
temp = Registry().get('test2')
assert temp is None, 'None should have been returned for missing service'
# WHEN: I add a component for the second time I am mad. # WHEN I try to replace a component I should be allowed
# THEN and I will get an exception Registry().remove('test1')
with self.assertRaises(KeyError) as context: # THEN I will get an exception
Registry().register('test1', mock_1) temp = Registry().get('test1')
assert context.exception.args[0] == 'Duplicate service exception test1', \ assert temp is None, 'None should have been returned for deleted service'
'KeyError exception should have been thrown for duplicate service'
# WHEN I try to get back a non existent component
# THEN I will get an exception
temp = Registry().get('test2')
assert temp is None, 'None should have been returned for missing service'
# WHEN I try to replace a component I should be allowed def test_registry_function(registry):
Registry().remove('test1') """
# THEN I will get an exception Test the registry function creation and their usages
temp = Registry().get('test1') """
assert temp is None, 'None should have been returned for deleted service' # GIVEN: An existing registry register a function
Registry().register_function('test1', dummy_function_1)
def test_registry_function(self): # WHEN: I execute the function
""" return_value = Registry().execute('test1')
Test the registry function creation and their usages
"""
# GIVEN: An existing registry register a function
Registry.create()
Registry().register_function('test1', self.dummy_function_1)
# WHEN: I execute the function # THEN: I expect then function to have been called and a return given
return_value = Registry().execute('test1') assert return_value[0] == 'function_1', 'A return value is provided and matches'
# THEN: I expect then function to have been called and a return given # WHEN: I execute the a function with the same reference and execute the function
assert return_value[0] == 'function_1', 'A return value is provided and matches' Registry().register_function('test1', dummy_function_1)
return_value = Registry().execute('test1')
# WHEN: I execute the a function with the same reference and execute the function # THEN: I expect then function to have been called and a return given
Registry().register_function('test1', self.dummy_function_1) assert return_value == ['function_1', 'function_1'], 'A return value list is provided and matches'
return_value = Registry().execute('test1')
# THEN: I expect then function to have been called and a return given # WHEN: I execute the a 2nd function with the different reference and execute the function
assert return_value == ['function_1', 'function_1'], 'A return value list is provided and matches' Registry().register_function('test2', dummy_function_2)
return_value = Registry().execute('test2')
# WHEN: I execute the a 2nd function with the different reference and execute the function # THEN: I expect then function to have been called and a return given
Registry().register_function('test2', self.dummy_function_2) assert return_value[0] == 'function_2', 'A return value is provided and matches'
return_value = Registry().execute('test2')
# THEN: I expect then function to have been called and a return given
assert return_value[0] == 'function_2', 'A return value is provided and matches'
def test_registry_working_flags(self): def test_registry_working_flags(registry):
""" """
Test the registry working flags creation and its usage Test the registry working flags creation and its usage
""" """
# GIVEN: A new registry # GIVEN: A new registry
Registry.create() # WHEN: I add a working flag it should save it
my_data = 'Lamas'
my_data2 = 'More Lamas'
Registry().set_flag('test1', my_data)
# WHEN: I add a working flag it should save it # THEN: we should be able retrieve the saved component
my_data = 'Lamas' temp = Registry().get_flag('test1')
my_data2 = 'More Lamas' assert temp == my_data, 'The value should have been saved'
Registry().set_flag('test1', my_data)
# THEN: we should be able retrieve the saved component # WHEN: I add a component for the second time I am not mad.
temp = Registry().get_flag('test1') # THEN and I will not get an exception
assert temp == my_data, 'The value should have been saved' Registry().set_flag('test1', my_data2)
temp = Registry().get_flag('test1')
assert temp == my_data2, 'The value should have been updated'
# WHEN: I add a component for the second time I am not mad. # WHEN I try to get back a non existent Working Flag
# THEN and I will not get an exception # THEN I will get an exception
Registry().set_flag('test1', my_data2) with pytest.raises(KeyError) as context1:
temp = Registry().get_flag('test1') Registry().get_flag('test2')
assert temp == my_data2, 'The value should have been updated' assert context1.value != KeyError('Working Flag test2 not found in list'), \
'KeyError exception should have been thrown for missing working flag'
# WHEN I try to get back a non existent Working Flag # WHEN I try to replace a working flag I should be allowed
# THEN I will get an exception Registry().remove_flag('test1')
with self.assertRaises(KeyError) as context1: # THEN I will get an exception
temp = Registry().get_flag('test2') with pytest.raises(KeyError) as context:
assert context1.exception.args[0] == 'Working Flag test2 not found in list', \ Registry().get_flag('test1')
'KeyError exception should have been thrown for missing working flag' assert context.value != 'Working Flag test1 not found in list', \
'KeyError exception should have been thrown for duplicate working flag'
# WHEN I try to replace a working flag I should be allowed
Registry().remove_flag('test1')
# THEN I will get an exception
with self.assertRaises(KeyError) as context:
temp = Registry().get_flag('test1')
assert context.exception.args[0] == 'Working Flag test1 not found in list', \
'KeyError exception should have been thrown for duplicate working flag'
def test_remove_function(self): def test_remove_function(registry):
""" """
Test the remove_function() method Test the remove_function() method
""" """
# GIVEN: An existing registry register a function # GIVEN: An existing registry register a function
Registry.create() Registry().register_function('test1', dummy_function_1)
Registry().register_function('test1', self.dummy_function_1)
# WHEN: Remove the function. # WHEN: Remove the function.
Registry().remove_function('test1', self.dummy_function_1) Registry().remove_function('test1', dummy_function_1)
# THEN: The method should not be available. # THEN: The method should not be available.
assert Registry().functions_list['test1'] == [], 'The function should not be in the dict anymore.' assert Registry().functions_list['test1'] == [], 'The function should not be in the dict anymore.'
def dummy_function_1(self):
return "function_1"
def dummy_function_2(self):
return "function_2"
class PlainStub(object): class PlainStub(object):
@ -157,30 +154,25 @@ class RegistryStub(RegistryBase):
super().__init__() super().__init__()
class TestRegistryBase(TestCase): def test_registry_mixin_missing(registry):
"""
Test the registry creation and its usage
"""
# GIVEN: A new registry
# WHEN: I create an instance of a class that doesn't inherit from RegistryMixin
PlainStub()
def test_registry_mixin_missing(self): # THEN: Nothing is registered with the registry
""" assert len(Registry().functions_list) == 0, 'The function should not be in the dict anymore.'
Test the registry creation and its usage
"""
# GIVEN: A new registry
Registry.create()
# WHEN: I create an instance of a class that doesn't inherit from RegistryMixin
PlainStub()
# THEN: Nothing is registered with the registry def test_registry_mixin_present(registry):
assert len(Registry().functions_list) == 0, 'The function should not be in the dict anymore.' """
Test the registry creation and its usage
"""
# GIVEN: A new registry
# WHEN: I create an instance of a class that inherits from RegistryMixin
RegistryStub()
def test_registry_mixin_present(self): # THEN: The bootstrap methods should be registered
""" assert len(Registry().functions_list) == 3, 'The bootstrap functions should be in the dict.'
Test the registry creation and its usage
"""
# GIVEN: A new registry
Registry.create()
# WHEN: I create an instance of a class that inherits from RegistryMixin
RegistryStub()
# THEN: The bootstrap methods should be registered
assert len(Registry().functions_list) == 3, 'The bootstrap functions should be in the dict.'

View File

@ -21,272 +21,271 @@
""" """
Package to test the openlp.core.lib.settings package. Package to test the openlp.core.lib.settings package.
""" """
import pytest
from pathlib import Path from pathlib import Path
from unittest import TestCase
from unittest.mock import call, patch from unittest.mock import call, patch
from openlp.core.common import settings from openlp.core.common import settings
from openlp.core.common.settings import Settings, media_players_conv from openlp.core.common.settings import Settings, media_players_conv
from tests.helpers.testmixin import TestMixin
class TestSettings(TestCase, TestMixin): def test_media_players_conv():
""" """Test the media players conversion function"""
Test the functions in the Settings module # GIVEN: A list of media players
""" media_players = 'phonon,webkit,vlc'
def setUp(self):
"""
Create the UI
"""
self.setup_application()
self.build_settings()
def tearDown(self): # WHEN: The media converter function is called
""" result = media_players_conv(media_players)
Delete all the C++ objects at the end so that we don't have a segfault
"""
self.destroy_settings()
def test_media_players_conv(self): # THEN: The list should have been converted correctly
"""Test the media players conversion function""" assert result == 'system,webkit,vlc'
# GIVEN: A list of media players
media_players = 'phonon,webkit,vlc'
# WHEN: The media converter function is called
result = media_players_conv(media_players)
# THEN: The list should have been converted correctly def test_default_value(settings):
assert result == 'system,webkit,vlc' """Test reading a setting that doesn't exist yet"""
# GIVEN: A setting that doesn't exist yet
def test_default_value(self): # WHEN reading a setting for the first time
"""Test reading a setting that doesn't exist yet""" default_value = Settings().value('core/has run wizard')
# GIVEN: A setting that doesn't exist yet
# WHEN reading a setting for the first time # THEN the default value is returned
default_value = Settings().value('core/has run wizard') assert default_value is False, 'The default value should be False'
# THEN the default value is returned
assert default_value is False, 'The default value should be False'
def test_save_new_value(self): def test_save_new_value(settings):
"""Test saving a new setting""" """Test saving a new setting"""
# GIVEN: A setting that hasn't been saved yet # GIVEN: A setting that hasn't been saved yet
# WHEN a new value is saved into config # WHEN a new value is saved into config
Settings().setValue('core/has run wizard', True) Settings().setValue('core/has run wizard', True)
# THEN the new value is returned when re-read # THEN the new value is returned when re-read
assert Settings().value('core/has run wizard') is True, 'The saved value should have been returned' assert Settings().value('core/has run wizard') is True, 'The saved value should have been returned'
def test_set_up_default_values(self):
"""Test that the default values are updated"""
# GIVEN: A Settings object with defaults
# WHEN: set_up_default_values() is called
Settings.set_up_default_values()
# THEN: The default values should have been added to the dictionary def test_set_up_default_values():
assert 'advanced/default service name' in Settings.__default_settings__ """Test that the default values are updated"""
# GIVEN: A Settings object with defaults
# WHEN: set_up_default_values() is called
Settings.set_up_default_values()
def test_get_default_value(self): # THEN: The default values should have been added to the dictionary
"""Test that the default value for a setting is returned""" assert 'advanced/default service name' in Settings.__default_settings__
# GIVEN: A Settings class with a default value
Settings.__default_settings__['test/moo'] = 'baa'
# WHEN: get_default_value() is called
result = Settings().get_default_value('test/moo')
# THEN: The correct default value should be returned def test_get_default_value():
assert result == 'baa' """Test that the default value for a setting is returned"""
# GIVEN: A Settings class with a default value
Settings.__default_settings__['test/moo'] = 'baa'
def test_settings_override(self): # WHEN: get_default_value() is called
"""Test the Settings creation and its override usage""" result = Settings().get_default_value('test/moo')
# GIVEN: an override for the settings
screen_settings = {
'test/extend': 'very wide',
}
Settings().extend_default_settings(screen_settings)
# WHEN reading a setting for the first time # THEN: The correct default value should be returned
extend = Settings().value('test/extend') assert result == 'baa'
# THEN the default value is returned
assert extend == 'very wide', 'The default value of "very wide" should be returned'
def test_save_existing_setting(self): def test_settings_override():
"""Test that saving an existing setting returns the new value""" """Test the Settings creation and its override usage"""
# GIVEN: An existing setting # GIVEN: an override for the settings
Settings().extend_default_settings({'test/existing value': None}) screen_settings = {
Settings().setValue('test/existing value', 'old value') 'test/extend': 'very wide',
}
Settings().extend_default_settings(screen_settings)
# WHEN a new value is saved into config # WHEN reading a setting for the first time
Settings().setValue('test/existing value', 'new value') extend = Settings().value('test/extend')
# THEN the new value is returned when re-read # THEN the default value is returned
assert Settings().value('test/existing value') == 'new value', 'The saved value should be returned' assert extend == 'very wide', 'The default value of "very wide" should be returned'
def test_settings_override_with_group(self):
"""Test the Settings creation and its override usage - with groups"""
# GIVEN: an override for the settings
screen_settings = {
'test/extend': 'very wide',
}
Settings.extend_default_settings(screen_settings)
# WHEN reading a setting for the first time def test_save_existing_setting():
settings = Settings() """Test that saving an existing setting returns the new value"""
settings.beginGroup('test') # GIVEN: An existing setting
extend = settings.value('extend') Settings().extend_default_settings({'test/existing value': None})
Settings().setValue('test/existing value', 'old value')
# THEN the default value is returned # WHEN a new value is saved into config
assert 'very wide' == extend, 'The default value defined should be returned' Settings().setValue('test/existing value', 'new value')
# WHEN a new value is saved into config # THEN the new value is returned when re-read
Settings().setValue('test/extend', 'very short') assert Settings().value('test/existing value') == 'new value', 'The saved value should be returned'
# THEN the new value is returned when re-read
assert 'very short' == Settings().value('test/extend'), 'The saved value should be returned'
def test_settings_nonexisting(self): def test_settings_override_with_group():
"""Test the Settings on query for non-existing value""" """Test the Settings creation and its override usage - with groups"""
# GIVEN: A new Settings setup # GIVEN: an override for the settings
with self.assertRaises(KeyError) as cm: screen_settings = {
# WHEN reading a setting that doesn't exists 'test/extend': 'very wide',
Settings().value('core/does not exists') }
Settings.extend_default_settings(screen_settings)
# THEN: An exception with the non-existing key should be thrown # WHEN reading a setting for the first time
assert str(cm.exception) == "'core/does not exists'", 'We should get an exception' settings = Settings()
settings.beginGroup('test')
extend = settings.value('extend')
def test_extend_default_settings(self): # THEN the default value is returned
"""Test that the extend_default_settings method extends the default settings""" assert 'very wide' == extend, 'The default value defined should be returned'
# GIVEN: A patched __default_settings__ dictionary
with patch.dict(Settings.__default_settings__,
{'test/setting 1': 1, 'test/setting 2': 2, 'test/setting 3': 3}, True):
# WHEN: Calling extend_default_settings # WHEN a new value is saved into config
Settings.extend_default_settings({'test/setting 3': 4, 'test/extended 1': 1, 'test/extended 2': 2}) Settings().setValue('test/extend', 'very short')
# THEN: The _default_settings__ dictionary_ should have the new keys # THEN the new value is returned when re-read
assert Settings.__default_settings__ == {'test/setting 1': 1, 'test/setting 2': 2, 'test/setting 3': 4, assert 'very short' == Settings().value('test/extend'), 'The saved value should be returned'
'test/extended 1': 1, 'test/extended 2': 2}
@patch('openlp.core.common.settings.QtCore.QSettings.contains')
@patch('openlp.core.common.settings.QtCore.QSettings.value')
@patch('openlp.core.common.settings.QtCore.QSettings.setValue')
@patch('openlp.core.common.settings.QtCore.QSettings.remove')
def test_upgrade_single_setting(self, mocked_remove, mocked_setValue, mocked_value, mocked_contains):
"""Test that the upgrade mechanism for settings works correctly for single value upgrades"""
# GIVEN: A settings object with an upgrade step to take (99, so that we don't interfere with real ones)
local_settings = Settings()
local_settings.__setting_upgrade_99__ = [
('single/value', 'single/new value', [(str, '')])
]
settings.__version__ = 99
mocked_value.side_effect = [98, 10]
mocked_contains.return_value = True
# WHEN: upgrade_settings() is called def test_settings_nonexisting():
local_settings.upgrade_settings() """Test the Settings on query for non-existing value"""
# GIVEN: A new Settings setup
with pytest.raises(KeyError) as cm:
# WHEN reading a setting that doesn't exists
Settings().value('core/does not exists')
# THEN: The correct calls should have been made with the correct values # THEN: An exception with the non-existing key should be thrown
assert mocked_value.call_count == 2, 'Settings().value() should have been called twice' assert str(cm.value) != KeyError("'core/does not exists'", 'We should get an exception')
assert mocked_value.call_args_list == [call('settings/version', 0), call('single/value')]
assert mocked_setValue.call_count == 2, 'Settings().setValue() should have been called twice'
assert mocked_setValue.call_args_list == [call('single/new value', '10'), call('settings/version', 99)]
mocked_contains.assert_called_once_with('single/value')
mocked_remove.assert_called_once_with('single/value')
@patch('openlp.core.common.settings.QtCore.QSettings.contains')
@patch('openlp.core.common.settings.QtCore.QSettings.value')
@patch('openlp.core.common.settings.QtCore.QSettings.setValue')
@patch('openlp.core.common.settings.QtCore.QSettings.remove')
def test_upgrade_setting_value(self, mocked_remove, mocked_setValue, mocked_value, mocked_contains):
"""Test that the upgrade mechanism for settings correctly uses the new value when it's not a function"""
# GIVEN: A settings object with an upgrade step to take (99, so that we don't interfere with real ones)
local_settings = Settings()
local_settings.__setting_upgrade_99__ = [
('values/old value', 'values/new value', [(True, 1)])
]
settings.__version__ = 99
mocked_value.side_effect = [98, 1]
mocked_contains.return_value = True
# WHEN: upgrade_settings() is called def test_extend_default_settings():
local_settings.upgrade_settings() """Test that the extend_default_settings method extends the default settings"""
# GIVEN: A patched __default_settings__ dictionary
with patch.dict(Settings.__default_settings__,
{'test/setting 1': 1, 'test/setting 2': 2, 'test/setting 3': 3}, True):
# THEN: The correct calls should have been made with the correct values # WHEN: Calling extend_default_settings
assert mocked_value.call_count == 2, 'Settings().value() should have been called twice' Settings.extend_default_settings({'test/setting 3': 4, 'test/extended 1': 1, 'test/extended 2': 2})
assert mocked_value.call_args_list == [call('settings/version', 0), call('values/old value')]
assert mocked_setValue.call_count == 2, 'Settings().setValue() should have been called twice'
assert mocked_setValue.call_args_list == [call('values/new value', True), call('settings/version', 99)]
mocked_contains.assert_called_once_with('values/old value')
mocked_remove.assert_called_once_with('values/old value')
@patch('openlp.core.common.settings.QtCore.QSettings.contains') # THEN: The _default_settings__ dictionary_ should have the new keys
@patch('openlp.core.common.settings.QtCore.QSettings.value') assert Settings.__default_settings__ == {'test/setting 1': 1, 'test/setting 2': 2, 'test/setting 3': 4,
@patch('openlp.core.common.settings.QtCore.QSettings.setValue') 'test/extended 1': 1, 'test/extended 2': 2}
@patch('openlp.core.common.settings.QtCore.QSettings.remove')
def test_upgrade_multiple_one_invalid(self, mocked_remove, mocked_setValue, mocked_value, mocked_contains):
"""Test that the upgrade mechanism for settings works correctly for multiple values where one is invalid"""
# GIVEN: A settings object with an upgrade step to take
local_settings = Settings()
local_settings.__setting_upgrade_99__ = [
(['multiple/value 1', 'multiple/value 2'], 'single/new value', [])
]
settings.__version__ = 99
mocked_value.side_effect = [98, 10]
mocked_contains.side_effect = [True, False]
# WHEN: upgrade_settings() is called
local_settings.upgrade_settings()
# THEN: The correct calls should have been made with the correct values @patch('openlp.core.common.settings.QtCore.QSettings.contains')
mocked_value.assert_called_once_with('settings/version', 0) @patch('openlp.core.common.settings.QtCore.QSettings.value')
mocked_setValue.assert_called_once_with('settings/version', 99) @patch('openlp.core.common.settings.QtCore.QSettings.setValue')
assert mocked_contains.call_args_list == [call('multiple/value 1'), call('multiple/value 2')] @patch('openlp.core.common.settings.QtCore.QSettings.remove')
def test_upgrade_single_setting(mocked_remove, mocked_setValue, mocked_value, mocked_contains):
"""Test that the upgrade mechanism for settings works correctly for single value upgrades"""
# GIVEN: A settings object with an upgrade step to take (99, so that we don't interfere with real ones)
local_settings = Settings()
local_settings.__setting_upgrade_99__ = [
('single/value', 'single/new value', [(str, '')])
]
settings.__version__ = 99
mocked_value.side_effect = [98, 10]
mocked_contains.return_value = True
def test_can_upgrade(self): # WHEN: upgrade_settings() is called
"""Test the Settings.can_upgrade() method""" local_settings.upgrade_settings()
# GIVEN: A Settings object
local_settings = Settings()
# WHEN: can_upgrade() is run # THEN: The correct calls should have been made with the correct values
result = local_settings.can_upgrade() assert mocked_value.call_count == 2, 'Settings().value() should have been called twice'
assert mocked_value.call_args_list == [call('settings/version', 0), call('single/value')]
assert mocked_setValue.call_count == 2, 'Settings().setValue() should have been called twice'
assert mocked_setValue.call_args_list == [call('single/new value', '10'), call('settings/version', 99)]
mocked_contains.assert_called_once_with('single/value')
mocked_remove.assert_called_once_with('single/value')
# THEN: The result should be True
assert result is True, 'The settings should be upgradeable'
def test_convert_value_setting_none_str(self): @patch('openlp.core.common.settings.QtCore.QSettings.contains')
"""Test the Settings._convert_value() method when a setting is None and the default value is a string""" @patch('openlp.core.common.settings.QtCore.QSettings.value')
# GIVEN: A settings object @patch('openlp.core.common.settings.QtCore.QSettings.setValue')
# WHEN: _convert_value() is run @patch('openlp.core.common.settings.QtCore.QSettings.remove')
result = Settings()._convert_value(None, 'string') def test_upgrade_setting_value(mocked_remove, mocked_setValue, mocked_value, mocked_contains):
"""Test that the upgrade mechanism for settings correctly uses the new value when it's not a function"""
# GIVEN: A settings object with an upgrade step to take (99, so that we don't interfere with real ones)
local_settings = Settings()
local_settings.__setting_upgrade_99__ = [
('values/old value', 'values/new value', [(True, 1)])
]
settings.__version__ = 99
mocked_value.side_effect = [98, 1]
mocked_contains.return_value = True
# THEN: The result should be an empty string # WHEN: upgrade_settings() is called
assert result == '', 'The result should be an empty string' local_settings.upgrade_settings()
def test_convert_value_setting_none_list(self): # THEN: The correct calls should have been made with the correct values
"""Test the Settings._convert_value() method when a setting is None and the default value is a list""" assert mocked_value.call_count == 2, 'Settings().value() should have been called twice'
# GIVEN: A settings object assert mocked_value.call_args_list == [call('settings/version', 0), call('values/old value')]
# WHEN: _convert_value() is run assert mocked_setValue.call_count == 2, 'Settings().setValue() should have been called twice'
result = Settings()._convert_value(None, [None]) assert mocked_setValue.call_args_list == [call('values/new value', True), call('settings/version', 99)]
mocked_contains.assert_called_once_with('values/old value')
mocked_remove.assert_called_once_with('values/old value')
# THEN: The result should be an empty list
assert result == [], 'The result should be an empty list'
def test_convert_value_setting_json_Path(self): @patch('openlp.core.common.settings.QtCore.QSettings.contains')
"""Test the Settings._convert_value() method when a setting is JSON and represents a Path object""" @patch('openlp.core.common.settings.QtCore.QSettings.value')
# GIVEN: A settings object @patch('openlp.core.common.settings.QtCore.QSettings.setValue')
# WHEN: _convert_value() is run @patch('openlp.core.common.settings.QtCore.QSettings.remove')
result = Settings()._convert_value( def test_upgrade_multiple_one_invalid(mocked_remove, mocked_setValue, mocked_value, mocked_contains):
'{"parts": ["openlp", "core"], "json_meta": {"class": "Path", "version": 1}}', None) """Test that the upgrade mechanism for settings works correctly for multiple values where one is invalid"""
# GIVEN: A settings object with an upgrade step to take
local_settings = Settings()
local_settings.__setting_upgrade_99__ = [
(['multiple/value 1', 'multiple/value 2'], 'single/new value', [])
]
settings.__version__ = 99
mocked_value.side_effect = [98, 10]
mocked_contains.side_effect = [True, False]
# THEN: The result should be a Path object # WHEN: upgrade_settings() is called
assert isinstance(result, Path), 'The result should be a Path object' local_settings.upgrade_settings()
def test_convert_value_setting_bool_str(self): # THEN: The correct calls should have been made with the correct values
"""Test the Settings._convert_value() method when a setting is supposed to be a boolean""" mocked_value.assert_called_once_with('settings/version', 0)
# GIVEN: A settings object mocked_setValue.assert_called_once_with('settings/version', 99)
# WHEN: _convert_value() is run assert mocked_contains.call_args_list == [call('multiple/value 1'), call('multiple/value 2')]
result = Settings()._convert_value('false', True)
# THEN: The result should be False
assert result is False, 'The result should be False' def test_can_upgrade():
"""Test the Settings.can_upgrade() method"""
# GIVEN: A Settings object
local_settings = Settings()
# WHEN: can_upgrade() is run
result = local_settings.can_upgrade()
# THEN: The result should be True
assert result is True, 'The settings should be upgradeable'
def test_convert_value_setting_none_str():
"""Test the Settings._convert_value() method when a setting is None and the default value is a string"""
# GIVEN: A settings object
# WHEN: _convert_value() is run
result = Settings()._convert_value(None, 'string')
# THEN: The result should be an empty string
assert result == '', 'The result should be an empty string'
def test_convert_value_setting_none_list():
"""Test the Settings._convert_value() method when a setting is None and the default value is a list"""
# GIVEN: A settings object
# WHEN: _convert_value() is run
result = Settings()._convert_value(None, [None])
# THEN: The result should be an empty list
assert result == [], 'The result should be an empty list'
def test_convert_value_setting_json_Path():
"""Test the Settings._convert_value() method when a setting is JSON and represents a Path object"""
# GIVEN: A settings object
# WHEN: _convert_value() is run
result = Settings()._convert_value(
'{"parts": ["openlp", "core"], "json_meta": {"class": "Path", "version": 1}}', None)
# THEN: The result should be a Path object
assert isinstance(result, Path), 'The result should be a Path object'
def test_convert_value_setting_bool_str():
"""Test the Settings._convert_value() method when a setting is supposed to be a boolean"""
# GIVEN: A settings object
# WHEN: _convert_value() is run
result = Settings()._convert_value('false', True)
# THEN: The result should be False
assert result is False, 'The result should be False'

View File

@ -18,96 +18,95 @@
# You should have received a copy of the GNU General Public License # # You should have received a copy of the GNU General Public License #
# along with this program. If not, see <https://www.gnu.org/licenses/>. # # along with this program. If not, see <https://www.gnu.org/licenses/>. #
########################################################################## ##########################################################################
import pytest
from pathlib import Path from pathlib import Path
from unittest import TestCase
from unittest.mock import MagicMock, patch from unittest.mock import MagicMock, patch
from openlp.core.common.registry import Registry from openlp.core.common.registry import Registry
from openlp.core.server import Server from openlp.core.server import Server
from tests.helpers.testmixin import TestMixin
class TestServer(TestCase, TestMixin): @pytest.fixture
def server(registry):
with patch('PyQt5.QtNetwork.QLocalSocket'):
server = Server()
yield server
server.close_server()
def test_is_another_instance_running(server):
""" """
Test the Server Class used to check if OpenLP is running. Run a test as if this was the first time and no instance is running
""" """
def setUp(self): # GIVEN: A running Server
Registry.create()
with patch('PyQt5.QtNetwork.QLocalSocket'):
self.server = Server()
def tearDown(self): # WHEN: I ask for it to start
self.server.close_server() value = server.is_another_instance_running()
def test_is_another_instance_running(self): # THEN the following is called
""" server.out_socket.waitForConnected.assert_called_once_with()
Run a test as if this was the first time and no instance is running server.out_socket.connectToServer.assert_called_once_with(server.id)
""" assert isinstance(value, MagicMock)
# GIVEN: A running Server
# WHEN: I ask for it to start
value = self.server.is_another_instance_running()
# THEN the following is called def test_is_another_instance_running_true(server):
self.server.out_socket.waitForConnected.assert_called_once_with() """
self.server.out_socket.connectToServer.assert_called_once_with(self.server.id) Run a test as if there is another instance running
assert isinstance(value, MagicMock) """
# GIVEN: A running Server
server.out_socket.waitForConnected.return_value = True
def test_is_another_instance_running_true(self): # WHEN: I ask for it to start
""" value = server.is_another_instance_running()
Run a test as if there is another instance running
"""
# GIVEN: A running Server
self.server.out_socket.waitForConnected.return_value = True
# WHEN: I ask for it to start # THEN the following is called
value = self.server.is_another_instance_running() server.out_socket.waitForConnected.assert_called_once_with()
server.out_socket.connectToServer.assert_called_once_with(server.id)
assert value is True
# THEN the following is called
self.server.out_socket.waitForConnected.assert_called_once_with()
self.server.out_socket.connectToServer.assert_called_once_with(self.server.id)
assert value is True
def test_on_read_ready(self): def test_on_read_ready(server):
""" """
Test the on_read_ready method calls the service_manager Test the on_read_ready method calls the service_manager
""" """
# GIVEN: A server with a service manager # GIVEN: A server with a service manager
self.server.in_stream = MagicMock() server.in_stream = MagicMock()
service_manager = MagicMock() service_manager = MagicMock()
Registry().register('service_manager', service_manager) Registry().register('service_manager', service_manager)
# WHEN: a file is added to the socket and the method called # WHEN: a file is added to the socket and the method called
file_name = '\\home\\superfly\\' file_name = '\\home\\superfly\\'
self.server.in_stream.readLine.return_value = file_name server.in_stream.readLine.return_value = file_name
self.server._on_ready_read() server._on_ready_read()
# THEN: the service will be loaded # THEN: the service will be loaded
assert service_manager.load_service.call_count == 1 assert service_manager.load_service.call_count == 1
service_manager.load_service.assert_called_once_with(Path(file_name)) service_manager.load_service.assert_called_once_with(Path(file_name))
@patch("PyQt5.QtCore.QTextStream")
def test_post_to_server(self, mocked_stream):
"""
A Basic test with a post to the service
:return:
"""
# GIVEN: A server
# WHEN: I post to a server
self.server.post_to_server(['l', 'a', 'm', 'a', 's'])
# THEN: the file should be passed out to the socket @patch("PyQt5.QtCore.QTextStream")
self.server.out_socket.write.assert_called_once_with(b'lamas') def test_post_to_server(mocked_stream, server):
"""
A Basic test with a post to the service
:return:
"""
# GIVEN: A server
# WHEN: I post to a server
server.post_to_server(['l', 'a', 'm', 'a', 's'])
@patch("PyQt5.QtCore.QTextStream") # THEN: the file should be passed out to the socket
def test_post_to_server_openlp(self, mocked_stream): server.out_socket.write.assert_called_once_with(b'lamas')
"""
A Basic test with a post to the service with OpenLP
:return:
"""
# GIVEN: A server
# WHEN: I post to a server
self.server.post_to_server(['l', 'a', 'm', 'a', 's', 'OpenLP'])
# THEN: the file should be passed out to the socket
self.server.out_socket.write.assert_called_once_with(b'lamas') @patch("PyQt5.QtCore.QTextStream")
def test_post_to_server_openlp(mocked_stream, server):
"""
A Basic test with a post to the service with OpenLP
:return:
"""
# GIVEN: A server
# WHEN: I post to a server
server.post_to_server(['l', 'a', 'm', 'a', 's', 'OpenLP'])
# THEN: the file should be passed out to the socket
server.out_socket.write.assert_called_once_with(b'lamas')

View File

@ -1,5 +1,4 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
########################################################################## ##########################################################################
# OpenLP - Open Source Lyrics Projection # # OpenLP - Open Source Lyrics Projection #
# ---------------------------------------------------------------------- # # ---------------------------------------------------------------------- #
@ -18,133 +17,114 @@
# You should have received a copy of the GNU General Public License # # You should have received a copy of the GNU General Public License #
# along with this program. If not, see <https://www.gnu.org/licenses/>. # # along with this program. If not, see <https://www.gnu.org/licenses/>. #
########################################################################## ##########################################################################
from unittest import TestCase
from unittest.mock import MagicMock from unittest.mock import MagicMock
from openlp.core.state import State from openlp.core.state import State
from openlp.core.common.registry import Registry from openlp.core.common.registry import Registry
from openlp.core.lib.plugin import PluginStatus from openlp.core.lib.plugin import PluginStatus
from tests.helpers.testmixin import TestMixin
""" """
Test the Status class. Test the States class.
""" """
class TestState(TestCase, TestMixin): def test_add_service(state):
""" # GIVEN a new state
Test the Server Class used to check if OpenLP is running. # WHEN I add a new service
""" State().add_service("test", 1, PluginStatus.Active)
def setUp(self):
Registry.create()
def tearDown(self): # THEN I have a saved service
pass assert len(State().modules) == 1
def test_add_service(self):
# GIVEN a new state
State().load_settings()
# WHEN I add a new service def test_add_service_multiple(state):
State().add_service("test", 1, PluginStatus.Active) # GIVEN a new state
# WHEN I add a new service twice
State().add_service("test", 1, PluginStatus.Active)
State().add_service("test", 1, PluginStatus.Active)
# THEN I have a saved service # THEN I have a single saved service
assert len(State().modules) == 1 assert len(State().modules) == 1
def test_add_service_multiple(self):
# GIVEN a new state
State().load_settings()
# WHEN I add a new service twice def test_add_service_multiple_depend(state):
State().add_service("test", 1, PluginStatus.Active) # GIVEN a new state
State().add_service("test", 1, PluginStatus.Active) # WHEN I add a new service twice
State().add_service("test", 1, 1, PluginStatus.Active)
State().add_service("test1", 1, 1, PluginStatus.Active, "test")
State().add_service("test1", 1, 1, PluginStatus.Active, "test")
# THEN I have a single saved service # THEN I have still have a single saved service and one dependency
assert len(State().modules) == 1 assert len(State().modules) == 2
assert len(State().modules['test'].required_by) == 1
def test_add_service_multiple_depend(self):
# GIVEN a new state
State().load_settings()
# WHEN I add a new service twice def test_add_service_multiple_depends(state):
State().add_service("test", 1, 1, PluginStatus.Active) # GIVEN a new state
State().add_service("test1", 1, 1, PluginStatus.Active, "test") # WHEN I add a new service twice
State().add_service("test1", 1, 1, PluginStatus.Active, "test") State().add_service("test", 1, 1, PluginStatus.Active)
State().add_service("test1", 1, 1, PluginStatus.Active, "test")
State().add_service("test2", 1, 1, PluginStatus.Active, "test")
# THEN I have still have a single saved service and one dependency # THEN I have a 3 modules and 2 dependencies
assert len(State().modules) == 2 assert len(State().modules) == 3
assert len(State().modules['test'].required_by) == 1 assert len(State().modules['test'].required_by) == 2
def test_add_service_multiple_depends(self):
# GIVEN a new state
State().load_settings()
# WHEN I add a new service twice def test_active_service(state):
State().add_service("test", 1, 1, PluginStatus.Active) # GIVEN a new state
State().add_service("test1", 1, 1, PluginStatus.Active, "test") # WHEN I add a new service which is Active
State().add_service("test2", 1, 1, PluginStatus.Active, "test") State().add_service("test", 1, 1, PluginStatus.Active)
# THEN I have a 3 modules and 2 dependencies # THEN I have a single saved service
assert len(State().modules) == 3 assert State().is_module_active('test') is True
assert len(State().modules['test'].required_by) == 2
def test_active_service(self):
# GIVEN a new state
State().load_settings()
# WHEN I add a new service which is Active def test_inactive_service(state):
State().add_service("test", 1, 1, PluginStatus.Active) # GIVEN a new state
# WHEN I add a new service which is Inactive
State().add_service("test", 1, 1, PluginStatus.Inactive)
# THEN I have a single saved service # THEN I have a single saved service
assert State().is_module_active('test') is True assert State().is_module_active('test') is False
def test_inactive_service(self):
# GIVEN a new state
State().load_settings()
# WHEN I add a new service which is Inactive def test_basic_preconditions_fail(state, registry):
State().add_service("test", 1, 1, PluginStatus.Inactive) # GIVEN a new state
Registry().register('test_plugin', MagicMock())
# THEN I have a single saved service # WHEN I add a new services with dependencies and a failed pre condition
assert State().is_module_active('test') is False State().add_service("test", 1, 1, PluginStatus.Inactive)
State().add_service("test2", 1, 1, PluginStatus.Inactive)
State().add_service("test1", 1, 1, PluginStatus.Inactive, 'test')
State().update_pre_conditions('test', False)
def test_basic_preconditions_fail(self): # THEN correct the state when I flush the preconditions
# GIVEN a new state assert State().modules['test'].pass_preconditions is False
State().load_settings() assert State().modules['test2'].pass_preconditions is False
Registry().register('test_plugin', MagicMock()) assert State().modules['test1'].pass_preconditions is False
State().flush_preconditions()
assert State().modules['test'].pass_preconditions is False
assert State().modules['test2'].pass_preconditions is False
assert State().modules['test1'].pass_preconditions is False
# WHEN I add a new services with dependencies and a failed pre condition
State().add_service("test", 1, 1, PluginStatus.Inactive)
State().add_service("test2", 1, 1, PluginStatus.Inactive)
State().add_service("test1", 1, 1, PluginStatus.Inactive, 'test')
State().update_pre_conditions('test', False)
# THEN correct the state when I flush the preconditions def test_basic_preconditions_pass(state, registry):
assert State().modules['test'].pass_preconditions is False # GIVEN a new state
assert State().modules['test2'].pass_preconditions is False Registry().register('test_plugin', MagicMock())
assert State().modules['test1'].pass_preconditions is False
State().flush_preconditions()
assert State().modules['test'].pass_preconditions is False
assert State().modules['test2'].pass_preconditions is False
assert State().modules['test1'].pass_preconditions is False
def test_basic_preconditions_pass(self): # WHEN I add a new services with dependencies and a failed pre condition
# GIVEN a new state State().add_service("test", 1, 1, PluginStatus.Inactive)
State().load_settings() State().add_service("test2", 1, 1, PluginStatus.Inactive)
Registry().register('test_plugin', MagicMock()) State().add_service("test1", 1, 1, PluginStatus.Inactive, 'test')
State().update_pre_conditions('test', True)
# WHEN I add a new services with dependencies and a failed pre condition # THEN correct the state when I flush the preconditions
State().add_service("test", 1, 1, PluginStatus.Inactive) assert State().modules['test'].pass_preconditions is True
State().add_service("test2", 1, 1, PluginStatus.Inactive) assert State().modules['test2'].pass_preconditions is False
State().add_service("test1", 1, 1, PluginStatus.Inactive, 'test') assert State().modules['test1'].pass_preconditions is False
State().update_pre_conditions('test', True) State().flush_preconditions()
assert State().modules['test'].pass_preconditions is True
# THEN correct the state when I flush the preconditions assert State().modules['test2'].pass_preconditions is False
assert State().modules['test'].pass_preconditions is True assert State().modules['test1'].pass_preconditions is True
assert State().modules['test2'].pass_preconditions is False
assert State().modules['test1'].pass_preconditions is False
State().flush_preconditions()
assert State().modules['test'].pass_preconditions is True
assert State().modules['test2'].pass_preconditions is False
assert State().modules['test1'].pass_preconditions is True