Ejemplo n.º 1
0
    def test_include_excelude_tuple(self, mock_time, get_value, init):
        """
        Include/exclude should accept a tuple of flags
        """
        self._helper()
        self.conf.watcher_added_at = 1
        add_watch = Mock()
        add_watch.side_effect = iter(["src descr", "conf descr"])
        self.conf.watch_manager.add_watch = add_watch

        filter_include = (1, 4094)
        filter_exclude = (8, 16, 32)
        get_value.side_effect = iter([
            filter_include, filter_exclude, "dir", None, "config"
        ])

        ored_include = 4095
        ored_exclude = 56
        expected_mask = ored_include & ~ored_exclude

        mock_time.return_value = 2

        self.conf.update_watch()

        self.assertEqual(add_watch.call_count, 2)
        add_watch.assert_has_calls([
            call(path="dir", mask=expected_mask, auto_add=True,
                 rec=True, exclude_filter=self.conf.filter_wrapper),
            call(path="config", mask=expected_mask),
        ])
        self.assertEqual(
            self.conf.watch_descriptors, ("src descr", "conf descr"))
        self.assertEqual(self.conf.watcher_added_at, 2)
    def test_purge_deleted_datasets(self, mock_get_action, mock_session_query):
        # prepare
        package1 = DummyClass()
        package1.id = 'abc'
        package1.name = 'package1_name'
        package2 = DummyClass()
        package2.id = 'xyz'
        package2.name = 'package2_name'
        mock_session_query.return_value.filter_by.return_value.filter.return_value = [package1, package2]

        self.target.log_deleted_packages_in_file = Mock()

        mock_action_methods = Mock("action-methods")
        mock_get_action.return_value = mock_action_methods

        admin_user = '******'
        self.target.admin_user = {'name': admin_user}

        # execute
        self.target.purge_deleted_datasets()

        # verify
        mock_session_query.assert_called_once_with(model.package.Package)
        mock_session_query.return_value.filter_by.assert_called_once_with(state=model.State.DELETED)
        mock_session_query.return_value.filter_by.return_value.filter.assert_called_once_with(ANY)
        expected_logging_calls = [call(package1, ANY), call(package2, ANY)]
        self.target.log_deleted_packages_in_file.assert_has_calls(expected_logging_calls)
        self.assertEqual(2, mock_get_action.call_count)
        self.assertEqual(mock_get_action.call_args_list, [call("dataset_purge"), call("dataset_purge")])
        expected_purge_calls = [call({'user': admin_user}, {'id': package1.id}),
                                  call({'user': admin_user}, {'id': package2.id})]
        mock_action_methods.assert_has_calls(expected_purge_calls)
Ejemplo n.º 3
0
    def test_resolve_1(self):
        # given
        argument1_name = 'var1'
        argument2_name = 'var2'
        rule1 = InputArgumentResolvingRule(argument1_name)
        rule2 = InputArgumentResolvingRule(argument2_name)
        rules = [rule1, rule2]
        resolve_value = 'some_value'

        resolver = InputArgumentResolver(rules)
        _resolve_mock = Mock(return_value=resolve_value)
        resolver._resolve = _resolve_mock
        ctx_mock = Mock()

        # when
        result = resolver.resolve(ctx_mock)

        # then
        self.assertEquals(result, {
            argument1_name: resolve_value,
            argument2_name: resolve_value
        })

        expected_calls = [call(rule1, ctx_mock), call(rule2, ctx_mock)]

        _resolve_mock.assert_has_calls(expected_calls)
Ejemplo n.º 4
0
    def test_merge(self):
        sut = MergePdfPage(key='test_content', destkey='test_merged_content')
        insert = {
            'inserts': ['a'],
            'deletes': [],
            'data': {
                'a': {
                    'test_content': [
                        'pdf page content',
                        'pdf watermark content'
                    ],
                }
            }
        }

        expected = copy.deepcopy(insert)
        expected['data']['a']['test_merged_content'] = ('pdf page with watermark',)
        matches = MatchesSendDeltaItemInvocation(expected, sut)
        send = Mock(spec=Scheduler.send)

        merge_mock = Mock(spec=pdfrw.PageMerge)
        merge_mock.return_value.render.return_value = 'pdf page with watermark'

        with patch('pdfrw.PageMerge', merge_mock):
            sut(insert, send)

        self.assertEquals(send.call_count, 1)
        self.assertThat(send.call_args, matches)

        merge_mock.assert_has_calls([
            call(),
            call().add('pdf page content'),
            call().add('pdf watermark content'),
            call().render()
        ])
Ejemplo n.º 5
0
 def test_ensure_testing_spec_base_image_build(self):
     mock_docker_client = Mock()
     mock_build = Mock()
     mock_docker_client.build = mock_build
     testing_spec = {"build": "/path/to/docker_file_folder"}
     _ensure_testing_spec_base_image(mock_docker_client, testing_spec)
     mock_build.assert_has_calls([call(path="/path/to/docker_file_folder", tag="dusty_testing_base/image")])
Ejemplo n.º 6
0
    def test_mock_asserts(self):
        """The mock object has four useful helpers (assert_called_with, assert_called_once_with, assert_any_call, assert_has_calls)
        that you can use to assert various things about what the mock has been called with since instantiation"""

        m = Mock()
        m(1)

        m.assert_called_with(1)
        self.assertRaises(AssertionError, m.assert_called_with, 2)

        # assert_called_with asserts what the Mock's most recent call was, not that a call occurred, ever.
        # calling m.assert_called_with(1) now will raise error
        m(2)
        m.assert_called_with(2)
        self.assertRaises(AssertionError, m.assert_called_with, 1)

        # assert_called_once_with is the stronger assertion that the mock has been called exactly once in its history, with the
        # specified argument. (this mock has already been called twice, so both of these fail)
        self.assertRaises(AssertionError, m.assert_called_once_with, 1)
        self.assertRaises(AssertionError, m.assert_called_once_with, 2)

        # assert_any_call means it was called with the given args at any point in history
        m.assert_any_call(1)
        m.assert_any_call(2)
        self.assertRaises(AssertionError, m.assert_called_with, 3)

        # use assert_has_calls to assert the whole call history. it takes a set of mock.call objects
        m.assert_has_calls([mock.call(1), mock.call(2)])

        # this fails because order of calls was m(1) then m(2) and by default any_order=False
        self.assertRaises(AssertionError, m.assert_has_calls, [mock.call(2), mock.call(1)])

        # this works because any_order=true
        m.assert_has_calls([mock.call(2), mock.call(1)], any_order=True)
Ejemplo n.º 7
0
    def test_add_field_processors(self):
        event = Mock()
        event.field.new_value = 'admin'
        config = Mock()
        processor = Mock(return_value='user12')

        events.add_field_processors(config, [processor, processor],
                                    model='User',
                                    field='username')
        assert config.add_subscriber.call_count == 5
        assert not event.set_field_value.called
        assert not processor.called

        last_call = config.add_subscriber.mock_calls[0]
        wrapper = last_call[1][0]
        wrapper(event)
        event.set_field_value.assert_called_once_with('username', 'user12')
        assert event.field.new_value == 'user12'

        processor.assert_has_calls([
            call(new_value='admin',
                 instance=event.instance,
                 field=event.field,
                 request=event.view.request,
                 model=event.model,
                 event=event),
            call(new_value='user12',
                 instance=event.instance,
                 field=event.field,
                 request=event.view.request,
                 model=event.model,
                 event=event),
        ])
