Skip to main content
Version: 13

viktor.testing

mock_ParamsFromFile

viktor.testing.mock_ParamsFromFile(controller)

Decorator that can be used for testing methods decorated with viktor.core.ParamsFromFile.

Example:

import unittest

from viktor.testing import mock_ParamsFromFile

from app.my_entity.controller import MyEntityController

class TestMyEntityController(unittest.TestCase):
    @mock_ParamsFromFile(MyEntityController)
    def test_process_file(self):
        file = File.from_data("abc")
        returned_dict = MyEntityController().process_file(file)
        self.assertDictEqual(returned_dict, {...})
Parameters

controller (Type[ViktorController]) – Controller class on which the ParamsFromFile should be mocked

Return type

Callable

mock_Storage

viktor.testing.mock_Storage(*, get=None, list=None)

Decorator that can be used for testing methods which invoke the viktor.core.Storage.

Use the get and list arguments to instruct which file(s) the respective Storage().get(…) and Storage().list(…) methods should return.

Example:

import unittest

from viktor.testing import mock_Storage

from app.my_entity.controller import MyEntityController

class TestMyEntityController(unittest.TestCase):
    @mock_Storage(
        get=[File.from_data("abc"), File.from_data("def")],
        list=[{'data_key_3': File.from_data("ghi")}]
    )
    def test_process_analysis_result(self):
        # Storage().get(...) invoked twice, Storage().list(...) invoked once
        result = MyEntityController().process_analysis_result()
        ...
Parameters
  • get (Optional[Sequence[File]]) – Files to be returned by Storage().get(…). The files are returned in order of the input list.

  • list (Optional[Sequence[Dict[str, File]]]) – File dicts to be returned by Storage().list(…). The dicts are returned in order of the input list.

Return type

Callable

MockedEntityType

class viktor.testing.MockedEntityType(name='MockedEntityType', entity_type_id=1)

Bases: viktor.api_v1.EntityType

To mock a EntityType (new in v13.3.0).

MockedEntityRevision

class viktor.testing.MockedEntityRevision(params=None, created_date=None)

Bases: viktor.api_v1.EntityRevision

To mock an EntityRevision (new in v13.3.0).

Example:

from viktor.testing import MockedEntityRevision, MockedEntity, MockedFileResource

params = {
    'number': 1,
    'entity': MockedEntity(name="MyEntity"),
    'file': MockedFileResource(File.from_data("content"), "file.txt")
}

mocked_entity_revision = MockedEntityRevision(params)

params can be passed from a JSON file by making use of mock_params():

from viktor import File
from viktor.testing import MockedEntityRevision, MockedEntity, MockedFileResource, mock_params

from app.my_entity.controller import MyEntityController

json_file = File.from_path("path to JSON file")
params = mock_params(
    json_file, MyEntityController.parametrization,
    entities={1: MockedEntity(name="MyEntity")},
    file_resources={1: MockedFileResource(File.from_data("content"), "file")}
)

mocked_entity_revision = MockedEntityRevision(params)
Parameters
  • params (Union[dict, Munch, None]) – Return value of EntityRevision.params. Must be the deserialized params (see mock_params()). None to set default (empty) params.

  • created_date (Optional[datetime]) – Return value of EntityRevision.created_date. None to set default date (2000, 1, 1).

MockedUser

class viktor.testing.MockedUser(*, first_name='John', last_name='Doe', email='john.doe@email.com', job_title='Employee')

Bases: viktor.api_v1.User

To mock a User (new in v13.3.0).

MockedFileResource

class viktor.testing.MockedFileResource(file=None, filename='mocked_file.txt')

To mock a FileResource (new in v13.3.0).

Parameters
  • file (Optional[File]) – Return value of FileResource.file. None to set default file with content = “mocked content”.

  • filename (str) – Return value of FileResource.filename.

MockedEntity

class viktor.testing.MockedEntity(*, entity_id=1, name='Mocked Entity', entity_type=None, last_saved_params=None, last_saved_summary=None, get_file=None, parent=None, children=None, siblings=None, revisions=None, invalid=False)

To mock an Entity (new in v13.3.0). All arguments are optional: instantiating MockedEntity without parameters returns a default MockedEntity.

Example:

from viktor.testing import MockedEntity, MockedEntityRevision

mocked_entity = MockedEntity(last_saved_params=params, revisions=[MockedEntityRevision(params)])

last_saved_params can be passed from a JSON file by making use of mock_params():

from viktor import File
from viktor.testing import MockedEntity, MockedEntityRevision, MockedFileResource, mock_params

from app.my_entity.controller import MyEntityController

json_file = File.from_path("path to JSON file")
params = mock_params(
    json_file, MyEntityController.parametrization,
    entities={1: MockedEntity(name="MyEntity")},
    file_resources={1: MockedFileResource(File.from_data("content"), "file")}
)

