def test_page_registry_resolve_raises_with_wrong_none_url(): def do_resolve_fail(): PageRegistry.resolve(Settings(), None, exists_func=fake_abs) exc = 'PageRegistry.resolve argument 2 must be a string. Got None.' assert_raises(TypeError, do_resolve_fail, exc_pattern=re_compile(exc))
def test_page_registry_resolve_raises_with_wrong_none_settings_and_none_url(): def do_resolve_fail(): PageRegistry.resolve(None, None, exists_func=fake_abs) exc = 'PageRegistry.resolve takes a pyccuracy.common.Settings ' \ 'object first parameter. Got None.' assert_raises(TypeError, do_resolve_fail, exc_pattern=re_compile(exc))
def test_macro_expansion_bad_variadic_position(self): alpha = ast.IdentifierNode(["alpha"]) omega = ast.IdentifierNode(["omega"]) vary_expand = ast.IdentifierNode(["vary"]) whitespace = ast.WhiteSpaceNode([' ']) plus = ast.ASCIILiteralNode(['+']) testutils.assert_raises( symtable.MacroExpansion, symtable.PepperSyntaxError, [ "Variadic macro argument must be at the end of the argument definition list" ], # NOQA 'foo', [alpha, whitespace, plus, whitespace, omega, plus, vary_expand], ['alpha', 'omega', 'varia...', 'extra...']) testutils.assert_raises( symtable.MacroExpansion, symtable.PepperSyntaxError, [ "Variadic macro argument must be at the end of the argument definition list" ], # NOQA 'foo', [alpha, whitespace, plus, whitespace, omega, plus, vary_expand], ['alpha', 'omega', 'varia...', 'notvaria'])
def test_render_html_param_filename_takes_string(): assert_raises(TypeError, template.render_html, None, None, exc_pattern=r'sponge.template.render_html ' \ 'takes a string as filename param, got None.') assert_raises(TypeError, template.render_html, 5, None, exc_pattern=r'sponge.template.render_html ' \ 'takes a string as filename param, got 5.')
def test_templates_render_html_raises_context_already_have_make_url(): assert_raises(KeyError, template.render_html, 'index.html', {'make_url': "ss"}, exc_pattern=r'The key "make_url" is already in ' \ 'template context as[:] %s' % re.escape(repr(template.make_url)))
def test_setup_all_path_must_be_absolute(): d = {} cf = core.ConfigValidator({}) sp = core.SpongeConfig(d, cf) assert_raises(TypeError, sp.setup_all, 'relative/path/', exc_pattern=r'SpongeConfig.setup_all takes a ' \ 'absolute path, got relative/path/.')
def test_model_file_manager_method_delete_takes_model_or_modelset(): codecs_mock = Mock() file_mock = Mock() path_mock = Mock() path_mock.expects(once()).exists(eq('/home/wee/Wee.json')).will(return_value(True)) path_mock.expects(once()).exists(eq('/home/wee')).will(return_value(True)) os_path_module = managers.os.path codecs_module = managers.codecs managers.codecs = codecs_mock managers.os.path = path_mock class Wee(Model): objects = managers.FileSystemModelManager(base_path='/home/wee') assert_raises(TypeError, Wee.objects.delete, None, exc_pattern=r'delete\(\) takes a Wee as parameter, got None') assert_raises(TypeError, Wee.objects.delete, 5, exc_pattern=r'delete\(\) takes a Wee as parameter, got 5') file_mock.verify() codecs_mock.verify() managers.codecs = codecs_module managers.os.path = os_path_module
def test_action_registry_raises_if_action_does_not_feature_regex(): def should_raise(): class ActionToTest5(ActionBase): def execute(): pass assert_raises(NotImplementedError, should_raise, exc_pattern=r'^The action ActionToTest5 does not implement the attribute regex$')
def test_file_handler_construction_fails_with_more_than_two_parameters(self): assert_raises(TypeError, models.FileHandler, None, None, None, exc_pattern=r'__init__.. takes at most 3 arguments .4 given.')
def test_set_as_lazy_fail_when_not_not_bool(self): rl = models.RelationShip() assert_raises(TypeError, rl.set_lazy, None) assert_raises(TypeError, rl.set_lazy, object()) assert_raises(TypeError, rl.set_lazy, {}) assert_raises(TypeError, rl.set_lazy, []) assert_raises(TypeError, rl.set_lazy, ())
def test_templates_render_html_raises_filename_empty(): assert_raises(TypeError, template.render_html, '', {}, exc_pattern=r'sponge.template.render_html ' \ 'filename param can not be empty.')
def test_set_as_self_referenced_fail_when_not_not_bool(self): rl = models.RelationShip() assert_raises(TypeError, rl.set_self_referenced, None) assert_raises(TypeError, rl.set_self_referenced, object()) assert_raises(TypeError, rl.set_self_referenced, {}) assert_raises(TypeError, rl.set_self_referenced, []) assert_raises(TypeError, rl.set_self_referenced, ())
def test_model_file_manager_get_raises_wrong_param(): class Woo(Model): objects = managers.FileSystemModelManager(base_path='/home/woo') def __unicode__(self): return '<FooBar(name=%r)>' % self.name assert_raises(TypeError, Woo.objects.get, blabla='x', exc_pattern=r'blabla is not a valid field in %r' % Woo)
def test_request_fails_url_non_string(): b = Bolacha() assert_raises(TypeError, b.request, None, None, exc_pattern=r'Bolacha.request, parameter url must be ' \ 'a string. Got None') assert_raises(TypeError, b.request, 99, None, exc_pattern=r'Bolacha.request, parameter url must be ' \ 'a string. Got 99')
def test_create_fails_without_argument(): b = bob.Bob() sys.stderr = StringIO() assert_raises(SystemExit, b.create, None) assert_equals(sys.stderr.getvalue(), '\nmissing project name, try something like ' \ '"bob create foobar"\n') sys.stderr = sys.__stderr__
def test_floatfield_fail_on_validate(self): class Person(Model): weight = fields.FloatField() person_dict = {'Person': {'weight': None}} assert_raises(fields.FieldValidationError, Person.from_dict, person_dict)
def test_textfield_fail(self): class Person(Model): biography = fields.TextField() person_dict = {'Person': {'biography': 00}} assert_raises(TypeError, Person.from_dict, person_dict)
def test_booleanfield_fail(self): class Person(Model): married = fields.BooleanField(positives=["true", "yes"], negatives=["false", "no"]) person_dict = {'Person': {'married': None}} assert_raises(TypeError, Person.from_dict, person_dict)
def test_time(): dta1 = TimeAttribute("%H:%M:%S") dta2 = TimeAttribute("%H:%M:%S") dta1.fill('creation_time', '23:44:10') dta2.fill('creation_time', time(hour=23, minute=44, second=10)) assert_equals(dta1.value, time(hour=23, minute=44, second=10)) assert_equals(dta2.value, time(hour=23, minute=44, second=10)) assert_raises(TypeError, dta1.fill, 'creation_time', 100.5)
def test_takes_dict_on_creation(): cf = core.ConfigValidator({}) assert_raises(TypeError, core.SpongeConfig, None, cf, exc_pattern=r'SpongeConfig parameter 1 ' \ 'must be a dict, got None.') assert_raises(TypeError, core.SpongeConfig, 5, cf, exc_pattern=r'SpongeConfig parameter 1 ' \ 'must be a dict, got 5.')
def test_integerfield_fail_on_validate(self): class Person(Model): childrens = fields.IntegerField() person_dict = {'Person': {'childrens': None}} assert_raises(fields.FieldValidationError, Person.from_dict, person_dict)
def test_request_fails_with_headers_non_dict(): b = Bolacha() assert_raises(TypeError, b.request, 'http://somewhere', 'GET', headers=5, exc_pattern=r'Bolacha.request, parameter headers must be ' \ 'a dict or NoneType. Got 5') assert_raises(TypeError, b.request, 'http://somewhere', 'GET', headers='bla', exc_pattern=r'Bolacha.request, parameter headers must be ' \ 'a dict or NoneType. Got \'bla\'')
def test_creation_takes_class(): msg = r'Bolacha takes a class or callable as parameter, got %r' assert_raises(TypeError, Bolacha, 5, exc_pattern=msg % 5) assert_raises(TypeError, Bolacha, 'blabla', exc_pattern=msg % 'blabla')
def test_request_fails_method_non_string(): b = Bolacha() assert_raises(TypeError, b.request, 'http://gnu', None, exc_pattern=r'Bolacha.request, parameter method must be ' \ 'a string. Got None') assert_raises(TypeError, b.request, 'http://gnu', 99, exc_pattern=r'Bolacha.request, parameter method must be ' \ 'a string. Got 99')
def test_picture_second_param_should_be_int(): assert_raises( TypeError, image.picture, '', None, None, exc_pattern=r'picture.. takes a integer as width parameter, got None.')
def test_picture_first_param_should_be_string(): assert_raises( TypeError, image.picture, None, None, None, exc_pattern=r'picture.. takes a string as path parameter, got None.')
def test_picture_third_param_should_be_int(): assert_raises( TypeError, image.picture, '', 1, None, exc_pattern=r'picture.. takes a integer as height parameter, got None.' )
def test_render_html_param_template_path_takes_string(): assert_raises(TypeError, template.render_html, 'index.html', {}, template_path=1, exc_pattern=r'sponge.template.render_html ' \ 'takes a string as template_path param, got 1.') assert_raises(TypeError, template.render_html, 'index.html', {}, template_path={}, exc_pattern=r'sponge.template.render_html ' \ 'takes a string as template_path param, got {}.')
def test_decimalfield_raises_on_setattr(self): class Person(Model): wage = fields.DecimalField(decimal_places=2, max_digits=6) expected_dict = {'Person': {'wage': None}} assert_raises(TypeError, Person.from_dict, expected_dict)
def test_decimalfield_fail_on_set(self): class Person(Model): wage = fields.DecimalField(max_digits=6, decimal_places=2) person_dict = {'Person': {'wage': '4000.55'}} man = Person.from_dict(person_dict) assert_raises(fields.FieldValidationError, setattr, man, 'wage', '10:10:10')
def test_urlfield_fail_value_nonstring(self): class Person(Model): blog = fields.URLField(verify_exists=False) person_dict = {'Person': {'blog': None}} assert_raises(TypeError, Person.from_dict, person_dict)
def test_selenium_driver_raises_on_start_test_when_selenium_cant_start(): context = Context(Settings()) selenium_mock = Mock() selenium_mock.expects(once()).start().will(raise_exception(DriverError("invalid usage"))) driver = SeleniumDriver(context, selenium=selenium_mock) assert_raises(DriverError, driver.start_test, url="http://localhost", exc_pattern=re.compile(r"Error when starting selenium. Is it running ?")) selenium_mock.verify()
def test_action_registry_raises_if_action_features_regex_with_different_type_than_string(): def should_raise(): class ActionToTest7(ActionBase): regex = 10 def execute(): pass assert_raises(TypeError, should_raise, exc_pattern="^ActionToTest7.regex attribute must be a string, got 10\('int'\).$")
def test_request_with_invalid_body(): b = Bolacha() assert_raises(TypeError, b.request, 'http://gnu', 'GET', body=['a list'], exc_pattern=r'Bolacha.request, parameter body must be ' \ 'a string or dict. Got .\'a list\'.') assert_raises(TypeError, b.request, 'http://gnu', 'GET', body=5, exc_pattern=r'Bolacha.request, parameter body must be ' \ 'a string or dict. Got 5')
def test_base_driver_instantiate_need_a_settings(): def do_instantiate_fail(): BaseDriver(None) assert_raises( TypeError, do_instantiate_fail, exc_pattern=re_compile( 'BaseDriver takes a pyccuracy.common.Settings object as construction parameter. Got None.' ))
def test_drivers_registry_must_raise_when_does_not_exist(): def do_get_must_fail(): null_driver = DriverRegistry.get('spam_eggs') assert_raises( DriverDoesNotExistError, do_get_must_fail, exc_pattern=re_compile( u'^Driver not found "spam_eggs". Is the driver in a known path[?]$' ))
def test_drivers_registry_should_raise_when_no_backend_specified(): def raise_my_stuff(): class MyBrowserDriver2(BaseDriver): pass assert_raises( BackendNotFoundError, raise_my_stuff, exc_pattern=re_compile( '^Backend not found in "MyBrowserDriver2" class. Did you forget to specify "backend" attribute[?]$' ))
def assert_invalid_option(option, value, method, *args, **kw): if isinstance(value, basestring): value = escape(value) else: value = repr(value) p = r'Invalid value in "%s" option: "%s". ' \ 'Read the Sponge documentation for more ' \ 'information.' % (escape(option), value) assert_raises(InvalidValueError, method, exc_pattern=p, *args, **kw)
def test_templates_render_html_raises_context_nondict(): assert_raises(TypeError, template.render_html, 'index.html', 'a string', exc_pattern=r'sponge.template.render_html ' \ 'takes a dict as context param, got \'a string\'.') assert_raises(TypeError, template.render_html, 'index.html', 5, exc_pattern=r'sponge.template.render_html ' \ 'takes a dict as context param, got 5.')
def test_selenium_driver_raises_on_start_test_when_selenium_cant_start(): mocker = Mocker() context = Context(Settings()) selenium_mock = mocker.mock() selenium_mock.start() mocker.throw(DriverError("invalid usage")) with mocker: driver = SeleniumDriver(context, selenium=selenium_mock) assert_raises(DriverError, driver.start_test, url="http://localhost", \ exc_pattern=re.compile(r"Error when starting selenium. Is it running ?"))
def test_run_fails_without_args(): mox = Mox() mock_parser = mox.CreateMockAnything() mock_parser.parse_args().AndReturn(("options", [])) mox.ReplayAll() b = bob.Bob(parser=mock_parser) sys.stderr = StringIO() assert_raises(SystemExit, b.run) assert_equals(sys.stderr.getvalue(), '\nmissing argument, choose one ' \ 'in create, go, start\n') sys.stderr = sys.__stderr__ mox.VerifyAll()
def test_caching_fails_if_cache_path_does_not_exist(self): mox = Mox() class ImageHandlerStub(controllers.ImageHandler): fs = mox.CreateMockAnything() ImageHandlerStub.fs.exists('/full/path/to/cache').AndReturn(False) mox.ReplayAll() assert_raises(controllers.InvalidCachePath, ImageHandlerStub, '/full/path/to/cache', exc_pattern=r'The given path \(/full/path/to/cache\) ' \ 'does not exist, so that ImageHandler can not save ' \ 'cache files there.') mox.VerifyAll()
def test_bucket_notexist(): name = '{prefix}foo'.format(prefix=prefix) print 'Trying bucket {name!r}'.format(name=name) e = assert_raises(boto.exception.S3ResponseError, s3.main.get_bucket, name) eq(e.status, 404) eq(e.reason, 'Not Found') eq(e.error_code, 'NoSuchBucket')
def test_object_read_notexist(): bucket = get_new_bucket() key = bucket.new_key('foobar') e = assert_raises(boto.exception.S3ResponseError, key.get_contents_as_string) eq(e.status, 404) eq(e.reason, 'Not Found') eq(e.error_code, 'NoSuchKey')
def test_bucket_create_naming_bad_short_empty(): # bucket creates where name is empty look like PUTs to the parent # resource (with slash), hence their error response is different e = assert_raises(boto.exception.S3ResponseError, s3.main.create_bucket, '') eq(e.status, 405) eq(e.reason, 'Method Not Allowed') eq(e.error_code, 'MethodNotAllowed')
def test_bucket_create_exists_nonowner(): # Names are shared across a global namespace. As such, no two # users can create a bucket with that same name. bucket = get_new_bucket() e = assert_raises(boto.exception.S3CreateError, s3.alt.create_bucket, bucket.name) eq(e.status, 409) eq(e.reason, 'Conflict') eq(e.error_code, 'BucketAlreadyExists')
def test_bucket_acl_grant_email_notexist(): # behavior not documented by amazon bucket = get_new_bucket() policy = bucket.get_acl() policy.acl.add_email_grant('FULL_CONTROL', NONEXISTENT_EMAIL) e = assert_raises(boto.exception.S3ResponseError, bucket.set_acl, policy) eq(e.status, 400) eq(e.reason, 'Bad Request') eq(e.error_code, 'UnresolvableGrantByEmailAddress')
def test_object_write_to_nonexist_bucket(): name = '{prefix}foo'.format(prefix=prefix) print 'Trying bucket {name!r}'.format(name=name) bucket = s3.main.get_bucket(name, validate=False) key = bucket.new_key('foo123bar') e = assert_raises(boto.exception.S3ResponseError, key.set_contents_from_string, 'foo') eq(e.status, 404) eq(e.reason, 'Not Found') eq(e.error_code, 'NoSuchBucket')
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_create_fails_if_path_already_exists(): mox = Mox() b = bob.Bob() b.fs = mox.CreateMockAnything() b.fs.current_dir('my-project'). \ AndReturn('/full/path/to/my-project') b.fs.exists('/full/path/to/my-project'). \ AndReturn(True) mox.ReplayAll() try: sys.stderr = StringIO() assert_raises(SystemExit, b.create, 'my-project') assert_equals(sys.stderr.getvalue(), '\nThe path "/full/path/to/my-project" ' \ 'already exists. Maybe you could choose ' \ 'another name for your project ?\n') finally: sys.stderr = sys.__stderr__
def test_bucket_create_delete(): name = '{prefix}foo'.format(prefix=prefix) print 'Trying bucket {name!r}'.format(name=name) bucket = s3.main.create_bucket(name) # make sure it's actually there s3.main.get_bucket(bucket.name) bucket.delete() # make sure it's gone e = assert_raises(boto.exception.S3ResponseError, bucket.delete) eq(e.status, 404) eq(e.reason, 'Not Found') eq(e.error_code, 'NoSuchBucket')
def test_macro_expansion_variadic_too_few_args(self): alpha = ast.IdentifierNode(["alpha"]) omega = ast.IdentifierNode(["omega"]) vary_expand = ast.IdentifierNode(["vary"]) whitespace = ast.WhiteSpaceNode([' ']) plus = ast.ASCIILiteralNode(['+']) macro = symtable.MacroExpansion( 'notfoo', [alpha, whitespace, plus, whitespace, omega, plus, vary_expand], ['alpha', 'omega', 'varia...']) testutils.assert_raises( macro.expand, symtable.PepperSyntaxError, ["notfoo was given 2 arguments, but takes a minimum of 4"], # NOQA ['1', '2']) testutils.assert_raises( macro.expand, symtable.PepperSyntaxError, ["notfoo was given 0 arguments, but takes a minimum of 4"], []) testutils.assert_raises( macro.expand, symtable.PepperSyntaxError, ["Macro notfoo invoked without args, but is variadic"], None)