Ejemplo n.º 8
0
 def test_ensure_testing_spec_base_image_build(self):
     mock_docker_client = Mock()
     mock_build = Mock()
     mock_docker_client.build = mock_build
     testing_spec = {'build': '/path/to/docker_file_folder'}
     _ensure_testing_spec_base_image(mock_docker_client, testing_spec)
     mock_build.assert_has_calls([call(path='/path/to/docker_file_folder', tag='dusty_testing_base/image')])
Ejemplo n.º 9
0
    def test_reset(self):
        client = ROSCLEClient.ROSCLEClient(0)

        simulation_recorder = Mock()
        reset_resp = Mock()
        reset_resp.success = True
        reset = Mock(return_value=reset_resp)
        client._ROSCLEClient__simulation_recorder = simulation_recorder
        client._ROSCLEClient__cle_reset = reset

        pop1 = Mock()
        pop2 = Mock()

        pop1.name = u'foo'
        pop1.step = 1
        pop2.name = 'bar'
        pop2.step = 0
        client.reset(ResetSimulationRequest.RESET_FULL, populations=[pop1, pop2])

        simulation_recorder.assert_has_calls(call(SimulationRecorderRequest.CANCEL))
        simulation_recorder.assert_has_calls(call(SimulationRecorderRequest.RESET))
        self.assertEqual(pop1.name, 'foo')
        self.assertEqual(pop2.name, 'bar')
        self.assertEqual(pop1.step, 1)
        self.assertEqual(pop2.step, 1)
        self.assertTrue(reset.called)

        reset_resp.success = False
        reset_resp.error_message = "Foobar"
        self.assertRaises(ROSCLEClientException, client.reset, ResetSimulationRequest.RESET_FULL)

        client.stop_communication("Test stop")
        self.assertRaises(ROSCLEClientException, client.reset, ResetSimulationRequest.RESET_FULL)
Ejemplo n.º 10
0
def test_alert_is_triggered_and_released():
    log_file_path = "./tmp.log"
    init_file(log_file_path)
    http_monitor_builder = HttpMonitorBuilder(log_file_path)
    mocked_callback = Mock()
    avg_alert_bundle = AvgAlertBundle(3, 2, mocked_callback)
    http_monitor_builder.add_monitor(avg_alert_bundle)

    frequencies = [2, 4, 4, 3, 2, 1]
    http_monitor = http_monitor_builder.get_monitor()
    http_monitor.start_workers(blocking=False)
    write_log_lines(log_file_path, frequencies)
    time.sleep(1)
    http_monitor.stop_workers()

    logger.debug("Removing files")
    if os.path.exists(log_file_path):
        os.remove(log_file_path)

    calls = [
        call(
            "High traffic generated an alert - hits = 3, triggered at 2018-05-09T18:01:01"
        ),
        call("High traffic alert recovered at 2018-05-09T18:01:04")
    ]
    mocked_callback.assert_has_calls(calls)
Ejemplo n.º 11
0
    def test_act_must_invoke_plugins_in_sequence(self):

        # Create three plugins, and setup hook methods on it
        plugin1 = _make_mock_plugin("plugin1")
        setattr(plugin1, "on_" + self.my_event.name, Mock())
        plugin2 = _make_mock_plugin("plugin2")
        setattr(plugin2, "on_" + self.my_event.name, Mock())
        plugin3 = _make_mock_plugin("plugin3")
        setattr(plugin3, "on_" + self.my_event.name, Mock())

        # Create a parent mock and attach child mocks to help assert order of the calls
        # https://stackoverflow.com/questions/32463321/how-to-assert-method-call-order-with-python-mock
        parent_mock = Mock()
        parent_mock.attach_mock(plugin1.on_my_event, "plugin1_hook")
        parent_mock.attach_mock(plugin2.on_my_event, "plugin2_hook")
        parent_mock.attach_mock(plugin3.on_my_event, "plugin3_hook")

        self.sam_plugins.register(plugin1)
        self.sam_plugins.register(plugin2)
        self.sam_plugins.register(plugin3)

        # Call the act method
        self.sam_plugins.act(self.my_event)

        # Verify calls were made in the specific sequence
        parent_mock.assert_has_calls(
            [call.plugin1_hook(),
             call.plugin2_hook(),
             call.plugin3_hook()])
Ejemplo n.º 12
0
class URLTestCase(ConnectionTestMixin, TestCase):
    def setUp(self):
        super(URLTestCase, self).setUp()
        self.plugin = self.connection.settings.enable(Default.name, [])
        self.fetch_title = Mock(return_value=succeed('title'))
        self.plugin.fetcher.fetch_title = self.fetch_title
        self.outgoing = self.connection.settings.enable(
            OutgoingPlugin.name, [])

    def test_simple(self):
        self.receive('PRIVMSG {} :http://www.example.com/'
                     .format(self.connection.nickname))
        self.fetch_title.assert_called_with(
            u'http://www.example.com/',
            hostname_tag=True, friendly_errors=True)
        self.assertEqual(self.outgoing.last_seen.content, 'title')

    def test_multiple_iris(self):
        self.receive('PRIVMSG {} :http://foo.test/ http://bar.test/'
                     .format(self.connection.nickname))
        self.fetch_title.assert_has_calls([
            call(u'http://foo.test/', hostname_tag=True, friendly_errors=True),
            call(u'http://bar.test/', hostname_tag=True, friendly_errors=True),
            ])
        self.assertEqual(self.outgoing.last_seen.content, 'title')
Ejemplo n.º 13
0
    def test_no_wait_after_get(self):
        log_manager = ExecuteLogManager()
        get_execute_log_details_mock = Mock(return_value=[{}])
        log_manager.get_execute_log_details = get_execute_log_details_mock
        log_manager.is_running = Mock(return_value=True)

        time = TimeMock()

        with patch("monitorrent.rest.execute_logs_details.time", time):
            execute_log_details = ExecuteLogsDetails(log_manager)

            self.api.add_route('/api/execute/logs/{execute_id}/details',
                               execute_log_details)

            body = self.simulate_request('/api/execute/logs/1/details',
                                         query_string="after=17",
                                         decode='utf-8')

            self.assertEqual(self.srmock.status, falcon.HTTP_OK)

            result = json.loads(body)

            self.assertEqual(result, {'is_running': True, 'logs': [{}]})

        get_execute_log_details_mock.assert_has_calls([call(1, 17)])
