unittest.mock.MagicMock

Here are the examples of the python api unittest.mock.MagicMock taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

11005 Examples 7

5 Source : __init__.py
with GNU General Public License v3.0
from Deric-W

    def test_values(self) -> None:
        """test CodeSourceContainer.values"""
        sources = {
            "a": unittest.mock.MagicMock(spec_set=CodeSource),
            "b": unittest.mock.MagicMock(spec_set=CodeSource),
            "c": unittest.mock.MagicMock(spec_set=CodeSource)
        }
        values = CodeSourceContainer.values(sources)
        for value in sources.values():
            value.__enter__ = lambda x: x
            value.__exit__ = context_manager_exit
            self.assertIn(value, values)
            value.close.assert_called()
        self.assertNotIn(1, values)

    def test_items(self) -> None:

5 Source : __init__.py
with GNU General Public License v3.0
from Deric-W

    def test_items(self) -> None:
        """test CodeSourceContainer.items"""
        sources = {
            "a": unittest.mock.MagicMock(spec_set=CodeSource),
            "b": unittest.mock.MagicMock(spec_set=CodeSource),
            "c": unittest.mock.MagicMock(spec_set=CodeSource)
        }
        items = CodeSourceContainer.items(sources)
        for name, source in sources.items():
            source.__enter__ = lambda x: x
            source.__exit__ = context_manager_exit
            self.assertIn((name, source), items)
            source.close.assert_called()
        self.assertNotIn(("a", 1), items)
        self.assertNotIn(("abc", 1), items)
        self.assertNotIn((1, 2), items)


class TestTimestampedCodeSourceContainer(unittest.TestCase):

5 Source : download_test.py
with MIT License
from sampottinger

    def setUp(self):
        self.__test_run = unittest.mock.MagicMock()
        self.__test_run.tags = ['tag1', 'tag2']
        self.__test_run.url = 'test/url'
        self.__test_run.name = 'test project'
        self.__test_run.state = 'finished'
        self.__test_run.created_at = 'creation str'
        self.__test_run.description = 'test description'
        self.__test_run.history = unittest.mock.MagicMock(return_value=[{'a': 1}, {'a': 2}])
        self.__test_run.config = {'config1': 1, 'config2': 2}

        self.__test_api = unittest.mock.MagicMock()
        self.__test_api.runs = unittest.mock.MagicMock(return_value=[self.__test_run])

        self.__test_logger = unittest.mock.MagicMock()
        self.__test_logger.debug = unittest.mock.MagicMock()

    def test_get_results(self):

3 Source : test_channel_control.py
with BSD 3-Clause "New" or "Revised" License
from 4DNucleome

    def test_settings_updated(self, qtbot, base_settings, monkeypatch):
        box = ColorComboBoxGroup(base_settings, "test", height=30)
        box.set_channels(4)
        mock = MagicMock()
        monkeypatch.setattr(box, "parameters_changed", mock)
        base_settings.set_in_profile("test.lock_0", True)
        mock.assert_called_once_with(0)
        dkt = dict(**base_settings.get_from_profile("test"))
        dkt["lock_0"] = False
        dkt["lock_1"] = True
        base_settings.set_in_profile("test", dkt)
        assert mock.call_count == 5
        mock.assert_called_with(3)

    def test_color_combo_box_group(self, qtbot):

3 Source : test_check_release.py
with BSD 3-Clause "New" or "Revised" License
from 4DNucleome

def test_create_ignore(qtbot, tmp_path, monkeypatch):
    monkeypatch.setattr(state_store, "save_folder", tmp_path)

    chk_thr = check_version.CheckVersionThread(base_version="0.10.0")
    chk_thr.release = "0.11.0"
    monkeypatch.setattr(check_version.QMessageBox, "exec_", MagicMock(return_value=check_version.QMessageBox.Ignore))
    chk_thr.show_version_info()
    assert (tmp_path / IGNORE_FILE).exists()
    with (tmp_path / IGNORE_FILE).open() as f_p:
        assert f_p.read() == date.today().isoformat()