mocked_entity = MockedEntity(last_saved_params=params, revisions=[MockedEntityRevision(params)])
Parameters
  • entity_id (int) – Return value of Entity.id.

  • name (str) – Return value of Entity.name.

  • entity_type (Optional[MockedEntityType]) – Return value of Entity.entity_type. None for default MockedEntityType.

  • last_saved_params (Union[dict, Munch, None]) – Return value of Entity.last_saved_params(). Must be the deserialized params (see mock_params()). None to simulate an entity without params.

  • last_saved_summary (Optional[dict]) – Return value of Entity.last_saved_summary(). None to simulate an entity without summary.

  • get_file (Optional[File]) – Return value of Entity.get_file. None to simulate an entity without file.

  • parent (Optional[MockedEntity]) – Return value of Entity.parent. None to simulate an entity without parent.

  • children (Optional[Sequence[MockedEntity]]) – Return value of Entity.children. None to simulate an entity without children.

  • siblings (Optional[Sequence[MockedEntity]]) – Return value of Entity.siblings. None to simulate an entity without siblings.

  • revisions (Optional[Sequence[MockedEntityRevision]]) – Return value of Entity.revisions. None to simulate an entity without revisions.

  • invalid (bool) – Set to True to simulate failing API calls on this Entity.

property id: int
Return type

int

property name: str
Return type

str

property entity_type: viktor.testing.MockedEntityType
Return type

MockedEntityType

property last_saved_params: munch.Munch
Return type

Munch

property last_saved_summary: munch.Munch
Return type

Munch

get_file(*args, **kwargs)
Return type

File

parent(*args, **kwargs)
Return type

MockedEntity

children(*args, entity_type_names=None, **kwargs)
Return type

MockedEntityList

siblings(*args, entity_type_names=None, **kwargs)
Return type

MockedEntityList

create_child(entity_type_name, name, *args, params=None, **kwargs)
Return type

MockedEntity

delete(*args, **kwargs)
Return type

None

rename(name, *args, **kwargs)
Return type

MockedEntity

revisions(*args, **kwargs)
Return type

List[MockedEntityRevision]

set_params(params, *args, **kwargs)
Return type

MockedEntity

MockedEntityList

class viktor.testing.MockedEntityList(entities, *, error=None)

mock_API

viktor.testing.mock_API(*, get_entity=None, create_child_entity=None, generate_upload_url=None, get_current_user=None, get_entities_by_type=None, get_entity_children=None, get_entity_siblings=None, get_root_entities=None, get_entity_parent=None, get_entity_revisions=None, get_entity_file=None, rename_entity=None, set_entity_params=None)

Decorator that can be used to mock API() method calls, to facilitate easier testing (new in v13.3.0).

Example:

import unittest

from viktor import File
from viktor.testing import mock_API, MockedEntity

from app.my_entity.controller import MyEntityController

class TestMyEntityController(unittest.TestCase):
    @mock_API(
        get_entity=[MockedEntity(entity_id=98), MockedEntity(entity_id=99)],
        get_entity_file=File.from_data("fake content")
    )
    def test_api_calls(self):
        MyEntityController().api_calls()

Note that last_saved_params can be passed to MockedEntity from a JSON file by making use of mock_params():

import unittest

from viktor import File
from viktor.testing import mock_API, MockedEntity, mock_params, MockedFileResource

from app.my_entity.controller import MyEntityController

class TestMyEntityController(unittest.TestCase):
    json_file = File.from_path("path to JSON file")
    params = mock_params(
        json_file, MyEntityController.parametrization,
        entities={1: MockedEntity(name="MyEntity")},
        file_resources={1: MockedFileResource(File.from_data("content"), "file")}
    )

    @mock_API(
        get_entity=MockedEntity(last_saved_params=params, revisions=[MockedEntityRevision(params)])
    )
    def test_api_calls(self):
        MyEntityController().api_calls()
For all parameters the following holds:
  • If a Sequence type is provided, the next entry is returned for each corresponding API method call. When an API method is called on a depleted iterable, an Exception is raised.

  • If a single object is provided, the object is returned each time the corresponding API method is called (endlessly).

  • If None is provided (default), a default object is returned each time the corresponding API method is called (endlessly).

Parameters
  • get_entity (Union[Sequence[MockedEntity], MockedEntity, None]) – Return value of API.get_entity.

  • create_child_entity (Union[Sequence[MockedEntity], MockedEntity, None]) – Return value of API.create_child_entity.

  • generate_upload_url (Union[Sequence[dict], dict, None]) – Return value of API.generate_upload_url.

  • get_current_user (Union[Sequence[MockedUser], MockedUser, None]) – Return value of API.get_current_user.

  • get_entities_by_type (Union[Sequence[Sequence[MockedEntity]], Sequence[MockedEntity], None]) – Return value of API.get_entities_by_type.

  • get_entity_children (Union[Sequence[Sequence[MockedEntity]], Sequence[MockedEntity], None]) – Return value of API.get_entity_children.

  • get_entity_siblings (Union[Sequence[Sequence[MockedEntity]], Sequence[MockedEntity], None]) – Return value of API.get_entity_siblings.

  • get_root_entities (Union[Sequence[Sequence[MockedEntity]], Sequence[MockedEntity], None]) – Return value of API.get_root_entities.

  • get_entity_parent (Union[Sequence[MockedEntity], MockedEntity, None]) – Return value of API.get_entity_parent.

  • get_entity_revisions (Union[Sequence[Sequence[MockedEntityRevision]], Sequence[MockedEntityRevision], None]) – Return value of API.get_entity_revisions.

  • get_entity_file (Union[Sequence[File], File, None]) – Return value of API.get_entity_file.

  • rename_entity (Union[Sequence[MockedEntity], MockedEntity, None]) – Return value of API.rename_entity.

  • set_entity_params (Union[Sequence[MockedEntity], MockedEntity, None]) – Return value of API.set_entity_params.