Ejemplo n.º 14
0
def test_display():
    # Given

    matrix = Mock()
    color = Mock()
    font = Mock()
    draw = Mock()
    sleep = Mock()

    canvas = Mock()
    canvas.width = 2
    matrix.CreateFrameCanvas.return_value = canvas
    matrix.SwapOnVSync.return_value = canvas
    draw.side_effect = [1, 0, 0]
    text = 'Hi'

    tape = Tape(matrix, color, font, draw, sleep)

    # When
    tape.display(text)

    # Then
    draw1 = call(canvas, font, 2, 12, color, text)
    draw2 = call(canvas, font, 2, 12, color, text)
    draw3 = call(canvas, font, 1, 12, color, text)
    draw.assert_has_calls([draw1, draw2, draw3], any_order=False)
    sleep.assert_has_calls([call(0.05), call(0.05)])
    assert canvas.Clear.call_count == 2
def test_build_dependent_packages(monkeypatch, mock_logger):
    mock_build_with_fpm = Mock()
    monkeypatch.setattr('vdt.versionplugin.buildout.shared.build_with_fpm', mock_build_with_fpm)
    monkeypatch.setattr('vdt.versionplugin.buildout.shared.ruby_to_json', MagicMock())
    monkeypatch.setattr('vdt.versionplugin.buildout.shared.read_dependencies_package',
                        Mock(side_effect=[['fabric', 'setuptools'],
                                          ['paramiko', 'fabric'],
                                          None]))
    monkeypatch.setattr('vdt.versionplugin.buildout.shared.lookup_versions',
                        Mock(side_effect=[[('fabric', '1.0.0'), ('setuptools', '2.0.0')],
                                          [('paramiko', None), ('fabric', '1.0.0')]]))

    dependencies = build_dependent_packages([('pyyaml', '1.0.0'), ('puka', None), ('pyasn1', '2.0.0')],
                                            'versions.cfg')

    build_with_fpm_calls = [call('pyyaml', no_python_dependencies=False, version='1.0.0'),
                            call('pyyaml', no_python_dependencies=True, extra_args=['-d', 'python-fabric >= 1.0.0', '-d', 'python-setuptools >= 2.0.0'], version='1.0.0'),
                            call('puka', no_python_dependencies=False, version=None),
                            call('puka', no_python_dependencies=True, extra_args=['-d', 'python-paramiko', '-d', 'python-fabric >= 1.0.0'], version=None),
                            call('pyasn1', no_python_dependencies=False, version='2.0.0')]

    mock_build_with_fpm.assert_has_calls(build_with_fpm_calls)

    assert dependencies == [('fabric', '1.0.0'), ('setuptools', '2.0.0'),
                            ('paramiko', None)]
Ejemplo n.º 16
0
class TestBatchLambda(unittest.TestCase):
    def setUp(self):
        self._metric_function = Mock(return_value='test')
        self._metric = BatchLambda('test', self._metric_function)
        self._states = [{
            torchbearer.Y_TRUE: Variable(torch.FloatTensor([1])),
            torchbearer.Y_PRED: Variable(torch.FloatTensor([2]))
        }, {
            torchbearer.Y_TRUE: Variable(torch.FloatTensor([3])),
            torchbearer.Y_PRED: Variable(torch.FloatTensor([4]))
        }, {
            torchbearer.Y_TRUE: Variable(torch.FloatTensor([5])),
            torchbearer.Y_PRED: Variable(torch.FloatTensor([6]))
        }]

    def test_train(self):
        self._metric.train()
        calls = []
        for i in range(len(self._states)):
            self._metric.process(self._states[i])
            calls.append(
                call(self._states[i][torchbearer.Y_PRED].data,
                     self._states[i][torchbearer.Y_TRUE].data))
        self._metric_function.assert_has_calls(calls)

    def test_validate(self):
        self._metric.eval()
        calls = []
        for i in range(len(self._states)):
            self._metric.process(self._states[i])
            calls.append(
                call(self._states[i][torchbearer.Y_PRED].data,
                     self._states[i][torchbearer.Y_TRUE].data))
        self._metric_function.assert_has_calls(calls)
Ejemplo n.º 17
0
    def test_print_report_if_header_prints_once(self):
        options = Mock()
        options.cpu_list = None
        options.cpu_filter = False
        cpu_filter = Mock()
        cpu_filter.filter_cpus = Mock(return_value=[self.cpu_usage_1])
        printer = Mock()
        cpu_util = Mock()
        cpu_util.get_totalcpu_util = Mock(return_value=self.cpu_usage_total)
        timestamp = '2016-7-18 IST'
        report = CpuUtilReporter(cpu_filter, printer, options)

        report.print_report(cpu_util, timestamp)
        report.print_report(cpu_util, timestamp)

        calls = [
            call(
                '\nTimestamp \tCPU\t%usr \t%nice \t%sys \t%iowait \t%irq \t%soft \t%steal \t%guest \t%nice \t%idle '
            ),
            call(
                '2016-7-18 IST\tall\t1.23 \t2.34  \t3.45 \t4.56    \t5.67 \t6.78  \t7.89   \t8.9    \t1.34  \t2.45  '
            ),
            call(
                '2016-7-18 IST\tall\t1.23 \t2.34  \t3.45 \t4.56    \t5.67 \t6.78  \t7.89   \t8.9    \t1.34  \t2.45  '
            )
        ]

        printer.assert_has_calls(calls)
Ejemplo n.º 18
0
class TestListenerWithSphinx(TestCase):
    def setUp(self):
        self.mock_recogniser = Mock(autospec='sr.Recognizer')
        self.mock_microphone = MagicMock(autospec='sr.Microphone')
        self.listener = Listener(service='sphinx',
                                 recogniser=self.mock_recogniser,
                                 microphone=self.mock_microphone)

    def test_create(self):
        self.assertIsInstance(self.listener, Listener)

    def test_listen(self):
        self.listener.listen()

        # __enter__ is needed due to logic in listener class being inside a python 'with' block
        # when you use 'with', this calls a magic method of __enter__ passing result to 'as'
        self.mock_recogniser.assert_has_calls([
            # Need to add if adjusting the main listener for ambient noise
            # call.adjust_for_ambient_noise(self.mock_microphone.__enter__()),
            call.listen(self.mock_microphone.__enter__())
        ])

    def test_listen_raises_value_error(self):
        with patch.object(self.listener, 'transcribe') as transcribe:
            transcribe.side_effect = sr.UnknownValueError()

            with self.assertRaises(ValueError) as context:
                self.listener.listen()

            self.assertIn('Could not translate speech', str(context.exception))

    def test_transcribe(self):
        audio = lambda: None
        self.listener.transcribe(audio)
        self.mock_recogniser.recognize_sphinx.assert_called_once_with(audio)
Ejemplo n.º 19
0
def assert_has_calls():
    mockFoo = Mock(spec=Foo)
    print mockFoo

    mockFoo.callFoo()
    mockFoo.doFoo("narf")
    mockFoo.doFoo("zort")

    fooCalls = [call.callFoo(), call.doFoo("narf"), call.doFoo("zort")]
    mockFoo.assert_has_calls(fooCalls)

    fooCalls = [call.callFoo(), call.doFoo("zort"), call.doFoo("narf")]
    mockFoo.assert_has_calls(fooCalls, any_order=True)
    try:
        mockFoo.assert_has_calls(fooCalls)
    except AssertionError as e:
        print e

    fooCalls = [call.callFoo(), call.dooFoo("zort"), call.doFoo("narf")]
    try:
        mockFoo.assert_has_calls(fooCalls, any_order=True)
    except AssertionError as e:
        print e
    try:
        mockFoo.assert_has_calls(fooCalls)
    except AssertionError as e:
        print e
