def test_post_user_reactivate(self, mocker, client, user, oauth_client): mocker.patch( "authlib.integrations.flask_oauth2.ResourceProtector.acquire_token", return_value=True, ) response = client.post("/users?action=deactivate", data=json.dumps({"id": user.id}), headers={}) expect(response.status_code).to(equal(200)) # Activate user response = client.post("/users?action=activate", data=json.dumps({"id": user.id}), headers={}) expect(response.status_code).to(equal(200)) # Assert that 'active' and 'can_login' have been toggled to 'True' response = client.get("/users/{}".format(user.id), headers={}) expect(response.json["response"]["active"]).to(be(True)) expect(response.json["response"]["can_login"]).to(be(True)) # Assert that associated client has a secret response = client.get('/clients/{}'.format(oauth_client.id), headers={}) expect(response.json['response']['client_secret']).to(have_len(48)) # Clean up (n.b., clean up should happen in the conftest – between each test.) client.delete(f"/users/{user.id}", headers={})
async def test_get_all(self, *args): with asynctest.patch.object(DB, 'fetch_members') as fetch_members_mock: response_codes_id = 'some-id' expected_cache = { 'endpoint': 'some-endpoint', 'timeout': 10, 'response_codes': response_codes_id, '_id': 'some-id' } expected_response_codes = [200, 300] mock_keys = ['some-id'] mock_db = MagicMock() mock_hgetall = CoroutineMock() mock_smembers = CoroutineMock() fetch_members_mock.return_value = mock_keys mock_hgetall.return_value = expected_cache mock_db.hgetall = mock_hgetall mock_db.smembers = mock_smembers mock_smembers.return_value = expected_response_codes caches = await EndpointCacher.get_all(mock_db) fetch_members_mock.assert_awaited() mock_hgetall.assert_awaited() mock_smembers.assert_awaited() expect(mock_smembers.await_args[0][0]).to(equal(response_codes_id)) expect(caches).to(have_len(1)) expect(caches[0]).to( equal( pydash.merge(expected_cache, {'response_codes': expected_response_codes})))
def it_should_return_the_correct_list_of_available_paths_equal_to_4_size(self): expected_paths = [ [self.vertexA, self.vertexB, self.vertexC, self.vertexD] ] expect(self.paths_equal_4_size).to(have_len(1)) for path in expected_paths: expect(self.paths_equal_4_size).to(contain(path))
def it_should_return_the_correct_list_of_available_paths(self): expected_paths = [ [self.vertexA, self.vertexC, self.vertexD, self.vertexA], [self.vertexA, self.vertexB, self.vertexC, self.vertexD, self.vertexA] ] expect(self.paths).to(have_len(2)) for path in expected_paths: expect(self.paths).to(contain(path))
def it_should_return_the_correct_list_of_available_paths_smaller_than_2_size(self): expected_paths = [ [self.vertexA, self.vertexD], [self.vertexA, self.vertexB, self.vertexD] ] expect(self.paths_less_than_cutoff).to(have_len(2)) for path in expected_paths: expect(self.paths_less_than_cutoff).to(contain(path))
def test_data_resources_endpoints(client, metrics_blob, mocker): response = _healthcheck_response(client, metrics_blob, mocker) expect(response).to(have_key('data_resources_metrics')) endpoints = response['data_resources_metrics'] expect(endpoints).to(have_len(1)) ep_names = [ep['endpoint'] for ep in endpoints] expected_ep_names = ['programs'] expect(expected_ep_names).to(equal(ep_names))
def test_mci_metrics_endpoints(client, metrics_blob, mocker): response = _healthcheck_response(client, metrics_blob, mocker) expect(response).to(have_key('mci_metrics')) endpoints = response['mci_metrics'] expect(endpoints).to(have_len(2)) ep_names = [ep['endpoint'] for ep in endpoints] expected_ep_names = ['users', 'gender'] expect(ep_names.sort()).to(equal(expected_ep_names.sort()))
def test_can_resolve_a_list_of_dependencies(): """ In this test we create a composite MessageSpeaker that depends on a list of MessageWriters. When we resolve the speaker, it should be provided with a list of all the registered writers. """ class BroadcastSpeaker: def __init__(self, writers: List[MessageWriter]) -> None: self.writers = writers container = Container() container.register(MessageWriter, StdoutMessageWriter) container.register(MessageWriter, TmpFileMessageWriter, path="my-file") container.register(MessageSpeaker, BroadcastSpeaker) instance = container.resolve(MessageSpeaker) expect(instance.writers).to(have_len(2))
expect((ok, res)).to(be_successful_api_call) expect(res).to(have_keys("ctx", "data")) expect(res["data"]).to(be_empty) with _context("and from the first event we retrieve the rest of events"): # Deactivated tests. There seems to be a bug in the API -- need confirmation with it("returns the list of all events except the first"): day_in_seconds = 7 * 24 * 60 * 60 _, res = self.client.get_policy_events_duration(day_in_seconds) ctx = {"cursor": res["data"][0]["cursor"]} qty_before = len(res["data"]) ok, res = self.client.get_more_policy_events(ctx) expect((ok, res)).to(be_successful_api_call) expect(res["data"]).to(have_len(qty_before - 1)) with context("when the parameters are wrong"): with it("returns an error retrieving events"): wrong_duration = -1 ok, res = self.client.get_policy_events_duration(wrong_duration) expect((ok, res)).to_not(be_successful_api_call) with it("returns an error with an incorrect context"): wrong_context = { "limit": -1, } call = self.client.get_more_policy_events(wrong_context) expect(call).to_not(be_successful_api_call)
expect((ok, res)).to(be_successful_api_call) expect(res).to( have_key("events", contain(have_key("name", equal(self.event_name))))) with it("retrieves an empty list when the name provided is not found"): ok, res = self.client.get_events(name="RandomUnexistingEvent") expect((ok, res)).to(be_successful_api_call) expect(res).to(have_key("events", be_empty)) with it("is able to retrieve the last event only"): ok, res = self.client.get_events(limit=1) expect((ok, res)).to(be_successful_api_call) expect(res).to(have_key("events", have_len(1))) with it("is able to retrieve the events from the last day"): to_s = datetime.now() from_s = to_s - timedelta(weeks=2) ok, res = self.client.get_events(from_s=from_s, to_s=to_s) expect((ok, res)).to(be_successful_api_call) expect(res).to(have_key("events", have_len(be_above_or_equal(1)))) with context("but the from and to parameters are incorrectly specified"): with it("returns an error if any of the parameters is specified but not the other" ): t = datetime.now() - timedelta(weeks=2) ok1, res1 = self.client.get_events(from_s=t) ok2, res2 = self.client.get_events(to_s=t)
with description("App spec"): with before.each: clean_db() load_data() self.client = app.test_client() with after.all: clean_db() with context("When listing"): with it("returns only apartments in the bounding box"): response = self.client.get('/apartments?la=1&lo=0&s=2&r=2&a=60') expect(response.status_code).to(equal(200)) apartments = json.loads(response.get_data().decode()) expect(apartments).to(have_len(2)) for flat in apartments: expect(flat).to(have_key("lat", '1')) if flat['lon'] == '1': expect(flat).to(have_keys({"rooms": 2, "area": '50'})) else: expect(flat).to(have_keys({"rooms": 3, "area": '60'})) with it("returns empty list when out of the bounding box"): response = self.client.get('/apartments?la=3&lo=3&s=2&r=2&a=60') expect(response.status_code).to(equal(200)) apartments = json.loads(response.get_data().decode()) expect(apartments).to(have_len(0)) with it("returns only apartments with +-1 rooms"): response = self.client.get('/apartments?la=1&lo=0&s=2&r=1&a=60')
def it_should_have_the_correct_number_of_vertices(self): expect(self.graph.vertices).to(have_len(4))
def it_should_have_the_correct_number_of_edges(self): expect(self.graph.edges).to(have_len(5))
def it_should_return_the_urls_for_alice_with_status_200(self): expect(self.alice_status).to(equal(200)) expect(self.result_alice['count']).to(equal(2)) expect(self.result_alice['items']).to(have_len(2)) expect(self.result_alice['items'][0]['url']).to(equal("http://url.2")) expect(self.result_alice['items'][1]['url']).to(equal("http://url.1"))
from specs.helpers.test_message_queue import TestMessageQueue from specs.helpers.mamba_keywords import description, it from src.actions.create_auction import CreateAuction with description('Create Auction'): #TODO: use the aggregate in the action with it('raises an auction created event'): with Stub() as id_generator: id_generator.new_id().delegates(['an_auction_id']) message_queue = TestMessageQueue() create_auction = CreateAuction(message_queue, id_generator) create_auction.execute({ 'auctioner': 'an_auctioner_id', 'item': 'an_item_id', 'period': 'anything', 'selling_price': 600 }) raised_events = message_queue.events expect(raised_events).to(have_len(1)) expect(message_queue.events[0]).to(equal({ 'type': 'AUCTION_CREATED', 'auction_id': 'an_auction_id', 'auctioner': 'an_auctioner_id', 'item': 'an_item_id', 'period': 'anything', 'selling_price': 600 }))
def we_should_have_loaded_a_single_issue(self): expect(self.issues).to(have_len(1))
def check_apartments(subject): expect(subject).to(be_a(list)) expect(subject).to(have_len(2)) for rec in subject: expect(rec).to(have_keys('area', 'lat', 'lon', 'rooms'))
with it('does not set any url'): finding = self.mapper.create_from(fixtures.event_falco()) expect(finding.url).to(be_none) with context('when checking the finding_id'): with it('uses an uuid as id'): finding = self.mapper.create_from(fixtures.event_falco()) expect(finding.finding_id).to(be_an_uuid()) with it('uses a shorter value than allowed by Google'): finding = self.mapper.create_from(fixtures.event_falco()) expect(finding.finding_id).to(have_len(be_below_or_equal(32))) with it('has a resource name empty'): finding = self.mapper.create_from(fixtures.event_falco()) expect(finding.resource_name).to(be_the_organization_resource_name()) with it('adds output'): output = "A shell was spawned in a container with an attached terminal (user=root unruffled_hamilton (id=32c415f00958) shell=bash parent=<NA> cmdline=bash terminal=34816)" finding = self.mapper.create_from(fixtures.event_falco()) expect(finding.summary).to(equal(output)) with it('adds priority'): finding = self.mapper.create_from(fixtures.event_falco())
def it_should_return_the_urls_for_bob_with_status_200(self): expect(self.bob_status).to(equal(200)) expect(self.result_bob['count']).to(equal(1)) expect(self.result_bob['items']).to(have_len(1)) expect(self.result_bob['items'][0]['url']).to(equal("http://url.3"))
from mamba import description, before, context, it, _it from expects import expect, equal, raise_error, have_len import xml.etree.ElementTree as ET import subprocess with description("Integration tests") as self: with it("should produce the expected graphml"): result = subprocess.check_output( "bunnyplot http://localhost:15672 ./out.graphml -u guest -p guest", shell=True) ns = {'g': 'http://graphml.graphdrawing.org/xmlns'} root = ET.parse('./out.graphml').getroot() print(root) nodes = root.findall(".//g:node", ns) edges = root.findall(".//g:edge", ns) expect(nodes).to(have_len(13)) expect(edges).to(have_len(11))
def it_should_send_an_email(self): expect(self.emailer.sent).to(have_len(1))
def it_should_not_have_raised_issue_assigned(self): expect(self.issue.events).to(have_len(0))
'price': 9.99, 'name': 'An Item', } } with Stub() as events_repository: events_repository.get_by_basket_id(ANY_ARG).returns([ create_basket_created_event(basket_id), ]) consumer = BasketConsumer(events_repository=events_repository, items_repository=items_repository) next_events = consumer.process(add_item_command) expect(next_events).to(have_len(1)) expect(next_events[0]).to( have_keys({ 'kind': ITEM_ADDED, 'payload': { 'basket_id': basket_id, 'item_id': item_id, 'item_name': 'An Item', 'item_price': 9.99, } })) with context('When processing a checkout command'): with it('generates a pay_order command and a checkout_started event'): basket_id = 'a_basket_id'
def the_handler_should_have_created_a_new_issue(self): expect(self.issues).to(have_len(1))
item=AN_ITEM_ID, expiration_date=expiration_date, selling_price=price) with description('Auction'): with it('is created'): expected_price = 600 auction = Auction.create(auction_id=AN_AUCTION_ID, auctioneer=AN_AUCTIONEER_ID, item=AN_ITEM_ID, expiration_date=date.today(), selling_price=expected_price) expect(auction.events).to(have_len(1)) expect(auction.events[0]).to( equal({ 'type': Auction.AUCTION_CREATED_TYPE, 'auction_id': AN_AUCTION_ID, 'auctioneer': AN_AUCTIONEER_ID, 'item': AN_ITEM_ID, 'expiration_date': date.today().isoformat(), 'selling_price': expected_price })) with it('is not created when selling price is less than 1'): auction = lambda: auction_with(price=0) expect(auction).to( raise_error(AuctionError, 'selling price must be greater than 1'))
def it_should_return_the_urls_only_for_that_user(self): expect(self.result).to(have_len(2)) for item in self.result: expect(self.alice_urls).to(contain(item))