def test_can_trap_errors_fails_if_error_does_not_happen(): class_name = "%s.RuntimeError" % RuntimeError.__module__ err = expect.error_to_happen(RuntimeError) try: with err: pass except AssertionError: error = sys.exc_info()[1] expect(error).to_have_an_error_message_of( 'Expected "%s" to happen but no errors happened during execution of with block.' % class_name ) else: expect.not_to_be_here() try: with expect.error_to_happen(RuntimeError): pass except AssertionError: error = sys.exc_info()[1] expect(error).to_have_an_error_message_of( 'Expected "%s" to happen but no errors happened during execution of with block.' % class_name ) else: expect.not_to_be_here()
def test_can_trap_errors_fails_if_error_does_not_happen(): class_name = "%s.RuntimeError" % RuntimeError.__module__ err = expect.error_to_happen(RuntimeError) try: with err: pass except AssertionError: error = sys.exc_info()[1] expect(error).to_have_an_error_message_of( 'Expected "%s" to happen but no errors happened during execution of with block.' % class_name) else: expect.not_to_be_here() try: with expect.error_to_happen(RuntimeError): pass except AssertionError: error = sys.exc_info()[1] expect(error).to_have_an_error_message_of( 'Expected "%s" to happen but no errors happened during execution of with block.' % class_name) else: expect.not_to_be_here()
async def test_should_raise_for_invalid_compatibility_storage(self): request = RequestParameters(url="/image.jpg", ) config = Config( FILE_LOADER_ROOT_PATH=STORAGE_PATH, STORES_CRYPTO_KEY_FOR_EACH_IMAGE=True, ) importer = Importer(config) importer.import_modules() image_bytes = self.get_image_bytes("image.jpg") ctx = Context(self.context.server, config, importer) ctx.request = request storage = Storage(ctx) with expect.error_to_happen( RuntimeError, message= ("The 'COMPATIBILITY_LEGACY_RESULT_STORAGE' configuration should point " "to a valid result storage when using compatibility result storage." ), ): await storage.get() with expect.error_to_happen( RuntimeError, message= ("The 'COMPATIBILITY_LEGACY_RESULT_STORAGE' configuration should point " "to a valid result storage when using compatibility result storage." ), ): await storage.put(image_bytes)
def test_task_get_by_task_id3(client): """Test getting a task by task id fails if task id is empty""" msg = "Task ID is required and can't be None or empty." with expect.error_to_happen(RuntimeError, message=msg): Task.get_by_task_id(None) with expect.error_to_happen(RuntimeError, message=msg): Task.get_by_task_id("")
def test_task_create2(client): """Test creating a new task fails when no task_id provided""" msg = "ValidationError (Task:None) (Field is required: ['task_id'])" with expect.error_to_happen(ValidationError, message=msg): Task.create_task(None) with expect.error_to_happen(ValidationError, message=msg): Task.create_task("")
def test_can_trap_errors(): err = expect.error_to_happen(RuntimeError) with err: raise RuntimeError("something is wrong") expect(err).to_have_an_error_message_of('something is wrong') with expect.error_to_happen(RuntimeError, message="something is wrong"): raise RuntimeError("something is wrong")
def test_can_trap_errors_unicode(): err = expect.error_to_happen(RuntimeError) with err: raise RuntimeError(six.u("algo está errado")) expect(err).to_have_an_error_message_of(six.u("algo está errado")) with expect.error_to_happen(RuntimeError, message=six.u("algo está errado")): raise RuntimeError(six.u("algo está errado"))
def test_exlude_failed_with_wrong_field_name(self): with expect.error_to_happen( ValueError, message="Invalid field 'wrong': Field not found in 'User'."): yield from User.objects.exclude("wrong").get(last_name="Else") with expect.error_to_happen(ValueError, message=("Invalid field 'embedded.wrong': " "Field not found in 'User'.")): yield from User.objects.exclude("embedded.wrong").get( last_name="Else")
def test_exlude_failed_with_wrong_field_name(self): with expect.error_to_happen( ValueError, message="Invalid field 'wrong': Field not found in 'User'." ): User.objects.exclude('wrong')\ .get(last_name="Else", callback=self.stop) with expect.error_to_happen( ValueError, message=("Invalid field 'embedded.wrong': " "Field not found in 'User'.") ): User.objects.exclude('embedded.wrong')\ .get(last_name="Else", callback=self.stop)
async def test_fails_without_func(self): with expect.error_to_happen( RuntimeError, message= "'func' argument can't be None when calling thumbor's compatibility layer.", ): await compatibility_get(1, second=2)
def test_field_required(self): # 'required' should not appear on the field err = expect.error_to_happen(KeyError) field = UserResource.first_name.json_schema() with err: field['required']
def test_status(self): with HTTMock(paynova_mock): with expect.error_to_happen(PaynovaException): self.paynova.request('POST', 'status/error') response = self.paynova.request('POST', 'status/success') expect(response).not_to_be_null()
def test_can_project_reference_field(self): posts = yield from Post.objects.only('title', 'category.name')\ .find_all(lazy=False) expect(posts).to_length(1) expect(posts[0].title).to_equal('post1 title') expect(posts[0].comments).to_length(0) expect(posts[0].text).to_be_null() expect(posts[0].category).to_be_instance_of(Category) expect(posts[0].category.name).to_equal('category1') expect(posts[0].category.descr).to_be_null() # the same with load_references posts = yield from Post.objects.only('title', 'category.name')\ .find_all(lazy=True) expect(posts).to_length(1) expect(posts[0].title).to_equal('post1 title') expect(posts[0].comments).to_length(0) expect(posts[0].text).to_be_null() with expect.error_to_happen(LoadReferencesRequiredError): cat = posts[0].category yield from posts[0].load_references() expect(posts[0].category).to_be_instance_of(Category) expect(posts[0].category.name).to_equal('category1') expect(posts[0].category.descr).to_be_null()
def test_cant_handle_exceptions_without_callback(self): @on_exception(None) def test_func(self): raise RuntimeError("Test") with expect.error_to_happen(RuntimeError): test_func(self)
def test_get_tree_of_non_existent_project_will_raise_exception(self): error_message = "Error when trying to obtain tree for path" \ " . on ref master of repository repository-fake " \ "(Error when trying to obtain tree . on ref master of repository repository-fake " \ "(Repository does not exist).). (Gandalf server response HTTP 400)" with expect.error_to_happen(GandalfException, message=error_message): tree = self.gandalf.repository_tree('repository-fake')
def test_adaptive_full_fit_in_fails_if_no_width_supplied(): with expect.error_to_happen( ValueError, message="When using fit-in or full-fit-in, " "you must specify width and/or height.", ): url_for(adaptive_full_fit_in=True, image_url=IMAGE_URL)
def test_can_project_reference_field(self): Post.objects.only('title', 'category.name').find_all( lazy=False, callback=self.stop ) posts = self.wait() expect(posts).to_length(1) expect(posts[0].title).to_equal('post1 title') expect(posts[0].comments).to_length(0) expect(posts[0].text).to_be_null() expect(posts[0].category).to_be_instance_of(Category) expect(posts[0].category.name).to_equal('category1') expect(posts[0].category.descr).to_be_null() # the same with load_references Post.objects.only('title', 'category.name').find_all( lazy=True, callback=self.stop ) posts = self.wait() expect(posts).to_length(1) expect(posts[0].title).to_equal('post1 title') expect(posts[0].comments).to_length(0) expect(posts[0].text).to_be_null() with expect.error_to_happen(LoadReferencesRequiredError): cat = posts[0].category posts[0].load_references(callback=self.stop) self.wait() expect(posts[0].category).to_be_instance_of(Category) expect(posts[0].category.name).to_equal('category1') expect(posts[0].category.descr).to_be_null()
def test_run2(client): """ Tests that a docker executor raises HostUnavailableError when host is not available when running a container and deletes host and port metadata from execution """ with client.application.app_context(): task, job, execution = JobExecutionFixture.new_defaults() _, pool_mock, client_mock = PoolFixture.new_defaults(r"test-.+") client_mock.containers.run.side_effect = requests.exceptions.ConnectionError( "failed") exe = Executor(app=client.application, pool=pool_mock) msg = "Connection to host host:1234 failed with error: failed" with expect.error_to_happen(HostUnavailableError, message=msg): exe.run( task, job, execution, "mock-image", "latest", "command", blacklisted_hosts=set(), ) expect(execution.metadata).not_to_include("docker_host") expect(execution.metadata).not_to_include("docker_port")
def test_mark_as_done2(client): """ Tests marking a container as done raises HostUnavailableError when docker host is not available """ with client.application.app_context(): containers = [ ContainerFixture.new( container_id="fastlane-job-123", name="fastlane-job-123", stdout="stdout", stderr="stderr", ) ] _, pool_mock, _ = PoolFixture.new_defaults(r"test.+", max_running=1, containers=containers) task, job, execution = JobExecutionFixture.new_defaults( container_id="fastlane-job-123") executor = Executor(client.application, pool_mock) containers[0].rename.side_effect = requests.exceptions.ConnectionError( "failed") message = "Connection to host host:1234 failed with error: failed" with expect.error_to_happen(HostUnavailableError, message=message): executor.mark_as_done(task, job, execution)
def test_circuit6(client): """ Tests that when marking a container as done with a docker host that's not accessible, the circuit is open and a HostUnavailableError is raised """ with client.application.app_context(): client.application.config["DOCKER_CIRCUIT_BREAKER_MAX_FAILS"] = 1 task, job, execution = JobExecutionFixture.new_defaults( docker_host="localhost", docker_port=4567, container_id=str(uuid4())) pool = DockerPool(([None, ["localhost:4567"], 2], )) executor = Executor(client.application, pool) expect(executor.get_circuit("localhost:4567").current_state).to_equal( "closed") with expect.error_to_happen(HostUnavailableError): executor.mark_as_done(task, job, execution) expect(executor.get_circuit("localhost:4567").current_state).to_equal( "open")
def test_run3(client): """ Tests that a docker executor raises RuntimeError if no docker_host and docker_port available in execution """ with client.application.app_context(): task, job, execution = JobExecutionFixture.new_defaults() _, pool_mock, _ = PoolFixture.new_defaults(r"test-.+") exe = Executor(app=client.application, pool=pool_mock) del execution.metadata["docker_host"] del execution.metadata["docker_port"] msg = "Can't run job without docker_host and docker_port in execution metadata." with expect.error_to_happen(RuntimeError, message=msg): exe.run( task, job, execution, "mock-image", "latest", "command", blacklisted_hosts=set(), ) expect(execution.metadata).not_to_include("docker_host") expect(execution.metadata).not_to_include("docker_port")
def test_when_invalid_configuration_of_filename_with_context_should_be_error( self, ): cfg = Config( ERROR_FILE_NAME_USE_CONTEXT="server..port", ERROR_FILE_LOGGER="toto", ) with expect.error_to_happen(RuntimeError): ErrorHandler(cfg)
def test_cant_delete_exactly_match(self): err = expect.error_to_happen(HTTPError) with err: yield self.http_client.fetch( self.get_url('/much/api'), method='DELETE' ) expect(err).to_have_an_error_message_of('HTTP 405: Method Not Allowed')
def test_can_set_error(self): err = expect.error_to_happen(HTTPError) with err: yield self.http_client.fetch( self.get_url('/much/error'), method='GET' ) expect(err).to_have_an_error_message_of('HTTP 404: Not Found')
def test_when_missing_dsn(self): self.config = Config( SECURITY_KEY="ACME-SEC", USE_CUSTOM_ERROR_HANDLING=True, ERROR_HANDLER_MODULE="thumbor.error_handlers.sentry", ) with expect.error_to_happen(RuntimeError): self.get_importer()
def test_convert_not_well_formed_svg_to_png(self): buffer = """<<svg width="10px" height="20px" viewBox="0 0 10 20" xmlns="http://www.w3.org/2000/svg"> <rect width="100%" height="10" x="0" y="0"/> </svg>""".encode('utf-8') with expect.error_to_happen(ParseError): self.engine.convert_svg_to_png(buffer) expect(self.engine.extension).to_be_null()
def test_proper_valigns(): """test_proper_haligns""" with expect.error_to_happen( ValueError, message=('Only "top", "middle" and "bottom"' " are valid values for vertical alignment."), ): url_for(valign="wrong", image_url=IMAGE_URL)
def test_convert_not_well_formed_svg_to_png(self): buffer = b"""<<svg width="10px" height="20px" viewBox="0 0 10 20" xmlns="http://www.w3.org/2000/svg"> <rect width="100%" height="10" x="0" y="0"/> </svg>""" with expect.error_to_happen(ParseError): self.engine.convert_svg_to_png(buffer) expect(self.engine.extension).to_be_null()
def test_proper_haligns(): """test_proper_haligns""" with expect.error_to_happen( ValueError, message=('Only "left", "center" and "right"' " are valid values for horizontal alignment."), ): url_for(halign="wrong", image_url=IMAGE_URL)
def test_getting_invalid_user_fails_with_403(self): objectid = oid.ObjectId() err = expect.error_to_happen(HTTPError) with err: yield self.http_client.fetch( self.get_url('/user/%s' % objectid) ) expect(err.error.code).to_equal(404)
def test_validate_config_security_key(self): server_parameters = mock.Mock(security_key=None) conf = Config(SECURITY_KEY=None) with expect.error_to_happen( RuntimeError, message="No security key was found for this instance of thumbor. " "Please provide one using the conf file or a security key file."): validate_config(conf, server_parameters)
def test_fields_failed_with_wrong_field_name(self): with expect.error_to_happen( ValueError, message="Invalid field 'wrong': Field not found in 'User'."): yield from User.objects.fields(wrong=QueryFieldList.ONLY).get( last_name="Else") with expect.error_to_happen(ValueError, message=("Invalid field 'embedded.wrong': " "Field not found in 'User'.")): yield from User.objects.fields( embedded__wrong=QueryFieldList.EXCLUDE).get(last_name="Else") with expect.error_to_happen(ValueError, message=("Invalid field 'embedded.wrong': " "Field not found in 'User'.")): yield from User.objects.fields(slice__embedded__wrong=10).get( last_name="Else")
def test_when_invalid_path(self): self.config = Config( SECURITY_KEY="ACME-SEC", USE_CUSTOM_ERROR_HANDLING=True, SENTRY_DSN_URL="https://[email protected]/12345", ERROR_HANDLER_MODULE="thumbor.error_handlers.invalid", ) with expect.error_to_happen(ImportError): self.get_importer()
def test_webhooks_2(**kwargs): """Test webhooks fail on 500""" rm = kwargs["rm"] url = "http://some.test.url" text = "whatever" headers = {"qwe": "rty"} rm.get(url, text=text, status_code=500, headers=headers) h = webhooks.WebhooksDispatcher() msg = 'The GET request to http://some.test.url with body of "whatever..." failed with status code of %d.' with expect.error_to_happen(webhooks.WebhooksDispatchError, message=msg % 500): h.dispatch("get", url, text, {}) rm.get(url, text=text, status_code=400, headers=headers) with expect.error_to_happen(webhooks.WebhooksDispatchError, message=msg % 400): h.dispatch("get", url, text, {})
async def test_queueing_task_when_no_pool_runs_sync_and_exception_happens(): instance = ThreadPool.instance(0) expect(instance).not_to_be_null() exception = Exception("Boom") def add(): raise exception with expect.error_to_happen(Exception, message="Boom"): await instance.queue(add)
async def test_can_run_task_in_foreground_and_exception_happens(): instance = ThreadPool.instance(0) expect(instance).not_to_be_null() exception = Exception("Boom") def add(): raise exception with expect.error_to_happen(Exception, message="Boom"): await instance._execute_in_foreground(add)
def test_should_be_an_error(self): iurl = self.get_image_url('image_3.jpg') ibytes = self.get_image_bytes('image.jpg') storage = FileStorage(self.context) storage.put(iurl, ibytes) with expect.error_to_happen( RuntimeError, message="STORES_CRYPTO_KEY_FOR_EACH_IMAGE can't be True if no SECURITY_KEY specified" ): storage.put_crypto(iurl)
def test_can_delete(self): user = fix.UserFactory.create() response = yield self.http_client.fetch( self.get_url('/user/%s' % user.id), method='DELETE' ) expect(response.code).to_equal(200) expect(response.body).to_equal('OK') with expect.error_to_happen(mongoengine.errors.DoesNotExist): models.User.objects.get(id=user.id)
async def test_should_be_an_error(self): iurl = self.get_image_url("image_3.jpg") ibytes = self.get_image_bytes("image.jpg") storage = FileStorage(self.context) await storage.put(iurl, ibytes) msg = "STORES_CRYPTO_KEY_FOR_EACH_IMAGE can't be True if no SECURITY_KEY specified" with expect.error_to_happen( RuntimeError, message=msg, ): await storage.put_crypto(iurl)
def test_validate_null_gifsicle_path(self, which_mock): server_parameters = mock.Mock(security_key=None) conf = Config(SECURITY_KEY='test', USE_GIFSICLE_ENGINE=True) which_mock.return_value = None with expect.error_to_happen( RuntimeError, message="If using USE_GIFSICLE_ENGINE configuration to True, " "the `gifsicle` binary must be in the PATH and must be an executable." ): validate_config(conf, server_parameters)
def test_can_trap_errors_fails_if_wrong_error(): class_name = "%s.RuntimeError" % RuntimeError.__module__ value_class_name = "%s.ValueError" % ValueError.__module__ err = expect.error_to_happen(RuntimeError) try: with err: raise ValueError("something else entirely") except AssertionError: error = sys.exc_info()[1] expect(error).to_have_an_error_message_of('Expected "%s" to happen but "%s" happened during execution of with block.' % (class_name, value_class_name)) else: expect.not_to_be_here()
def test_can_get_user_instance_with_custom_queryset(self): user = models.CustomQuerySet(prop="Bernardo Heynemann") user.save(self.server.application.db) user = models.CustomQuerySet(prop="Rafael Floriano") user.save(self.server.application.db) err = expect.error_to_happen(HTTPError) with err: yield self.http_client.fetch( self.get_url('/custom_query_set/%s' % user.id), ) expect(err.error.code).to_equal(404)
async def test_unique_field(self): class UniqueFieldDocument(Document): name = StringField(unique=True) await UniqueFieldDocument.objects.delete() await UniqueFieldDocument.ensure_index() await UniqueFieldDocument.objects.create(name="test") # msg = 'The index "test.UniqueFieldDocument.$name_1" was violated when trying to save this "UniqueFieldDocument" (error code: E11000).' with expect.error_to_happen(UniqueKeyViolationError): await UniqueFieldDocument.objects.create(name="test")
def test_cant_load_invalid_security_key_file(self): expected_msg = 'Could not find security key file at /bogus. Please verify the keypath argument.' with expect.error_to_happen(ValueError, message=expected_msg): ServerParameters( port=8888, ip='0.0.0.0', config_path='/tmp/config_path.conf', keyfile='/bogus', log_level='debug', app_class='app', fd='fd', gifsicle_path='gifsicle_path', )
def test_errors_on_gifsicle_should_raises_errors(self): engine = Engine(self.context) with open(join(STORAGE_PATH, "animated.gif"), "r") as im: buffer = im.read() engine.load(buffer, ".gif") with expect.error_to_happen( GifSicleError, message="gifsicle command returned errorlevel 1 for command" ' "{0} --some-invalid-opt /foo/' 'bar.gif" (image maybe corrupted?)'.format(self.server.gifsicle_path), ): engine.run_gifsicle("--some-invalid-opt")
def test_can_trap_errors_fails_if_wrong_error_message(): class_name = "%s.ValueError" % ValueError.__module__ err = expect.error_to_happen(ValueError, message="Woot?") try: with err: raise ValueError("something else entirely") except AssertionError: error = sys.exc_info()[1] expect(error).to_have_an_error_message_of( 'Expected "%s" to have a message of "Woot?", but the actual error was "something else entirely".' % class_name ) else: expect.not_to_be_here()
def test_document_failed_to_save_partly_loaded_document(self): User.objects.only('first_name')\ .get(first_name='Someone', callback=self.stop) user = self.wait() with expect.error_to_happen( PartlyLoadedDocumentError, message=( "Partly loaded document User can't be saved. Document should " "be loaded without 'only', 'exclude' or 'fields' " "QuerySet's modifiers" ) ): user.save(self.stop)
def test_fields_failed_with_wrong_field_name(self): with expect.error_to_happen( ValueError, message="Invalid field 'wrong': Field not found in 'User'." ): User.objects.fields(wrong=QueryFieldList.ONLY)\ .get(last_name="Else", callback=self.stop) with expect.error_to_happen( ValueError, message=("Invalid field 'embedded.wrong': " "Field not found in 'User'.") ): User.objects.fields(embedded__wrong=QueryFieldList.EXCLUDE)\ .get(last_name="Else", callback=self.stop) with expect.error_to_happen( ValueError, message=("Invalid field 'embedded.wrong': " "Field not found in 'User'.") ): User.objects.fields(slice__embedded__wrong=10)\ .get(last_name="Else", callback=self.stop)
def test_can_resize_images_with_detection_error_not_ignoring_it(self): test_data = TestData( source_width=800, source_height=600, target_width=400, target_height=150, halign="center", valign="middle", focal_points=[], crop_left=0, crop_top=75, crop_right=800, crop_bottom=375 ) context = test_data.to_context(detectors=[MockErrorSyncDetector], ignore_detector_error=False) trans = Transformer(context) with expect.error_to_happen(Exception, message='x'): trans.transform(None) expect(test_data.engine.calls['resize']).to_length(0)
def test_queryset_failed_to_save_partly_loaded_document(self): User.objects.only('first_name').filter(first_name='Someone')\ .order_by(User.index).find_all(callback=self.stop) users = self.wait() expect(users).to_length(1) with expect.error_to_happen( PartlyLoadedDocumentError, message=( "Partly loaded document User can't be saved. Document should " "be loaded without 'only', 'exclude' or 'fields' " "QuerySet's modifiers" ) ): User.objects.save(users[0], callback=self.stop)
def test_get_repository_tags_raise_exception_if_cannot_obtain_refs(self, m): repo = str(uuid.uuid4()) url = 'http://*****:*****@globo.com>\tThu Jul 10 15:19:41 2014 -0300\t' u'Fulano de Tal\t<*****@*****.**>\tThu Jul 10 15:19:41 2014 -0300\t' u'Mantém configuração original da aplicação XPTO\n' u'6f3a27b391d65e0526acd152db9a1c3747791ff1\t1.2.3-xpto\t\t\t\t\t\t\t' ) error = u'Error when trying to obtain the refs of repository %s ' % repo error += u'(Invalid git for-each-ref output [%s]).' % for_each_ref_out message = u'Error when trying to obtain tags on ref of repository %s (%s).' % (repo, error) m.get(url, text=message, status_code=400) with expect.error_to_happen(GandalfException): self.gandalf.repository_get(repo)
def test_can_create_unique_user(self): models.UniqueUser.objects.delete() models.UniqueUser(name="unique").save() err = expect.error_to_happen(HTTPError) with err: yield self.http_client.fetch( self.get_url('/unique_user/'), method='POST', body='name=unique' ) expect(err.error.code).to_equal(409) encoding = locale.getdefaultlocale()[1] expect('unique keys' in err.error.response.body.decode(encoding)).to_be_true()
def test_cannot_add_mandate_events_twice(self): date = datetime.utcnow().date() mandate_events_type = MandateEventsTypeFactory.create() mandate = MandateFactory.create() MandateEventsFactory.create( mandate_events_type=mandate_events_type, date=date, mandate=mandate ) with expect.error_to_happen(IntegrityError): MandateEventsFactory.create( mandate_events_type=mandate_events_type, date=date, mandate=mandate )
def test_can_create_invalid_user(self): models.ValidationUser.objects.delete() models.UniqueUser.objects.delete() user = models.UniqueUser(name="unique") user.save() err = expect.error_to_happen(HTTPError) with err: yield self.http_client.fetch( self.get_url('/validation_user/'), method='POST', body='items[]=%s' % user.id ) expect(err.error.code).to_equal(400) expect(err.error.response.body).to_equal("ValidationError (ValidationUser:None) (Field is required: ['name'])")