Ejemplo n.º 20
0
    def test_do_load_stack_sample_and_flat(self, load_p_mock: mock.Mock,
                                           load_log_mock: mock.Mock):
        lp = LoadingParameters()
        sample_mock = mock.Mock()
        lp.sample = sample_mock
        lp.dtype = "dtype_test"
        lp.sinograms = False
        lp.pixel_size = 101

        flat_before_mock = mock.Mock()
        lp.flat_before = flat_before_mock
        flat_after_mock = mock.Mock()
        lp.flat_after = flat_after_mock
        progress_mock = mock.Mock()

        self.model.do_load_stack(lp, progress_mock)

        load_p_mock.assert_has_calls([
            mock.call(sample_mock, lp.dtype, progress_mock),
            mock.call(flat_before_mock, lp.dtype, progress_mock),
            mock.call(flat_after_mock, lp.dtype, progress_mock)
        ])
        load_log_mock.assert_has_calls([
            mock.call(sample_mock.log_file),
            mock.call(flat_before_mock.log_file),
            mock.call(flat_after_mock.log_file)
        ])
Ejemplo n.º 21
0
    def test_print_report_with_online_cpus(self):
        options = Mock()
        options.cpu_list = "ON"
        options.cpu_filter = True
        cpu_filter = Mock()
        cpu_filter.filter_cpus = Mock(
            return_value=[self.cpu_usage_1, self.cpu_usage_2])
        printer = Mock()
        cpu_util = Mock()
        cpu_util.get_totalcpu_util = Mock(return_value=self.cpu_usage_total)
        timestamp = '2016-7-18 IST'
        report = CpuUtilReporter(cpu_filter, printer, options)

        report.print_report(cpu_util, timestamp)

        calls = [
            call(
                '\nTimestamp \tCPU\t%usr \t%nice \t%sys \t%iowait \t%irq \t%soft \t%steal \t%guest \t%nice \t%idle '
            ),
            call(
                '2016-7-18 IST\tall\t1.23 \t2.34  \t3.45 \t4.56    \t5.67 \t6.78  \t7.89   \t8.9    \t1.34  \t2.45  '
            ),
            call(
                '2016-7-18 IST\t1  \t1.43 \t2.35  \t2.45 \t3.76    \t6.45 \t2.58  \t2.59   \t5.6    \t2.34  \t6.67  '
            ),
            call(
                '2016-7-18 IST\t2  \t2.43 \t3.35  \t5.45 \t2.76    \t7.45 \t3.58  \t6.59   \t2.6    \t7.34  \t3.67  '
            )
        ]

        printer.assert_has_calls(calls)
Ejemplo n.º 22
0
    def test_autoCreateSensor(self):
        sensorNotFound = Mock()
        sensorNotFound.status_code = 404
        sensorNotFound.text = '{"errorcode": "404-001", "message": ""}'

        created = Mock()
        created.status_code = 201

        ok = Mock()
        ok.status_code = 200

        request = Mock()
        request.side_effect = [authRequest(), sensorNotFound, created, ok]
        sensorcloud.webrequest.Requests.Request = request

        device = sensorcloud.Device("FAKE", "fake")
        sensor = device.sensor("sensor")
        self.assertTrue("channel" in sensor)

        calls = [
                mock.call('GET', 'https://dsx.sensorcloud.microstrain.com/SensorCloud/devices/FAKE/sensors/sensor/channels/channel/attributes/', mock.ANY),
                mock.call('PUT', 'https://dsx.sensorcloud.microstrain.com/SensorCloud/devices/FAKE/sensors/sensor/', mock.ANY),
                mock.call('GET', 'https://dsx.sensorcloud.microstrain.com/SensorCloud/devices/FAKE/sensors/sensor/channels/channel/attributes/', mock.ANY)
        ]
        request.assert_has_calls(calls)
Ejemplo n.º 23
0
    def test_get_cuts(self):
        gps_station = (datetime_to_gps(datetime(2014, 1, 1, 10, 3)),
                       datetime_to_gps(datetime(2014, 3, 1, 11, 32)))
        gps_ref_station = (datetime_to_gps(datetime(2014, 1, 5, 0, 1, 1)),
                           datetime_to_gps(datetime(2014, 3, 5, 3, 34, 4)))
        elec_station = (datetime_to_gps(datetime(2014, 1, 3, 3, 34, 3)),
                        datetime_to_gps(datetime(2014, 3, 5, 23, 59, 59)))
        elec_ref_station = (datetime_to_gps(datetime(2014, 1, 9, 0, 0, 0)),
                            datetime_to_gps(datetime(2014, 3, 15, 1, 2, 3)))
        gps_mock = Mock()
        elec_mock = Mock()

        gps_mock.side_effect = [array(gps_station), array(gps_ref_station)]
        elec_mock.side_effect = [array(elec_station), array(elec_ref_station)]

        self.off._get_electronics_timestamps = elec_mock
        self.off._get_gps_timestamps = gps_mock

        cuts = self.off._get_cuts(sentinel.station, sentinel.ref_station)

        elec_mock.assert_has_calls([call(sentinel.ref_station), call(sentinel.station)], any_order=True)
        gps_mock.assert_has_calls([call(sentinel.ref_station), call(sentinel.station)], any_order=True)

        self.assertEqual(len(cuts), 8)
        six.assertCountEqual(self, sorted(cuts), cuts)
        self.assertEqual(cuts[0], datetime(2014, 1, 1))
        today = datetime.now()
        self.assertEqual(cuts[-1], datetime(today.year, today.month, today.day))
Ejemplo n.º 24
0
def test_two_different_alarms_are_triggered():
    log_file_path = "./tmp.log"
    init_file(log_file_path)
    http_monitor_builder = HttpMonitorBuilder(log_file_path)
    mocked_callback = Mock()
    avg_alert_bundle_a = AvgAlertBundle(3, 3, mocked_callback, 0.01)
    avg_alert_bundle_b = AvgAlertBundle(4, 2, mocked_callback, 0.01)
    http_monitor_builder.add_monitor(avg_alert_bundle_a)
    http_monitor_builder.add_monitor(avg_alert_bundle_b)

    frequencies = [2, 4, 3, 3, 5, 2, 1, 1]

    http_monitor = http_monitor_builder.get_monitor()
    http_monitor.start_workers(blocking=False)
    write_log_lines(log_file_path, frequencies)
    time.sleep(1)
    http_monitor.stop_workers()

    logger.debug("Removing files")
    if os.path.exists(log_file_path):
        os.remove(log_file_path)

    calls = [
        call(
            "High traffic generated an alert - hits = 3, triggered at 2018-05-09T18:01:02"
        ),
        call(
            "High traffic generated an alert - hits = 4, triggered at 2018-05-09T18:01:04"
        ),
        call("High traffic alert recovered at 2018-05-09T18:01:05"),
        call("High traffic alert recovered at 2018-05-09T18:01:06")
    ]
    mocked_callback.assert_has_calls(calls, any_order=True)