Return type

Callable

mock_params

viktor.testing.mock_params(params, parametrization, file_resources=None, entities=None)

Convert a plain dict to the (deserialized) params, replacing FileResource and Entity objects with their mocked counterpart (MockedFileResource, MockedEntity). Can be used to test methods with params in their signature that are called by the VIKTOR platform (e.g. view methods, button methods).

Example:

import unittest

from viktor import File
from viktor.testing import mock_params, MockedEntity, MockedFileResource

from app.my_entity.controller import MyEntityController

class TestMyEntityController(unittest.TestCase):
    def test_button_method(self):
        // provide the params manually...
        params_dict = {'number': 1, 'entity': 2, 'file': 3}

        // or from a JSON file...
        params_dict = File.from_path("path to my JSON file")

        mocked_params = mock_params(
            params, MyEntityController.parametrization
            entities={2: MockedEntity(entity_id=2, name="My Entity")}
            file_resources={3: MockedFileResource(File.from_data("content"), "file.txt")},
        )

        MyEntityController().button_method(mocked_params)

Deserialization only affects the raw values associated with the following fields:

  • DateField

  • EntityOptionField

  • ChildEntityOptionField

  • SiblingEntityOptionField

  • EntityMultiSelectField

  • ChildEntityMultiSelectField

  • SiblingEntityMultiSelectField

  • GeoPointField

  • GeoPolylineField

  • GeoPolygonField

  • FileField

  • MultiFileField

Parameters
  • params (Union[dict, File]) – Plain dict or JSON file (with serialized params) to be converted to the (deserialized) params.

  • parametrization (Parametrization) – Parametrization corresponding to the params.

  • file_resources (Optional[Dict[int, MockedFileResource]]) – Maps FileResource source id in params to mocked file resource. If source id is not in file_resources, a default MockedFileResource (with default filename and File) is returned.

  • entities (Optional[Dict[int, MockedEntity]]) – Maps entity id in params to mocked entity. If entity id is not in entities, a default MockedEntity is returned.

Return type

Munch

mock_View

viktor.testing.mock_View(controller)

Decorator that can be used to mock @View decorators (any subclass of viktor.views.View), to facilitate easier testing of view methods (new in v13.3.0).

Example:

import unittest

from viktor.testing import mock_View

from app.my_entity.controller import MyEntityController

class TestMyEntityController(unittest.TestCase):
    @mock_View(MyEntityController)
    def test_geometry_view(self):
        params = ...
        geometry_result = MyEntityController().geometry_view(params=params)
        self.assertIsInstance(geometry_result.geometry, TransformableObject)
        self.assertEqual(geometry_result.labels, ...)
Parameters

controller (Type[ViktorController]) – Controller class on which the @View decorator should be mocked

Return type

Callable

mock_SciaAnalysis

viktor.testing.mock_SciaAnalysis(get_engineering_report=None, get_updated_esa_model=None, get_xml_output_file=None)

Decorator that can be used to mock viktor.external.scia.SciaAnalysis, to facilitate easier testing (new in v13.3.0).

Example:

import unittest

from viktor.testing import mock_SciaAnalysis

from app.my_entity.controller import MyEntityController

class TestMyEntityController(unittest.TestCase):
    @mock_SciaAnalysis(get_xml_output_file=File.from_path(Path(__file__).parent / 'test_output.xml'))
    def test_scia_analysis(self):
        MyEntityController().scia_analysis()
For all parameters the following holds:
  • If a Sequence type is provided, the next entry is returned for each corresponding method call. When a call is performed on a depleted iterable, an Exception is raised.

  • If a single object is provided, the object is returned each time the corresponding method is called (endlessly).

  • If None is provided (default), a default File/BytesIO object (with empty content) is returned each time the corresponding method is called (endlessly).

Parameters
  • get_engineering_report (Union[Sequence[Union[BytesIO, File]], BytesIO, File, None]) – Return value of SciaAnalysis.get_engineering_report.

  • get_updated_esa_model (Union[Sequence[Union[BytesIO, File]], BytesIO, File, None]) – Return value of SciaAnalysis.get_updated_esa_model.

  • get_xml_output_file (Union[Sequence[Union[BytesIO, File]], BytesIO, File, None]) – Return value of SciaAnalysis.get_xml_output_file.

Return type

Callable