3 Source : test_common_gui.py
with BSD 3-Clause "New" or "Revised" License
from 4DNucleome

    def test_click(self, qtbot, monkeypatch):
        popup = QtPopup(None)
        monkeypatch.setattr(popup, "close", MagicMock())
        qtbot.addWidget(popup)
        qtbot.keyClick(popup, Qt.Key_8)
        popup.close.assert_not_called()
        qtbot.keyClick(popup, Qt.Key_Return)
        popup.close.assert_called_once()


@pytest.mark.parametrize("function_name", SaveBase.need_functions)

3 Source : test_common_gui.py
with BSD 3-Clause "New" or "Revised" License
from 4DNucleome

    def test_theme_select(self, qtbot, base_settings, monkeypatch):
        monkeypatch.setattr(base_settings, "theme_list", lambda: ["aaa", "bbb", "ccc"])
        monkeypatch.setattr(base_settings, "napari_settings", MagicMock())
        monkeypatch.setattr(base_settings, "theme_name", "bbb")
        app = Appearance(base_settings)
        qtbot.add_widget(app)
        assert app.layout_list.currentText() == "bbb"
        app.layout_list.setCurrentIndex(0)
        assert app.layout_list.currentText() == "aaa"
        assert base_settings.theme_name == "aaa"

3 Source : test_napari_image_view.py
with BSD 3-Clause "New" or "Revised" License
from 4DNucleome

def test_search_component_modal(qtbot, image_view, monkeypatch):
    monkeypatch.setattr(image_view, "component_mark", MagicMock())
    monkeypatch.setattr(image_view, "component_zoom", MagicMock())
    monkeypatch.setattr(image_view, "component_unmark", MagicMock())
    modal = SearchComponentModal(image_view, SearchType.Highlight, component_num=1, max_components=5)
    qtbot.addWidget(modal)
    image_view.component_mark.assert_called_with(1, flash=True)
    modal.component_selector.setValue(2)
    image_view.component_mark.assert_called_with(2, flash=True)
    assert image_view.component_zoom.call_count == 0
    modal.zoom_to.setCurrentEnum(SearchType.Zoom_in)
    image_view.component_zoom.assert_called_with(2)
    assert image_view.component_mark.call_count == 2
    modal.component_selector.setValue(1)
    image_view.component_zoom.assert_called_with(1)
    modal.close()
    image_view.component_unmark.assert_called_once()

3 Source : test_json_hooks.py
with BSD 3-Clause "New" or "Revised" License
from 4DNucleome

    def test_propagate_signal(self):
        receiver = MagicMock()
        dkt = EventedDict(baz={"foo": 1})
        dkt.setted.connect(receiver.set)
        dkt.deleted.connect(receiver.deleted)
        dkt["baz"].base_key = ""
        dkt["baz"]["foo"] = 2
        receiver.set.assert_called_with("foo")
        receiver.set.assert_called_once()
        del dkt["baz"]["foo"]
        receiver.deleted.assert_called_with("foo")
        receiver.deleted.assert_called_once()


class TestProfileDict:

3 Source : base.py
with MIT License
from 5783354

    def patch_session(self, session_patch):
        class X:
            session = self.session

        mock_client = mock.MagicMock(spec=Transaction)
        mock_client.__enter__.return_value = X
        session_patch.return_value = mock_client

    def create_author(self, name):

3 Source : test_example_api.py
with MIT License
from aalhour

    async def test_returns_404_if_resource_not_found(self, session, get_by_id, client):
        ###
        # Arrange
        example_id = "1"
        session_mock = mock.MagicMock(name='transactional_session_mock')
        session.return_value = TransactionalSessionFixture(target_mock=session_mock)
        get_by_id.return_value = ExampleFixture.get_by_id.none.output()

        ###
        # Act
        response = await client.get(f"/api/v1.0/examples/{example_id}")

        ###
        # Assert
        assert response.status == 404
        json_response = await response.json()
        assert isinstance(json_response, dict)
        get_by_id.assert_called_once_with(example_id, session_mock)

3 Source : conftest.py
with MIT License
from abaisero

def forbidden_action_maker():
    def _forbidden_action_maker() -> Action:
        action = MagicMock()
        return action

    yield _forbidden_action_maker

3 Source : test_observation_functions.py
with MIT License
from abaisero

def test_factory_valid(name: str, kwargs):
    observation_space = MagicMock()
    factory(name, area=observation_space.area, **kwargs)