Ejemplo n.º 25
0
    def test_infer_release(
        self,
        mock_get_region: Mock,
        mock_validate_regions: Mock,
        mock_update_phase: Mock,
        mock_get_most_recent_session: Mock,
        mock_infer_release: Mock,
    ) -> None:
        headers = {"X-Appengine-Cron": "test-cron"}
        mock_validate_regions.return_value = [r.region_code for r in _REGIONS]
        mock_get_region.side_effect = _REGIONS

        time = datetime(2014, 8, 31)
        recent_session = ScrapeSession.new(
            key=None,
            start=time,
            scrape_type=constants.ScrapeType.BACKGROUND,
            phase=scrape_phase.ScrapePhase.RELEASE,
        )
        mock_get_most_recent_session.return_value = recent_session

        response = self.client.get(
            "/release?region=us_ut&region=us_wy", headers=headers
        )
        assert response.status_code == 200
        mock_infer_release.assert_has_calls(
            [
                call("us_ut", time, CustodyStatus.INFERRED_RELEASE),
                call("us_wy", time, CustodyStatus.REMOVED_WITHOUT_INFO),
            ]
        )

        mock_update_phase.assert_called_with(
            recent_session, scrape_phase.ScrapePhase.DONE
        )
Ejemplo n.º 26
0
    def test_add_field_processors(self):
        event = Mock()
        event.field.new_value = 'admin'
        config = Mock()
        processor = Mock(return_value='user12')

        events.add_field_processors(
            config, [processor, processor],
            model='User', field='username')
        assert config.add_subscriber.call_count == 5
        assert not event.set_field_value.called
        assert not processor.called

        last_call = config.add_subscriber.mock_calls[0]
        wrapper = last_call[1][0]
        wrapper(event)
        event.set_field_value.assert_called_once_with(
            'username', 'user12')
        assert event.field.new_value == 'user12'

        processor.assert_has_calls([
            call(new_value='admin', instance=event.instance,
                 field=event.field, request=event.view.request,
                 model=event.model, event=event),
            call(new_value='user12', instance=event.instance,
                 field=event.field, request=event.view.request,
                 model=event.model, event=event),
        ])
Ejemplo n.º 27
0
    def test_rename_datasets_before_delete(self, mock_get_action):
        # prepare
        package1 = {'id': 'abc', 'name': 'one'}
        package2 = {'id': 'efg', 'name': 'two'}

        mock_action_methods = Mock("action-methods")
        # 3) get_action('package_update')(context, package)
        mock_get_action.return_value = mock_action_methods

        deprecated_package_dicts = [package1, package2]

        oldnames = []
        for pkg in deprecated_package_dicts:
            oldnames.append(pkg['name'])

        # execute
        HarvestUtils.rename_datasets_before_delete(deprecated_package_dicts)

        # verify
        self.assertEqual(mock_get_action.call_count, 1)
        mock_get_action.assert_any_call("package_update")
        self.assertEqual(mock_action_methods.call_count,
                         len(deprecated_package_dicts))

        expected_action_calls = []
        for pkg in deprecated_package_dicts:
            self.assertTrue(
                pkg['name'] not in oldnames, "Expected dataset " + pkg['id'] +
                " to be renamed, but wasn't.")

            expected_action_calls.append(
                call(TestHarvestUtils._mock_api_context(), pkg))

        mock_action_methods.assert_has_calls(expected_action_calls,
                                             any_order=True)
Ejemplo n.º 28
0
    def test_act_must_abort_hooks_after_exception(self):
        # ie. after a hook raises an exception, subsequent hooks must NOT be run

        # Create three plugins, and setup hook methods on it
        plugin1 = _make_mock_plugin("plugin1"); setattr(plugin1, "on_"+self.my_event.name, Mock())
        plugin2 = _make_mock_plugin("plugin2"); setattr(plugin2, "on_"+self.my_event.name, Mock())
        plugin3 = _make_mock_plugin("plugin3"); setattr(plugin3, "on_"+self.my_event.name, Mock())

        # Create a parent mock and attach child mocks to help assert order of the calls
        # https://stackoverflow.com/questions/32463321/how-to-assert-method-call-order-with-python-mock
        parent_mock = Mock()
        parent_mock.attach_mock(plugin1.on_my_event, "plugin1_hook")
        parent_mock.attach_mock(plugin2.on_my_event, "plugin2_hook")
        parent_mock.attach_mock(plugin3.on_my_event, "plugin3_hook")

        self.sam_plugins.register(plugin1)
        self.sam_plugins.register(plugin2)
        self.sam_plugins.register(plugin3)

        # setup plugin2 to raise exception
        plugin2.on_my_event.side_effect = IOError

        # Call the act method
        with self.assertRaises(IOError):
            self.sam_plugins.act(self.my_event)

        # Since Plugin2 raised the exception, plugin3's hook must NEVER be called
        parent_mock.assert_has_calls([call.plugin1_hook(), call.plugin2_hook()])
Ejemplo n.º 29
0
    def test_print_report_with_filtered_cpus(self):
        timestamp = "2016-19-07 IST"
        total_interrupt_usage = Mock()
        total_interrupt_usage.total_interrupt_per_delta_time = Mock(
            return_value=1.23)
        options = Mock()
        options.cpu_list = 'ALL'
        options.cpu_filter = True
        printer = Mock()
        cpu_filter = Mock()
        cpu_interrupt = Mock()
        cpu_interrupt.cpu_number = Mock(return_value=0)
        cpu_interrupt.value = Mock(return_value=2.4)
        cpu_filter.filter_cpus = Mock(return_value=[cpu_interrupt])
        report = TotalInterruptUsageReporter(cpu_filter, printer, options)

        report.print_report(total_interrupt_usage, timestamp)

        calls = [
            call('\nTimestamp\tCPU  \tintr/s'),
            call('2016-19-07 IST\tall  \t1.23 '),
            call('2016-19-07 IST\t0    \t2.4  ')
        ]

        printer.assert_has_calls(calls)
Ejemplo n.º 30
0
 def test_validate_list_calls_validate_for_schema_values_as_necessary(self):
     def mock_return(schema, data, path):
         if not isinstance(data, schema):
             raise Invalid("")
         return data
     mocked = Mock(side_effect=mock_return)
     with patch.object(Schema, "_validate", mocked):
         Schema._validate_list([int, unicode], [], [])
         self.assertFalse(mocked.called)
         mocked.reset_mock()
         Schema._validate_list([int, unicode], ["a"], [])
         mocked.assert_has_calls([
             call(int, "a", [0]),
             call(unicode, "a", [0])
         ])
         mocked.reset_mock()
         Schema._validate_list([int, unicode], [1], [])
         mocked.assert_called_once_with(int, 1, [0])
         mocked.reset_mock()
         with self.assertRaises(InvalidGroup):
             Schema._validate_list([int, unicode], [None], [])
         mocked.assert_has_calls([
             call(int, None, [0]),
             call(unicode, None, [0])
         ])
    def test_disconnect_device(self, sleep_mock):
        adapter_mock = Mock()
        env = Simulation(device=Mock(), adapter=adapter_mock)

        # connected device calls adapter_mock
        env._process_cycle(0.5)
        adapter_mock.assert_has_calls([call.handle(env.cycle_delay)])
        sleep_mock.assert_not_called()

        adapter_mock.reset_mock()
        sleep_mock.reset_mock()

        # disconnected device calls sleep_mock
        env.disconnect_device()
        env._process_cycle(0.5)

        sleep_mock.assert_has_calls([call.handle(env.cycle_delay)])
        adapter_mock.assert_not_called()

        adapter_mock.reset_mock()
        sleep_mock.reset_mock()

        # re-connecting returns to previous behavior
        env.connect_device()
        env._process_cycle(0.5)
        adapter_mock.assert_has_calls([call.handle(env.cycle_delay)])
        sleep_mock.assert_not_called()
