def test_lru(self): lru_limit = 2 cache = caches.DequeOutLRUCache(lru_limit) cache[1] = 1 cache[2] = 2 cache[3] = 3 expect(len(cache)).to(equal(2)) expect(cache[2]).to(equal(2)) expect(cache[3]).to(equal(3)) expect(cache.get(1)).to(be_none) expect(len(cache.out_deque)).to(be(1)) cache[4] = 4 expect(cache.get(2)).to(be_none) expect(len(cache.out_deque)).to(be(2))
def test_configures_container_information_protobuf(self): mesos_task = Task('id','name''slave-id').configure_container_protobuf() container_protobuf = mesos_task.task.container expect(container_protobuf.docker.image).to(equal('hussainsultan/dcenter')) expect(container_protobuf.docker.network).to(equal(self.MESOS_DOCKER_NETWORK_BRIDGE)) expect(container_protobuf.docker.force_pull_image).to(be(True)) expect(container_protobuf.docker.port_mappings[0].host_port).to(equal(33001)) expect(container_protobuf.docker.port_mappings[0].container_port).to(equal(8787))
def test_declines_offers_if_dscheduler_and_worker_are_already_running(self): task_director = MagicMock(spec=TaskDirector) task_director().make_task_with_id.return_value = 'task' task_director.reset_mock() scheduler = DistributedScheduler(task_director, self.id_generator) scheduler.started_dcenter=1 scheduler.started_dworker=1 scheduler.resourceOffers(self.driver, self.offers) expect(self.driver.declineOffer.called).to(be(True)) self.driver.declineOffer.assert_called_with(1)
def test_request_aggregation(self): req = _make_test_request(self.SERVICE_NAME, self.FAKE_OPERATION_ID) req = req.allocateQuotaRequest resp = sc_messages.AllocateQuotaResponse( operationId=self.FAKE_OPERATION_ID) item = quota_request.CachedItem(req, resp, self.SERVICE_NAME, None) expect(item._op_aggregator).to(be_none) with mock.patch.object(quota_request, 'QuotaOperationAggregator') as QOA: agg = QOA.return_value item.aggregate(req) expect(item._op_aggregator).to(be(agg)) QOA.assert_called_once_with(req.allocateOperation) item.aggregate(req) agg.merge_operation.assert_called_once_with(req.allocateOperation)
with Mock() as some_integration_instance: some_integration_instance.get_subject().returns(rx.subjects.Subject()) integration_config.loaded_integrations = { 'some_integration': some_integration_instance } with after.each: integrations.registered_integrations = {} integration_config.loaded_integrations = {} with it('returns the decorated function as is'): decorated_function = Spy().decorated_function expect(on_failure('some_integration')(decorated_function)).to(be(decorated_function)) with it('doesn\'t call the decorated function'): decorated_function = Spy().decorated_function on_failure('some_integration')(decorated_function) expect(decorated_function).to_not(have_been_called) with it('has the (convenient) side effect of registering the integration name with a subject'): decorated_function = Spy().decorated_function on_failure('some_integration')(decorated_function) expect(list(integrations.registered_integrations.keys())).to(contain_exactly(decorated_function.__name__))
from expects import expect, be from mamba import description, it from unittest.mock import MagicMock from crowd_anki.representation import deck_initializer DYNAMIC_DECK = {'dyn': True} TEST_DECK = "test deck" with description("Initializer from deck") as self: with it("should return None when trying to export dynamic deck"): collection = MagicMock() collection.decks.byName.return_value = DYNAMIC_DECK expect(deck_initializer.from_collection(collection, TEST_DECK)).to(be(None))
def test_constructor_should_accept_deques(self): a_deque = collections.deque() c = caches.DequeOutLRUCache(_TEST_NUM_ENTRIES, out_deque=a_deque) expect(c.out_deque).to(be(a_deque))
from mamba import description, context, it try: from unittest.mock import patch except ImportError: from mock import patch from expects import expect, be class ExampleClass(object): def hello(self): return 'Hello' with description('Testing with unittest.mock'): with context('when class method is mocked'): with it('returns mocked value'): with patch.object(ExampleClass, 'hello', return_value='World!') as mock_method: expect(mock_method()).to(be('World!'))
# coding: spec from expects import expect, be from noseOfYeti.tokeniser.support import noy_sup_setUp from unittest import TestCase import nose it 'exists': expect(False).to(be(True))
def test_inherits_fake_from_parent_context(self): parent = DependencyContext(supply_logging=True) child = DependencyContext(parent=parent) expect(child.logging).to(be(parent.logging))
def test_fake_logging_is_passthrough_to_real_logging(self): with dependency_context(supply_logging=True): injected = dependency(logging) expect(injected).to(be_a(Passthrough)) expect(injected._target).to(be(logging))
def test_does_not_supply_fake_unless_specified(self): with dependency_context(): expect(dependency(logging)).to(be(logging))
def test_user_api(self, client, token_generator): # Common headers go in this dict headers = { "content-type": "application/json", "authorization": f"bearer {token_generator.get_token(client)}", } response = client.get("/users", headers=headers) response_data = response.json expect(response.status_code).to(be(200)) expect(len(response_data["response"])).to(equal(1)) # Populate database with users post_users(USERS, client, token_generator.get_token(client)) # GET all users response = client.get("/users", headers=headers) response_data = response.json expect(response.status_code).to(be(200)) expect(len(response_data["response"])).to(be_above_or_equal(3)) added_users = response_data["response"] # Store ID for all users since we will break the data. added_user_ids = [] for user in added_users: added_user_ids.append(user["id"]) # Attempt to POST an existing user response = client.post("/users", data=json.dumps(USERS[0]), headers=headers) expect(response.status_code).to(be_above_or_equal(400)) # Get all users by ID for user in added_users: response = client.get("/users/{}".format(user["id"]), headers=headers) expect(response.status_code).to(be(200)) # Update a user with a PATCH user_id = added_users[len(added_users) - 1]["id"] new_person_id = str( reversed(added_users[len(added_users) - 1]["person_id"])) single_field_update = {"person_id": new_person_id} response = client.patch( "/users/{}".format(user_id), data=json.dumps(single_field_update), headers=headers, ) expect(response.status_code).to(equal(200)) # Rename a user with a PUT, expect to fail because not all fields specified response = client.put( "/users/{}".format(user_id), data=json.dumps(single_field_update), headers=headers, ) expect(response.status_code).to(equal(422)) # Rename a user with a PUT, providing the entire object user_to_update = added_users[len(added_users) - 1] user_to_update["password"] = "******" user_to_update.pop("role", None) user_to_update.pop("date_created", None) user_to_update.pop("id", None) user_to_update.pop("date_last_updated", None) response = client.put( "/users/{}".format(user_id), data=json.dumps(user_to_update), headers=headers, ) expect(response.status_code).to(equal(200)) # Delete users for user_id in added_user_ids: response = client.delete(f"/users/{user_id}", headers=headers) expect(response.status_code).to(be(200))
from unittest.mock import Mock from expects import expect, be from mamba import description, it from pollycast.bucket import Bucket with description("Bucket"): with it("should report file present when it is and return it"): episode_id = "episode_id" file_name = f"{episode_id}.voice_id.etc" s3_bucket = Mock() s3_bucket.objects.all.return_value = [Mock(key=file_name)] bucket = Bucket("test_name", Mock(return_value=s3_bucket)) expect(bucket.has_file(episode_id)).to(be(True)) expect(bucket.get_file(episode_id)).to(be(file_name))
def test_constructor_should_accept_deques(self): a_deque = collections.deque() c = caches.DequeOutTTLCache(3, 3, out_deque=a_deque) expect(c.out_deque).to(be(a_deque))
def test_as_class(self): injected = object() with dependency_context() as context: context.inject_as_class(Thing, injected) retrieved = dependency(Thing)() expect(retrieved).to(be(injected))
def validate_data_types(): validator = Validator(None) for field in TEST_VALID_FIELDS: if field['type'] == 'string': expect(validator.is_valid_string(field['good'])).to(be(True)) expect(validator.is_valid_string(field['bad'])).to(be(False)) elif field['type'] == 'integer': expect(validator.is_valid_integer(field['good'])).to(be(True)) expect(validator.is_valid_integer(field['bad'])).to(be(False)) elif field['type'] == 'float': expect(validator.is_valid_float(field['good'])).to(be(True)) expect(validator.is_valid_float(field['bad'])).to(be(False)) elif field['type'] == 'date': expect(validator.is_valid_date(field['good'])).to(be(True)) expect(validator.is_valid_date(field['bad'])).to(be(False)) elif field['type'] == 'url': expect(validator.is_valid_url(field['good'])).to(be(True)) expect(validator.is_valid_url(field['bad'])).to(be(False)) elif field['type'] == 'email': expect(validator.is_valid_email(field['good'])).to(be(True)) expect(validator.is_valid_email(field['bad'])).to(be(False))
with description('the threader module'): with it('should create as many threads as streams in the supplied dict'): a_stream = Mock() another_stream = Mock() a_tester = Spy().a_tester another_tester = Spy().another_tester stream_to_testers = { a_stream: [a_tester], another_stream: [a_tester, another_tester] } threads = threader.build_threads(stream_to_testers) expect(len(threads)).to(be(len(stream_to_testers))) with it('should initialize threads by calling the given target function'): a_stream = Mock() a_subject = Spy() target_function = Spy().target_function thread = threader._make_thread(target_function, a_stream, a_subject) thread.start() thread.join() expect(target_function).to(have_been_called.once) with it('should call the target function with the correct arguments'): a_stream = Mock()
from mamba import description, context, it, before from expects import expect, be_none, be from simpledatamigrate import repositories with description('SchemaVersion repository') as self: with before.each: self.data_schema = repositories.SchemaVersionRepository() with context('when query schema version'): with context('initial version case'): with it('returns none as initial schema version'): version = self.data_schema.current_schema() expect(version).to(be_none) with context('when change schema version'): with it('returns new state'): version = '001' self.data_schema.set_schema_version(version) current_version = self.data_schema.current_schema() expect(current_version).to(be(version))
from expects import expect, be, have_key from pysellus.stock_integrations import slack, integration_classes with description('the slack integration module'): with it('should be in the integration classes dictionary'): expect(integration_classes).to(have_key('slack')) expect(integration_classes['slack']).to(be(slack.SlackIntegration)) with it('should initialize with the correct arguments'): slack_url = 'an_url' slack_channel = 'a_channel' slack_instance = slack.SlackIntegration(slack_url) another_slack_instance = slack.SlackIntegration(slack_url, slack_channel) expect(slack_instance._url).to(be(slack_url)) expect(slack_instance._channel).to(be(None)) expect(another_slack_instance._url).to(be(slack_url)) expect(another_slack_instance._channel).to(be(slack_channel)) with it('should compose a correct on_next message'): slack_url = 'an_url' slack_element = { 'test_name': 'some test' } expected_payload = {
def test_can_replace_unhashable(self): with dependency_context() as context: thing = object() context.inject(os.environ, thing) expect(dependency(os.environ)).to(be(thing))
def check_disables_redirect(self, method): client = HttpClient() client.enable_cookies() getattr(client, method)("http://something") expect(self.send_spy["allow_redirects"]).to(be(False))
with it("should hash http-link form id's"): http_id = "http://example.com" entry = Entry(FeedParserDict(id=http_id), None) expect(entry.id).not_to(contain("http")) with it("should not change it if it is does not contain http"): entry = Entry(BASIC_INPUT_ENTRY, None) expect(entry.id).to(equal(EXAMPLE_ID)) with it("should be marked as processed if the file with given id is in the bucket" ): entry = Entry(BASIC_INPUT_ENTRY, mock_bucket(True)) expect(entry.processed).to(be(True)) with it("should redirect unset fields to input_entry"): test_field = "whee" entry = Entry(FeedParserDict(id=EXAMPLE_ID, test_field=test_field), None) expect(entry.test_field).to(equal(test_field)) with it("should use file in the bucket if the file for given id exists"): file_name = "mock_file_name" bucket = mock_bucket(True, file_name) entry = Entry(BASIC_INPUT_ENTRY, bucket) entry.file_name bucket.get_file.assert_called_with(EXAMPLE_ID)