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_terrain_import_exception(): "lettuce error tries to import " string = 'Lettuce has tried to load the conventional environment ' \ 'module "terrain"\nbut it has errors, check its contents and ' \ 'try to run lettuce again.\n\nOriginal traceback below:\n\n' mox = Mox() mox.StubOutWithMock(lettuce.fs, 'FileSystem') mox.StubOutWithMock(lettuce.exceptions, 'traceback') mox.StubOutWithMock(lettuce.sys, 'stderr') exc = Exception('foo bar') lettuce.fs.FileSystem._import('terrain').AndRaise(exc) lettuce.exceptions.traceback.format_exc(exc). \ AndReturn('I AM THE TRACEBACK FOR IMPORT ERROR') lettuce.sys.stderr.write(string) lettuce.sys.stderr.write('I AM THE TRACEBACK FOR IMPORT ERROR') mox.ReplayAll() try: reload(lettuce) except SystemExit: mox.VerifyAll() finally: mox.UnsetStubs()
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_delete_raises_when_unable_to_delete_file(): mox = Mox() FAKE_WEB_ROOT = 'test_web_root' FILE_PATH = 'some_path' FILE_RELATIVE_PATH = os.path.join(FAKE_WEB_ROOT, FILE_PATH) settings = CustomSettings(WEB_ROOT=FAKE_WEB_ROOT) mox.StubOutWithMock(os.path, 'exists') mox.StubOutWithMock(os, 'remove') os.path.exists(FILE_RELATIVE_PATH).AndReturn(True) os.remove(FILE_RELATIVE_PATH).AndRaise(Exception()) mox.ReplayAll() with remove_web_root_from_settings(): instance = StaticGenerator(settings=settings, ) try: instance.delete_from_path(FILE_PATH) except StaticGeneratorException, e: assert str(e) == 'Could not delete file: {file_path}'.format( file_path=FILE_RELATIVE_PATH) mox.VerifyAll() return finally:
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 StatsHandlerTest(TestCase): def setUp(self): self.m = Mox() def tearDown(self): self.m.UnsetStubs() def test_get(self): request, response = new_mock_request_response(self.m) self.m.StubOutWithMock(ArtifactSourceAccessor, "find_artifact_counts") self.m.StubOutWithMock(ArtifactSourceAccessor, "find_artifact_counts_newer") self.m.StubOutWithMock(memcache, "get_stats") self.m.StubOutWithMock(ConfigurationAccessor, "get_or_create") ArtifactSourceAccessor.find_artifact_counts().AndReturn({}) ArtifactSourceAccessor.find_artifact_counts_newer(IgnoreArg()).AndReturn({}) memcache.get_stats().AndReturn({}) # token = "oauth_token_secret=hi&oauth_token=hi" # config = MockEntity(key_name="hi", twitter_oauth_enabled=True, twitter_access_token=token, twitter_read_only=False) # ConfigurationAccessor.get_or_create().AndReturn(config) api = new_mock_twitter_api(self.m) api.GetUserTimeline(count=IgnoreArg()).AndReturn(()) api.GetDirectMessages(since=IgnoreArg()).AndReturn(()) api.GetReplies(since=IgnoreArg()).AndReturn(()) handler = StatsHandler() handler.initialize(request, response) self.m.ReplayAll() handler.get() self.m.VerifyAll()
def _test_post_no_user(self): moxer = Mox() request, response = new_mock_request_response(moxer) moxer.StubOutWithMock(users, "get_current_user", use_mock_anything=True) moxer.StubOutWithMock(User, "__init__", use_mock_anything=True) moxer.StubOutWithMock(Feed, "get_by_source_name", use_mock_anything=True) moxer.StubOutWithMock(model, "ingest_feed_entries") source_name = "hi" username = Services.API_USER user = MockEntity(key_name=username, email=lambda: username) # passes auth (via cron) users.get_current_user().AndReturn(user) handler = IngestHandler() # no logged in user users.get_current_user() User.__init__(username) handler.initialize(request, response) feed = MockEntity(key_name=source_name, url="no") Feed.get_by_source_name(source_name, return_none=True).AndReturn(feed) model.ingest_feed_entries(feed, None, error_call=IgnoreArg()).AndReturn(()) moxer.ReplayAll() handler.post(source_name) moxer.VerifyAll()
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_publish_raises_when_unable_to_create_folder(): mox = Mox() http_request, model_base, manager, model, queryset = get_mocks(mox) FAKE_WEB_ROOT = 'test_web_root' mox.StubOutWithMock(os, 'makedirs') mox.StubOutWithMock(os.path, 'exists') os.makedirs(FAKE_WEB_ROOT).AndRaise(ValueError()) os.path.exists(FAKE_WEB_ROOT).AndReturn(False) settings = CustomSettings(WEB_ROOT=FAKE_WEB_ROOT) mox.ReplayAll() with remove_web_root_from_settings(): instance = StaticGenerator( http_request=http_request, 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 directory: ' + FAKE_WEB_ROOT mox.VerifyAll() return finally:
class SeeAlsoFinderTest(unittest.TestCase): def setUp(self): self.finder = SeeAlsoFinder() self.mox = Mox() debian.services.RES_BASEURI = "base" debian.services.FROM_GRAPH = None def test__fetch_seealso_uris(self): sourcename = "pkg" unversionedsourceuri = "base/source/%s" % sourcename mock = self.mox.CreateMock(SPARQLQueryProcessor) expectedarg = \ r".+SELECT\s*\?uri.+\<%s\>\sa\sdeb:UnversionedSource\s*;\s*rdfs:seeAlso\s\?uri" % \ re.escape(unversionedsourceuri) mock.execute_query(Regex(expectedarg, flags=re.DOTALL)) binding1 = {'uri': {'value': "http://example.org/1"}} binding2 = {'uri': {'value': "http://example.org/2"}} bindings = [binding1, binding2] fakeresults = {'results': {'bindings': bindings}} self.finder.processor = mock self.mox.ReplayAll() self.finder.processor.results = fakeresults uris = self.finder._fetch_seealso_uris(unversionedsourceuri) self.mox.VerifyAll() self.assertEqual(2, len(uris)) self.assertTrue("http://example.org/1" in uris) self.assertTrue("http://example.org/2" in uris) def test_find_forbidden_characters(self): self.assertRaises(SPARQLQueryBuilderPackageNameSchemeError, self.finder.find, "{}@") def test_find(self): srcpkgname = "source" srcpkguri = "base/source/%s" % srcpkgname self.mox.StubOutWithMock(self.finder, "_fetch_seealso_uris") returnvals = ["http://example.org/1", "http://example.org/2"] self.finder._fetch_seealso_uris(srcpkguri).AndReturn(returnvals) self.mox.ReplayAll() uris = self.finder.find(srcpkgname) self.mox.VerifyAll() self.assertEqual(2, len(uris)) self.assertTrue("http://example.org/1" in uris) self.assertTrue("http://example.org/2" in uris) def test_find_escape(self): srcpkgname = "source.+-" srcpkguri = "base/source/%s" % "source.%2B-" self.mox.StubOutWithMock(self.finder, "_fetch_seealso_uris") returnvals = ["http://example.org/1", "http://example.org/2"] self.finder._fetch_seealso_uris(srcpkguri).AndReturn(returnvals) self.mox.ReplayAll() uris = self.finder.find(srcpkgname) self.mox.VerifyAll()
def test_retweet_not_previously_retweeted(self): moxer = Mox() api = _create_api(moxer) bundle = _create_actor_and_delegates(api, moxer) actor = bundle.actor analyzer = bundle.analyzer status_user = Record(screen_name=self.id()) status_ids = [5, 10, 15] timeline = (Record(id=id, text="epic, fail is epic %s" % id, user=status_user) for id in status_ids) api.GetFriendsTimeline(count=10).AndReturn(timeline) # print "timeline: %s" % [t for t in timeline] # I choose a status to be the one I will retweet not_already_retweeted_id = status_ids[2] moxer.StubOutWithMock(TwitterResponseAccessor, "get_by_message_id") moxer.StubOutWithMock(TwitterResponseAccessor, "create") print "not_already_retweeted_id: %s " % not_already_retweeted_id for status_id in status_ids: print "status_id: %s" % status_id print "%s != %s == %s" % (status_id, not_already_retweeted_id, status_id != not_already_retweeted_id) if status_id != not_already_retweeted_id: # returns a result which means "already retweeted". id is meaningless result = Record(message_id=status_id, response_id=status_id * 10) TwitterResponseAccessor.get_by_message_id( IsA(str)).AndReturn(result) print "returned %s for %s" % (result, status_id) continue # this status is the one I will retweet status_id_str = str(status_id) TwitterResponseAccessor.get_by_message_id(status_id_str) _should_retweet(analyzer) retweet_id = str(status_id + 1) retweet = Record(id=retweet_id, user=self.id()) api.PostRetweet(status_id).AndReturn(retweet) TwitterResponseAccessor.create(status_id_str, response_id=retweet_id, tweet_type=TwitterResponse.RETWEET, user=status_user.screen_name) moxer.ReplayAll() actor.retweet() 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()
class ArtifactSourceAccessorTest(TestCase): def setUp(self): self.m = Mox() def tearDown(self): self.m.UnsetStubs() def test_delete_by_name_missing_source(self): self.m.StubOutWithMock(ArtifactSource, "get_by_name") name = "mhawthorne" ArtifactSource.get_by_name(name) self.m.ReplayAll() self.assertRaises(NotFoundException, ArtifactSourceAccessor.delete_by_name, name) self.m.VerifyAll() def test_delete_by_name_deletes_source_with_referencing_feed(self): # self.m.StubOutWithMock(antonym_model, 'ArtifactSource') self.m.StubOutWithMock(ArtifactSource, "get_by_name") self.m.StubOutWithMock(FeedAccessor, "get_by_source_name") name = "mhawthorne" source = MockEntity(key_name=name) ArtifactSource.get_by_name(name).AndReturn(source) FeedAccessor.get_by_source_name(name, return_none=True).AndReturn( MockEntity(key=name, url="http://real.ly")) self.m.ReplayAll() self.assertRaises(ConflictingDataException, ArtifactSourceAccessor.delete_by_name, name) self.m.VerifyAll() def test_delete_by_name_deletes_source_with_no_referencing_feed(self): self.m.StubOutWithMock(ArtifactSource, "get_by_name") self.m.StubOutWithMock(FeedAccessor, "get_by_source_name") self.m.StubOutWithMock(ArtifactInfo, "find_by_source") self.m.StubOutWithMock(ArtifactContent, "find_by_source") self.m.StubOutWithMock(db, "delete") self.m.StubOutWithMock(memcache, "delete") name = "mhawthorne" source = MockEntity(key_name=name) ArtifactSource.get_by_name(name).AndReturn(source) FeedAccessor.get_by_source_name(name, return_none=True) ArtifactInfo.find_by_source(source, keys_only=True).AndReturn( MockQuery(range(0, 0))) ArtifactContent.find_by_source(source).AndReturn(MockQuery(range(0, 0))) db.delete(source) memcache.delete(IsA(str)).AndReturn(1) self.m.ReplayAll() ArtifactSourceAccessor.delete_by_name(name) self.m.VerifyAll()
def test_posted(self): # TODO: shouldn't be mocking memcache, should be mocking MemcacheQueue. # but this is a good quick test m = Mox() m.StubOutWithMock(memcache, "incr") m.StubOutWithMock(memcache, "get") m.StubOutWithMock(memcache, "set") memcache.incr(IgnoreArg()) memcache.get(IgnoreArg()).AndReturn(1) memcache.set(IgnoreArg(), IgnoreArg(), time=IgnoreArg()) m.ReplayAll() ActivityReporter().posted("hi") m.VerifyAll()
def test_can_be_get_object(): mox = Mox() class MockObject(object): pass mockobject = MockObject() key = "should-be-key" value = mockobject mox.StubOutWithMock(backend, 'memcache', use_mock_anything=True) cache_mock = mox.CreateMockAnything() cache_mock.get(key).AndReturn(value) backend.memcache.Client(["localhost:11211"]).AndReturn(cache_mock) mox.ReplayAll() try: memcache = backend.MemcachedClass(server=["localhost:11211"], timeout=30) assert memcache.get(key) == value mox.VerifyAll() finally: mox.UnsetStubs()
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()
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_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_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 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(self): """ this test is verifying that things are wired up correct. not testing any functionality. """ m = Mox() m.StubOutWithMock(memcache, "get") m.StubOutWithMock(memcache, "set") m.StubOutWithMock(memcache, "get_multi") memcache.get(IgnoreArg()) memcache.set(IgnoreArg(), IgnoreArg(), time=IgnoreArg()) memcache.get_multi(IgnoreArg()).AndReturn({}) m.ReplayAll() q = MemcacheQueue(self.id()) q.items() m.VerifyAll()
def test_calls_jpeg_when_args_length_equals_3_and_crop(self): mox = Mox() mox.StubOutWithMock(controllers, 'jpeg') mox.StubOutWithMock(controllers, 'picture') ret = 'should_be_a_pil_img' controllers.jpeg(path='crop/200x100/image.jpg') controllers.picture(path='image.jpg', width=200, height=100). \ AndReturn(ret) mox.ReplayAll() got = self.handler('crop', '200x100', 'image.jpg') mox.VerifyAll() msg = 'Expected "%s", got %r' % (ret, got) assert got == ret, msg
def test_create_success(): mox = Mox() b = bob.Bob() b.fs = mox.CreateMockAnything() b.fs.join = join mox.StubOutWithMock(bob, 'SpongeData') mox.StubOutWithMock(bob, 'yaml') full_path = '/full/path/to/my-project' b.fs.current_dir('my-project'). \ AndReturn(full_path) b.fs.exists(full_path). \ AndReturn(False) b.fs.mkdir(full_path) file_mock = mox.CreateMockAnything() b.fs.open(join(full_path, 'settings.yml'), 'w'). \ AndReturn(file_mock) expected_dict = basic_config.copy() expected_dict['application'].update({ 'static': { '/media': join('media') }, 'path': join('app', 'controllers.py'), 'image-dir': join('media', 'img'), 'template-dir': join('templates'), }) bob.yaml.dump(expected_dict, indent=True).AndReturn('should-be-a-yaml') file_mock.write('should-be-a-yaml') file_mock.close() bob.SpongeData.get_file('project.zip'). \ AndReturn('should-be-path-to-zip-file') b.fs.extract_zip('should-be-path-to-zip-file', full_path) mox.ReplayAll() b.create('my-project') mox.VerifyAll()
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_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 tes_mkdir_raises_when_path_is_not_a_dir(): mox = Mox() mox.StubOutWithMock(io, 'os') mox.StubOutWithMock(io.os, 'path') class MyFs(io.FileSystem): pass oserror = OSError() oserror.errno = 17 io.os.makedirs('/make/all/those/subdirs').AndRaise(oserror) io.os.isdir('/make/all/those/subdirs').AndReturn(False) mox.ReplayAll() try: assert_raises(OSError, MyFs.mkdir, '/make/all/those/subdirs') mox.VerifyAll() finally: mox.UnsetStubs()
def tes_mkdir_raises_on_oserror_errno_not_17(): mox = Mox() mox.StubOutWithMock(io, 'os') mox.StubOutWithMock(io.os, 'path') class MyFs(io.FileSystem): pass oserror = OSError() oserror.errno = 0 io.os.makedirs('/make/all/those/subdirs').AndRaise(oserror) mox.ReplayAll() try: assert_raises(OSError, MyFs.mkdir, '/make/all/those/subdirs') mox.VerifyAll() finally: mox.UnsetStubs()
def test_can_be_get_key_from_expire(): mox = Mox() class ShouldBeModule(object): def ShouldBeMethod(self, param=None): pass ShouldBeMethod.fn = ShouldBeMethod expire = "ShouldBeModule.ShouldBeMethod(should-be-params)" instance_mock = mox.CreateMockAnything() instance_mock.id = 101 instance_mock.ShouldBeMethod = "should-be-method-instance" cached_extension = cache.CachedExtension() mox.StubOutWithMock(cached_extension, 'prepare_parameters', use_mock_anything=True) mox.StubOutWithMock(cached_extension, 'load_model', use_mock_anything=True) cached_extension.prepare_parameters( instance_mock, "should-be-params").AndReturn({"param": "should-be-prepare-params"}) module_instance = ShouldBeModule() cached_extension.load_model('shouldbemodule', 'ShouldBeModule').AndReturn(module_instance) mox.ReplayAll() try: md5, key = cached_extension.get_key_from_expires(instance_mock, expire) assert md5 == hashlib.md5( "mss.tests.unit.core.cache.test_cache.ShouldBeModule().ShouldBeMethod(param=should-be-prepare-params)" ).hexdigest() mox.VerifyAll() finally: mox.UnsetStubs()
def test_mkdir_ignore_dirs_already_exists(): mox = Mox() mox.StubOutWithMock(io, 'os') mox.StubOutWithMock(io.os, 'path') class MyFs(io.FileSystem): pass oserror = OSError() oserror.errno = 17 io.os.makedirs('/make/all/those/subdirs').AndRaise(oserror) io.os.path.isdir('/make/all/those/subdirs').AndReturn(True) mox.ReplayAll() try: MyFs.mkdir('/make/all/those/subdirs') mox.VerifyAll() finally: mox.UnsetStubs()
def test_extract_zip_non_verbose(): mox = Mox() 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) mox.VerifyAll() finally: mox.UnsetStubs()