Ejemplo n.º 32
0
 def test_loads_from_default_if_bad_dir(self, file_storage_mock):
     """Should try to load JSON from default dir if the dir in settings does not exist."""
     model = Mock()
     model.objects.exists.return_value = False
     storage_mock = file_storage_mock.return_value
     storage_mock.all_json_files.side_effect = [[],
                                                ['dude.json', 'bunny.json']]
     storage_mock.json_dir = '/does/not/exist'
     storage.json_file_data_to_db(model)
     file_storage_mock.assert_called_with(
         json_dir=settings_defaults.PROD_DETAILS_DIR)
     eq_(file_storage_mock.call_count, 2)
     model.assert_has_calls([
         call(name='dude.json',
              content=storage_mock.content.return_value,
              last_modified=storage_mock.last_modified.return_value),
         call(name='bunny.json',
              content=storage_mock.content.return_value,
              last_modified=storage_mock.last_modified.return_value),
         call(name='/',
              last_modified=storage_mock.last_modified.return_value),
         call(name='regions/',
              last_modified=storage_mock.last_modified.return_value),
     ])
     storage_mock.content.assert_has_calls(
         [call('dude.json'), call('bunny.json')])
     storage_mock.last_modified.assert_has_calls(
         [call('dude.json'), call('bunny.json')])
Ejemplo n.º 33
0
 def test_event_handle_registation_with_list_of_strings(self):
     func_mock = Mock()
     handler("foo", "bar")(func_mock)
     event1 = self._call_handlers("foo.bar", {"data": "foo"})  # handled
     event2 = self._call_handlers("bar.foo", {"data": "bar"})  # handled
     self.assertEqual(2, func_mock.call_count)
     func_mock.assert_has_calls([call(event=event1), call(event=event2)])
Ejemplo n.º 34
0
 def test_loads_from_settings_dir(self, file_storage_mock):
     """Should try to load JSON from default dir if the dir in settings does not exist."""
     model = Mock()
     model.objects.exists.return_value = False
     storage_mock = file_storage_mock.return_value
     storage_mock.all_json_files.return_value = [
         'walter.json', 'donnie.json'
     ]
     storage.json_file_data_to_db(model)
     file_storage_mock.assert_called_once_with()
     model.assert_has_calls([
         call(name='walter.json',
              content=storage_mock.content.return_value,
              last_modified=storage_mock.last_modified.return_value),
         call(name='donnie.json',
              content=storage_mock.content.return_value,
              last_modified=storage_mock.last_modified.return_value),
         call(name='/',
              last_modified=storage_mock.last_modified.return_value),
         call(name='regions/',
              last_modified=storage_mock.last_modified.return_value),
     ])
     storage_mock.content.assert_has_calls(
         [call('walter.json'), call('donnie.json')])
     storage_mock.last_modified.assert_has_calls(
         [call('walter.json'), call('donnie.json')])
    def test__teardown_stage_error(self, ntf_class_mock, rap_mock):
        ntf_instance_mock = ntf_class_mock.return_value
        ntf_instance_mock.name = self.OUTPUT_FILE
        rap_mock.side_effect = [0, 0, 1]

        test = Test(self.TEST_PLAYBOOK, self.INVENTORY, self.SETUP_PLAYBOOK, self.TEARDOWN_PLAYBOOK)
        events_callback = Mock()
        expected_result_status = TestResultStatus.error
        expected = TestResult(test, expected_result_status)

        returned = run_single_test(test, events_callback)

        self.assertEqual(expected, returned)

        self.assertEqual(5, events_callback.call_count)
        events_callback.assert_has_calls([
            call(TestStartedEvent(self.TEST_NAME, self.OUTPUT_FILE)),
            call(TestLifeCycleEvent(self.TEST_NAME, TestLifeCycleStage.setup)),
            call(TestLifeCycleEvent(self.TEST_NAME, TestLifeCycleStage.test)),
            call(TestLifeCycleEvent(self.TEST_NAME, TestLifeCycleStage.teardown)),
            call(TestFinishedEvent(self.TEST_NAME, expected_result_status))
        ])

        self.assertEqual(3, rap_mock.call_count)
        rap_mock.assert_has_calls([
            call(self.INVENTORY, self.SETUP_PLAYBOOK, self.OUTPUT_FILE),
            call(self.INVENTORY, self.TEST_PLAYBOOK, self.OUTPUT_FILE),
            call(self.INVENTORY, self.TEARDOWN_PLAYBOOK, self.OUTPUT_FILE)
        ])
Ejemplo n.º 36
0
    def test_delete_packages(self, mock_get_action):
        # prepare
        package1_id = 'abc'
        package2_id = 'efg'

        mock_action_methods = Mock("action-methods")
        # 3) get_action('package_delete')(context, {'id': to_delete_id})
        mock_get_action.return_value = mock_action_methods

        package_ids_to_delete = [package1_id, package2_id]

        # execute
        HarvestUtils.delete_packages(package_ids_to_delete)

        # verify
        self.assertEqual(mock_get_action.call_count, 1)
        mock_get_action.assert_any_call("package_delete")
        self.assertEqual(mock_action_methods.call_count,
                         len(package_ids_to_delete))
        expected_action_calls_original = []
        for to_delete_id in package_ids_to_delete:
            expected_action_calls_original.append(
                call(TestHarvestUtils._mock_api_context(),
                     {'id': to_delete_id}))
        mock_action_methods.assert_has_calls(expected_action_calls_original,
                                             any_order=True)
Ejemplo n.º 37
0
class TestTweeter(TestCase):
    def setUp(self):
        self.mock_tweepy = Mock(autospec='tweepy')
        self.tweeter = Tweeter(api=self.mock_tweepy)

    def test_create(self):
        self.assertIsInstance(self.tweeter, Tweeter)

    def test_tweet_image(self):
        image = '/path/to/image.jpg'
        message = 'tweet'
        self.tweeter.tweet_message_with_image(message, image)
        self.mock_tweepy.assert_has_calls(
            [call.update_with_media(image, message)])

    @patch('tweepy.OAuthHandler')
    @patch('tweepy.API')
    def test_twitter_auth(self, api, auth):
        tweeter = Tweeter()
        auth.assert_has_calls([
            call(os.getenv('TWITTER_CONSUMER_KEY'),
                 os.getenv('TWITTER_CONSUMER_SECRET')),
            call().set_access_token(os.getenv('TWITTER_ACCESS_TOKEN'),
                                    os.getenv('TWITTER_ACCESS_TOKEN_SECRET'))
        ])

        api.assert_called()
