Python unittest2.mock() Examples
The following are 30
code examples of unittest2.mock().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
unittest2
, or try the search function
.
Example #1
Source File: test_color.py From imgaug with MIT License | 6 votes |
def test_n_colors_tuple(self): aug = self.augmenter(n_colors=(2, 1000)) mock_quantize_func = mock.MagicMock( return_value=np.zeros((4, 4, 3), dtype=np.uint8)) n_images = 10 fname = self.quantization_func_name with mock.patch(fname, mock_quantize_func): image = np.zeros((4, 4, 3), dtype=np.uint8) _ = aug.augment_images([image] * n_images) # call i, args, argument 1 n_colors = [mock_quantize_func.call_args_list[i][0][1] for i in sm.xrange(n_images)] assert all([2 <= n_colors_i <= 1000 for n_colors_i in n_colors]) assert len(set(n_colors)) > 1
Example #2
Source File: test_tlsfuzzer_timing_runner.py From tlsfuzzer with GNU General Public License v2.0 | 6 votes |
def test_run_no_extraction(self): self.runner.tests = {"A": None, "B": None, "C": None} self.runner.tcpdump_running = True extract = mock.Mock() extract.return_value = False with mock.patch('__main__.__builtins__.open', self._mock_open(read_data="A,B,C\r\n0,2,1\r\n2,0,1\r\n2,1,0\r\n")): with mock.patch('tlsfuzzer.timing_runner.TimingRunner.sniff'): with mock.patch('tlsfuzzer.timing_runner.TimingRunner.extract', extract): with mock.patch('tlsfuzzer.timing_runner.TimingRunner.analyse') as analyse: with mock.patch('tlsfuzzer.timing_runner.Thread'): with mock.patch('tlsfuzzer.timing_runner.time.sleep'): with mock.patch('tlsfuzzer.timing_runner.Runner') as runner: ret = self.runner.run() self.assertEqual(runner.call_count, WARM_UP + 9) extract.assert_called_once() self.assertEqual(analyse.call_count, 0) self.assertEqual(ret, 2)
Example #3
Source File: test_polys.py From imgaug with MIT License | 6 votes |
def test_mocked(self): poly_oi = ia.PolygonsOnImage( [ia.Polygon([(1, 1), (8, 1), (8, 9), (1, 9)]), ia.Polygon([(1, 1), (15, 1), (15, 9), (1, 9)])], shape=(10, 11, 3)) mock_sub = mock.Mock() mock_sub.return_value = "foo" poly_oi.items[0].subdivide_ = mock_sub poly_oi.items[1].subdivide_ = mock_sub poly_oi_sub = self._func(poly_oi, 2) # When the PSOI is copied, each polygon is also copied. That leads # to new Polygon instances that have no longer the subdivide_ # method overwritten by the mock. Hence, the mock is never actually # called here. assert mock_sub.call_count == 0 assert poly_oi_sub.items != ["foo", "foo"]
Example #4
Source File: test_polys.py From imgaug with MIT License | 6 votes |
def test_mocked(self): poly_oi = ia.PolygonsOnImage( [ia.Polygon([(1, 1), (8, 1), (8, 9), (1, 9)]), ia.Polygon([(1, 1), (15, 1), (15, 9), (1, 9)])], shape=(10, 11, 3)) mock_sub = mock.Mock() mock_sub.return_value = "foo" poly_oi.items[0].subdivide_ = mock_sub poly_oi.items[1].subdivide_ = mock_sub poly_oi_sub = self._func(poly_oi, 2) assert mock_sub.call_count == 2 assert mock_sub.call_args_list[0][0][0] == 2 assert mock_sub.call_args_list[1][0][0] == 2 assert poly_oi_sub.items == ["foo", "foo"]
Example #5
Source File: test_tlsfuzzer_timing_runner.py From tlsfuzzer with GNU General Public License v2.0 | 6 votes |
def test_run(self): self.runner.tests = {"A": None, "B": None, "C": None} self.runner.tcpdump_running = True analyse = mock.Mock() analyse.return_value = 1 with mock.patch('__main__.__builtins__.open', self._mock_open(read_data="A,B,C\r\n0,2,1\r\n2,0,1\r\n2,1,0\r\n")): with mock.patch('tlsfuzzer.timing_runner.TimingRunner.sniff'): with mock.patch('tlsfuzzer.timing_runner.TimingRunner.extract') as extract: with mock.patch('tlsfuzzer.timing_runner.TimingRunner.analyse', analyse): with mock.patch('tlsfuzzer.timing_runner.Thread'): with mock.patch('tlsfuzzer.timing_runner.time.sleep'): with mock.patch('tlsfuzzer.timing_runner.Runner') as runner: ret = self.runner.run() self.assertEqual(runner.call_count, WARM_UP + 9) extract.assert_called_once() analyse.assert_called_once() self.assertEqual(ret, 1)
Example #6
Source File: test_tlsfuzzer_timing_runner.py From tlsfuzzer with GNU General Public License v2.0 | 6 votes |
def test_run_test_failure(self): self.runner.tests = {"A": None, "B": None, "C": None} self.runner.tcpdump_running = True def raise_error(*args, **kwargs): raise Exception() with mock.patch('__main__.__builtins__.open', self._mock_open(read_data="A,B,C\r\n0,2,1\r\n2,0,1\r\n2,1,0\r\n")): with mock.patch('tlsfuzzer.timing_runner.TimingRunner.sniff'): with mock.patch('tlsfuzzer.timing_runner.TimingRunner.analyse'): with mock.patch('tlsfuzzer.timing_runner.TimingRunner.extract'): with mock.patch('tlsfuzzer.timing_runner.Thread'): with mock.patch('tlsfuzzer.timing_runner.time.sleep'): with mock.patch('tlsfuzzer.timing_runner.Runner') as runner: runner.return_value.run.side_effect = raise_error self.assertRaises(AssertionError, self.runner.run)
Example #7
Source File: test_multicore.py From imgaug with MIT License | 6 votes |
def test_without_seed_start_simulate_py36_or_lower(self, mock_cp, mock_ia_seed, mock_time, mock_vi): def version_info(index): return 3 if index == 0 else 6 mock_vi.__getitem__.side_effect = version_info mock_time.return_value = 1 mock_cp.return_value = mock.MagicMock() mock_cp.return_value.name = "foo" augseq = mock.MagicMock() multicore._Pool_initialize_worker(augseq, None) assert mock_time.call_count == 1 assert mock_ia_seed.call_count == 1 assert augseq.seed_.call_count == 1 seed_global = mock_ia_seed.call_args_list[0][0][0] seed_local = augseq.seed_.call_args_list[0][0][0] assert seed_global != seed_local
Example #8
Source File: test_tlsfuzzer_expect.py From tlsfuzzer with GNU General Public License v2.0 | 6 votes |
def test_gen_srv_ext_handler_record_limit_with_too_large_size_in_TLS_1_3(self): # in TLS 1.3 the maximum size supported is 2**14 + 1, check if we # reject sizes larger than that ext = RecordSizeLimitExtension().create(2**14+2) state = ConnectionState() state.version = (3, 4) client_hello = ClientHello() cl_ext = RecordSizeLimitExtension().create(2**10+1) client_hello.extensions = [cl_ext] state.handshake_messages.append(client_hello) state.msg_sock = mock.MagicMock() handler = gen_srv_ext_handler_record_limit() with self.assertRaises(AssertionError): handler(state, ext)
Example #9
Source File: test_color.py From imgaug with MIT License | 6 votes |
def test_from_colorspace(self): def _noop(img): return img aug = self.augmenter(from_colorspace="BGR") mock_change_colorspace = mock.MagicMock() mock_change_colorspace.return_value = mock_change_colorspace mock_change_colorspace.augment_image.side_effect = _noop mock_change_colorspace._draw_samples.return_value = (None, ["foo"]) fname = "imgaug.augmenters.color.ChangeColorspace" with mock.patch(fname, mock_change_colorspace): _ = aug.augment_image(np.zeros((4, 4, 3), dtype=np.uint8)) # call 0, kwargs, argument 'from_colorspace' assert ( mock_change_colorspace.call_args_list[0][1]["from_colorspace"] == "BGR") # call 1, kwargs, argument 'from_colorspace' (inverse transform) assert ( mock_change_colorspace.call_args_list[1][1]["from_colorspace"] == "foo")
Example #10
Source File: test_segmentation.py From imgaug with MIT License | 6 votes |
def _test_image_with_n_channels(cls, nb_channels): image = np.zeros((10, 20), dtype=np.uint8) if nb_channels is not None: image = image[..., np.newaxis] image = np.tile(image, (1, 1, nb_channels)) sampler = iaa.RegularGridPointsSampler(1, 1) aug = iaa.Voronoi(sampler) mock_segment_voronoi = mock.MagicMock() if nb_channels is None: mock_segment_voronoi.return_value = image[..., np.newaxis] else: mock_segment_voronoi.return_value = image fname = "imgaug.augmenters.segmentation.segment_voronoi" with mock.patch(fname, mock_segment_voronoi): image_aug = aug(image=image) assert image_aug.shape == image.shape
Example #11
Source File: test_blur.py From imgaug with MIT License | 6 votes |
def test_backends_called(self): def side_effect_cv2(image, ksize, sigmaX, sigmaY, borderType): return image + 1 def side_effect_scipy(image, sigma, mode): return image + 1 mock_GaussianBlur = mock.Mock(side_effect=side_effect_cv2) mock_gaussian_filter = mock.Mock(side_effect=side_effect_scipy) image = np.arange(4*4).astype(np.uint8).reshape((4, 4)) with mock.patch('cv2.GaussianBlur', mock_GaussianBlur): _observed = iaa.blur_gaussian_( np.copy(image), sigma=1.0, eps=0, backend="cv2") assert mock_GaussianBlur.call_count == 1 with mock.patch('scipy.ndimage.gaussian_filter', mock_gaussian_filter): _observed = iaa.blur_gaussian_( np.copy(image), sigma=1.0, eps=0, backend="scipy") assert mock_gaussian_filter.call_count == 1
Example #12
Source File: test_blur.py From imgaug with MIT License | 6 votes |
def test_draw_samples(self): aug = iaa.MeanShiftBlur( spatial_radius=[1.0, 2.0, 3.0], color_radius=(1.0, 2.0) ) batch = mock.Mock() batch.nb_rows = 100 samples = aug._draw_samples(batch, iarandom.RNG(0)) assert np.all( np.isclose(samples[0], 1.0) | np.isclose(samples[0], 2.0) | np.isclose(samples[0], 3.0) ) assert np.all((1.0 <= samples[1]) | (samples[1] <= 2.0))
Example #13
Source File: test_contrast.py From imgaug with MIT License | 6 votes |
def test_basic_functionality_3d(self): # image with three channels img = [ [99, 100, 101], [99, 100, 101], [99, 100, 101] ] img = np.uint8(img) img3d = np.tile(img[:, :, np.newaxis], (1, 1, 3)) img3d[..., 1] += 1 img3d[..., 2] += 2 aug = iaa.AllChannelsCLAHE(clip_limit=20, tile_grid_size_px=17) mock_clahe = ArgCopyingMagicMock() mock_clahe.apply.return_value = img with mock.patch('cv2.createCLAHE') as mock_createCLAHE: mock_createCLAHE.return_value = mock_clahe _ = aug.augment_image(img3d) clist = mock_clahe.apply.call_args_list assert np.array_equal(clist[0][0][0], img3d[..., 0]) assert np.array_equal(clist[1][0][0], img3d[..., 1]) assert np.array_equal(clist[2][0][0], img3d[..., 2])
Example #14
Source File: test_random.py From imgaug with MIT License | 6 votes |
def test_standard_normal_np117_mocked(self): fname = "standard_normal" arr = np.zeros((1,), dtype="float16") args = [] kwargs = {"size": (1,), "dtype": "float16", "out": arr} mock_gen = mock.MagicMock() getattr(mock_gen, fname).return_value = "foo" rng = iarandom.RNG(0) rng.generator = mock_gen rng._is_new_rng_style = True result = getattr(rng, fname)(*args, **kwargs) assert result == "foo" getattr(mock_gen, fname).assert_called_once_with(*args, **kwargs)
Example #15
Source File: test_contrast.py From imgaug with MIT License | 6 votes |
def test_unit_sized_kernels(self): img = np.zeros((1, 1), dtype=np.uint8) tile_grid_sizes = [0, 0, 0, 1, 1, 1, 3, 3, 3] tile_grid_min_sizes = [0, 1, 3, 0, 1, 3, 0, 1, 3] nb_calls_expected = [0, 0, 1, 0, 0, 1, 1, 1, 1] gen = zip(tile_grid_sizes, tile_grid_min_sizes, nb_calls_expected) for tile_grid_size_px, tile_grid_size_px_min, nb_calls_exp_i in gen: with self.subTest(tile_grid_size_px=tile_grid_size_px, tile_grid_size_px_min=tile_grid_size_px_min, nb_calls_expected_i=nb_calls_exp_i): aug = iaa.AllChannelsCLAHE( clip_limit=20, tile_grid_size_px=tile_grid_size_px, tile_grid_size_px_min=tile_grid_size_px_min) mock_clahe = mock.Mock() mock_clahe.apply.return_value = img mock_createCLAHE = mock.MagicMock(return_value=mock_clahe) with mock.patch('cv2.createCLAHE', mock_createCLAHE): _ = aug.augment_image(img) assert mock_createCLAHE.call_count == nb_calls_exp_i
Example #16
Source File: utils.py From wakadump with BSD 3-Clause "New" or "Revised" License | 6 votes |
def setUp(self): # disable logging while testing logging.disable(logging.CRITICAL) self.patched = {} if hasattr(self, 'patch_these'): for patch_this in self.patch_these: namespace = patch_this[0] if isinstance(patch_this, (list, set)) else patch_this patcher = mock.patch(namespace) mocked = patcher.start() mocked.reset_mock() self.patched[namespace] = mocked if isinstance(patch_this, (list, set)) and len(patch_this) > 0: retval = patch_this[1] if callable(retval): retval = retval() mocked.return_value = retval
Example #17
Source File: test_parameters.py From imgaug with MIT License | 6 votes |
def test_prefetches_at_second_call(self): other_param = mock.Mock() other_param.draw_samples.return_value = np.zeros((100,), dtype=np.uint8) param = iap.AutoPrefetcher(other_param, 10) rng = iarandom.RNG(0) _samples = param.draw_samples((1,), rng) _samples = param.draw_samples((1,), rng) # rng is currently not identical in call args, # because draw_samples() creates a new one with same state assert other_param.draw_samples.call_count == 2 assert other_param.draw_samples.call_args_list[0][0][0] == (1,) assert other_param.draw_samples.call_args_list[0][0][1].equals(rng) assert other_param.draw_samples.call_args_list[1][0][0] == (10,) assert other_param.draw_samples.call_args_list[1][0][1].equals(rng) # (100,) because that's what the mock always returns assert param.samples.shape == (100,) assert param.index == 1 assert param.last_rng_idx == rng._idx
Example #18
Source File: test_random.py From imgaug with MIT License | 6 votes |
def test_standard_gamma_np117_mocked(self): fname = "standard_gamma" arr = np.zeros((1,), dtype="float16") args = [] kwargs = {"shape": 1.0, "size": (1,), "dtype": "float16", "out": arr} mock_gen = mock.MagicMock() getattr(mock_gen, fname).return_value = "foo" rng = iarandom.RNG(0) rng.generator = mock_gen rng._is_new_rng_style = True result = getattr(rng, fname)(*args, **kwargs) assert result == "foo" getattr(mock_gen, fname).assert_called_once_with(*args, **kwargs)
Example #19
Source File: test_random.py From imgaug with MIT License | 6 votes |
def test_standard_exponential_np117_mocked(self): fname = "standard_exponential" arr = np.zeros((1,), dtype="float16") args = [] kwargs = {"size": (1,), "dtype": "float16", "method": "foo", "out": arr} mock_gen = mock.MagicMock() getattr(mock_gen, fname).return_value = "foo" rng = iarandom.RNG(0) rng.generator = mock_gen rng._is_new_rng_style = True result = getattr(rng, fname)(*args, **kwargs) assert result == "foo" getattr(mock_gen, fname).assert_called_once_with(*args, **kwargs)
Example #20
Source File: test_random.py From imgaug with MIT License | 5 votes |
def test_standard_gamma_np116_mocked(self): fname = "standard_gamma" arr_out = np.zeros((1,), dtype="float16") arr_result = np.ones((1,), dtype="float16") def _side_effect(x): return arr_result args = [] kwargs = {"shape": 1.0, "size": (1,), "dtype": "float16", "out": arr_out} kwargs_subcall = {"shape": 1.0, "size": (1,)} mock_gen = mock.MagicMock() mock_gen.astype.side_effect = _side_effect getattr(mock_gen, fname).return_value = mock_gen rng = iarandom.RNG(0) rng.generator = mock_gen rng._is_new_rng_style = False result = getattr(rng, fname)(*args, **kwargs) getattr(mock_gen, fname).assert_called_once_with(*args, **kwargs_subcall) mock_gen.astype.assert_called_once_with("float16") assert np.allclose(result, arr_result) assert np.allclose(arr_out, arr_result)
Example #21
Source File: test_tlsfuzzer_timing_runner.py From tlsfuzzer with GNU General Public License v2.0 | 5 votes |
def test_run_tcpdump_failure(self): self.runner.tests = {"A": None, "B": None, "C": None} with mock.patch('__main__.__builtins__.open', self._mock_open(read_data="A,B,C\r\n0,2,1\r\n2,0,1\r\n2,1,0\r\n")): with mock.patch('tlsfuzzer.timing_runner.TimingRunner.sniff'): with mock.patch('tlsfuzzer.timing_runner.TimingRunner.extract'): with mock.patch('tlsfuzzer.timing_runner.TimingRunner.analyse'): with mock.patch('tlsfuzzer.timing_runner.Thread'): with mock.patch('tlsfuzzer.timing_runner.time.sleep'): with mock.patch('tlsfuzzer.timing_runner.Runner') as runner: self.runner.tcpdump_running = False self.assertRaises(SystemExit, self.runner.run) self.assertEqual(runner.call_count, 0)
Example #22
Source File: test_random.py From imgaug with MIT License | 5 votes |
def test_standard_exponential_np116_mocked(self): fname = "standard_exponential" arr_out = np.zeros((1,), dtype="float16") arr_result = np.ones((1,), dtype="float16") def _side_effect(x): return arr_result args = [] kwargs = {"size": (1,), "dtype": "float16", "method": "foo", "out": arr_out} kwargs_subcall = {"size": (1,)} mock_gen = mock.MagicMock() mock_gen.astype.side_effect = _side_effect getattr(mock_gen, fname).return_value = mock_gen rng = iarandom.RNG(0) rng.generator = mock_gen rng._is_new_rng_style = False result = getattr(rng, fname)(*args, **kwargs) getattr(mock_gen, fname).assert_called_once_with(*args, **kwargs_subcall) mock_gen.astype.assert_called_once_with("float16") assert np.allclose(result, arr_result) assert np.allclose(arr_out, arr_result)
Example #23
Source File: test_contrast.py From imgaug with MIT License | 5 votes |
def test_basic_functionality(self): gen = itertools.product([None, 1, 2, 3], [1, 2, 3], [False, True]) for nb_channels, nb_images, is_array in gen: with self.subTest(nb_channels=nb_channels, nb_images=nb_images, is_array=is_array): img = [ [0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14, 15], [16, 17, 18, 19] ] img = np.uint8(img) if nb_channels is not None: img = np.tile(img[..., np.newaxis], (1, 1, nb_channels)) imgs = [img] * nb_images if is_array: imgs = np.uint8(imgs) def _side_effect(img_call): return img_call + 1 mock_equalizeHist = mock.MagicMock(side_effect=_side_effect) with mock.patch('cv2.equalizeHist', mock_equalizeHist): aug = iaa.AllChannelsHistogramEqualization() imgs_aug = aug.augment_images(imgs) if is_array: assert ia.is_np_array(imgs_aug) else: assert isinstance(imgs_aug, list) assert len(imgs_aug) == nb_images for i in sm.xrange(nb_images): assert imgs_aug[i].dtype.name == "uint8" assert np.array_equal(imgs_aug[i], imgs[i] + 1)
Example #24
Source File: test_tlsfuzzer_expect.py From tlsfuzzer with GNU General Public License v2.0 | 5 votes |
def test___init__(self): timeout = mock.Mock() exp = ExpectNoMessage(timeout) self.assertIsNotNone(exp) self.assertTrue(exp.is_expect()) self.assertFalse(exp.is_command()) self.assertFalse(exp.is_generator()) self.assertIs(exp.timeout, timeout)
Example #25
Source File: test_tlsfuzzer_timing_runner.py From tlsfuzzer with GNU General Public License v2.0 | 5 votes |
def test_extract(self): check_extract = mock.Mock() check_extract.return_value = False with mock.patch("tlsfuzzer.timing_runner.TimingRunner.check_extraction_availability", check_extract): self.assertFalse(self.runner.extract()) self.runner.log = mock.Mock(autospec=True) with mock.patch("__main__.__builtins__.__import__"): self.assertTrue(self.runner.extract())
Example #26
Source File: test_random.py From imgaug with MIT License | 5 votes |
def _test_sampling_func(cls, fname, *args, **kwargs): mock_gen = mock.MagicMock() getattr(mock_gen, fname).return_value = "foo" rng = iarandom.RNG(0) rng.generator = mock_gen result = getattr(rng, fname)(*args, **kwargs) assert result == "foo" getattr(mock_gen, fname).assert_called_once_with(*args, **kwargs) # # outdated methods from RandomState #
Example #27
Source File: test_random.py From imgaug with MIT License | 5 votes |
def _test_sampling_func_alias(cls, fname_alias, fname_subcall, *args, **kwargs): rng = iarandom.RNG(0) mock_func = mock.Mock() mock_func.return_value = "foo" setattr(rng, fname_subcall, mock_func) result = getattr(rng, fname_alias)(*args, **kwargs) assert result == "foo" assert mock_func.call_count == 1
Example #28
Source File: test_random.py From imgaug with MIT License | 5 votes |
def test_np117_mocked(self): dummy_bitgen = np.random.SFC64(1) with mock.patch("numpy.random.SFC64") as mock_bitgen: mock_bitgen.return_value = dummy_bitgen result = iarandom._create_fully_random_generator_np117() assert mock_bitgen.call_count == 1 assert iarandom.is_generator_equal_to( result, np.random.Generator(dummy_bitgen))
Example #29
Source File: test_random.py From imgaug with MIT License | 5 votes |
def test_mocked_call_with_default_values_np116(self): def side_effect(low, high=None, size=None, dtype='l'): return "np116" gen = mock.MagicMock() gen.randint.side_effect = side_effect result = iarandom.polyfill_integers(gen, 2) assert result == "np116" gen.randint.assert_called_once_with(low=2, high=None, size=None, dtype="int32")
Example #30
Source File: test_random.py From imgaug with MIT License | 5 votes |
def test_np116_mocked(self): dummy_rs = np.random.RandomState(1) with mock.patch("numpy.random.RandomState") as mock_rs: mock_rs.return_value = dummy_rs result = iarandom._create_fully_random_generator_np116() assert mock_rs.call_count == 1 assert iarandom.is_generator_equal_to(result, np.random.RandomState(1))