def test_to_page_without_url(self): other_page_cls = Mock(url=None) class TestPage(Page): linktopage = Link('id=linktopage', to=other_page_cls) page = TestPage() page.linktopage() other_page_cls.assert_called_once_with(assert_is_on_page=False)
def test_manual_execute_with_ids_ignored_while_in_execute(self): waiter = Event() long_execute_waiter = Event() # noinspection PyUnusedLocal def execute(*args, **kwargs): waiter.set() long_execute_waiter.wait(1) self.assertTrue(long_execute_waiter.is_set) execute_mock = Mock(side_effect=execute) self.trackers_manager.execute = execute_mock self.create_runner(interval=1) self.engine_runner.execute(None) waiter.wait(0.3) waiter.clear() ids = [1, 2, 3] self.engine_runner.execute(ids) long_execute_waiter.set() waiter.wait(0.3) self.assertTrue(waiter.is_set) self.stop_runner() execute_mock.assert_called_once_with(ANY, None)
def test_new_mode_callback(self): """Create a Controller object, call on_new_mode_online method and check that the callback fires when set_composite_mode is called """ self.setup_server() self.setup_controller() self.log.info("setting callback") test_cb = Mock(side_effect=self.quit_mainloop) self.controller.on_new_mode_online(test_cb) self.log.info("starting test-sources") self.setup_video_sources(count=2) self.log.info("waiting for initial callback with default-mode" "COMPOSITE_DUAL_EQUAL") self.run_mainloop(timeout=5) test_cb.assert_called_once_with(Controller.COMPOSITE_DUAL_EQUAL) test_cb.reset_mock() self.log.info("setting new composite mode COMPOSITE_NONE") assert self.controller.set_composite_mode(Controller.COMPOSITE_NONE) self.run_mainloop(timeout=5) self.log.info("waiting for callback with new mode COMPOSITE_NONE") test_cb.assert_called_once_with(Controller.COMPOSITE_NONE)
def test_extract_from_files_callback_works(self): """extract_from_files should call our callback""" testfile = ('templates/even_more_lang_files.html',) callback = Mock() next(extract_from_files(testfile, callback=callback, method_map=METHODS), None) callback.assert_called_once_with(testfile[0], METHODS[0][1], ANY)
def test_exception_request_handlers(self, f): ex = wac.requests.HTTPError() ex.response = Mock() ex.response.status_code = 402 ex.response.content = ( '{"status": "Bad Request", "status_code": ' '"400", "description": "Invalid field \'your mom\' -- make ' 'sure its your dad too", "additional": "nothing personal"}') ex.response.headers = { 'Content-Type': 'application/json', } f.__name__ = 'post' f.side_effect = ex before_request = Mock() after_request = Mock() with self.cli: self.cli.config.root_url = '/test' self.cli.config.keep_alive = False self.cli.config.before_request.append(before_request) self.cli.config.after_request.append(after_request) with self.assertRaises(wac.Error) as ex_ctx: self.cli.post('/a/post/w/hooks', data={'hi': 'ya'}) self.assertEqual(ex_ctx.exception.status_code, 402) self.assertEqual(ex_ctx.exception.additional, 'nothing personal') before_request.assert_called_once_with( 'POST', '/test/a/post/w/hooks', {'headers': {'Content-Type': 'application/json'}, 'allow_redirects': False, 'data': '{"hi": "ya"}', } ) after_request.assert_called_once_with(ex.response)
def test_injects_match_groups_to_app(self): app = Mock(name='app') r = wsgi.PathRouter( ('{foo}/{bar}', lambda foo, bar: app(foo, bar)), ) self.assertIs(r(self.context, 'oof/rab'), app.return_value) app.assert_called_once_with('oof', 'rab')
def test12_player_info(self): player_id = 20 player_name = u"pl\xe1y\u1ebdr" player_avatar_url = "http://example.com/test.jpg" player_score = 4141 player_level, _, _ = cardstories.levels.calculate_level(player_score) sql = "INSERT INTO players (player_id, score) VALUES (%d, %d)" c = self.db.cursor() c.execute(sql % (player_id, player_score)) self.db.commit() # Fake calls to auth module default_get_player_name = self.service.auth.get_player_name fake_get_player_name = Mock(return_value=player_name) self.service.auth.get_player_name = fake_get_player_name default_get_player_avatar_url = self.service.auth.get_player_avatar_url fake_get_player_avatar_url = Mock(return_value=player_avatar_url) self.service.auth.get_player_avatar_url = fake_get_player_avatar_url players_info = yield self.service.player_info({'type': 'player_info', 'player_id': [player_id]}) fake_get_player_name.assert_called_once_with(player_id) fake_get_player_avatar_url.assert_called_once_with(player_id) self.assertEquals(players_info, [{ 'type': 'players_info', str(player_id): {'name': player_name, 'avatar_url': player_avatar_url, 'level': player_level} }]) self.service.auth.get_player_name = default_get_player_name self.service.auth.get_player_avatar_url = default_get_player_avatar_url
def test_main_loop_no_task(self): config = Mock() pool_size = 4 mocked_pool = Mock() mocked_pool.free_count = Mock(return_value=pool_size) mocked_done_with_processed_tasks = Mock(side_effect=self.main_loop_done_with_processed_tasks) mocked_worker = Mock() mocked_gevent_queue = Mock() mocked_task = Mock() mocked_tube = Mock(return_value=mocked_task) mocked_tube.take = Mock(return_value=None) mocked_tarantool_queue = Mock() mocked_tarantool_queue.tube = Mock(return_value=mocked_tube) with patch('notification_pusher.tarantool_queue.Queue', Mock(return_value=mocked_tarantool_queue)): with patch('notification_pusher.Pool', Mock(return_value=mocked_pool)): with patch('notification_pusher.done_with_processed_tasks', mocked_done_with_processed_tasks): with patch('notification_pusher.Greenlet', Mock(return_value=mocked_worker)): with patch('notification_pusher.gevent_queue.Queue', Mock(return_value=mocked_gevent_queue)): notification_pusher.run_application = True main_loop(config) assert not mocked_worker.start.called mocked_done_with_processed_tasks.assert_called_once_with(mocked_gevent_queue)
def test_run_in_subprocess(): with patch.multiple('pkglib_testing.cmdline', cPickle=DEFAULT, execnet=DEFAULT) as mocks: fn = Mock(__name__='fn') res = cmdline.run_in_subprocess(fn, python='sentinel.python')(sentinel.arg, kw=sentinel.kw) mocks['execnet'].makegateway.assert_called_once_with('popen//python=sentinel.python') gw = mocks['execnet'].makegateway.return_value ((remote_fn,), _) = gw.remote_exec.call_args chan = gw.remote_exec.return_value mocks['cPickle'].dumps.assert_called_with((fn, (sentinel.arg,), {'kw': sentinel.kw}), protocol=0) chan.send.assert_called_with(mocks['cPickle'].dumps.return_value) chan.receive.assert_has_calls([call(None) for _i in range(gw.remote_exec.call_count)]) mocks['cPickle'].loads.assert_called_once_with(chan.receive.return_value) assert res is mocks['cPickle'].loads.return_value chan.close.assert_has_calls([call() for _i in range(gw.remote_exec.call_count)]) gw.exit.assert_called_once_with() with patch('pkglib_util.six.moves.cPickle') as cPickle: channel, fn = Mock(), Mock() cPickle.loads.return_value = (fn, (sentinel.arg,), {'kw': sentinel.kw}) remote_fn(channel) channel.receive.assert_called_once_with(None) cPickle.loads.assert_called_once_with(channel.receive.return_value) fn.assert_called_once_with(sentinel.arg, kw=sentinel.kw) cPickle.dumps.assert_called_once_with(fn.return_value, protocol=0) channel.send.assert_called_once_with(cPickle.dumps.return_value)
def test_rmtree_ignore_unlink_rmdir_exception(self): dir1_list = ["dir2", "file"] empty_list = [] mock_listdir = Mock() mock_listdir.side_effect = [dir1_list, empty_list] mock_isdir = Mock() mock_isdir.side_effect = [True, False] mock_unlink = Mock() mock_unlink.side_effect = [OSError] mock_rmdir = Mock() mock_rmdir.side_effect = [0, OSError] mock_islink = Mock() mock_islink.return_value = False with nested(patch("gluster.gfapi.Volume.listdir", mock_listdir), patch("gluster.gfapi.Volume.isdir", mock_isdir), patch("gluster.gfapi.Volume.islink", mock_islink), patch("gluster.gfapi.Volume.unlink", mock_unlink), patch("gluster.gfapi.Volume.rmdir", mock_rmdir)): self.vol.rmtree("dir1", True) mock_rmdir.assert_any_call("dir1/dir2") mock_unlink.assert_called_once_with("dir1/file") mock_rmdir.assert_called_with("dir1")
def test_set_logging_err(self): v = Volume("host", "vol") v.fs = 12345 _m_set_logging = Mock(return_value=-1) with patch("gluster.gfapi.api.glfs_set_logging", _m_set_logging): self.assertRaises(LibgfapiException, v.set_logging, "/dev/null", 7) _m_set_logging.assert_called_once_with(v.fs, None, 7)
def test_connect_default_type(self): transport = Mock() with patch.dict(pyeapi.client.TRANSPORTS, {'https': transport}): pyeapi.client.connect() kwargs = dict(host='localhost', username='******', password='', port=None) transport.assert_called_once_with(**kwargs)
def test_mdtol_intercept(self): call_func = Mock() data = sentinel.data axis = sentinel.axis aggregator = Aggregator('', call_func) aggregator.aggregate(data, axis, wibble='wobble', mdtol=0.8) call_func.assert_called_once_with(data, axis=axis, wibble='wobble')
def test_open(self, sleep): fn = Mock() connection = Mock(url=URL, retry=True) fx = retry(ConnectError)(fn) fx(connection) fn.assert_called_once_with(connection) self.assertFalse(sleep.called)
def test_subscriber_predicate(config): """Test that the ``asset_request`` subscriber predicate. It should correctly match asset requests when its value is ``True``, and other requests when ``False``. """ config.include(assets) mock1 = Mock() mock2 = Mock() config.add_subscriber(mock1, DummyEvent, asset_request=False) config.add_subscriber(mock2, DummyEvent, asset_request=True) request1 = DummyRequest('/') request1.matched_route = None pattern = config.get_webassets_env().url + '*subpath' request2 = DummyRequest(config.get_webassets_env().url + '/t.png') request2.matched_route = Route('__' + pattern, pattern) event1 = DummyEvent(request1) event2 = DummyEvent(request2) config.registry.notify(event1) config.registry.notify(event2) mock1.assert_called_once_with(event1) mock2.assert_called_once_with(event2)
def test_calls_provided_test(self): client = fake_juju_client() with temp_dir() as juju_home: client.env.juju_home = juju_home bs_manager = make_bootstrap_manager(client) bs_manager.log_dir = os.path.join(juju_home, 'log-dir') os.mkdir(bs_manager.log_dir) timing = gpr.TimingData(datetime.utcnow(), datetime.utcnow()) deploy_details = gpr.DeployDetails('test', dict(), timing) noop_test = Mock(return_value=deploy_details) pprof_collector = Mock() with patch.object(gpr, 'dump_performance_metrics_logs', autospec=True): with patch.object(gpr, 'generate_reports', autospec=True): with patch.object( gpr, 'PPROFCollector', autospec=True) as p_pc: p_pc.return_value = pprof_collector gpr.run_perfscale_test( noop_test, bs_manager, get_default_args()) noop_test.assert_called_once_with( client, pprof_collector, get_default_args())
def test_create_report_graph_returns_base_file_path(self): """The returned filepath should just be the basename.""" generator = Mock() start = 0000 end = 9999 file_list = ['example.rrd'] rrd_dir = '/foo' output_file = '/bar/test.png' output_file_base = 'test.png' graph_period = '0' with patch.object( gpr.os, 'listdir', autospec=True, return_value=file_list) as m_list: with patch.object( gpr, 'get_duration_points', autospec=True, return_value=(start, end)) as m_gdp: self.assertEqual( output_file_base, gpr.create_report_graph( rrd_dir, output_file, generator, graph_period) ) m_gdp.assert_called_once_with('/foo/example.rrd', graph_period) m_list.assert_called_once_with(rrd_dir) generator.assert_called_once_with( start, end, rrd_dir, output_file)
def file_type_test(self, bucket_method, test_file, content_type, resized_size): bucket = Mock() bucket_method.return_value = bucket new_key = Mock() bucket.new_key.return_value = new_key image_handler = ImageHandler(filename=test_file) truck = ImageTruck.new_from_file(test_file) session = Client().session() image = ImageTable(filename='badcafe') session.add(image) session.flush() after_upload = Mock() ResizeImage._resize_image(image, image_handler, truck, 'thumbnail', after_upload) new_key.set_metadata.assert_called_with('Content-Type', content_type) resized_contents = new_key.set_contents_from_string.call_args[0][0] image_handler = ImageHandler(blob=resized_contents) eq_(image_handler.size, resized_size) after_upload.assert_called_once_with('thumbnail')
def test_multiple_errbacks(self): session = self.make_session() pool = session._pools.get.return_value connection = Mock(spec=Connection) pool.borrow_connection.return_value = (connection, 1) query = SimpleStatement("INSERT INFO foo (a, b) VALUES (1, 2)") query.retry_policy = Mock() query.retry_policy.on_unavailable.return_value = (RetryPolicy.RETHROW, None) message = QueryMessage(query=query, consistency_level=ConsistencyLevel.ONE) rf = ResponseFuture(session, message, query, 1) rf.send_request() callback = Mock() arg = "positional" kwargs = {'one': 1, 'two': 2} rf.add_errback(callback, arg, **kwargs) callback2 = Mock() arg2 = "another" kwargs2 = {'three': 3, 'four': 4} rf.add_errback(callback2, arg2, **kwargs2) expected_exception = Unavailable("message", 1, 2, 3) result = Mock(spec=UnavailableErrorMessage, info={'something': 'here'}) result.to_exception.return_value = expected_exception rf._set_result(result) self.assertRaises(Exception, rf.result) callback.assert_called_once_with(expected_exception, arg, **kwargs) callback2.assert_called_once_with(expected_exception, arg2, **kwargs2)
def test_add_callbacks(self): session = self.make_session() query = SimpleStatement("INSERT INFO foo (a, b) VALUES (1, 2)") query.retry_policy = Mock() query.retry_policy.on_unavailable.return_value = (RetryPolicy.RETHROW, None) message = QueryMessage(query=query, consistency_level=ConsistencyLevel.ONE) # test errback rf = ResponseFuture(session, message, query, 1) rf.send_request() rf.add_callbacks( callback=self.assertEqual, callback_args=([{'col': 'val'}],), errback=self.assertIsInstance, errback_args=(Exception,)) result = Mock(spec=UnavailableErrorMessage, info={}) rf._set_result(result) self.assertRaises(Exception, rf.result) # test callback rf = ResponseFuture(session, message, query, 1) rf.send_request() callback = Mock() expected_result = [{'col': 'val'}] arg = "positional" kwargs = {'one': 1, 'two': 2} rf.add_callbacks( callback=callback, callback_args=(arg,), callback_kwargs=kwargs, errback=self.assertIsInstance, errback_args=(Exception,)) rf._set_result(self.make_mock_response(expected_result)) self.assertEqual(rf.result(), expected_result) callback.assert_called_once_with(expected_result, arg, **kwargs)
def test15_poll_notification(self): args = { 'type': ['tabs'], 'action': ['poll'], 'player_id': [13], 'game_id': [20], 'modified': [10000000000000000] } # Fake poll controlled from the test poll = defer.Deferred() mock_poll_tabs = Mock() mock_poll_tabs.return_value = poll orig_service_poll_tabs = self.service.poll_tabs self.service.poll_tabs = mock_poll_tabs mock_listener = Mock() self.service.listen().addCallback(mock_listener) self.service.poll(args) mock_listener.assert_called_once_with({'player_id': 13, 'type': 'poll_start'}) mock_listener.reset_mock() self.service.listen().addCallback(mock_listener) poll.callback(args) mock_listener.assert_called_once_with({'player_id': 13, 'type': 'poll_end'}) self.service.poll_tabs = orig_service_poll_tabs
def test_register_controller_extensions_without_mail(self): from horus.views import RegisterController from horus.interfaces import IRegisterSchema from horus.interfaces import IRegisterForm from horus.interfaces import IUserClass from horus.interfaces import IUIStrings from horus.strings import UIStringsBase from horus.tests.models import User from horus.interfaces import IActivationClass from horus.tests.models import Activation self.config.registry.registerUtility(Activation, IActivationClass) self.config.registry.registerUtility(User, IUserClass) self.config.registry.registerUtility(UIStringsBase, IUIStrings) self.config.add_route('index', '/') request = testing.DummyRequest() getUtility = Mock() getUtility.return_value = True schema = Mock() form = Mock() self.config.registry.settings['horus.require_activation'] = False self.config.registry.registerUtility(schema, IRegisterSchema) self.config.registry.registerUtility(form, IRegisterForm) with patch('horus.views.get_mailer') as get_mailer: RegisterController(request) assert not get_mailer.called schema.assert_called_once_with() assert form.called
def test_trigger_events(self, mock_from): mock_after = Mock() mock_before = Mock() mock_from.return_value = {'foo': 1} ctx = Mock() view = Mock( request=Mock(action='index'), _json_params={'bar': 1}, context=ctx, _silent=False) view.index._silent = False view.index._event_action = None with patch.dict(events.BEFORE_EVENTS, {'index': mock_before}): with patch.dict(events.AFTER_EVENTS, {'index': mock_after}): with events.trigger_events(view): pass mock_after.assert_called_once_with( fields={'foo': 1}, model=view.Model, instance=ctx, view=view) mock_before.assert_called_once_with( fields={'foo': 1}, model=view.Model, instance=ctx, view=view) view.request.registry.notify.assert_has_calls([ call(mock_before()), call(mock_after()), ]) mock_from.assert_called_once_with({'bar': 1}, view.Model)
def test_dependencer(Wheel): "Dependencer#handle() should emit the signal dependency_found when scanning a new package" # Given that I have the depencencer service callback = Mock() dependencer = Dependencer() dependencer.connect('dependency_found', callback) # And that the package to test the service will have the following # dependencies: Wheel.return_value = Mock(metadata=Mock(dependencies={ 'install': ['forbiddenfruit (0.1.1)'], 'extras': {}, })) # When I queue a package and a sentinel and then call the worker dependencer.queue('tests', requirement='sure', wheel='forbiddenfruit-0.1-cp27.whl') dependencer.queue(None) dependencer._worker() # Than I see that the signal was called for the dependency with the right # parameters callback.assert_called_once_with( 'dependencer', requirement='forbiddenfruit (0.1.1)', dependency_of='sure')
def test_kwarg_pass_through_no_kwargs(self): call_func = Mock() data = sentinel.data axis = sentinel.axis aggregator = Aggregator('', call_func) aggregator.aggregate(data, axis) call_func.assert_called_once_with(data, axis=axis)
class LinkTests(TestCase): def setUp(self): self.other_page_cls = Mock() class TestPage(Page): clickme = Link('id=clickme') linktopage = Link('id=linktopage', to=self.other_page_cls) self.webelement = Mock() self.driver = Mock(**{'find_elements.return_value': [self.webelement]}) set_driver(self.driver) self.page = TestPage(assert_is_on_page=False) def test_call(self): ret = self.page.clickme() self.assertIsNone(ret) self.webelement.click.assert_called_once_with() def test_click(self): ret = self.page.clickme.click() self.assertIsNone(ret) self.webelement.click.assert_called_once_with() def test_to_page(self): page = self.page.linktopage() self.other_page_cls.assert_called_once_with(assert_is_on_page=True) self.assertIs(page, self.other_page_cls()) def test_to_page_without_url(self): other_page_cls = Mock(url=None) class TestPage(Page): linktopage = Link('id=linktopage', to=other_page_cls) page = TestPage() page.linktopage() other_page_cls.assert_called_once_with(assert_is_on_page=False)
def test_kwarg_pass_through_no_kwargs(self): lazy_func = Mock() data = sentinel.data axis = sentinel.axis aggregator = Aggregator('', None, lazy_func=lazy_func) aggregator.lazy_aggregate(data, axis) lazy_func.assert_called_once_with(data, axis)
def test_accept(self): rmock = Mock() rmock.return_value = sentinel.msg cacmock = Mock() transport = Mock() self.ch.recv = rmock self.ch._recv_queue.await_n = MagicMock() self.ch._create_accepted_channel = cacmock self.ch.on_channel_open(transport) self.ch._fsm.current_state = self.ch.S_ACTIVE self.ch._consuming = True retch = self.ch.accept() self.assertEquals(self.ch._fsm.current_state, self.ch.S_ACCEPTED) cacmock.assert_called_once_with(transport, [sentinel.msg]) retch._recv_queue.put.assert_called_once_with(sentinel.msg) # we've mocked all the working machinery of accept's return etc, so we must manually exit accept # as if we've ack'd/reject'd self.ch.exit_accept() self.assertEquals(self.ch._fsm.current_state, self.ch.S_ACTIVE) self.assertTrue(self.ch._consuming)
def test_put(self): func = Mock() value = "test_value" a = Attribute("test", Mock()) a.set_put_function(func) a.put(value) func.assert_called_once_with(value)
def test_update(self, include_prerelease, is_started, start_interval, enabled, interval, start_called, stop_called): checker = NewVersionChecker(False) def start_side_effect(i): checker.interval = i start_mock = Mock(side_effect=start_side_effect) stop_mock = Mock() is_started_mock = Mock(return_value=is_started) checker.interval = start_interval checker.start = start_mock checker.stop = stop_mock checker.is_started = is_started_mock checker.update(include_prerelease, enabled, interval) self.assertEqual(checker.interval, interval) self.assertEqual(checker.include_prereleases, include_prerelease) if start_called: start_mock.assert_called_once_with(interval) else: start_mock.assert_not_called() if stop_called: stop_mock.assert_called_once() else: stop_mock.assert_not_called()
def test_callbacks(self): coord = ServiceCoord("Foo", 0) client = self.get_client(coord) self.sleep() client.disconnect() on_connect_handler = Mock() client.add_on_connect_handler(on_connect_handler) on_disconnect_handler = Mock() client.add_on_disconnect_handler(on_disconnect_handler) client.connect() self.sleep() self.assertTrue(client.connected) on_connect_handler.assert_called_once_with(coord) on_connect_handler.reset_mock() self.assertFalse(on_disconnect_handler.called) client.disconnect() self.sleep() self.assertFalse(client.connected) self.assertFalse(on_connect_handler.called) on_disconnect_handler.assert_called_once_with() on_disconnect_handler.reset_mock() client.connect() self.sleep() self.assertTrue(client.connected) on_connect_handler.assert_called_once_with(coord) on_connect_handler.reset_mock() self.assertFalse(on_disconnect_handler.called) self.disconnect_servers() gevent.sleep(0.1) self.assertFalse(client.connected) self.assertFalse(on_connect_handler.called) on_disconnect_handler.assert_called_once_with() on_disconnect_handler.reset_mock()
def testInit(self): # # patch functions called in constructor # # patch os.path.exists() to always return False mockedExists = Mock(return_value=False) self.patch(os.path, "exists", mockedExists) # capture calls to os.makedirs() mockedMakedirs = Mock() self.patch(os, 'makedirs', mockedMakedirs) # capture calls to tempfile.mkstemp() mockedMkstemp = Mock(return_value=(7, "tmpname")) self.patch(tempfile, "mkstemp", mockedMkstemp) # capture calls to os.fdopen() mockedFdopen = Mock() self.patch(os, "fdopen", mockedFdopen) # # call _FileWriter constructor # destfile = os.path.join("dir", "file") remotetransfer.FileWriter(destfile, 64, stat.S_IRUSR) # # validate captured calls # absdir = os.path.dirname(os.path.abspath(os.path.join("dir", "file"))) mockedExists.assert_called_once_with(absdir) mockedMakedirs.assert_called_once_with(absdir) mockedMkstemp.assert_called_once_with(dir=absdir, prefix='buildbot-transfer-') mockedFdopen.assert_called_once_with(7, 'wb')
def test_default_transform_fn(): transformer = Transformer() input_fn = Mock(return_value=PREPROCESSED_DATA) predict_fn = Mock(return_value=PREDICT_RESULT) output_fn = Mock(return_value=PROCESSED_RESULT) transformer._input_fn = input_fn transformer._predict_fn = predict_fn transformer._output_fn = output_fn result = transformer._default_transform_fn(MODEL, INPUT_DATA, CONTENT_TYPE, ACCEPT) input_fn.assert_called_once_with(INPUT_DATA, CONTENT_TYPE) predict_fn.assert_called_once_with(PREPROCESSED_DATA, MODEL) output_fn.assert_called_once_with(PREDICT_RESULT, ACCEPT) assert result == PROCESSED_RESULT
def test_add_listener(self): """Can add a listener to an allowed event""" foo_listener = Mock() bar_listener = Mock() subject = simpleobserver.Subject('foo', 'bar', 'baz') subject('foo', foo_listener) subject('bar', bar_listener) self.assertEqual(foo_listener.call_count, 0) self.assertEqual(bar_listener.call_count, 0) subject.fire('foo', 123, 456) foo_listener.assert_called_once_with(123, 456) self.assertEqual(bar_listener.call_count, 0) subject.fire('bar', 'skidoo', 23) foo_listener.assert_called_once_with(123, 456) bar_listener.assert_called_once_with('skidoo', 23)
def test_display_nd_interact_whenUserChooses1_shouldDo1( self, save_search: Mock, load_interactor: Mock, subprocess_mock: Mock, print_mock: Mock) -> None: command = Command('grep command') results = [command, Command('vim command')] user_input = ['1'] with patch('builtins.input', side_effect=user_input): rr = display_and_interact_results( results, 1, 'save_dir', 'history_file', ['grep'], True) self.assertEqual(rr, None) expected_path = os.path.join("save_dir", command_store_lib.DEFAULT_LAST_SAVE_FILE_NAME) results = results[:1] save_search.assert_called_once_with(expected_path, results) load_interactor.assert_called_once_with('history_file') shell_env = os.getenv('SHELL') call_args = [shell_env, '-i', '-c', command.get_unique_command_id()] subprocess_mock.assert_called_once_with(call_args) print_mock.assert_called_once()
def test_verbose(monkeypatch, mock_hardware, mock_proxy_server): basicConfig = Mock() monkeypatch.setattr(spinner.scripts.proxy_server.logging, "basicConfig", basicConfig) main("-n 3 --bmp 0 0 localhost".split()) assert len(basicConfig.mock_calls) == 0 main("-n 3 --bmp 0 0 localhost -v".split()) basicConfig.assert_called_once_with(level=logging.INFO) basicConfig.reset_mock() main("-n 3 --bmp 0 0 localhost -vv".split()) basicConfig.assert_called_once_with(level=logging.DEBUG) basicConfig.reset_mock() main("-n 3 --bmp 0 0 localhost -vvv".split()) basicConfig.assert_called_once_with(level=logging.DEBUG) basicConfig.reset_mock()
def test_rmtree_success(self): s_file = api.Stat() s_file.st_mode = stat.S_IFREG d = DirEntry(None, 'dirpath', 'file1', s_file) mock_scandir = MagicMock() mock_scandir.return_value = [d] mock_unlink = Mock() mock_rmdir = Mock() mock_islink = Mock(return_value=False) with nested(patch("gluster.gfapi.Volume.scandir", mock_scandir), patch("gluster.gfapi.Volume.islink", mock_islink), patch("gluster.gfapi.Volume.unlink", mock_unlink), patch("gluster.gfapi.Volume.rmdir", mock_rmdir)): self.vol.rmtree("dirpath") mock_islink.assert_called_once_with("dirpath") mock_unlink.assert_called_once_with("dirpath/file1") mock_rmdir.assert_called_once_with("dirpath")
def test_get_text_stats(self): mock_cleanup = Mock(return_value=['foo', 'bar']) mock_normalize = Mock(return_value=(['foo', 'ba'], False)) mock_get_ratio = Mock(return_value=0.2) with Replacer() as r: r.replace('nausea.bl.get_nausea_ratio', mock_get_ratio) r.replace('nausea.bl.normalize_words', mock_normalize) r.replace('nausea.bl.cleanup_words', mock_cleanup) get_text_stats([]) self.assertEqual(mock_get_ratio.call_count, 0) self.assertEqual(mock_normalize.call_count, 0) self.assertEqual(mock_cleanup.call_count, 0) result = get_text_stats((1, 'Foo is Bar')) mock_cleanup.assert_called_once_with('Foo is Bar') mock_normalize.assert_called_once_with(['foo', 'bar']) mock_get_ratio.assert_called_once_with(['foo', 'ba']) self.assertEqual(result, (1, 0.2, False))
def test_rmtree_ignore_unlink_rmdir_exception(self): s_file = api.Stat() s_file.st_mode = stat.S_IFREG d = DirEntry(None, 'dirpath', 'file1', s_file) mock_scandir = MagicMock() mock_scandir.return_value = [d] mock_unlink = Mock(side_effect=OSError) mock_rmdir = Mock(side_effect=OSError) mock_islink = Mock(return_value=False) with patch("gluster.gfapi.Volume.scandir", mock_scandir): with patch("gluster.gfapi.Volume.islink", mock_islink): with patch("gluster.gfapi.Volume.unlink", mock_unlink): with patch("gluster.gfapi.Volume.rmdir", mock_rmdir): self.vol.rmtree("dirpath", True) mock_islink.assert_called_once_with("dirpath") mock_unlink.assert_called_once_with("dirpath/file1") mock_rmdir.assert_called_once_with("dirpath")
def test_resolve_specfile_async(self, mocked_glob: Mock, mocked_cmd_assert_async: Mock, mocked_open: Mock): self.rpm_dg.distgit_dir = "/path/to/distgit" mocked_file = mocked_open.return_value.__aenter__.return_value mocked_file.__aiter__.return_value = iter( ["hello", "%global commit abcdef012345", "world!"]) actual = asyncio.get_event_loop().run_until_complete( self.rpm_dg.resolve_specfile_async()) expected = (Path("/path/to/distgit/foo.spec"), ["foo", "1.2.3", "1"], "abcdef012345") self.assertEqual(actual, expected) mocked_open.assert_called_once_with(Path("/path/to/distgit/foo.spec"), "r") mocked_glob.assert_called_once_with(self.rpm_dg.distgit_dir + "/*.spec") mocked_cmd_assert_async.assert_called_once_with([ "rpmspec", "-q", "--qf", "%{name}-%{version}-%{release}", "--srpm", "--undefine", "dist", "--", Path("/path/to/distgit/foo.spec") ], strip=True)
def testBuildGerritCommand(self): gsp = yield self.setupGerritStatusPushSimple() spawnSkipFirstArg = Mock() gsp.spawnProcess = lambda _, *a, **k: spawnSkipFirstArg(*a, **k) yield gsp.sendCodeReview("project", "revision", { "message": "bla", "labels": { 'Verified': 1 } }) spawnSkipFirstArg.assert_called_once_with( 'ssh', ['ssh', 'user@serv', '-p', '29418', 'gerrit', 'version']) gsp.processVersion("2.6", lambda: None) spawnSkipFirstArg = Mock() yield gsp.sendCodeReview("project", "revision", { "message": "bla", "labels": { 'Verified': 1 } }) spawnSkipFirstArg.assert_called_once_with('ssh', [ 'ssh', 'user@serv', '-p', '29418', 'gerrit', 'review', '--project project', "--message 'bla'", '--label Verified=1', 'revision' ]) # <=2.5 uses other syntax gsp.processVersion("2.4", lambda: None) spawnSkipFirstArg = Mock() yield gsp.sendCodeReview("project", "revision", { "message": "bla", "labels": { 'Verified': 1 } }) spawnSkipFirstArg.assert_called_once_with('ssh', [ 'ssh', 'user@serv', '-p', '29418', 'gerrit', 'review', '--project project', "--message 'bla'", '--verified 1', 'revision' ])
def test_rebase_and_build_rpm(self, cmd_assert_async: Mock, open: Mock): runtime = MagicMock(dry_run=False, working_dir=Path("/path/to/working")) pipeline = RebuildPipeline(runtime, group="openshift-4.9", assembly="art0001", type=RebuildType.RPM, dg_key="foo") release = "202107160000.p?" open.return_value.__enter__.return_value = StringIO( "build_rpm|nvrs=foo-v1.2.3-202107160000.p0.assembly.art0001.el8,foo-v1.2.3-202107160000.p0.assembly.art0001.el7|" ) nvrs = get_event_loop().run_until_complete( pipeline._rebase_and_build_rpm(release)) self.assertEqual(nvrs, [ "foo-v1.2.3-202107160000.p0.assembly.art0001.el8", "foo-v1.2.3-202107160000.p0.assembly.art0001.el7" ]) excepted_doozer_cmd = [ "doozer", "--group", "openshift-4.9", "--assembly", "art0001", "-r", "foo", "rpms:rebase-and-build", "--version", "4.9", "--release", release ] cmd_assert_async.assert_called_once_with(excepted_doozer_cmd, env=ANY) open.assert_called_once_with( runtime.working_dir / "doozer-working/record.log", "r") runtime.dry_run = True cmd_assert_async.reset_mock() nvrs = get_event_loop().run_until_complete( pipeline._rebase_and_build_rpm(release)) self.assertEqual(nvrs, []) excepted_doozer_cmd = [ "doozer", "--group", "openshift-4.9", "--assembly", "art0001", "-r", "foo", "rpms:rebase-and-build", "--version", "4.9", "--release", release, "--dry-run" ] cmd_assert_async.assert_called_once_with(excepted_doozer_cmd, env=ANY)
def test_get_cart_from_request( monkeypatch, customer_user, cart_request_factory): queryset = Cart.objects.all() token = uuid4() request = cart_request_factory(user=customer_user, token=token) user_cart = Cart(user=customer_user) mock_get_for_user = Mock(return_value=user_cart) monkeypatch.setattr('saleor.cart.utils.get_user_cart', mock_get_for_user) returned_cart = utils.get_cart_from_request(request, queryset) mock_get_for_user.assert_called_once_with(customer_user, queryset) assert returned_cart == user_cart assert list(returned_cart.discounts) == list(request.discounts) mock_get_for_user = Mock(return_value=None) monkeypatch.setattr('saleor.cart.utils.get_user_cart', mock_get_for_user) returned_cart = utils.get_cart_from_request(request, queryset) mock_get_for_user.assert_called_once_with(customer_user, queryset) assert not Cart.objects.filter(token=returned_cart.token).exists() anonymous_cart = Cart() mock_get_for_anonymous = Mock(return_value=anonymous_cart) monkeypatch.setattr( 'saleor.cart.utils.get_anonymous_cart_from_token', mock_get_for_anonymous) request = cart_request_factory(user=None, token=token) returned_cart = utils.get_cart_from_request(request, queryset) mock_get_for_user.assert_called_once_with(customer_user, queryset) assert returned_cart == anonymous_cart mock_get_for_anonymous = Mock(return_value=None) monkeypatch.setattr( 'saleor.cart.utils.get_anonymous_cart_from_token', mock_get_for_anonymous) returned_cart = utils.get_cart_from_request(request, queryset) assert not Cart.objects.filter(token=returned_cart.token).exists()
class TestUniqueField(unittest.TestCase): def setUp(self): self.dao_find = Mock() self.dao_get = Mock() self.validator = UsernameChanged('username', self.dao_find, self.dao_get) def test_given_username_has_not_changed_then_validation_passes(self): model = Mock(id=sentinel.id, username=sentinel.username) self.dao_get.return_value = model self.validator.validate(model) self.dao_get.assert_called_once_with(sentinel.id) def test_given_username_has_changed_but_is_unique_then_validation_passes( self): old_model = Mock(id=sentinel.id, username=sentinel.old_username) new_model = Mock(id=sentinel.id, username=sentinel.new_username) self.dao_get.return_value = old_model self.dao_find.return_value = None self.validator.validate(new_model) self.dao_get.assert_called_once_with(sentinel.id) self.dao_find.assert_called_once_with(sentinel.new_username) def test_given_username_has_changed_but_is_(self): old_model = Mock(id=sentinel.id, username=sentinel.old_username) new_model = Mock(id=sentinel.id, username=sentinel.new_username) existing_model = Mock(id=sentinel.existing_id, username=sentinel.new_username) self.dao_get.return_value = old_model self.dao_find.return_value = existing_model self.assertRaises(ResourceError, self.validator.validate, new_model)
def emit_changed_test(self): """Test emitting changed properties.""" test2 = self.Test2() callback = Mock() test2.PropertiesChanged.connect(callback) self.assertEqual(test2.A, 1) test2.DoNothing() self.assertEqual(test2.A, 1) callback.assert_not_called() test2.SetA(10) self.assertEqual(test2.A, 10) callback.assert_called_once_with("I2", {"A": 10}, []) callback.reset_mock() test2.SetA(1000) self.assertEqual(test2.A, 1000) callback.assert_called_once_with("I2", {"A": 1000}, []) callback.reset_mock() test2.SetADirectly(20) self.assertEqual(test2.A, 20) callback.assert_not_called() callback.reset_mock() test2.flush_changes() callback.assert_not_called() test2.SetANoSignal(200) self.assertEqual(test2.A, 200) callback.assert_not_called() test2.flush_changes() callback.assert_called_once_with("I2", {"A": 200}, [])
class TestQueueMemberCTISubscriber(unittest.TestCase): def setUp(self): self.send_cti_event = Mock() self.queue_member_cti_subscriber = QueueMemberCTISubscriber() self.queue_member_cti_subscriber.send_cti_event = self.send_cti_event def test_on_queue_member_added(self, message_formatter): queue_member = Mock() queue_member.id = 'someid' message_formatter.add_queue_members.return_value = 'add_msg' self.queue_member_cti_subscriber.on_queue_member_added(queue_member) message_formatter.add_queue_members.assert_called_once_with( [queue_member.id]) self.send_cti_event.assert_called_once_with('add_msg') def test_on_queue_member_updated(self, message_formatter): queue_member = Mock() message_formatter.update_queue_member_config.return_value = 'update_msg' self.queue_member_cti_subscriber.on_queue_member_updated(queue_member) message_formatter.update_queue_member_config.assert_called_once_with( queue_member) self.send_cti_event.assert_called_once_with('update_msg') def test_on_queue_member_removed(self, message_formatter): queue_member = Mock() queue_member.id = 'someid' message_formatter.delete_queue_members.return_value = 'delete_msg' self.queue_member_cti_subscriber.on_queue_member_removed(queue_member) message_formatter.delete_queue_members.assert_called_once_with( [queue_member.id]) self.send_cti_event.assert_called_once_with('delete_msg')
def test_can_specify_state_handlers_as_dict(self): on_entry = Mock() in_state = Mock() on_exit = Mock() sm = StateMachine({ 'initial': 'foo', 'states': { 'foo': { 'on_entry': on_entry, 'in_state': in_state, 'on_exit': on_exit }, }, 'transitions': { ('foo', 'bar'): lambda: True } }) # First cycle enters and executes initial state, but forces delta T to zero sm.process(1.0) on_entry.assert_called_once_with(0) in_state.assert_called_once_with(0) on_entry.reset_mock() in_state.reset_mock() # Second cycle transitions due to lambda: True above sm.process(2.0) on_exit.assert_called_once_with(2.0) on_exit.reset_mock() # Third cycle only does an in_state in bar, shouldn't affect foo sm.process(3.0) on_entry.assert_not_called() in_state.assert_not_called() on_exit.assert_not_called()
def template_test(self): """Test the template with support for properties.""" test3implementation = self.Test3Implementation() test3 = self.Test3(test3implementation) callback = Mock() test3.PropertiesChanged.connect(callback) self.assertEqual(test3.A, 1) self.assertEqual(test3.B, 2) test3.SetA(10) self.assertEqual(test3.A, 10) callback.assert_called_once_with("I3", {"A": 10}, []) callback.reset_mock() test3.B = 20 self.assertEqual(test3.B, 20) callback.assert_called_once_with("I3", {"B": 20}, []) callback.reset_mock() test3implementation.do_external_changes(100, 200) self.assertEqual(test3.A, 100) self.assertEqual(test3.B, 200) callback.assert_not_called() test3implementation.module_properties_changed.emit() callback.assert_called_once_with("I3", {"A": 100, "B": 200}, []) callback.reset_mock() test3implementation.do_secret_changes(1000, 2000) self.assertEqual(test3.A, 1000) self.assertEqual(test3.B, 2000) callback.assert_not_called() test3implementation.module_properties_changed.emit() callback.assert_not_called()
def test_can_specify_state_handlers_as_dict(self): on_entry = Mock() in_state = Mock() on_exit = Mock() sm = StateMachine( { "initial": "foo", "states": { "foo": { "on_entry": on_entry, "in_state": in_state, "on_exit": on_exit, }, }, "transitions": {("foo", "bar"): lambda: True}, } ) # First cycle enters and executes initial state, but forces delta T to zero sm.process(1.0) on_entry.assert_called_once_with(0) in_state.assert_called_once_with(0) on_entry.reset_mock() in_state.reset_mock() # Second cycle transitions due to lambda: True above sm.process(2.0) on_exit.assert_called_once_with(2.0) on_exit.reset_mock() # Third cycle only does an in_state in bar, shouldn't affect foo sm.process(3.0) on_entry.assert_not_called() in_state.assert_not_called() on_exit.assert_not_called()
def test_save_stripe_token(self, mock_save_customer: mock.Mock, mock_save_card: mock.Mock, mock_retrieve_customer: mock.Mock, mock_create_customer: mock.Mock, mock_list_sources: mock.Mock, mock_create_source: mock.Mock, mock_billing_logger_info: mock.Mock) -> None: self.assertFalse(Customer.objects.filter(realm=self.realm)) number_of_cards = save_stripe_token(self.user, self.token) self.assertEqual(number_of_cards, 1) description = "{} ({})".format(self.realm.name, self.realm.string_id) mock_create_customer.assert_called_once_with(description=description, source=self.token, metadata={'string_id': self.realm.string_id}) mock_list_sources.assert_called_once() mock_save_card.assert_called_once() mock_billing_logger_info.assert_called() customer_object = Customer.objects.get(realm=self.realm) # Add another card number_of_cards = save_stripe_token(self.user, self.token) # Note: customer.sources.list is mocked to return 2 cards all the time. self.assertEqual(number_of_cards, 2) mock_retrieve_customer.assert_called_once_with(customer_object.stripe_customer_id) create_source_metadata = {'added_user_id': self.user.id, 'added_user_email': self.user.email} mock_create_source.assert_called_once_with(metadata=create_source_metadata, source='token') mock_save_customer.assert_called_once() mock_billing_logger_info.assert_called()
class TestInstallerHelp(TestCase): def setUp(self): self.button_mock = Mock() self.patcher = patch.dict(jinja_env.globals, download_firefox=self.button_mock) self.patcher.start() self.view_name = 'firefox.installer-help' with self.activate('en-US'): self.url = reverse(self.view_name) def tearDown(self): self.patcher.stop() def test_buttons_use_lang(self): """ The buttons should use the lang from the query parameter. """ self.client.get(self.url, { 'installer_lang': 'fr' }) self.button_mock.assert_has_calls([ call(alt_copy=Markup('Download Now'), button_class='mzp-t-secondary mzp-t-md', force_direct=True, force_full_installer=True, locale='fr'), call('beta', alt_copy=Markup('Download Now'), button_class='mzp-t-secondary mzp-t-md', force_direct=True, force_full_installer=True, locale='fr'), call('alpha', alt_copy=Markup('Download Now'), button_class='mzp-t-secondary mzp-t-md', force_direct=True, force_full_installer=True, locale='fr', platform='desktop'), call('nightly', alt_copy=Markup('Download Now'), button_class='mzp-t-secondary mzp-t-md', force_direct=True, force_full_installer=True, locale='fr', platform='desktop'), ]) def test_buttons_ignore_non_lang(self): """ The buttons should ignore an invalid lang. """ self.client.get(self.url, { 'installer_lang': 'not-a-locale' }) self.button_mock.assert_has_calls([ call(alt_copy=Markup('Download Now'), button_class='mzp-t-secondary mzp-t-md', force_direct=True, force_full_installer=True, locale=None), call('beta', alt_copy=Markup('Download Now'), button_class='mzp-t-secondary mzp-t-md', force_direct=True, force_full_installer=True, locale=None), call('alpha', alt_copy=Markup('Download Now'), button_class='mzp-t-secondary mzp-t-md', force_direct=True, force_full_installer=True, locale=None, platform='desktop'), call('nightly', alt_copy=Markup('Download Now'), button_class='mzp-t-secondary mzp-t-md', force_direct=True, force_full_installer=True, locale=None, platform='desktop'), ]) def test_invalid_channel_specified(self): """ All buttons should show when channel is invalid. """ self.client.get(self.url, { 'channel': 'dude', }) self.button_mock.assert_has_calls([ call(alt_copy=Markup('Download Now'), button_class='mzp-t-secondary mzp-t-md', force_direct=True, force_full_installer=True, locale=None), call('beta', alt_copy=Markup('Download Now'), button_class='mzp-t-secondary mzp-t-md', force_direct=True, force_full_installer=True, locale=None), call('alpha', alt_copy=Markup('Download Now'), button_class='mzp-t-secondary mzp-t-md', force_direct=True, force_full_installer=True, locale=None, platform='desktop'), call('nightly', alt_copy=Markup('Download Now'), button_class='mzp-t-secondary mzp-t-md', force_direct=True, force_full_installer=True, locale=None, platform='desktop'), ]) def test_one_button_when_channel_specified(self): """ There should be only one button when the channel is given. """ self.client.get(self.url, { 'channel': 'beta', }) self.button_mock.assert_called_once_with('beta', alt_copy=Markup('Download Now'), button_class='mzp-t-md', force_direct=True, force_full_installer=True, locale=None)
class TestTimer(TestCase): TICK_START = Scheduler.FIRST_TICK_ID TICK_PER_SEC = GAME_SPEED.TICKS_PER_SECOND TIME_START = 1000 TIME_TICK = 1.0 / TICK_PER_SEC def setUp(self): self.callback = Mock() self.test = Mock() # Mock fife self.fife = Mock() self.pump = MagicMock() self.fife.pump = self.pump self.fifePatcher = patch('horizons.globals.fife', self.fife) self.fifePatcher.start() # Mock system time self.timePatcher = patch('time.time') self.clock = self.timePatcher.start() self.clock.return_value = self.TIME_START # Create timer self.timer = Timer(freeze_protection=False) self.timer.ticks_per_second = self.TICK_PER_SEC self.timer.add_call(self.callback) def tearDown(self): self.fifePatcher.stop() self.timePatcher.stop() def test_activate_register_end_unregister_from_pump(self): self.timer.activate() self.fife.pump.append.assert_called_once_with(self.timer.check_tick) self.fife.pump.__contains__.return_value = True self.timer.end() self.fife.pump.remove.assert_called_once_with(self.timer.check_tick) def test_first_pump_then_one_tick(self): self.timer.check_tick() self.callback.assert_called_once_with(TestTimer.TICK_START) def test_two_pump_same_time_only_one_tick(self): self.timer.check_tick() self.timer.check_tick() self.callback.assert_called_once_with(TestTimer.TICK_START) def test_two_pump_with_delay_then_two_ticks(self): self.timer.check_tick() self.callback.reset_mock() self.clock.return_value = self.TIME_START + self.TIME_TICK self.timer.check_tick() self.callback.assert_called_once_with(TestTimer.TICK_START + 1) def test_two_pump_close_in_time_then_only_one_tick(self): self.timer.check_tick() self.callback.reset_mock() self.clock.return_value = self.TIME_START + (self.TIME_TICK / 2) self.timer.check_tick() self.assertFalse(self.callback.called) def test_fast_pumping_only_tick_alternately(self): # tick 1 self.timer.check_tick() self.clock.return_value = self.TIME_START + (0.5 * self.TIME_TICK) self.timer.check_tick() # tick 2 self.callback.reset_mock() self.clock.return_value = self.TIME_START + (1.0 * self.TIME_TICK) self.timer.check_tick() self.callback.assert_called_once_with(TestTimer.TICK_START + 1) self.callback.reset_mock() self.clock.return_value = self.TIME_START + (1.5 * self.TIME_TICK) self.timer.check_tick() self.assertFalse(self.callback.called) def test_slow_pump_multiple_ticks(self): self.timer.check_tick() self.clock.return_value = self.TIME_START + (3.0 * self.TIME_TICK) self.callback.reset_mock() self.timer.check_tick() expected = [((self.TICK_START + 1, ), ), ((self.TICK_START + 2, ), ), ((self.TICK_START + 3, ), )] self.assertEquals(expected, self.callback.call_args_list) def test_paused_pump_then_no_ticks(self): self.timer.check_tick() self.callback.reset_mock() self.timer.ticks_per_second = 0 self.clock.return_value = self.TIME_START + self.TIME_TICK self.timer.check_tick() self.assertFalse(self.callback.called) def test_pause_pump_unpack_pump(self): self.timer.check_tick() self.timer.ticks_per_second = 0 self.clock.return_value = self.TIME_START + (1.0 * self.TIME_TICK) self.timer.check_tick() self.timer.ticks_per_second = self.TICK_PER_SEC self.clock.return_value = self.TIME_START + (1.0 * self.TIME_TICK) self.callback.reset_mock() self.timer.check_tick() self.callback.assert_called_once_with(TestTimer.TICK_START + 1) def test_pause_on_callback(self): def set_paused(tick_id): self.timer.ticks_per_second = 0 self.callback.side_effect = set_paused self.timer.check_tick() self.clock.return_value = self.TIME_START + (1.0 * self.TIME_TICK) self.callback.side_effect = None self.callback.reset_mock() self.timer.check_tick() self.assertFalse(self.callback.called) def test_freeze_protection(self): self.timer = Timer(freeze_protection=True) self.timer.ticks_per_second = self.TICK_PER_SEC self.timer.add_call(self.callback) self.timer.check_tick() self.callback.reset_mock() self.clock.return_value = self.TIME_START + ( 1.01 * self.TIME_TICK) + Timer.ACCEPTABLE_TICK_DELAY self.timer.check_tick() self.assertTrue(self.callback.called ) # some number of ticks depending on tick delay self.callback.reset_mock() # will tick once after defer timeout self.clock.return_value = self.TIME_START + ( 2.02 * self.TIME_TICK) + Timer.DEFER_TICK_ON_DELAY_BY self.timer.check_tick() self.callback.assert_called_once_with(TestTimer.TICK_START + 2) def test_pump_test_func_pass(self): self.test.return_value = Timer.TEST_PASS self.timer.add_test(self.test) self.timer.check_tick() self.assertTrue(self.callback.called) def test_pump_test_func_skip(self): self.test.return_value = Timer.TEST_SKIP self.timer.add_test(self.test) self.timer.check_tick() self.assertFalse(self.callback.called)
class SecurityInterfaceTestCase(unittest.TestCase): """Test DBus interface for the Security module.""" def setUp(self): """Set up the security module.""" # Set up the security module. self.security_module = SecurityService() self.security_interface = SecurityInterface(self.security_module) # Connect to the properties changed signal. self.callback = Mock() self.security_interface.PropertiesChanged.connect(self.callback) def kickstart_properties_test(self): """Test kickstart properties.""" self.assertEqual(self.security_interface.KickstartCommands, ["auth", "authconfig", "authselect", "selinux", "realm"]) self.assertEqual(self.security_interface.KickstartSections, []) self.assertEqual(self.security_interface.KickstartAddons, []) self.callback.assert_not_called() def selinux_property_test(self): """Test the selinux property.""" self.security_interface.SetSELinux(SELINUX_ENFORCING) self.assertEqual(self.security_interface.SELinux, SELINUX_ENFORCING) self.callback.assert_called_once_with(SECURITY.interface_name, {'SELinux': SELINUX_ENFORCING}, []) def authselect_property_test(self): """Test the authselect property.""" self.security_interface.SetAuthselect(["sssd", "with-mkhomedir"]) self.assertEqual(self.security_interface.Authselect, ["sssd", "with-mkhomedir"]) self.callback.assert_called_once_with(SECURITY.interface_name, {'Authselect': ["sssd", "with-mkhomedir"]}, []) def authconfig_property_test(self): """Test the authconfig property.""" self.security_interface.SetAuthconfig(["--passalgo=sha512", "--useshadow"]) self.assertEqual(self.security_interface.Authconfig, ["--passalgo=sha512", "--useshadow"]) self.callback.assert_called_once_with(SECURITY.interface_name, {'Authconfig': ["--passalgo=sha512", "--useshadow"]}, []) def realm_property_test(self): """Test the realm property.""" realm_in = { "name": "domain.example.com", "discover-options": ["--client-software=sssd"], "join-options": ["--one-time-password=password"], "discovered": True } realm_out = { "name": get_variant(Str, "domain.example.com"), "discover-options": get_variant(List[Str], ["--client-software=sssd"]), "join-options": get_variant(List[Str], ["--one-time-password=password"]), "discovered": get_variant(Bool, True), "required-packages": get_variant(List[Str], []) } self.security_interface.SetRealm(realm_in) self.assertEqual(realm_out, self.security_interface.Realm) self.callback.assert_called_once_with(SECURITY.interface_name, {'Realm': realm_out}, []) def _test_kickstart(self, ks_in, ks_out): check_kickstart_interface(self, self.security_interface, ks_in, ks_out) def no_kickstart_test(self): """Test with no kickstart.""" ks_in = None ks_out = "" self._test_kickstart(ks_in, ks_out) def kickstart_empty_test(self): """Test with empty string.""" ks_in = "" ks_out = "" self._test_kickstart(ks_in, ks_out) def selinux_kickstart_test(self): """Test the selinux command.""" ks_in = """ selinux --permissive """ ks_out = """ # SELinux configuration selinux --permissive """ self._test_kickstart(ks_in, ks_out) def auth_kickstart_test(self): """Test the auth command.""" ks_in = """ auth --passalgo=sha512 --useshadow """ ks_out = """ # System authorization information auth --passalgo=sha512 --useshadow """ self._test_kickstart(ks_in, ks_out) def authconfig_kickstart_test(self): """Test the authconfig command.""" ks_in = """ authconfig --passalgo=sha512 --useshadow """ ks_out = """ # System authorization information auth --passalgo=sha512 --useshadow """ self._test_kickstart(ks_in, ks_out) def authselect_kickstart_test(self): """Test the authselect command.""" ks_in = """ authselect select sssd with-mkhomedir """ ks_out = """ # System authorization information authselect select sssd with-mkhomedir """ self._test_kickstart(ks_in, ks_out) def realm_kickstart_test(self): """Test the realm command.""" ks_in = """ realm join --one-time-password=password --client-software=sssd domain.example.com """ ks_out = """ # Realm or domain membership realm join --one-time-password=password --client-software=sssd domain.example.com """ self._test_kickstart(ks_in, ks_out) @patch_dbus_publish_object def realm_discover_default_test(self, publisher): """Test module in default state with realm discover task.""" realm_discover_task_path = self.security_interface.DiscoverRealmWithTask() publisher.assert_called() # realm discover obj = check_task_creation(self, realm_discover_task_path, publisher, RealmDiscoverTask) self.assertEqual(obj.implementation._realm_data.name, "") self.assertEqual(obj.implementation._realm_data.discover_options, []) @patch_dbus_publish_object def realm_discover_configured_test(self, publisher): """Test module in configured state with realm discover task.""" realm_in = { "name": "domain.example.com", "discover-options": ["--client-software=sssd"], } self.security_interface.SetRealm(realm_in) realm_discover_task_path = self.security_interface.DiscoverRealmWithTask() publisher.assert_called() # realm discover obj = check_task_creation(self, realm_discover_task_path, publisher, RealmDiscoverTask) self.assertEqual(obj.implementation._realm_data.name, "domain.example.com") self.assertEqual(obj.implementation._realm_data.discover_options, ["--client-software=sssd"]) @patch_dbus_publish_object def install_with_tasks_default_test(self, publisher): """Test install tasks - module in default state.""" tasks = self.security_interface.InstallWithTasks() selinux_task_path = tasks[0] publisher.assert_called() # SELinux configuration object_path = publisher.call_args_list[0][0][0] obj = publisher.call_args_list[0][0][1] self.assertEqual(selinux_task_path, object_path) self.assertIsInstance(obj, TaskInterface) self.assertIsInstance(obj.implementation, ConfigureSELinuxTask) self.assertEqual(obj.implementation._selinux_mode, SELinuxMode.DEFAULT) @patch_dbus_publish_object def realm_join_default_test(self, publisher): """Test module in default state with realm join task.""" realm_join_task_path = self.security_interface.JoinRealmWithTask() publisher.assert_called() # realm join obj = check_task_creation(self, realm_join_task_path, publisher, RealmJoinTask) self.assertEqual(obj.implementation._realm_data.discovered, False) self.assertEqual(obj.implementation._realm_data.name, "") self.assertEqual(obj.implementation._realm_data.join_options, []) @patch_dbus_publish_object def install_with_tasks_configured_test(self, publisher): """Test install tasks - module in configured state.""" realm_in = { "name": "domain.example.com", "discover-options": ["--client-software=sssd"], "join-options": ["--one-time-password=password"], "discovered": True } self.security_interface.SetRealm(realm_in) self.security_interface.SetSELinux(SELINUX_PERMISSIVE) tasks = self.security_interface.InstallWithTasks() selinux_task_path = tasks[0] publisher.assert_called() # SELinux configuration object_path = publisher.call_args_list[0][0][0] obj = publisher.call_args_list[0][0][1] self.assertEqual(selinux_task_path, object_path) self.assertIsInstance(obj, TaskInterface) self.assertIsInstance(obj.implementation, ConfigureSELinuxTask) self.assertEqual(obj.implementation._selinux_mode, SELinuxMode.PERMISSIVE) @patch_dbus_publish_object def realm_join_configured_test(self, publisher): """Test module in configured state with realm join task.""" realm_in = { "name": "domain.example.com", "discover-options": ["--client-software=sssd"], "join-options": ["--one-time-password=password"], "discovered": True } self.security_interface.SetRealm(realm_in) realm_join_task_path = self.security_interface.JoinRealmWithTask() publisher.assert_called() # realm join obj = check_task_creation(self, realm_join_task_path, publisher, RealmJoinTask) self.assertEqual(obj.implementation._realm_data.discovered, True) self.assertEqual(obj.implementation._realm_data.name, "domain.example.com") self.assertEqual(obj.implementation._realm_data.join_options, ["--one-time-password=password"]) @patch_dbus_publish_object def realm_data_propagation_test(self, publisher): """Test that realm data changes propagate to realm join task.""" # We connect to the realm_changed signal and update the realm data holder # in the realm join task when the signal is triggered. realm_in_1 = { "name": "domain.example.com", "discover-options": ["--client-software=sssd"], "discovered": False } self.security_interface.SetRealm(realm_in_1) realm_join_task_path = self.security_interface.JoinRealmWithTask() publisher.assert_called() # realm join - after task creation obj = check_task_creation(self, realm_join_task_path, publisher, RealmJoinTask) self.assertEqual(obj.implementation._realm_data.discovered, False) self.assertEqual(obj.implementation._realm_data.name, "domain.example.com") self.assertEqual(obj.implementation._realm_data.join_options, []) # change realm data and check the changes propagate to the realm join task realm_in_2 = { "name": "domain.example.com", "discover-options": ["--client-software=sssd"], "join-options": ["--one-time-password=password"], "discovered": True } self.security_interface.SetRealm(realm_in_2) # realm join - after realm data update self.assertEqual(obj.implementation._realm_data.discovered, True) self.assertEqual(obj.implementation._realm_data.name, "domain.example.com") self.assertEqual(obj.implementation._realm_data.join_options, ["--one-time-password=password"]) def collect_requirements_default_test(self): """Test requrements are empty by default.""" reqs = self.security_interface.CollectRequirements() self.assertListEqual(reqs, []) def realmd_requirements_test(self): """Test that package requirements in realm data propagate correctly.""" realm_in = { "name": "domain.example.com", "discover-options": ["--client-software=sssd"], "join-options": ["--one-time-password=password"], "discovered": True, "required-packages" : ["realmd", "foo", "bar"] } self.security_interface.SetRealm(realm_in) # check that the teamd package is requested self.assertEqual(self.security_interface.CollectRequirements(), [ { "type": get_variant(Str, "package"), "name": get_variant(Str, "realmd"), "reason": get_variant(Str, "Needed to join a realm.") }, { "type": get_variant(Str, "package"), "name": get_variant(Str, "foo"), "reason": get_variant(Str, "Needed to join a realm.") }, { "type": get_variant(Str, "package"), "name": get_variant(Str, "bar"), "reason": get_variant(Str, "Needed to join a realm.") } ])
def test_longer_extraction(self): text = """The ancient settlement of Brighthelmstone dates from before Domesday Book (1086), but it emerged as a health resort featuring sea bathing during the 18th century and became a destination for day-trippers from London after the arrival of the railway in 1841. Brighton experienced rapid population growth, reaching a peak of over 160,000 by 1961. Modern Brighton forms part of the Brighton/Worthing/Littlehampton conurbation stretching along the coast, with a population of around 480,000 inhabitants.""" tokens = [ 'The', 'ancient', 'settlement', 'of', 'Brighthelmstone', 'dates', 'from', 'before', 'Domesday', 'Book', '(', '1086', ')', ',', 'but', 'it', 'emerged', 'as', 'a', 'health', 'resort', 'featuring', 'sea', 'bathing', 'during', 'the', '18th', 'century', 'and', 'became', 'a', 'destination', 'for', 'day-trippers', 'from', 'London', 'after', 'the', 'arrival', 'of', 'the', 'railway', 'in', '1841.', 'Brighton', 'experienced', 'rapid', 'population', 'growth', ',', 'reaching', 'a', 'peak', 'of', 'over', '160,000', 'by', '1961', '.', 'Modern', 'Brighton', 'forms', 'part', 'of', 'the', 'Brighton/Worthing/Littlehampton', 'conurbation', 'stretching', 'along', 'the', 'coast', ',', 'with', 'a', 'population', 'of', 'around', '480,000', 'inhabitants', '.' ] tags = [('The', 'DT'), ('ancient', 'JJ'), ('settlement', 'NN'), ('of', 'IN'), ('Brighthelmstone', 'NNP'), ('dates', 'VBZ'), ('from', 'IN'), ('before', 'IN'), ('Domesday', 'NNP'), ('Book', 'NNP'), ('(', 'NNP'), ('1086', 'CD'), (')', 'CD'), (',', ','), ('but', 'CC'), ('it', 'PRP'), ('emerged', 'VBD'), ('as', 'IN'), ('a', 'DT'), ('health', 'NN'), ('resort', 'NN'), ('featuring', 'VBG'), ('sea', 'NN'), ('bathing', 'VBG'), ('during', 'IN'), ('the', 'DT'), ('18th', 'JJ'), ('century', 'NN'), ('and', 'CC'), ('became', 'VBD'), ('a', 'DT'), ('destination', 'NN'), ('for', 'IN'), ('day-trippers', 'NNS'), ('from', 'IN'), ('London', 'NNP'), ('after', 'IN'), ('the', 'DT'), ('arrival', 'NN'), ('of', 'IN'), ('the', 'DT'), ('railway', 'NN'), ('in', 'IN'), ('1841.', 'CD'), ('Brighton', 'NNP'), ('experienced', 'VBD'), ('rapid', 'JJ'), ('population', 'NN'), ('growth', 'NN'), (',', ','), ('reaching', 'VBG'), ('a', 'DT'), ('peak', 'NN'), ('of', 'IN'), ('over', 'IN'), ('160,000', 'CD'), ('by', 'IN'), ('1961', 'CD'), ('.', '.'), ('Modern', 'NNP'), ('Brighton', 'NNP'), ('forms', 'NNS'), ('part', 'NN'), ('of', 'IN'), ('the', 'DT'), ('Brighton/Worthing/Littlehampton', 'NNP'), ('conurbation', 'NN'), ('stretching', 'VBG'), ('along', 'IN'), ('the', 'DT'), ('coast', 'NN'), (',', ','), ('with', 'IN'), ('a', 'DT'), ('population', 'NN'), ('of', 'IN'), ('around', 'IN'), ('480,000', 'CD'), ('inhabitants', 'NNS'), ('.', '.')] html = """<html><head><title="Brighton"></head><body>""" + text + """</body></html>""" mocked_tokenizer = Mock(return_value=tokens) mocked_tagger = Mock(return_value=tags) result = AdjPhraseExtractor.extract(html, tagger=mocked_tagger, tokenizer=mocked_tokenizer) mocked_tokenizer.assert_called_once_with(text) mocked_tagger.assert_called_once_with(mocked_tokenizer.return_value) self.assertEqual(result, [['ancient', 'settlement'], ['18th', 'century'], ['rapid', 'population', 'growth']])
def test_memoize(): fn = Mock(__name__='fn') memoized = memoize(fn) memoized() memoized() fn.assert_called_once_with()
def test_sudo_support(return_value, command, called, result): fn = Mock(return_value=return_value, __name__='') assert sudo_support(fn)(Command(command), None) == result fn.assert_called_once_with(Command(called), None)
class LocalizationInterfaceTestCase(unittest.TestCase): """Test DBus interface for the localization module.""" def setUp(self): """Set up the localization module.""" # Set up the localization module. self.localization_module = LocalizationModule() self.localization_interface = LocalizationInterface(self.localization_module) # Connect to the properties changed signal. self.callback = Mock() self.localization_interface.PropertiesChanged.connect(self.callback) def kickstart_properties_test(self): """Test kickstart properties.""" self.assertEqual(self.localization_interface.KickstartCommands, ["keyboard", "lang"]) self.assertEqual(self.localization_interface.KickstartSections, []) self.assertEqual(self.localization_interface.KickstartAddons, []) self.callback.assert_not_called() def language_property_test(self): """Test the Language property.""" self.localization_interface.SetLanguage("cs_CZ.UTF-8") self.assertEqual(self.localization_interface.Language, "cs_CZ.UTF-8") self.callback.assert_called_once_with(LOCALIZATION.interface_name, {'Language': 'cs_CZ.UTF-8'}, []) def language_support_property_test(self): """Test the LanguageSupport property.""" self.localization_interface.SetLanguageSupport(["fr_FR"]) self.assertEqual(self.localization_interface.LanguageSupport, ["fr_FR"]) self.callback.assert_called_once_with(LOCALIZATION.interface_name, {'LanguageSupport': ["fr_FR"]}, []) def keyboard_property_test(self): """Test the Keyboard property.""" self.localization_interface.SetKeyboard("cz") self.assertEqual(self.localization_interface.Keyboard, "cz") self.callback.assert_called_once_with(LOCALIZATION.interface_name, {'Keyboard': 'cz'}, []) def vc_keymap_property_test(self): """Test the VirtualConsoleKeymap property.""" self.localization_interface.SetVirtualConsoleKeymap("cz") self.assertEqual(self.localization_interface.VirtualConsoleKeymap, "cz") self.callback.assert_called_once_with(LOCALIZATION.interface_name, {'VirtualConsoleKeymap': 'cz'}, []) def x_layouts_property_test(self): """Test the XLayouts property.""" self.localization_interface.SetXLayouts(["en", "cz(querty)"]) self.assertEqual(self.localization_interface.XLayouts, ["en", "cz(querty)"]) self.callback.assert_called_once_with(LOCALIZATION.interface_name, {'XLayouts': ["en", "cz(querty)"]}, []) def switch_options_property_test(self): """Test the LayoutSwitchOptions property.""" self.localization_interface.SetLayoutSwitchOptions(["grp:alt_shift_toggle"]) self.assertEqual(self.localization_interface.LayoutSwitchOptions, ["grp:alt_shift_toggle"]) self.callback.assert_called_once_with(LOCALIZATION.interface_name, {'LayoutSwitchOptions': ["grp:alt_shift_toggle"]}, []) def keyboard_seen_test(self): """Test the KeyboardKickstarted property.""" self.assertEqual(self.localization_interface.KeyboardKickstarted, False) ks_in = """ lang cs_CZ.UTF-8 """ ks_in = dedent(ks_in).strip() self.localization_interface.ReadKickstart(ks_in) self.assertEqual(self.localization_interface.KeyboardKickstarted, False) ks_in = """ lang cs_CZ.UTF-8 keyboard cz """ ks_in = dedent(ks_in).strip() self.localization_interface.ReadKickstart(ks_in) self.assertEqual(self.localization_interface.KeyboardKickstarted, True) def language_seen_test(self): """Test the LanguageKickstarted property.""" self.assertEqual(self.localization_interface.LanguageKickstarted, False) ks_in = """ keyboard cz """ ks_in = dedent(ks_in).strip() self.localization_interface.ReadKickstart(ks_in) self.assertEqual(self.localization_interface.LanguageKickstarted, False) ks_in = """ keyboard cz lang cs_CZ.UTF-8 """ ks_in = dedent(ks_in).strip() self.localization_interface.ReadKickstart(ks_in) self.assertEqual(self.localization_interface.LanguageKickstarted, True) def set_language_kickstarted_test(self): """Test SetLanguageKickstart.""" self.localization_interface.SetLanguageKickstarted(True) self.assertEqual(self.localization_interface.LanguageKickstarted, True) self.callback.assert_called_once_with(LOCALIZATION.interface_name, {'LanguageKickstarted': True}, []) @patch('pyanaconda.dbus.DBus.publish_object') def install_language_with_task_test(self, publisher): """Test InstallLanguageWithTask.""" self.localization_interface.SetLanguage("cs_CZ.UTF-8") task_path = self.localization_interface.InstallWithTasks("/")[0] publisher.assert_called_once() object_path, obj = publisher.call_args[0] self.assertEqual(task_path, object_path) self.assertIsInstance(obj, TaskInterface) self.assertIsInstance(obj.implementation, LanguageInstallationTask) self.assertEqual(obj.implementation._sysroot, "/") self.assertEqual(obj.implementation._lang, "cs_CZ.UTF-8") def _test_kickstart(self, ks_in, ks_out): check_kickstart_interface(self, self.localization_interface, ks_in, ks_out) def no_kickstart_test(self): """Test with no kickstart.""" ks_in = None ks_out = "" self._test_kickstart(ks_in, ks_out) def kickstart_empty_test(self): """Test with empty string.""" ks_in = "" ks_out = "" self._test_kickstart(ks_in, ks_out) def lang_kickstart_test(self): """Test the lang command.""" ks_in = """ lang cs_CZ.UTF-8 """ ks_out = """ # System language lang cs_CZ.UTF-8 """ self._test_kickstart(ks_in, ks_out) def lang_kickstart2_test(self): """Test the lang command with added language support..""" ks_in = """ lang en_US.UTF-8 --addsupport=cs_CZ.UTF-8 """ ks_out = """ # System language lang en_US.UTF-8 --addsupport=cs_CZ.UTF-8 """ self._test_kickstart(ks_in, ks_out) def keyboard_kickstart1_test(self): """Test the keyboard command.""" ks_in = """ keyboard --vckeymap=us --xlayouts='us','cz (qwerty)' """ ks_out = """ # Keyboard layouts keyboard --vckeymap=us --xlayouts='us','cz (qwerty)' """ self._test_kickstart(ks_in, ks_out) def keyboard_kickstart2_test(self): """Test the keyboard command.""" ks_in = """ keyboard us """ ks_out = """ # Keyboard layouts keyboard 'us' """ self._test_kickstart(ks_in, ks_out) def keyboard_kickstart3_test(self): """Test the keyboard command.""" ks_in = """ keyboard --xlayouts=cz,'cz (qwerty)' --switch=grp:alt_shift_toggle """ ks_out = """ # Keyboard layouts keyboard --xlayouts='cz','cz (qwerty)' --switch='grp:alt_shift_toggle' """ self._test_kickstart(ks_in, ks_out) def keyboard_kickstart4_test(self): """Test the keyboard command.""" ks_in = """ keyboard --xlayouts='cz (qwerty)','en' en """ ks_out = """ # Keyboard layouts # old format: keyboard en # new format: keyboard --xlayouts='cz (qwerty)','en' """ self._test_kickstart(ks_in, ks_out)
def test_set_serial(self, sh): m = Mock() sh.setinterface = m self.serials.update(1, {"mode": "rs422/rs485-4w"}) m.assert_called_once_with("/dev/ttyM0", 2)
class BsonBottleTest(unittest.TestCase): """Bottle plugin for automatic parse a BSON request and pass a """ def setUp(self): self.plugin = BSONBottlePlugin() self.ip = "84.34.13.122" self.callback = Mock(wraps=self._callback) self.callbacknobson = Mock(wraps=self._callbackno) bottle.request.environ['REMOTE_ADDR'] = self.ip bottle.request.environ['CONTENT_TYPE'] = 'application/bson' self.context = Mock() self.context.callback = self._callback self.contextnobson = Mock(wraps=self._callbackno) self.contextnobson.callback = self._callbackno self.__set_bson_content({"therivermen": "ehhhhhmacarena"}) def tearDown(self): pass def testAddOtherPluginWithSameKeywork(self): app = Mock() bad_plugin = Mock() bad_plugin.keyword = "bson_data" app.plugins = set([bad_plugin]) self.assertRaises(PluginError, self.plugin.setup, app) def testCallbackCalled(self): self.plugin.apply(self.callback, self.context)() self.assertTrue(self.callback.called) def testNotBsonRequest(self): bottle.request.environ['CONTENT_TYPE'] = 'mouse/mikey' self.assertRaises(BSONBottlePluginException, self.plugin.apply(self.callback, self.context)) def testNotBsonRequestWithNoBonDataParameter(self): bottle.request.environ['CONTENT_TYPE'] = 'mouse/mikey' # If there is not bson_data parameter callback will be called correctly and without bson_data parameter self.plugin.apply(self.callbacknobson, self.contextnobson)() self.callbacknobson.assert_called_once_with() def testNoContent(self): bottle.request.environ["CONTENT_LENGTH"] = 0 self.assertRaises(BSONBottlePluginException, self.plugin.apply(self.callback, self.context)) def testMaxContent(self): bottle.request.environ["CONTENT_LENGTH"] = ( BII_MAX_MEMORY_PER_REQUEST) + 1 self.assertRaises(BSONBottlePluginException, self.plugin.apply(self.callback, self.context)) def testAbortWithBSON(self): tmp = self.plugin.abort_with_bson(401, {"kk": 2}) self.assertIsInstance(tmp, HTTPResponse) self.assertEquals("application/bson", tmp.content_type) self.assertEquals(401, tmp.status_code) self.assertEquals(str(BSON.encode({"kk": 2})), tmp.body) def _callback(self, bson_data=""): logger.debug("Bson: " + str(bson_data)) pass def _callbackno(self): pass def __set_bson_content(self, data): bottle.request.environ['wsgi.input'] = str(BSON.encode(data)) bottle.request.environ["CONTENT_LENGTH"] = len( bottle.request.environ['wsgi.input']) bottle.request.body = Mock bottle.request.body.read = Mock( return_value=bottle.request.environ['wsgi.input'])
class ServicesInterfaceTestCase(unittest.TestCase): """Test DBus interface for the services module.""" def setUp(self): """Set up the services module.""" # Set up the services module. self.services_module = ServicesModule() self.services_interface = ServicesInterface(self.services_module) # Connect to the properties changed signal. self.callback = Mock() self.services_interface.PropertiesChanged.connect(self.callback) def kickstart_properties_test(self): """Test kickstart properties.""" self.assertEqual(self.services_interface.KickstartCommands, ["firstboot", "services", "skipx", "xconfig"]) self.assertEqual(self.services_interface.KickstartSections, []) self.assertEqual(self.services_interface.KickstartAddons, []) self.callback.assert_not_called() def enabled_services_property_test(self): """Test the enabled services property.""" self.services_interface.SetEnabledServices(["a", "b", "c"]) self.assertEqual(self.services_interface.EnabledServices, ["a", "b", "c"]) self.callback.assert_called_once_with( SERVICES.interface_name, {'EnabledServices': ["a", "b", "c"]}, []) def disabled_services_property_test(self): """Test the disabled services property.""" self.services_interface.SetDisabledServices(["a", "b", "c"]) self.assertEqual(self.services_interface.DisabledServices, ["a", "b", "c"]) self.callback.assert_called_once_with( SERVICES.interface_name, {'DisabledServices': ["a", "b", "c"]}, []) def default_target_property_test(self): """Test the default target property.""" self.services_interface.SetDefaultTarget(GRAPHICAL_TARGET) self.assertEqual(self.services_interface.DefaultTarget, GRAPHICAL_TARGET) self.callback.assert_called_once_with( SERVICES.interface_name, {'DefaultTarget': GRAPHICAL_TARGET}, []) def default_desktop_property_test(self): """Test the default desktop property.""" self.services_interface.SetDefaultDesktop("KDE") self.assertEqual(self.services_interface.DefaultDesktop, "KDE") self.callback.assert_called_once_with(SERVICES.interface_name, {'DefaultDesktop': "KDE"}, []) def setup_on_boot_property_test(self): """Test the setup on boot property.""" self.services_interface.SetSetupOnBoot(SETUP_ON_BOOT_DISABLED) self.assertEqual(self.services_interface.SetupOnBoot, SETUP_ON_BOOT_DISABLED) self.callback.assert_called_once_with( SERVICES.interface_name, {'SetupOnBoot': SETUP_ON_BOOT_DISABLED}, []) def post_install_tools_disabled_test(self): """Test the post-install-tools-enabled property.""" # should not be marked as disabled by default self.assertEqual(self.services_interface.PostInstallToolsEnabled, True) # mark as disabled self.services_interface.SetPostInstallToolsEnabled(False) self.assertEqual(self.services_interface.PostInstallToolsEnabled, False) self.callback.assert_called_once_with( SERVICES.interface_name, {'PostInstallToolsEnabled': False}, []) # mark as not disabled again self.services_interface.SetPostInstallToolsEnabled(True) self.assertEqual(self.services_interface.PostInstallToolsEnabled, True) self.callback.assert_called_with(SERVICES.interface_name, {'PostInstallToolsEnabled': True}, []) def _test_kickstart(self, ks_in, ks_out): check_kickstart_interface(self, self.services_interface, ks_in, ks_out) def no_kickstart_test(self): """Test with no kickstart.""" ks_in = None ks_out = "" self._test_kickstart(ks_in, ks_out) self.assertEqual(self.services_interface.SetupOnBoot, SETUP_ON_BOOT_DEFAULT) self.assertEqual(self.services_interface.PostInstallToolsEnabled, True) def kickstart_empty_test(self): """Test with empty string.""" ks_in = "" ks_out = "" self._test_kickstart(ks_in, ks_out) self.assertEqual(self.services_interface.SetupOnBoot, SETUP_ON_BOOT_DEFAULT) self.assertEqual(self.services_interface.PostInstallToolsEnabled, True) def services_kickstart_test(self): """Test the services command.""" ks_in = """ services --disabled=a,b,c --enabled=d,e,f """ ks_out = """ # System services services --disabled="a,b,c" --enabled="d,e,f" """ self._test_kickstart(ks_in, ks_out) def skipx_kickstart_test(self): """Test the skipx command.""" ks_in = """ skipx """ ks_out = """ # Do not configure the X Window System skipx """ self._test_kickstart(ks_in, ks_out) def xconfig_kickstart_test(self): """Test the xconfig command.""" ks_in = """ xconfig --defaultdesktop GNOME --startxonboot """ ks_out = """ # X Window System configuration information xconfig --defaultdesktop=GNOME --startxonboot """ self._test_kickstart(ks_in, ks_out) def firstboot_disabled_kickstart_test(self): """Test the firstboot command - disabled.""" ks_in = """ firstboot --disable """ ks_out = """ firstboot --disable """ self._test_kickstart(ks_in, ks_out) self.assertEqual(self.services_interface.SetupOnBoot, SETUP_ON_BOOT_DISABLED) self.assertEqual(self.services_interface.PostInstallToolsEnabled, False) def firstboot_enabled_kickstart_test(self): """Test the firstboot command - enabled.""" ks_in = """ firstboot --enable """ ks_out = """ # Run the Setup Agent on first boot firstboot --enable """ self._test_kickstart(ks_in, ks_out) self.assertEqual(self.services_interface.SetupOnBoot, SETUP_ON_BOOT_ENABLED) self.assertEqual(self.services_interface.PostInstallToolsEnabled, True) def firstboot_reconfig_kickstart_test(self): """Test the firstboot command - reconfig.""" ks_in = """ firstboot --reconfig """ ks_out = """ # Run the Setup Agent on first boot firstboot --reconfig """ self._test_kickstart(ks_in, ks_out) self.assertEqual(self.services_interface.SetupOnBoot, SETUP_ON_BOOT_RECONFIG) self.assertEqual(self.services_interface.PostInstallToolsEnabled, True)