Ejemplo n.º 38
0
    def test_act_must_abort_hooks_after_exception(self):
        # ie. after a hook raises an exception, subsequent hooks must NOT be run

        # Create three plugins, and setup hook methods on it
        plugin1 = _make_mock_plugin("plugin1")
        setattr(plugin1, "on_" + self.my_event.name, Mock())
        plugin2 = _make_mock_plugin("plugin2")
        setattr(plugin2, "on_" + self.my_event.name, Mock())
        plugin3 = _make_mock_plugin("plugin3")
        setattr(plugin3, "on_" + self.my_event.name, Mock())

        # Create a parent mock and attach child mocks to help assert order of the calls
        # https://stackoverflow.com/questions/32463321/how-to-assert-method-call-order-with-python-mock
        parent_mock = Mock()
        parent_mock.attach_mock(plugin1.on_my_event, "plugin1_hook")
        parent_mock.attach_mock(plugin2.on_my_event, "plugin2_hook")
        parent_mock.attach_mock(plugin3.on_my_event, "plugin3_hook")

        self.sam_plugins.register(plugin1)
        self.sam_plugins.register(plugin2)
        self.sam_plugins.register(plugin3)

        # setup plugin2 to raise exception
        plugin2.on_my_event.side_effect = IOError

        # Call the act method
        with self.assertRaises(IOError):
            self.sam_plugins.act(self.my_event)

        # Since Plugin2 raised the exception, plugin3's hook must NEVER be called
        parent_mock.assert_has_calls(
            [call.plugin1_hook(), call.plugin2_hook()])
