class TwitterUserHandlerTest(TestCase): def setUp(self): self.m = Mox() def tearDown(self): self.m.UnsetStubs() def test_put_friend(self): request, response = new_mock_request_response(self.m) self.m.StubOutWithMock(TwitterConnector, "new_api") api = _create_api(self.m) TwitterConnector.new_api().AndReturn(api) username = "******" api.GetUser(username).AndReturn( Mock(name="hi", screen_name=username, url="hi", statuses_count=1, followers_count=1, friends_count=1)) handler = TwitterUserHandler() handler.initialize(request, response) set_api_user(self.m) self.m.ReplayAll() handler.get(username) self.m.VerifyAll()
def test_picture_with_crop_true_will_crop_to_fit(): base_path = '/basepath/for/test_picture_success' path = 'my_picture.jpg' mox = Mox() mox.StubOutWithMock(image, 'Image') mox.StubOutWithMock(image, 'StringIO') mox.StubOutWithMock(image, 'crop_to_fit') img_mock = mox.CreateMockAnything() img_mock.size = 300, 300 stringio_mock = mox.CreateMockAnything() return_mock = mox.CreateMockAnything() stringio_mock.getvalue().AndReturn(return_mock) image.StringIO.StringIO().AndReturn(stringio_mock) cherrypy.config['image.dir'] = base_path image.Image.open(join(base_path, path)).AndReturn(img_mock) img_mock.save(stringio_mock, 'JPEG', quality=100) image.crop_to_fit(img_mock, (100, 100)).AndReturn(img_mock) mox.ReplayAll() ret = image.picture(path, 100, 100, crop=True, center=False) assert ret == return_mock, "Expected %r. Got %r." % (return_mock, ret) mox.VerifyAll() del cherrypy.config['image.dir']
def test_act_public_message(self): moxer = Mox() bundle = _create_api_actor_and_selector(moxer) api = bundle.api actor = bundle.actor analyzer = bundle.analyzer _no_direct_messages(api) msg = _create_message( moxer, 1, "mmattozzi", "@livelock why is blood spattered all over @mhawthorne's car?") _mentions(api, msg) _should_respond(analyzer, msg, True) _no_response_found(msg) _search_results("spattered", create_content_list(1)) response = _post_response_to(moxer, api, msg) _save_response(msg, response) _format(response) moxer.ReplayAll() actor.act() moxer.VerifyAll()
def test_publish_raises_when_unable_to_create_folder(): mox = Mox() http_request, model_base, manager, model, queryset = get_mocks(mox) fs_mock = mox.CreateMockAnything() fs_mock.join("test_web_root", "some_path").AndReturn("test_web_root/some_path") fs_mock.dirname("test_web_root/some_path").AndReturn("test_web_root") fs_mock.exists("test_web_root").AndReturn(False) fs_mock.makedirs("test_web_root").AndRaise(ValueError()) settings = CustomSettings(WEB_ROOT="test_web_root") mox.ReplayAll() instance = StaticGenerator(http_request=http_request, model_base=model_base, manager=manager, model=model, queryset=queryset, settings=settings, fs=fs_mock) try: instance.publish_from_path("some_path", content="some_content") except StaticGeneratorException, e: assert str(e) == 'Could not create the directory: test_web_root' mox.VerifyAll() return
def test_publish_raises_when_unable_to_create_temp_file(): mox = Mox() _, model_base, manager, model, queryset = get_mocks(mox) FAKE_WEB_ROOT = 'test_web_root' mox.StubOutWithMock(tempfile, 'mkstemp') tempfile.mkstemp(dir="test_web_root").AndRaise(ValueError()) settings = CustomSettings(WEB_ROOT=FAKE_WEB_ROOT) mox.ReplayAll() with remove_web_root_from_settings(): instance = StaticGenerator( model_base=model_base, manager=manager, model=model, queryset=queryset, settings=settings, ) try: instance.publish_from_path("some_path", content="some_content") except StaticGeneratorException, e: assert str( e) == 'Could not create the file: test_web_root/some_path' mox.VerifyAll() return finally:
def test_extract_resources_when_resource_is_a_model(): mox = Mox() http_request, model_base, manager, model, queryset = get_mocks(mox) class Model(object): def get_absolute_url(self): return 'some_model_url' resources_mock = Model() model = Model settings = CustomSettings(WEB_ROOT="some_web_root") mox.ReplayAll() instance = StaticGenerator(resources_mock, http_request=http_request, model_base=model_base, manager=manager, model=model, queryset=queryset, settings=settings) assert len(instance.resources) == 1 assert instance.resources[0] == 'some_model_url' mox.VerifyAll()
def test_get_filename_from_path_when_path_ends_with_slash(): mox = Mox() http_request, model_base, manager, model, queryset = get_mocks(mox) settings = CustomSettings(WEB_ROOT="test_web_root") fs_mock = mox.CreateMockAnything() fs_mock.join( "test_web_root", "foo/bar/index.html").AndReturn("test_web_root/foo/bar/index.html") fs_mock.dirname("test_web_root/foo/bar/index.html").AndReturn( "test_web_root/foo/bar") path_mock = '/foo/bar/' mox.ReplayAll() instance = StaticGenerator(http_request=http_request, model_base=model_base, manager=manager, model=model, queryset=queryset, settings=settings, fs=fs_mock) result = instance.get_filename_from_path(path_mock) assert result == ('test_web_root/foo/bar/index.html', 'test_web_root/foo/bar') mox.VerifyAll()
def test_picture_with_center_true_will_create_new_image_and_paste(): base_path = '/base/path' path = 'image.jpg' mox = Mox() mox.StubOutWithMock(image, 'Image') mox.StubOutWithMock(image, 'StringIO') img_mock = mox.CreateMockAnything() img_mock.size = 300, 300 stringio_mock = mox.CreateMockAnything() return_mock = mox.CreateMockAnything() stringio_mock.getvalue().AndReturn(return_mock) image.StringIO.StringIO().AndReturn(stringio_mock) cherrypy.config['image.dir'] = base_path new_img_mock = mox.CreateMockAnything() new_img_mock.paste(img_mock, (-100, -100)) new_img_mock.save(stringio_mock, 'JPEG', quality=100) image.Image.open(join(base_path, path)).AndReturn(img_mock) image.Image.new('RGBA', (100, 100), 0xffffff).AndReturn(new_img_mock) mox.ReplayAll() ret = image.picture(path, 100, 100, crop=False, center=True) assert ret == return_mock, "Expected %r. Got %r." % (return_mock, ret) mox.VerifyAll() del cherrypy.config['image.dir']
class BlogCommentTest(TestCase): def setUp(self): initialize(rdb_path='sqlite:///:memory:') self.mocker = Mox() model = KMBlogComment() model.save() # id = 1のデータを登録 def tearDown(self): pass def test_set_data(self): model = KMBlogComment() test_article_id = 'test_article_id' test_comment = 'test_comment' data = self.mocker.CreateMock(KMData) data.get_request_parameter('article_id', default='', decode=True).AndReturn(test_article_id) data.get_request_parameter('comment', default='', decode=True).AndReturn(test_comment) self.mocker.ReplayAll() model.set_data(data); # KMDataで指定した値が設定されること eq_(model.article_id, test_article_id) eq_(model.comment, test_comment) eq_(model.error, None) self.mocker.UnsetStubs() self.mocker.VerifyAll()
class MoxTestBase(object): def setup_method(self, method): self.mox = Mox() def teardown_method(self, method): self.mox.UnsetStubs() self.mox.VerifyAll()
class TwitterFriendHandlerTest(TestCase): def setUp(self): self.m = Mox() def tearDown(self): self.m.UnsetStubs() def test_put_friend(self): request, response = new_mock_request_response(self.m) self.m.StubOutWithMock(TwitterConnector, "new_api") api = _create_api(self.m) TwitterConnector.new_api().AndReturn(api) username = "******" api.CreateFriendship(username) response.set_status(204) handler = TwitterFriendHandler() handler.initialize(request, response) set_api_user(self.m) self.m.ReplayAll() handler.put(username) self.m.VerifyAll()
def test_delete_raises_when_unable_to_delete_file(): mox = Mox() http_request, model_base, manager, model, queryset = get_mocks(mox) fs_mock = mox.CreateMockAnything() fs_mock.join("test_web_root", "some_path").AndReturn("test_web_root/some_path") fs_mock.dirname("test_web_root/some_path").AndReturn("test_web_root") fs_mock.exists("test_web_root/some_path").AndReturn(True) fs_mock.remove("test_web_root/some_path").AndRaise(ValueError()) settings = CustomSettings(WEB_ROOT="test_web_root") mox.ReplayAll() instance = StaticGenerator(http_request=http_request, model_base=model_base, manager=manager, model=model, queryset=queryset, settings=settings, fs=fs_mock) try: instance.delete_from_path("some_path") except StaticGeneratorException, e: assert str(e) == 'Could not delete file: test_web_root/some_path' mox.VerifyAll() return
def test_delete_ignores_folder_delete_when_unable_to_delete_folder(): mox = Mox() http_request, model_base, manager, model, queryset = get_mocks(mox) fs_mock = mox.CreateMockAnything() fs_mock.join("test_web_root", "some_path").AndReturn("test_web_root/some_path") fs_mock.dirname("test_web_root/some_path").AndReturn("test_web_root") fs_mock.exists("test_web_root/some_path").AndReturn(True) fs_mock.remove("test_web_root/some_path") fs_mock.rmdir("test_web_root").AndRaise(OSError()) settings = CustomSettings(WEB_ROOT="test_web_root") mox.ReplayAll() instance = StaticGenerator(http_request=http_request, model_base=model_base, manager=manager, model=model, queryset=queryset, settings=settings, fs=fs_mock) instance.delete_from_path("some_path") assert True, "Should work even when raising OSError"
def test_class_loader_loads_from_file(): mox = Mox() mox.StubOutWithMock(io, 'os') mox.StubOutWithMock(io.sys, 'path') io.os.path = mox.CreateMockAnything() io.__import__ = mox.CreateMockAnything() class_dir = '/full/path/to/module/or' class_file = 'file.py' class_path = '%s/%s' % (class_dir, class_file) io.os.path.isdir(class_path).AndReturn(False) io.os.path.split(class_path).AndReturn((class_dir, class_file)) io.os.path.splitext(class_file).AndReturn(('file', '.py')) io.sys.path.append(class_dir) io.sys.path.pop() module_mock = mox.CreateMockAnything() module_mock.ClassIWantToLoad = 'should_be_expected_class' io.__import__('file').AndReturn(module_mock) mox.ReplayAll() try: cl = io.ClassLoader(class_path) assert_equals(cl.load('ClassIWantToLoad'), 'should_be_expected_class') mox.VerifyAll() finally: io.__import__ = __import__ mox.UnsetStubs()
def test_delete_from_path(): mox = Mox() http_request, model_base, manager, model, queryset = get_mocks(mox) fs_mock = mox.CreateMockAnything() fs_mock.join("test_web_root", "some_path").AndReturn("test_web_root/some_path") fs_mock.dirname("test_web_root/some_path").AndReturn("test_web_root") fs_mock.exists("test_web_root/some_path").AndReturn(True) fs_mock.remove("test_web_root/some_path") fs_mock.rmdir("test_web_root") settings = CustomSettings(WEB_ROOT="test_web_root") mox.ReplayAll() instance = StaticGenerator(http_request=http_request, model_base=model_base, manager=manager, model=model, queryset=queryset, settings=settings, fs=fs_mock) instance.delete_from_path("some_path") mox.VerifyAll()
def test_locate_recursive(): "FileSystem.locate recursive" mox = Mox() base_path = '../to/project' full_path = '/full/path/to/project' class MyFs(io.FileSystem): stack = [] abspath = mox.CreateMockAnything() walk = mox.CreateMockAnything() io.glob('%s/*match*.py' % full_path) MyFs.abspath(base_path).AndReturn(full_path) walk_list = [(None, None, ['file1.py', 'file2.jpg']), (None, None, ['path1/file3.png', 'path1/file4.html'])] MyFs.walk(full_path).AndReturn(walk_list) mox.ReplayAll() try: MyFs.locate(base_path, '*match*.py', recursive=True) mox.VerifyAll() finally: mox.UnsetStubs()
def test_go_through_main_run(): mox = Mox() bobby = bob.Bob old_sys = bob.sys mock_parser = mox.CreateMockAnything() file_system = mox.CreateMockAnything() bob.sys = mox.CreateMockAnything() bob_mock = mox.CreateMockAnything() bob_instance_mock = mox.CreateMockAnything() bob_instance_mock.run = mox.CreateMockAnything() bob_instance_mock.run().AndReturn(0) bob_mock.__call__(parser=mock_parser, fs=file_system).AndReturn(bob_instance_mock) bob.sys.exit(0) bob.Bob = bob_mock mox.ReplayAll() try: got = bob.run(parser=mock_parser, fs=file_system) mox.VerifyAll() finally: mox.UnsetStubs() bob.Bob = bobby bob.sys = old_sys
def test_get_registers_appropriate_tasks(self): moxer = Mox() request, response = new_mock_request_response(moxer) _stub_taskqueue(moxer) moxer.StubOutWithMock(Feed, "find_active", use_mock_anything=True) def create_call(i): source_name = "source-%i" % i source = MockEntity(key_name=source_name, name=source_name) return MockEntity(key_name="feed-%i" % i, artifact_source=source, url="hi") q_range = xrange(0, 5) Feed.find_active().AndReturn( MockQuery(q_range, create_call=create_call)) # expects queued tasks for each feed for i in q_range: taskqueue.add(name=IgnoreArg(), url=IgnoreArg()) moxer.ReplayAll() handler = CronIngestDriverHandler() handler.initialize(request, response) handler.get() moxer.VerifyAll()
def setUp(self): self.mox = Mox() self.fakedsource = "http://rdf.debian.net/source/src/1.0" def fake_get_sources_linked_to_homepage(uri, endpoint, graph): return [self.fakedsource] self.gslth = io._get_sources_linked_to_homepage io._get_sources_linked_to_homepage = \ fake_get_sources_linked_to_homepage
class APITest(unittest.TestCase): """ The test for low level API calls """ @classmethod def setUpClass(cls): magnetodb_api_fake.run_fake_magnetodb_api() @classmethod def tearDownClass(cls): magnetodb_api_fake.stop_fake_magnetodb_api() def setUp(self): self.storage_mocker = Mox() def tearDown(self): self.storage_mocker.UnsetStubs() def test_describe_unexisting_table(self): self.storage_mocker.StubOutWithMock(storage, 'describe_table') storage.describe_table(IgnoreArg(), 'test_table1').AndRaise(TableNotExistsException) self.storage_mocker.ReplayAll() headers = { 'Host': 'localhost:8080', 'Content-Type': 'application/x-amz-json-1.0', 'X-Amz-Target': 'DynamoDB_20120810.DescribeTable' } conn = httplib.HTTPConnection('localhost:8080') conn.request("POST", "/", body='{"TableName": "test_table1"}', headers=headers) response = conn.getresponse() json_response = response.read() response_model = json.loads(json_response) self.assertEqual( response_model['__type'], 'com.amazonaws.dynamodb.v20111205#ResourceNotFoundException') self.assertEqual( response_model['message'], 'The resource which is being requested does not exist.') self.assertEqual(400, response.status) self.assertEqual(response.getheader('Content-Type'), 'application/x-amz-json-1.0')
def test_jpeg_success(): mox = Mox() path = '/path/to/mocked/img.jpg' mox.StubOutWithMock(image, 'Image') mox.StubOutWithMock(image, 'StringIO') stringio_mock = mox.CreateMockAnything() return_mock = mox.CreateMockAnything() img_mock = mox.CreateMockAnything() stringio_mock.getvalue().AndReturn(return_mock) image.StringIO.StringIO().AndReturn(stringio_mock) image.Image.open(path).AndReturn(img_mock) img_mock.save(stringio_mock, "JPEG", quality=100) cherrypy.config['image.dir'] = path mox.ReplayAll() return_got = image.jpeg(path) assert return_got == return_mock, 'The return of image.jpeg() should be %r, got %r' % ( return_mock, return_got) mime = cherrypy.response.headers['Content-type'] assert mime == 'image/jpeg', 'The response header "Content-type" should be image/jpeg, but got %r' % mime mox.VerifyAll() del cherrypy.config['image.dir']
def test_extract_zip_verbose(): mox = Mox() sys.stdout = StringIO() class MyFs(io.FileSystem): stack = [] abspath = mox.CreateMockAnything() pushd = mox.CreateMockAnything() popd = mox.CreateMockAnything() open_raw = mox.CreateMockAnything() mkdir = mox.CreateMockAnything() mox.StubOutWithMock(io, 'zipfile') filename = 'modafoca.zip' base_path = '../to/project' full_path = '/full/path/to/project' MyFs.abspath(base_path).AndReturn(full_path) MyFs.pushd(full_path) zip_mock = mox.CreateMockAnything() io.zipfile.ZipFile(filename).AndReturn(zip_mock) file_list = [ 'settings.yml', 'app', 'app/controllers.py' ] zip_mock.namelist().AndReturn(file_list) zip_mock.read('settings.yml').AndReturn('settings.yml content') zip_mock.read('app/controllers.py').AndReturn('controllers.py content') file_mock1 = mox.CreateMockAnything() MyFs.open_raw('settings.yml', 'w').AndReturn(file_mock1) file_mock1.write('settings.yml content') file_mock1.close() MyFs.open_raw('app', 'w').AndRaise(IOError('it is a directory, dumb ass!')) MyFs.mkdir('app') file_mock2 = mox.CreateMockAnything() MyFs.open_raw('app/controllers.py', 'w').AndReturn(file_mock2) file_mock2.write('controllers.py content') file_mock2.close() MyFs.popd() mox.ReplayAll() try: MyFs.extract_zip('modafoca.zip', base_path, verbose=True) assert_equals(sys.stdout.getvalue(), 'Extracting files to /full/path/to/project\n ' \ '-> Unpacking settings.yml\n -> Unpacking app' \ '\n---> Creating directory app\n -> Unpacking' \ ' app/controllers.py\n') mox.VerifyAll() finally: mox.UnsetStubs() sys.stdout = sys.__stdout__
def test_get_user(self): m = Mox() api = m.CreateMock(Api) ro_api = ReadOnlyTwitterApi(api) api.GetUser(IgnoreArg()) m.ReplayAll() ro_api.GetUser("mhawthorne") m.VerifyAll()
def test_get_friends(self): m = Mox() api = m.CreateMock(Api) ro_api = ReadOnlyTwitterApi(api) api.GetFriends() m.ReplayAll() ro_api.GetFriends() m.VerifyAll()
def test_sanitize_encoding_handles_string_with_unicode_exception(self): m = Mox() m.StubOutWithMock(strings, '_unicode') try: strings._unicode(self._string_with_unicode_char, "utf8", "replace").AndRaise(TypeError("testing")) m.ReplayAll() strings.sanitize_encoding(self._string_with_unicode_char) self.fail("exception expected") except TypeError, e: pass
def setUp(self): self.mox = Mox() self.mox.StubOutClassWithMocks(AuroraAdmin, 'Client') self.mox.StubOutClassWithMocks(scheduler_client, 'SchedulerClient') self.mock_scheduler_client = self.mox.CreateMock(scheduler_client.SchedulerClient) self.mock_thrift_client = self.mox.CreateMock(AuroraAdmin.Client) scheduler_client.SchedulerClient.get(IgnoreArg(), verbose=IgnoreArg()).AndReturn( self.mock_scheduler_client) self.mock_scheduler_client.get_thrift_client().AndReturn(self.mock_thrift_client)
def test_cron_twitter_actor_handler(self): moxer = Mox() request, response = new_mock_request_response(moxer) _stub_taskqueue(moxer) taskqueue.add(url=IgnoreArg(), countdown=IgnoreArg()) moxer.ReplayAll() handler = CronTwitterActorHandler() handler.initialize(request, response) handler.get() moxer.VerifyAll()
def test_after_each_all_is_executed_before_each_all(): "terrain.before.each_all and terrain.after.each_all decorators" import lettuce from lettuce.fs import FeatureLoader world.all_steps = [] mox = Mox() loader_mock = mox.CreateMock(FeatureLoader) mox.StubOutWithMock(lettuce.sys, 'path') mox.StubOutWithMock(lettuce, 'fs') mox.StubOutWithMock(lettuce.fs, 'FileSystem') mox.StubOutWithMock(lettuce, 'Feature') lettuce.fs.FeatureLoader('some_basepath').AndReturn(loader_mock) lettuce.sys.path.insert(0, 'some_basepath') lettuce.sys.path.remove('some_basepath') loader_mock.find_and_load_step_definitions() loader_mock.find_feature_files().AndReturn(['some_basepath/foo.feature']) lettuce.Feature.from_file('some_basepath/foo.feature'). \ AndReturn(Feature.from_string(FEATURE2)) mox.ReplayAll() runner = lettuce.Runner('some_basepath') CALLBACK_REGISTRY.clear() @before.all def set_state_to_before(): world.all_steps.append('before') @step('append "during" to states') def append_during_to_all_steps(step): world.all_steps.append("during") @after.all def set_state_to_after(total): world.all_steps.append('after') isinstance(total, TotalResult) runner.run() mox.VerifyAll() assert_equals( world.all_steps, ['before', 'during', 'during', 'after'], ) mox.UnsetStubs()
def test_calls_jpeg_when_args_length_bigger_than_3_no_crop(self): mox = Mox() mox.StubOutWithMock(controllers, 'jpeg') ret = 'should_be_a_pil_img' controllers.jpeg(path='arg1/arg2/arg3/arg4').AndReturn(ret) mox.ReplayAll() got = self.handler('arg1', 'arg2', 'arg3', 'arg4') mox.VerifyAll() msg = 'Expected "%s", got %r' % (ret, got) assert got == ret, msg
def test_act_when_is_tweeting_is_0(self): moxer = Mox() config = moxer.CreateMock(Configuration) config.is_tweeting = "0" self.__mock_config(config, moxer) api = _create_api(moxer) actor = _create_actor_and_delegates(api, moxer).actor moxer.ReplayAll() actor.act() moxer.VerifyAll()