@pytest.mark.parametrize(

3 Source : test_transition_functions.py
with MIT License
from abaisero

def make_moving_obstacle_state():
    grid = Grid.from_shape((3, 3))
    grid[1, 1] = MovingObstacle()
    agent = MagicMock()
    return State(grid, agent)


@pytest.mark.parametrize(

3 Source : test_transition_functions.py
with MIT License
from abaisero

def test_move_obstacles(
    objects: Sequence[Sequence[GridObject]],
    expected_objects: Sequence[Sequence[GridObject]],
):
    state = State(Grid(objects), MagicMock())
    expected_state = State(Grid(expected_objects), MagicMock())

    action = MagicMock()
    move_obstacles(state, action)
    assert state.grid == expected_state.grid


@pytest.mark.parametrize(

3 Source : test_cli.py
with Mozilla Public License 2.0
from abravalheri

def test_critical_logging_sets_log_level_on_error(monkeypatch, caplog):
    spy = MagicMock()
    monkeypatch.setattr(sys, "argv", ["-vv"])
    monkeypatch.setattr(logging, "basicConfig", spy)
    with pytest.raises(ValueError):
        with cli.critical_logging():
            raise ValueError
    _args, kwargs = spy.call_args
    assert kwargs["level"] == logging.DEBUG


def test_critical_logging_does_nothing_if_no_argv(monkeypatch, caplog):

3 Source : test_cli.py
with Mozilla Public License 2.0
from abravalheri

def test_critical_logging_does_nothing_if_no_argv(monkeypatch, caplog):
    spy = MagicMock()
    monkeypatch.setattr(sys, "argv", [])
    monkeypatch.setattr(logging, "basicConfig", spy)
    with pytest.raises(ValueError):
        with cli.critical_logging():
            raise ValueError
    assert spy.call_args is None


def test_exceptisons2exit():

3 Source : test_controllers.py
with Apache License 2.0
from accelero-cloud

def setup_module(module):
    current_file_path = os.path.dirname(os.path.realpath(__file__))
    print('\nModule: >> {} at {}'.format(module, current_file_path))
    kernel = AppKernelEngine('test_app', app=flask_app, cfg_dir='{}/../'.format(current_file_path), development=True)
    kernel.register(payment_service)
    payment_service.sink = MagicMock(name='sink')
    list_flask_routes(flask_app)


def setup_function(function):

3 Source : playback_sync_tests.py
with Mozilla Public License 2.0
from ACMILabs

def test_get_current_time_interpolates():
    """
    Check that get_current_time interpolates the time from vlc.
    """
    player = MediaPlayer()
    mock_player = MagicMock()
    mock_player.get_time = MagicMock(return_value=250)
    player.vlc['player'] = mock_player
    assert player.get_current_time() == 250
    assert player.get_current_time() == 260
    assert player.get_current_time() == 270


def test_run_timer():

3 Source : playback_sync_tests.py
with Mozilla Public License 2.0
from ACMILabs

def test_client_drifts_from_server_sets_playlist_position():
    """
    Check that if the time drifts on a server playing a playlist,
    the client calls play_item_at_index on its player.
    """
    player = MediaPlayer()
    player.client.receive = MagicMock(return_value=[2, 50])
    player.get_current_time = MagicMock(return_value=100)
    player.get_current_playlist_position = MagicMock(return_value=1)
    player.vlc['player'].get_length = MagicMock(return_value=3000)
    assert_called_in_infinite_loop(
        'vlc.MediaListPlayer.play_item_at_index',
        player.sync_to_server
    )


@patch('media_player.network.Client', MagicMock())

3 Source : playback_sync_tests.py
with Mozilla Public License 2.0
from ACMILabs

def test_sync_to_server():
    """
    Test that sync_to_server successfully resyncs for exceptions.
    """
    player = MediaPlayer()
    player.client.receive = MagicMock(return_value=None)
    player.client.sync_attempts = 1
    assert_called_in_infinite_loop(
        'media_player.MediaPlayer.sync_check',
        player.sync_to_server,
    )

    player.client.receive = MagicMock(return_value=[0, 0])
    player.client.sync_attempts = 1
    assert_called_in_infinite_loop(
        'media_player.MediaPlayer.sync_check',
        player.sync_to_server,
    )

3 Source : test_circup.py
with MIT License
from adafruit

def test_find_device_posix_no_mount_command():
    """
    When the user doesn't have administrative privileges on OSX then the mount
    command isn't on their path. In which case, check circup uses the more
    explicit /sbin/mount instead.
    """
    with open("tests/mount_exists.txt", "rb") as fixture_file:
        fixture = fixture_file.read()
    mock_check = mock.MagicMock(side_effect=[FileNotFoundError, fixture])
    with mock.patch("os.name", "posix"), mock.patch("circup.check_output", mock_check):
        assert circup.find_device() == "/media/ntoll/CIRCUITPY"
        assert mock_check.call_count == 2
        assert mock_check.call_args_list[0][0][0] == "mount"
        assert mock_check.call_args_list[1][0][0] == "/sbin/mount"


def test_find_device_posix_missing():

3 Source : test_circup.py
with MIT License
from adafruit

def test_find_device_nt_exists():
    """
    Simulate being on os.name == 'nt' and a disk with a volume name 'CIRCUITPY'
    exists indicating a connected device.
    """
    mock_windll = mock.MagicMock()
    mock_windll.kernel32 = mock.MagicMock()
    mock_windll.kernel32.GetVolumeInformationW = mock.MagicMock()
    mock_windll.kernel32.GetVolumeInformationW.return_value = None
    fake_buffer = ctypes.create_unicode_buffer("CIRCUITPY")
    with mock.patch("os.name", "nt"), mock.patch(
        "os.path.exists", return_value=True
    ), mock.patch("ctypes.create_unicode_buffer", return_value=fake_buffer):
        ctypes.windll = mock_windll
        assert circup.find_device() == "A:\\"


def test_find_device_nt_missing():

3 Source : test_circup.py
with MIT License
from adafruit

def test_find_device_nt_missing():
    """
    Simulate being on os.name == 'nt' and a disk with a volume name 'CIRCUITPY'
    does not exist for a device.
    """
    mock_windll = mock.MagicMock()
    mock_windll.kernel32 = mock.MagicMock()
    mock_windll.kernel32.GetVolumeInformationW = mock.MagicMock()
    mock_windll.kernel32.GetVolumeInformationW.return_value = None
    fake_buffer = ctypes.create_unicode_buffer(1024)
    with mock.patch("os.name", "nt"), mock.patch(
        "os.path.exists", return_value=True
    ), mock.patch("ctypes.create_unicode_buffer", return_value=fake_buffer):
        ctypes.windll = mock_windll
        assert circup.find_device() is None


def test_find_device_unknown_os():

3 Source : test_circup.py
with MIT License
from adafruit

def test_get_latest_release_from_url():
    """
    Ensure the expected tag value is extracted from the returned URL (resulting
    from a call to the expected endpoint).
    """
    response = mock.MagicMock()
    response.headers = {
        "Location": "https://github.com/adafruit"
        "/Adafruit_CircuitPython_Bundle/releases/tag/20190903"
    }
    expected_url = "https://github.com/" + TEST_BUNDLE_NAME + "/releases/latest"
    with mock.patch("circup.requests.head", return_value=response) as mock_get:
        result = circup.get_latest_release_from_url(expected_url)
        assert result == "20190903"
        mock_get.assert_called_once_with(expected_url)


def test_extract_metadata_python():

3 Source : test_utils.py
with MIT License
from adamghill

def test_get_cacheable_component_request_is_none():
    component = FakeComponent(component_id="asdf123498", component_name="hello-world")
    component.request = MagicMock()
    assert component.request

    actual = get_cacheable_component(component)

    assert actual.request is None


def test_get_cacheable_component_extra_context_is_none():

3 Source : test_utils.py
with MIT License
from adamghill

def test_get_cacheable_component_extra_context_is_none():
    component = FakeComponent(component_id="asdf123499", component_name="hello-world")
    component.extra_context = MagicMock()
    assert component.extra_context

    actual = get_cacheable_component(component)

    assert actual.extra_context is None


def test_is_non_string_sequence_list():

3 Source : test_api.py
with MIT License
from adimian

def test_throw_error_at_init_if_server_error(
    session_mock, kirby_expected_env, kirby_hidden_env
):
    session_mock.return_value.patch.return_value = MagicMock(
        status_code=500, json=MagicMock(return_value={})
    )

    # Kirby register itself at init, at least to update 'last_seen' in the DB
    with pytest.raises(ServerError):
        Kirby(kirby_expected_env)


@pytest.mark.parametrize(

3 Source : test_utils.py
with GNU General Public License v3.0
from agajdosi

def _create_app_mock() -> mock.MagicMock:
    def get_dict(app: Any, key: str) -> Any:
        return app.__app_dict[key]

    def set_dict(app: Any, key: str, value: Any) -> None:
        app.__app_dict[key] = value

    app = mock.MagicMock()
    app.__app_dict = {}
    app.__getitem__ = get_dict
    app.__setitem__ = set_dict

    app._debug = False
    app.on_response_prepare = Signal(app)
    app.on_response_prepare.freeze()
    return app


def _create_transport(sslcontext: Optional[SSLContext]=None) -> mock.Mock:

3 Source : mock.py
with MIT License
from AHCoder

def coroutine_mock():
    """
    .. deprecated:: 0.45
      Use: :class:`MagicMock` with meth:`~.async_return_value`.
    """
    coro = MagicMock(name="CoroutineResult")
    corofunc = MagicMock(name="CoroutineFunction", side_effect=asyncio.coroutine(coro))
    corofunc.coro = coro
    return corofunc


async def skip_loop(iterations=1):

3 Source : test_k8s.py
with Apache License 2.0
from aidtechnology

    def test_ingress_read(self, mock_api_ext, mock_pretty_print):
        mock_ingress = MagicMock()
        mock_ingress.spec.rules.__getitem__.side_effect = [
            IngressHost("a-url"),
            IngressHost("another-url"),
        ]
        mock_api_ext.read_namespaced_ingress.side_effect = [mock_ingress]
        ingress_read("an_ingress", "a-namespace")
        mock_api_ext.read_namespaced_ingress.assert_called_once_with(
            name="an_ingress", namespace="a-namespace"
        )
        mock_pretty_print.assert_not_called()

    @patch("nephos.helpers.k8s.pretty_print")

3 Source : test_k8s.py
with Apache License 2.0
from aidtechnology

    def test_ingress_read_verbose(self, mock_api_ext, mock_pretty_print):
        mock_ingress = MagicMock()
        mock_ingress.spec.rules.__iter__.return_value = [
            IngressHost("a-url"),
            IngressHost("another-url"),
        ]
        mock_api_ext.read_namespaced_ingress.side_effect = [mock_ingress]
        ingress_read("an_ingress", "a-namespace", verbose=True)
        mock_api_ext.read_namespaced_ingress.assert_called_once_with(
            name="an_ingress", namespace="a-namespace"
        )
        mock_pretty_print.assert_called_once_with('["a-url", "another-url"]')

    @patch("nephos.helpers.k8s.pretty_print")

3 Source : test_environment_preset.py
with Apache License 2.0
from airflowdocker

    def setup(self):
        class Operator:
            task_id = "food"
            extra_kwargs = {}
            log = MagicMock()
            environment = {}

        self.operator = Operator()

    def test_no_config_no_op(self):

3 Source : test_node_lookup.py
with Apache License 2.0
from airshipit

    def test_NodeLookup_lookup(self, *args):
        """Test the functionality of the setup and lookup functions"""
        nl = NodeLookup(mock.MagicMock(), {"design": "ref"})

        assert nl.design_ref == {"design": "ref"}
        assert nl.drydock_client

        sel = GroupNodeSelector({
            'node_names': [],
            'node_labels': ['label1:label1'],
            'node_tags': ['tag1', 'tag2'],
            'rack_names': ['rack3', 'rack1'],
        })

        resp = nl.lookup([sel])
        assert resp == ['node1', 'node2']

    @mock.patch('shipyard_airflow.common.deployment_group.node_lookup'

3 Source : test_node_lookup.py
with Apache License 2.0
from airshipit

    def test_NodeLookup_lookup_retry(self, get_nodes):
        """Test the functionality of the setup and lookup functions"""
        nl = NodeLookup(mock.MagicMock(), {"design": "ref"}, retry_delay=0.1)
        sel = GroupNodeSelector({
            'node_names': [],
            'node_labels': [],
            'node_tags': [],
            'rack_names': [],
        })
        with pytest.raises(errors.ClientError) as ex:
            resp = nl.lookup([sel])
        assert get_nodes.call_count == 3

    @mock.patch('shipyard_airflow.common.deployment_group.node_lookup'

3 Source : test_node_lookup.py
with Apache License 2.0
from airshipit

    def test_NodeLookup_lookup_retry_exception(self, get_nodes):
        """Test the functionality of the setup and lookup functions"""
        nl = NodeLookup(mock.MagicMock(), {"design": "ref"}, retry_delay=0.1)
        sel = GroupNodeSelector({
            'node_names': [],
            'node_labels': [],
            'node_tags': [],
            'rack_names': [],
        })
        with pytest.raises(Exception) as ex:
            resp = nl.lookup([sel])
        assert get_nodes.call_count == 3

    @mock.patch('shipyard_airflow.common.deployment_group.node_lookup'

3 Source : test_node_lookup.py
with Apache License 2.0
from airshipit

    def test_NodeLookup_lookup_client_unauthorized(self, get_nodes):
        """Test the functionality of the setup and lookup functions"""
        nl = NodeLookup(mock.MagicMock(), {"design": "ref"}, retry_delay=0.1)
        sel = GroupNodeSelector({
            'node_names': [],
            'node_labels': [],
            'node_tags': [],
            'rack_names': [],
        })
        with pytest.raises(errors.ClientUnauthorizedError) as ex:
            resp = nl.lookup([sel])
        assert get_nodes.call_count == 1

    @mock.patch('shipyard_airflow.common.deployment_group.node_lookup'

3 Source : test_node_lookup.py
with Apache License 2.0
from airshipit

    def test_NodeLookup_lookup_client_forbidden(self, get_nodes):
        """Test the functionality of the setup and lookup functions"""
        nl = NodeLookup(mock.MagicMock(), {"design": "ref"}, retry_delay=0.1)
        sel = GroupNodeSelector({
            'node_names': [],
            'node_labels': [],
            'node_tags': [],
            'rack_names': [],
        })
        with pytest.raises(errors.ClientForbiddenError) as ex:
            resp = nl.lookup([sel])
        assert get_nodes.call_count == 1

    def test_NodeLookup_lookup_missing_design_ref(self):

3 Source : test_document_validator_manager.py
with Apache License 2.0
from airshipit

def get_doc_returner():
    placeholder = MagicMock()
    placeholder.data = {"nothing": "here"}

    def doc_returner(revision_id, rendered, **filters):
        if not revision_id == 99:
            doc = filters['metadata.name']
            if 'document-placeholder' in doc:
                return [placeholder]
        return []
    return doc_returner


def _dh_doc_client():

3 Source : test_document_validator_manager.py
with Apache License 2.0
from airshipit

def _dh_doc_client():
    dhc = MagicMock()
    dhc.revisions.documents = get_doc_returner()
    return dhc


class ValidatorA(DocumentValidator):

3 Source : test_document_validator_manager.py
with Apache License 2.0
from airshipit

    def test_val_msg_defaults(self):
        vb = ValidatorB(deckhand_client=MagicMock(), revision=1, doc_name="no")
        msg = vb.val_msg("hi", "nm")
        assert msg['error']
        assert msg['level'] == "Error"
        assert msg['diagnostic'] == "Message generated by Shipyard."
        assert msg['documents'] == [{"name": "no",
                                     "schema": "schema/Schema/v1"}]

3 Source : test_action_validators.py
with Apache License 2.0
from airshipit

def fake_dh_doc_client(style, ds_name='dep-strat'):
    dhc = MagicMock()
    dhc.revisions.documents = get_doc_returner(style, ds_name)
    return dhc


class TestActionValidator:

3 Source : test_check_k8s_node_status.py
with Apache License 2.0
from airshipit

    def __init__(self, name, status, message):
        self.metadata = mock.MagicMock()
        self.metadata.name = name
        self.item = mock.MagicMock()
        self.item.status = status
        self.item.message = message
        self.status = mock.MagicMock()
        self.status.conditions = [self.item]


class MalformedNodeStatus:

3 Source : test_check_k8s_node_status.py
with Apache License 2.0
from airshipit

    def __init__(self, name=None):
        if name:
            self.metadata = mock.MagicMock()
            self.metadata.name = name

        self.status = mock.MagicMock()
        self.status.conditions = "broken"


def gen_check_node_status(response_dict):

3 Source : test_deployment_configuration_operator.py
with Apache License 2.0
from airshipit

def test_get_revision_id(ti):
    """Test that get revision id follows desired exits"""
    dco = DeploymentConfigurationOperator(main_dag_name="main",
                                          shipyard_conf="shipyard.conf",
                                          task_id="t1")
    ti = airflow.models.TaskInstance(task=mock.MagicMock(),
                                     execution_date=None)
    rid = dco.get_revision_id(ti)
    assert rid == 2


@mock.patch.object(airflow.models.TaskInstance, 'xcom_pull',

3 Source : test_deployment_configuration_operator.py
with Apache License 2.0
from airshipit

def test_get_revision_id_none(ti):
    """Test that get revision id follows desired exits"""
    dco = DeploymentConfigurationOperator(main_dag_name="main",
                                          shipyard_conf="shipyard.conf",
                                          task_id="t1")
    ti = airflow.models.TaskInstance(task=mock.MagicMock(),
                                     execution_date=None)
    with pytest.raises(AirflowException) as expected_exc:
        rid = dco.get_revision_id(ti)
    assert "Design_revision is not set." in str(expected_exc)


def test_get_doc_no_deckhand():

3 Source : test_deployment_configuration_operator.py
with Apache License 2.0
from airshipit

def get_m_client(data):
    doc_obj = mock.MagicMock()
    doc_obj.data = data
    doc_obj_l = [doc_obj]
    mock_client = mock.MagicMock()
    mock_client.revisions.documents = lambda r, rendered, **filters: doc_obj_l
    return mock_client


@mock.patch.object(DeckhandClientFactory, 'get_client',

3 Source : test_drydock_nodes_operator.py
with Apache License 2.0
from airshipit

def _fake_deployment_group_manager(cgf_bool):

    def dgm_func(group_dict_list, node_lookup):
        dgm_mock = mock.MagicMock()
        dgm_mock.critical_groups_failed = mock.Mock(return_value=cgf_bool)
        return dgm_mock
    return dgm_func(None, None)


GROUP_DICT = {

3 Source : test_drydock_nodes_operator.py
with Apache License 2.0
from airshipit

    def test_execute_prepare(self):
        op = DrydockNodesOperator(main_dag_name="main",
                                  shipyard_conf=CONF_FILE,
                                  task_id="t1")
        op.dc = copy.deepcopy(
            DeploymentConfigurationOperator.config_keys_defaults
        )
        op._setup_configured_values()
        op._execute_task = mock.MagicMock(return_value=TASK_RESULT)
        group = DeploymentGroup(GROUP_DICT, mock.MagicMock())
        group.actionable_nodes = ['node1', 'node2', 'node3']
        op._execute_prepare(group)
        assert op._execute_task.call_count == 1

    @mock.patch("shipyard_airflow.plugins.check_k8s_node_status."

3 Source : test_drydock_nodes_operator.py
with Apache License 2.0
from airshipit

    def test_execute_deployment(self, cns):
        op = DrydockNodesOperator(main_dag_name="main",
                                  shipyard_conf=CONF_FILE,
                                  task_id="t1")
        op.dc = copy.deepcopy(
            DeploymentConfigurationOperator.config_keys_defaults
        )
        op._setup_configured_values()
        op._execute_task = mock.MagicMock(return_value=TASK_RESULT)
        op.join_wait = 0
        group = DeploymentGroup(GROUP_DICT, mock.MagicMock())
        group.actionable_nodes = ['node1', 'node2', 'node3']
        succ_prep_nodes = ['node1', 'node2', 'node3']
        op._execute_deployment(group, succ_prep_nodes)
        assert op._execute_task.call_count == 1
        assert cns.call_count == 1

    @mock.patch("shipyard_airflow.plugins.check_k8s_node_status."

See More Examples