Ejemplo n.º 39
0
    def test_gossip_about_membership(self, fake_socket):
        server_configs = {
            'servers': [{
                'address': 'a',
                'port': 'a'
            }, {
                'address': 'b',
                'port': 'b'
            }, {
                'address': 'c',
                'port': 'c'
            }],
            'gossip_list': [0, 0, 0],
            'suspect_list': [0, 0, 0],
            'suspect_matrix': [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
        }
        current_membership = {'server_configs': server_configs}
        gossiper = Gossiper(0)
        fake_send_string = Mock()
        gossiper.send_string = fake_send_string

        gossiper.gossip_about_membership(('a', 'b'), current_membership)

        fake_socket.socket().connect.assert_has_calls([call(('a', 'b'))])
        fake_send_string.assert_has_calls([
            call(
                fake_socket.socket(),
                "{}{}".format(constants.MEMBERSHIP_STRING,
                              yaml.dump(current_membership))),
            call(fake_socket.socket(), constants.STRING_TERMINATOR)
        ])
Ejemplo n.º 40
0
class TestPlugin(unittest.TestCase):
    def setUp(self):
        self.mock = Mock()

    def test__pytest_adoption__gets_general_group(self):
        pytest_addoption(self.mock)
        self.mock.assert_has_calls([call.getgroup('general')])

    def test__pytest_adoption__adds_spec_option(self):
        pytest_addoption(self.mock)
        self.mock.assert_has_calls([
            call.getgroup().addoption(
                '--spec',
                action='store_true',
                dest='spec',
                help='Print test result in specification format')
        ])

    @patch('imp.reload')
    def test__pytest_configure__should_not_reload_configuration(
            self, imp_mock):
        pytest_configure(FakeConfig(spec=False))
        self.assertEqual(len(imp_mock.mock_calls), 0)

    @patch('imp.reload')
    def test__pytest_configure__reloads_pytest_after_patching(self, imp_mock):
        pytest_configure(FakeConfig(spec=True))
        self.assertEqual(len(imp_mock.mock_calls), 1)
Ejemplo n.º 41
0
  def test_stream_process_stdout(self):
    ret = StringIO(u'hello\nworld\n')
    log_fn = Mock()
    with patch("subprocess.Popen") as mock_process:
      mock_process.stdout = ret
      proc.stream_process_stdout(mock_process, log_fn)

    log_fn.assert_has_calls([call(u'hello\n'), call(u'world\n')])
Ejemplo n.º 42
0
 def test_ensure_base_image_build(self, fake_docker_client, fake_testing_spec, fake_expanded_libs):
     fake_docker_client.return_value = fake_docker_client
     mock_build = Mock()
     fake_docker_client.build = mock_build
     testing_spec = {"build": "/path/to/docker_file_folder"}
     fake_testing_spec.return_value = testing_spec
     _ensure_base_image(testing_spec)
     mock_build.assert_has_calls([call(path="/path/to/docker_file_folder", tag="dusty_testing_base/image")])
Ejemplo n.º 43
0
def test_retry_on_error_three_retries(monkeypatch: MonkeyPatch):
    monkeypatch.setattr(interactive.questionary, "confirm", QuestionaryConfirmMock(3))

    m = Mock(side_effect=PermissionError())
    with pytest.raises(PermissionError):
        interactive._retry_on_error(m, "export_path", 1, a=2)
    c = mock.call("export_path", 1, a=2)
    m.assert_has_calls([c, c, c])
Ejemplo n.º 44
0
  def test_stream_process_stdout(self):
    ret = StringIO(u'hello\nworld\n')
    log_fn = Mock()
    with patch("subprocess.Popen") as mock_process:
      mock_process.stdout = ret
      proc.stream_process_stdout(mock_process, log_fn)

    log_fn.assert_has_calls([call(u'hello\n'), call(u'world\n')])
Ejemplo n.º 45
0
        def expect_out_func_called_for_each_output_line(docker_client_fixture):
            docker_client_fixture.exec_start.return_value = [b'line1', b'line2']
            mock_out_func = Mock()

            create_container_obj(docker_client_fixture).execute('my_cmd', mock_out_func)

            calls = [call('line1'), call('line2')]
            mock_out_func.assert_has_calls(calls)
 def test_lambda_decoration(self):
     """Test data provider with a lambda function"""
     called_func_mock = Mock()
     dummy = Dummy(called_func_mock)
     dummy.decorated_by_lambda_method()
     called_func_mock.assert_has_calls([
         call(Dummy.ARG1, Dummy.ARG2),
         call(Dummy.ARG3, Dummy.ARG4),
     ])
 def test_def_decoration(self):
     """Test data provider with a class static method"""
     called_func_mock = Mock()
     dummy = Dummy(called_func_mock)
     dummy.decorated_by_def_method()
     called_func_mock.assert_has_calls([
         call(Dummy.ARG1, Dummy.ARG2),
         call(Dummy.ARG3, Dummy.ARG4),
     ])
def test_delete_old_packages(monkeypatch, mock_logger):
    monkeypatch.setattr('vdt.versionplugin.buildout.shared.glob.glob',
                        Mock(return_value=['test-1.deb', 'test-2.deb', 'test-3.deb']))
    mock_os = Mock()
    monkeypatch.setattr('vdt.versionplugin.buildout.shared.os.remove', mock_os)

    delete_old_packages()

    mock_os.assert_has_calls([call('test-1.deb'), call('test-2.deb'), call('test-3.deb')])
Ejemplo n.º 49
0
 def test_process_chunks_multiple(self):
     obj = es.ES('Foo', 'foondex', chunk_size=3)
     operation = Mock()
     documents = [1, 2, 3, 4, 5]
     obj.process_chunks(documents, operation)
     operation.assert_has_calls([
         call(documents_actions=[1, 2, 3]),
         call(documents_actions=[4, 5]),
     ])
def test_download_bdist_dependencies(monkeypatch):
    monkeypatch.setattr('vdt.versionplugin.buildout.shared.os',
                        Mock(**{'getcwd.return_value': sentinel.path}))
    mock_download_package = Mock()
    monkeypatch.setattr('vdt.versionplugin.buildout.shared.download_package', mock_download_package)
    deps_with_versions = [('puka', '1.0.0'), ('mock', '2.0.0'), ('pbr', '3.0.0')]
    download_bdist_dependencies(deps_with_versions)
    mock_download_package.assert_has_calls([call('puka', '1.0.0', sentinel.path),
                                           call('mock', '2.0.0', sentinel.path),
                                           call('pbr', '3.0.0', sentinel.path)])
Ejemplo n.º 51
0
 def test_event_handle_registation_with_list_of_strings(self):
     func_mock = Mock()
     handler("foo", "bar")(func_mock)
     event1 = self._call_handlers("foo.bar", {"data": "foo"})  # handled
     event2 = self._call_handlers("bar.foo", {"data": "bar"})  # handled
     self.assertEqual(2, func_mock.call_count)
     func_mock.assert_has_calls([
         call(event=event1),
         call(event=event2)
     ])
Ejemplo n.º 52
0
 def deduping_treats_different_calls_to_same_task_differently(self):
     body = Mock()
     t1 = Task(body)
     pre = [call(t1, 5), call(t1, 7), call(t1, 5)]
     t2 = Task(Mock(), pre=pre)
     c = Collection(t1=t1, t2=t2)
     e = Executor(collection=c)
     e.execute('t2')
     # Does not call the second t1(5)
     body.assert_has_calls([mock_call(5), mock_call(7)])
    def test_delete_loops_through_all_resources(self):
        instance = StaticGenerator('/some_path', '/some_path_2')
        remove = Mock()
        with nested(patch('os.path.exists', Mock(return_value=True)),
                    patch('os.remove', remove)):

            instance.delete()

        remove.assert_has_calls([call('test_web_root/fresh/some_path'),
                                 call('test_web_root/fresh/some_path_2')])
Ejemplo n.º 54
0
    def test_delete_from_path_deletes_current_file(self):
        instance = StaticGenerator()
        remove = Mock()
        with nested(patch('os.path.exists', Mock(return_value=True)),
                    patch('os.remove', remove)):

            instance.delete_from_path('/some_path')

        remove.assert_has_calls([call('test_web_root/fresh/some_path'),
                                 call('test_web_root/fresh/some_path.gz')])
Ejemplo n.º 55
0
def test_call_id_stack(rabbit_config, predictable_call_ids, runner_factory):
    child_do_called = Mock()

    stack_request = Mock()
    LoggingWorkerContext = get_logging_worker_context(stack_request)

    class Child(object):
        name = 'child'

        @rpc
        def child_do(self):
            child_do_called()
            return 1

    class Parent(object):
        name = "parent"

        child_service = RpcProxy('child')

        @rpc
        def parent_do(self):
            return self.child_service.child_do()

    class Grandparent(object):
        name = "grandparent"

        parent_service = RpcProxy('parent')

        @rpc
        def grandparent_do(self):
            return self.parent_service.parent_do()

    runner = runner_factory(rabbit_config)
    runner.add_service(Child, LoggingWorkerContext)
    runner.add_service(Parent, LoggingWorkerContext)
    runner.add_service(Grandparent, LoggingWorkerContext)
    runner.start()

    container = get_container(runner, Grandparent)
    with entrypoint_hook(container, "grandparent_do") as grandparent_do:
        assert grandparent_do() == 1

    # Check child is called
    child_do_called.assert_called_with()
    assert child_do_called.call_count == 1

    # Check IDs were requested
    assert predictable_call_ids.call_count == 3

    # Check call ID stack persisted over RPC
    stack_request.assert_has_calls([
        call(None),
        call(['grandparent.grandparent_do.0']),
        call(['grandparent.grandparent_do.0', 'parent.parent_do.1']),
    ])
Ejemplo n.º 56
0
class TestOnSuccess(TestCase):
    def setUp(self):
        self.streamer = daemon.TranslationStreamer(*daemon.get_twitter_auth())
        self.mock_tc = Mock()
        self.mock_gc = Mock()
        self.streamer.set_twitter_client(self.mock_tc)
        self.streamer.set_google_client(self.mock_gc)

    def test_not_a_tweet(self):
        data = {
            'some':'thing'
        }
        self.streamer.on_success(data)
        self.assertEqual(self.mock_tc.update_status.call_count, 0)
        self.assertEqual(self.mock_gc.translations.call_count, 0)

    def test_a_tweet(self):
        data = {
            'user': {
                'screen_name': 'foo',
            },
            'text': 'bar @someone #awesome http://www.foobarbaz.quux'
        }
        self.mock_gc.translations().list().execute.return_value = {
            'translations': [{'translatedText':'quux XZ0 XZ1 XZ2'}]
        }
        self.mock_gc.translations.reset_mock()

        self.streamer.on_success(data)

        self.assertEqual(self.mock_gc.translations.call_count, 1)
        self.mock_tc.update_status.assert_called_once_with(status='.@foo: quux @someone #awesome http://www.foobarbaz.quux')

    def test_n_tweets(self):
        data = {
            'user': {
                'screen_name': 'foo',
            },
            'text': 'Once upon a time long long ago in a galaxy far far away away away some things happend to some people of varying aspects and intents and gerbils wondered why cosmonauts drank iced kool-aid from the cups of woe, the cups of prison, the cups of prospect, the cups of ultimate eventuality'
        }
        self.mock_gc.translations().list().execute.return_value = {
            'translations': [{'translatedText':'Thrice upon a time long long ago in a galaxy far far away away away some things happend to some people of varying aspects and intents and gerbils wondered why cosmonauts drank iced kool-aid from the cups of woe, the cups of prison, the cups of prospect, the cups of ultimate eventuality'}]
        }
        self.mock_gc.translations.reset_mock()

        self.streamer.on_success(data)

        self.assertEqual(self.mock_gc.translations.call_count, 1)
        calls = [
            mock.call.update_status(status='.@foo: Thrice upon a time long long ago in a galaxy far far away away away some things happend to some people of varying aspects and...'),
            mock.call.update_status(status='intents and gerbils wondered why cosmonauts drank iced kool-aid from the cups of woe, the cups of prison, the cups of prospect, the cups...'),
            mock.call.update_status(status='of ultimate eventuality')
        ]
        self.mock_tc.assert_has_calls(calls)