IRRELEVANT_PATH = spec_abspath('without_inner_contexts.py') PENDING_DECORATOR_PATH = spec_abspath('with_pending_decorator.py') PENDING_DECORATOR_AS_ROOT_PATH = spec_abspath( 'with_pending_decorator_as_root.py') WITH_RELATIVE_IMPORT_PATH = spec_abspath('with_relative_import.py') WITH_TAGS_PATH = spec_abspath('with_tags.py') WITH_FOCUS_PATH = spec_abspath('with_focus.py') def _load_module(path): example_collector = ExampleCollector([path]) return list(example_collector.modules())[0] with description(ExampleCollector): with context('when loading from file'): with it('loads module from absolute path'): module = _load_module(IRRELEVANT_PATH) expect(inspect.ismodule(module)).to(be_true) with it('loads module from relative path'): module = _load_module(spec_relpath('without_inner_contexts.py')) expect(inspect.ismodule(module)).to(be_true) #FIXME: Mixed responsabilities in test [collect, load]?? with context('when loading'): with it('orders examples by line number'): module = _load_module(spec_abspath('without_inner_contexts.py'))
from mamba import description, context, it from expects import expect, equal def fibonacci(index): pass with description('fibonacci specs'): with context('for index 0'): with it('has value 0'): index = 0 value = fibonacci(index) expect(value).to(equal(0))
#-*- coding: utf-8 -*- from spec.unit.fixtures import Internal, patch_gpod_module gpod = patch_gpod_module() from ipodio.track import Track from ipodio.database import Database from expects import expect from mamba import describe, context, before with describe(Database) as _: with context('when fabricated'): def should_have_an_internal_database(): expect(_.fabricated.internal).to.be.an(_.internal_class) with context('when constructed'): def should_have_an_empty_index(): expect(_.database.index).to.be.empty def should_be_marked_as_not_updated(): expect(_.database.updated).to.be.false with context('when calling find_by_hash'): def should_return_an_empty_collection(): expect(_.database.find_by_hash(_.hash)).to.be.empty
with describe('ipodio playlist create') as _: @before.all def setup_all(): _.playlist_name = 'playlist' update_environment(_) bootstrap_ipod(_.mountpoint_path) def should_print_an_error(): execution = _.env.run(*_.cmd + ['playlist', 'create'], expect_error=True) expect(execution.stderr).to.have('Usage:') with context('given a playlist name'): def should_create_a_new_playlist(): execution = _.env.run(*_.cmd + ['playlist', 'create', 'name']) expect(execution.stdout).to.have('Created playlist: "name"') with context('given an existing playlist name'): def should_refuse_to_create_a_new_playlist(): execution = _.env.run(*_.cmd + ['playlist', 'create', _.playlist_name]) expect(execution.stdout).to.have( 'A playlist named "{}" already exists'.format(_.playlist_name)) @before.all def setup_with_playlists(): create_playlist(_.mountpoint_path, _.playlist_name)
from mamba import describe, it, context from unittest.mock import MagicMock from test_utils.anki import mock_anki_modules mock_anki_modules() from crowd_anki.export.anki_exporter_wrapper import AnkiJsonExporterWrapper DUMMY_EXPORT_DIRECTORY = "/tmp" TEST_DECK_ID = 1 with describe(AnkiJsonExporterWrapper) as self: with context("user is trying to export dynamic deck"): with it("should warn and exit without initiating export"): exporter_mock = MagicMock() notifier_mock = MagicMock() collection_mock = MagicMock() collection_mock.decks.get.return_value = {'dyn': True} subject = AnkiJsonExporterWrapper(collection_mock, TEST_DECK_ID, exporter_mock, notifier_mock) subject.exportInto(DUMMY_EXPORT_DIRECTORY) notifier_mock.warning.assert_called_once() exporter_mock.export_to_directory.assert_not_called()
def setup_all(): _.new_name = 'leño' _.playlist_name = 'playlist' _.existing_name = 'roña' update_environment(_) bootstrap_ipod(_.mountpoint_path) create_playlist(_.mountpoint_path, _.playlist_name) create_playlist(_.mountpoint_path, _.existing_name) def should_print_an_error(): execution = _.env.run(*_.cmd + ['playlist', 'rename'], expect_error=True) expect(execution.stderr).to.have('Usage:') with context('given a non existing playlist name'): def should_print_an_error_(): execution = _.env.run( *_.cmd + ['playlist', 'rename', _.new_name, _.playlist_name]) expect(execution.stdout).to.have('does not exist') with context('given an existing playlist name'): def should_print_an_error__(): execution = _.env.run(*_.cmd + ['playlist', 'rename'], expect_error=True) expect(execution.stderr).to.have('Usage:')
PENDING_DECORATOR_AS_ROOT_PATH = spec_abspath('with_pending_decorator_as_root.py') WITH_RELATIVE_IMPORT_PATH = spec_abspath('with_relative_import.py') WITH_TAGS_PATH = spec_abspath('with_tags.py') WITH_FOCUS_PATH = spec_abspath('with_focus.py') SHARED_CONTEXT_PATH = spec_abspath('with_shared_context.py') INCLUDED_CONTEXT_PATH = spec_abspath('with_included_context.py') HELPER_METHODS_PATH = spec_abspath('with_helper_methods.py') def _load_module(path): example_collector = ExampleCollector([path]) return list(example_collector.modules())[0] with description(ExampleCollector): with context('when loading from file'): with it('loads module from absolute path'): module = _load_module(IRRELEVANT_PATH) expect(inspect.ismodule(module)).to(be_true) with it('loads module from relative path'): module = _load_module(spec_relpath('without_inner_contexts.py')) expect(inspect.ismodule(module)).to(be_true) #FIXME: Mixed responsabilities in test [collect, load]?? with context('when loading'): with it('orders examples by line number'): module = _load_module(spec_abspath('without_inner_contexts.py'))
from expects import expect from mamba import describe, context, before, after from spec.ui._ipod_helpers import * from spec.ui._fixture import update_environment with describe('ipodio playlist') as _: @before.all def setup_all(): _.playlist_name = 'playlist' update_environment(_) bootstrap_ipod(_.mountpoint_path) with context('with an empty iPod'): def should_only_print_the_default_master_playlist(): execution = _.env.run(*_.cmd + ['playlist', 'list']) expect(execution.stdout).to.be.equal('my iPod\n') with context('given the master playlist name'): def should_print_nothing(): execution = _.env.run(*_.cmd + ['playlist', 'list', 'my iPod']) expect(execution.stdout).to.be.empty with context('given a non existing playlist name'): def should_print_a_non_existing_error(): execution = _.env.run(*_.cmd + ['playlist', 'list', 'foo'])
def __call__(self, fd, operation, data): expect(data).to.have.length(8) expect(operation).to.be(termios.TIOCGWINSZ) if self.fail: raise Exception('ioctl failure') return struct.pack('HHHH', *self._data) ioctl = IoctlMock() ioctl.monkey_patch() from ipodio.console import Console with describe(Console) as _: with context('when created'): def it_should_have_a_width_property(): expect(_.console()).to.have.property('width') with context('when accesing width'): def it_should_return_system_console_width(): expect(_.console().width).to.be(_.width) with context('when calling relative_width'): def it_should_return_the_proportional_size(): relative_width = _.console().relative_width(0.8) expect(relative_width).to.be(_.relative_width_80) with context('when ioctl fails'): def it_should_return_default_values():
from mamba import description, it, context with description('Fixture#with_inner_contexts'): with it('first example'): pass with it('second example'): pass with context('#inner_context'): with it('fourth example'): pass with it('third example'): pass
def it_should_fail_if_actual_has_key_without_expected_value(): with failure(_.dct, "to have key 'bar' with value 1 but was 0"): expect(_.dct).to.have.key('bar', 1) def it_should_fail_if_actual_has_key_without_none_value(): with failure(_.dct, "to have key 'bar' with value None but was 0"): expect(_.dct).to.have.key('bar', None) def it_should_fail_if_actual_is_not_a_dict(): # issue-10 with failure(_.str, "to have key 'foo' but not a dict"): expect(_.str).to.have.key('foo', 0) with context('#negated'): def it_should_pass_if_actual_does_not_have_expected_key(): expect(_.dct).not_to.have.key('foo') def it_should_pass_if_actual_does_not_have_expected_key_with_value(): expect(_.dct).not_to.have.key('foo', 0) def it_should_pass_if_actual_has_expected_key_without_value(): expect(_.dct).not_to.have.key('bar', 1) def it_should_fail_if_actual_has_expected_key(): with failure(_.dct, "not to have key 'bar'"): expect(_.dct).not_to.have.key('bar') def it_should_fail_if_actual_has_expected_key_with_value(): with failure(_.dct, "not to have key 'bar' with value 0 but was 0"):
from mamba import describe, context with describe("Fixture#with_inner_contexts"): def first_example(): pass def second_example(): pass with context("#inner_context"): def fourth_example(): pass def third_example(): pass
from mamba.example_group import ExampleGroup from mamba.example import Example with describe(ExampleGroup) as _: @before.each def create_example_group(): _.was_run = False _.example_group = an_example_group() _.reporter = Spy(reporter.Reporter) def it_should_have_same_name_than_subject(): expect(_.example_group.name).to.be.equals(IRRELEVANT_SUBJECT) with context('when run'): @before.each def append_examples_and_run_example_group(): _.example_group.append(an_example(_)) _.example_group.append(an_example(_)) _.example_group.run(_.reporter) def it_should_run_the_example(): expect(_.was_run).to.be.true def it_should_calculate_elapsed_time(): expect(_.example_group.elapsed_time.total_seconds()).to.be.greater_than(0) def it_notifies_that_a_example_group_is_started():
#-*- coding: utf-8 -*- from ipodio.track import Track from ipodio.database import Playlist from expects import expect from mockito import mock, when, verify, any from mamba import describe, context, before with describe(Playlist) as _: with context('when fabricated'): def should_have_an_internal_playlist(): expect(_.fabricated_playlist).to.have.property( 'internal', _.created_internal_playlist) def should_have_an_internal_database(): verify(_.internal_playlist).constructor( _.database.internal, _.playlist_name) with context('the name property'): def should_be_the_playlist_name(): expect(_.playlist.name).to.be.equal(_.playlist_name) def should_be_editable(): _.playlist.name = 'foo' verify(_.internal_playlist).set_name('foo') with context('the tracks property'): def should_be_a_list():
#-*- coding: utf-8 -*- from ipodio.track import Track from ipodio.database import Playlist from expects import expect from mockito import mock, when, verify, any from mamba import describe, context, before with describe(Playlist) as _: with context('when fabricated'): def should_have_an_internal_playlist(): expect(_.fabricated_playlist).to.have.property( 'internal', _.created_internal_playlist) def should_have_an_internal_database(): verify(_.internal_playlist).constructor(_.database.internal, _.playlist_name) with context('the name property'): def should_be_the_playlist_name(): expect(_.playlist.name).to.be.equal(_.playlist_name) def should_be_editable(): _.playlist.name = 'foo' verify(_.internal_playlist).set_name('foo') with context('the tracks property'):
from mamba import describe, context, before from sure import expect from doublex import * from spec.object_mother import * from mamba import reporter from mamba.example import PendingExample with describe(PendingExample) as _: @before.each def create_pending_example_and_reporter(): _.was_run = False _.example = a_pending_example(_) _.reporter = Spy(reporter.Reporter) with context('when run'): @before.each def run_pending_example(): _.example.run(_.reporter) def it_should_not_run_the_example(): expect(_.was_run).to.be.false def it_notifies_is_pending(): assert_that(_.reporter.example_pending, called().with_args(_.example))
from doublex import Stub, ANY_ARG from expects import expect, equal, be_a, have_keys, have_len from mamba import description, it, context, before from apartments import get_apartments 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 description("Apartments Spec"): with context("When no data"): with it("returns empty list"): with Stub() as db: db.execute_query(ANY_ARG).returns([]) expect( get_apartments(db=db, longitude=1, latitude=1, side=1, rooms=1, area=1)).to(equal([])) expect(get_apartments(db=db)).to(equal([])) with context("When there is data"): with before.each: self.apartments = [{
with describe('ipodio rm') as _: @before.all def setup_all(): update_environment(_) bootstrap_ipod(_.mountpoint_path) def should_return_an_error_when_called_without_arguments(): execution = _.env.run(*_.cmd + ['rm'], expect_error=True) expect(execution.stderr).to.have("Usage:") def should_return_an_error_when_rm_with_bad_expressions(): execution = _.env.run(*_.cmd + ['rm', _.bad_expression], expect_error=True) expect(execution.stdout).to.have("Error: Invalid expression") def should_print_message_when_removing_no_songs(): execution = _.env.run(*_.cmd + ['rm', 'foobarbaztaz']) expect(execution.stdout).to.have("No tracks removed.") with context('with songs in the iPod'): def should_list_all_songs_that_were_removed(): populate_ipod(_.mountpoint_path, _.songs) execution = _.env.run(*_.cmd + ['-y', 'rm', '.']) expect(execution.stdout.count('\n')).to.be(2 + len(_.songs))
from mamba import context, description, it from util.payslip_functional import calc_tax with description("calculate_tax"): # with context("given a annual salary") as cont: # with it("when salary is 17000"): expected_income_tax = 0 response_income_tax = calc_tax(17000) assert response_income_tax == expected_income_tax with it("when salary is 20000"): expected_income_tax = 29 response_income_tax = calc_tax(20000) assert response_income_tax == expected_income_tax with it("when salary is 60000"): expected_income_tax = 921 response_income_tax = calc_tax(60000) assert response_income_tax == expected_income_tax with it("when salary is 100000"): expected_income_tax = 2053 response_income_tax = calc_tax(100000) assert response_income_tax == expected_income_tax with it("when salary is 200000"): expected_income_tax = 5270 response_income_tax = calc_tax(200000)
with describe('ipodio playlist rm') as _: @before.all def setup_all(): _.playlist_name = 'playlist' update_environment(_) bootstrap_ipod(_.mountpoint_path) populate_ipod(_.mountpoint_path, _.songs) def should_print_an_error_message(): execution = _.env.run(*_.cmd + ['playlist', 'rm'], expect_error=True) expect(execution.stderr).to.have('Usage:') with context('given the master playlist name'): def should_print_an_error__(): execution = _.env.run(*_.cmd + ['playlist', 'rm', 'my iPod']) expect(execution.stdout).to.have('Cannot remove master playlist') with context('given an unknown playlist name'): def should_print_an_error_(): execution = _.env.run(*_.cmd + ['playlist', 'rm', 'foo', _.expression, '--yes']) expect(execution.stdout).to.have('does not exist') with context('given a playlist name'): def should_delete_the_playlist(): execution = _.env.run(*_.cmd + ['playlist', 'rm', _.playlist_name, '--yes']) expect(execution.stdout).to.have('')
from unittest.mock import MagicMock from expects import expect, contain from mamba import describe, it, context from test_utils.anki import mock_anki_modules mock_anki_modules() from aqt import mw from crowd_anki.config.config_settings import ConfigSettings, NoteSortingMethods with describe(ConfigSettings) as self: with context("someone interacts with any config setting"): with it("do not sort / sort by none"): config = ConfigSettings(mw.addonManager, { "automated_snapshot": True }) assert config.automated_snapshot with it("get all the NoteSortingMethod values"): valid_sorting_methods = list(NoteSortingMethods.values()) assert len(valid_sorting_methods) > 0 assert isinstance(valid_sorting_methods, list) with it("tries to find the invalid config entries"): config = ConfigSettings(mw.addonManager) valid_sorting_methods = list(NoteSortingMethods.values())
from mamba import describe, context, pending with describe('Fixture#with_pending_decorator'): @pending def pending_spec(): pass with pending(context('when pending context')): pass
with describe('length'): def it_should_pass_if_actual_has_the_expected_length(): expect('foo').to.have.length(3) def it_should_fail_if_actual_does_not_have_the_expected_length(): actual = 'foo' with failure(actual, 'to have length 2 but was 3'): expect(actual).to.have.length(2) def it_should_pass_if_actual_iterable_has_the_expected_length(): expect(iter('foo')).to.have.length(3) def it_should_fail_if_actual_iterable_does_not_have_the_expected_length(): actual = iter('foo') with failure(actual, 'to have length 2 but was 3'): expect(actual).to.have.length(2) with context('#negated'): def it_should_pass_if_actual_does_not_have_the_expected_length(): expect('foo').not_to.have.length(2) def it_should_fail_if_actual_has_the_expected_length(): actual = 'foo' with failure(actual, 'not to have length 3 but was 3'): expect(actual).not_to.have.length(3)
# -*- coding: utf-8 -*- from ipodio.cli import Options from expects import expect from mamba import describe, context, before with describe(Options) as _: with context('when created'): def it_should_have_a_docopt_parsing_result_as_input(): Options(_.parsed_input) def it_should_take_a_dictionary_of_defaults_as_input(): Options(_.parsed_input, _.defaults) def it_should_have_a_defaults_property(): expect(_.options).to.have.property('defaults') def it_should_have_an_options_property(): expect(_.options).to.have.property('options') def it_should_have_all_options_in_the_options_property(): expect(_.options.options).to.equal(_.all_options) def it_should_have_an_arguments_property(): expect(_.options).to.have.property('arguments') def it_should_have_all_arguments_in_the_arguments_property(): expect(_.options.arguments).to.equal(_.all_arguments)
# Test ceases for messageset admin_1 import os from mamba import description, context, it from expects import expect, equal from common.CommonUtils import * # CSPLIST is defined in hw_disc.txt in JSON format, you can define any alias for the port, CSP1 and CSP2 is used for a B2B setup with description('Admin:', 'admin') as self: with context('when a chassis is given,'): with context('and connects to the chassis,'): with before.all: # Don't use multiple before.all/after.all(or .each) in different contexts, see https://github.com/nestorsalceda/mamba/issues/130 for details # using the first chassis/slot/port self.chassis = '172.18.0.2' self.slot = 1 self.port = 1 #print(os.environ) if os.environ.has_key('CSP1'): (self.chassis, self.slot, self.port) = extract_chassis(os.environ['CSP1']) # conn and msg_set is a must for calling send_message self.conn = connect_chassis(self.chassis) self.msg_set_name = 'admin_1' self.reservedports = False with after.all: # Don't use multiple before.all/after.all(or .each) in different contexts, see https://github.com/nestorsalceda/mamba/issues/130 for details pass # The last test case has released the port with it('gets port group type'): msg_name = 'admin_1.GetPortGroupType' msg_content = {
# -*- coding: utf-8 -*- from mamba import describe, context from sure import expect from mamba.settings import Settings IRRELEVANT_SLOW_TEST_THRESHOLD = 'irrelevant slow test threeshold' IRRELEVANT_ENABLE_CODE_COVERAGE = 'irrelevant enable code coverage' IRRELEVANT_ENABLE_FILE_WATCHER = 'irrelevant enable file watcher' IRRELEVANT_NO_COLOR = 'irrelevant no color' with describe(Settings) as _: with context('when loading defaults'): def it_has_75_millis_as_slow_test_threshold(): expect(_.subject).to.have.property('slow_test_threshold').to.be.equal(0.075) def it_has_code_coverage_disabled_by_default(): expect(_.subject).to.have.property('enable_code_coverage').to.be.false def it_has_file_watcher_disabled_by_default(): expect(_.subject).to.have.property('enable_file_watcher').to.be.false def it_has_no_color_disabled_by_default(): expect(_.subject).to.have.property('no_color').to.be.false with context('when setting custom values'): def it_sets_slow_test_threshold(): _.subject.slow_test_threshold = IRRELEVANT_SLOW_TEST_THRESHOLD
from mamba import description, context, it from expects import expect, contain with description('checking if string contains a character'): with context('given a character and a string'): with context('when the string contains the character'): with it('returns true'): character = 'C' string = 'PyConES2018' expect(string).to(contain(character)) with context('when the string does NOT contain the character'): with it('return false'): character = 'x' string = 'PyConES2018' expect(string).not_to(contain(character))
client = EndpointClient()\ .set_default_data({ 'first_name': 'John', 'last_name': 'Smith', 'date_of_birth': '1989-11-27', 'email': '*****@*****.**', 'phone': '+12025550160' })\ .set_url('/users')\ .set_method('post') with description('POST /users') as self: with before.each: clean_database() with context('when creating a new contact'): with context('with correct arguments'): with before.each: self.response = client.request() with it('responds with 201'): expect(self.response.status_code).to(equal(201)) with it('dw with valid JSON'): expect(json.loads(self.response.content)).not_to( raise_error(ValueError)) with it('shows success message'): expect(self.response.content.decode()).to( contain('User successfully created', 'John', 'Smith'))
self.key = frozenset(key) self.handler = handler @property def handler_args(self): function = self.handler return function.func_code.co_varnames[: function.func_code.co_argcount] def call(self, **kwargs): expected_args = {name: kwargs.get(name) for name in self.handler_args} return self.handler(**expected_args) with describe(Command) as _: with context("the key property"): def should_be_a_frozenset(): expect(_.command.key).to.be.a(frozenset) def should_contain_the_given_key_words(): expect(_.command.key).to.have(*_.key) with context("the handler property"): def should_be_a_function(): expect(_.command.handler).to.be.a(types.FunctionType) def should_be_the_given_handler(): expect(_.command.handler).to.be(_.handler)
# -*- coding: utf-8 -*- from spec.unit.fixtures import Internal, patch_gpod_module patch_gpod_module() from ipodio.track import Track from expects import expect from mockito import mock, spy, when, verify, any from mamba import describe, context, before with describe(Track) as _: with context("when fabricated"): def should_have_an_internal_track(): expect(_.fabricated_track.internal).to.be.an(_.internal_class) with context("when constructed"): def should_have_an_internal_track_(): expect(_.track.internal).to.be.an(_.internal_class) def should_set_hash_to_none(): expect(_.track.hash).to.be(None) with context("when update_hash"): def should_compute_hash():
# -*- coding: utf-8 -*- from expects import * from scales import get_notes_of from mamba import describe, description, it, context with description('Generating get_notes_of'): with context("escala englimatic"): with it('escala_englimatic_primer_grado'): note = "C" scale = "escala_englimatic_primer_grado" expect(get_notes_of(scale, note)).to( equal(['C', 'Db', 'E', 'F#', 'G#', 'A#', 'B'])) with it('escala_englimatic_segundo_grado'): note = "C#" scale = "escala_englimatic_segundo_grado" expect(get_notes_of(scale, note)).to( equal(['Db', 'E', 'F#', 'G#', 'A#', 'B', 'C'])) with it('escala_englimatic_tercer_grado'): note = "E" scale = "escala_englimatic_tercer_grado" expect(get_notes_of(scale, note)).to( equal(['E', 'F#', 'G#', 'A#', 'B', 'C', 'Db']))
from spec.object_mother import * from mamba import reporter from mamba.example import Example with describe(Example) as _: @before.each def create_new_example_and_reporter(): _.was_run = False _.example = an_example(_) _.reporter = Spy(reporter.Reporter) with context('when run'): @before.each def run_example(): _.example.run(_.reporter) def it_should_run_the_example(): expect(_.was_run).to.be.true def it_should_calculate_elapsed_time(): expect(_.example.elapsed_time.total_seconds()).to.be.greater_than(0) def it_notifies_is_started(): assert_that(_.reporter.example_started, called().with_args(_.example)) def it_notifies_is_passed(): assert_that(_.reporter.example_passed, called().with_args(_.example))
outs, errs = server.communicate(timeout=5) print("Assertion failed in ctx mgr") if outs is not None: print("server STDOUT:") print(decode(outs, 'utf-8', 'replace')) if errs is not None: print("server STDERR:") print(decode(errs, 'utf-8', 'replace')) raise finally: server.kill() outs, errs = server.communicate() with description('Corpus Server') as self: with context('run in a directory with no mbox or DB'): with it('fails to run the server'): with corpus_server(mbox_path="nonex.mbox", wait=False) as server_info: poll = server_info["proc"].wait(timeout=30) expect(poll).to(equal(1)) with context('run in a directory with an empty mbox, but no DB'): with it('is able to return /status successfully'): with corpus_server() as server_info: response = requests.get("http://localhost:5000/status") expect(response.status_code).to(equal(200)) with it('is able to return /api/emails successfully with empty result' ):
from expects import expect from mamba import describe, context, before, after from spec.ui._ipod_helpers import * from spec.ui._fixture import update_environment with describe('ipodio playlist add') as _: @before.all def setup_all(): _.playlist_name = 'playlist' update_environment(_) bootstrap_ipod(_.mountpoint_path) populate_ipod(_.mountpoint_path, _.songs) with context('without a name'): def should_print_an_error(): execution = _.env.run(*_.cmd + ['playlist', 'add'], expect_error=True) expect(execution.stderr).to.have('Usage:') with context('given a name which is not an existing playlist'): def should_print_an_error_(): execution = _.env.run(*_.cmd + ['playlist', 'add', 'foo', _.expression]) expect( execution.stdout).to.have('The playlist "foo" does not exist')
from spec.object_mother import * from mamba import reporter from mamba.example import PendingExample from mamba.example_group import PendingExampleGroup with describe(PendingExampleGroup) as _: @before.each def create_example_group(): _.was_run = False _.example_group = a_pending_example_group() _.reporter = Spy(reporter.Reporter) with context('when run'): @before.each def append_examples_and_run_example_group(): _.example_group.append(a_pending_example(_)) _.example_group.run(_.reporter) def it_should_not_run_its_children(): expect(_.was_run).to.be.false def it_notifies_that_a_example_group_is_pending(): assert_that(_.reporter.example_group_pending, called().with_args(_.example_group)) with context('when adding a new examples as children'): def it_raises_a_type_error_if_is_not_a_pending_example():
from expects import equal, expect from mamba import describe, description, it, context from get_chords_by_scale import get_data_by with description("App pyChords"): with context('must return chord list:'): with it('must return chord list by a given note and scale'): note = 'C' scale = 'escala_mayor_natural' chord_deep = 1 expect(get_data_by(note, scale, chord_deep)).to( equal(['C', 'D-', 'E-', 'F', 'G', 'A-', 'B-'])) with it('must return chord list by a given note and scale'): note = 'D' scale = 'escala_dorica' chord_deep = 1 expect(get_data_by(note, scale, chord_deep)).to( equal(['D-', 'E-', 'F', 'G', 'A-', 'B-', 'C']))
from mamba import description, context, it import apple with description('Database Management') as self: with context('find a user'): with it('returns a user'): assert (apple.find_one_user("joe bloggs")) == "joe bloggs" with description('Database Management') as self: with context('find all users'): with it('returns all users'): assert (apple.find_user_count()) > 0 with description('Database Management') as self: with context('finsert a user'): with it('inserts a user'): apple.insert_one_user() assert (apple.find_one_user("winston wolf")) == "winston wolf" with description('Database Management') as self: with context('delete a user'): with it('delete a user'): apple.delete_one_user("winston wolf") assert (apple.find_one_user("winston wolf")) == None
'date_end': '20201031', 'type_import': 'perd_files' }, "losses_by_dict_TD": { 'tariffs': td_tariffs_list, 'date_start': '20210601', 'date_end': '20210630', 'type_import': 'perd_files' } } with description('A'): with before.each: pass with context('tariff losses iteration by tariff'): with it('must be performed as expected'): expected_count = len(tariffs_list) * len(subsystems_list) losses = Perdidas(**called['losses_by_dict']) for counter, a_loss in enumerate(losses, start=1): if a_loss is not None: print("Testing {} {}".format(a_loss.subsystem, a_loss.tariff)) else: print("Losses file not available in ESIOS") assert expected_count == counter, \ "Incongruent count of elements while iterating losses [expected '{}' vs '{}']".format( expected_count, counter) with context('Tariff losses download'):
verify_ssl=False) with it('creates a container in Phantom Server'): container = { 'name': 'My Container', 'description': 'Useful description of this container.', 'label': 'events', 'run_automation': False, 'severity': 'high', 'status': 'new', 'start_time': '2015-03-21T19:28:13.759Z', } container = self.phantom_client.create_container(container) expect(container['id']).not_to(be_none) with context('when an error happens'): with it('raises an error'): container = { 'description': 'Useful description of this container.', 'label': 'events', 'run_automation': False, 'severity': 'high', 'status': 'new', 'start_time': '2015-03-21T19:28:13.759Z', } expect(lambda: self.phantom_client.create_container(container))\ .to(raise_error(RuntimeError))
PENDING_DECORATOR_PATH = spec_abspath('with_pending_decorator.py') PENDING_DECORATOR_AS_ROOT_PATH = spec_abspath('with_pending_decorator_as_root.py') WITH_RELATIVE_IMPORT_PATH = spec_abspath('with_relative_import.py') WITH_TAGS_PATH = spec_abspath('with_tags.py') WITH_FOCUS_PATH = spec_abspath('with_focus.py') SHARED_CONTEXT_PATH = spec_abspath('with_shared_context.py') INCLUDED_CONTEXT_PATH = spec_abspath('with_included_context.py') def _load_module(path): example_collector = ExampleCollector([path]) return list(example_collector.modules())[0] with description(ExampleCollector): with context('when loading from file'): with it('loads module from absolute path'): module = _load_module(IRRELEVANT_PATH) expect(inspect.ismodule(module)).to(be_true) with it('loads module from relative path'): module = _load_module(spec_relpath('without_inner_contexts.py')) expect(inspect.ismodule(module)).to(be_true) #FIXME: Mixed responsabilities in test [collect, load]?? with context('when loading'): with it('orders examples by line number'): module = _load_module(spec_abspath('without_inner_contexts.py'))
SNMP_PORT = 1161 def snmp_integer(value): return types.PySnmpValue(types.PySnmpTypes().integer(value)) def snmp_octect_string(value): return types.PySnmpValue(types.PySnmpTypes().octect_string(value)) with description('SNMP Client') as self: with before.each: self.snmp_client = clients.PySnmpClient() with context('FEATURE: snmpget'): with context('happy path'): with it('returns the values'): oid1 = '1.3.6.1.4.1.4998.1.1.10.1.4.2.1.29.1.10' oid2 = '1.3.6.1.4.1.4998.1.1.10.1.4.2.1.29.1.11' result = self.snmp_client.get(SNMP_HOST, READ_ONLY_COMMUNITY, [oid1, oid2], port=SNMP_PORT) expect(result).to( equal([(oid1, snmp_integer(999)), (oid2, snmp_integer(31))])) with context('having an invalid community'):
from mamba import description, it, context from expects import expect, equal RETURN_VALUE = '42' with description('Refactoring goodies') as self: def a_method(self, return_value=RETURN_VALUE): return return_value with it('uses methods defined inside its context'): expect(self.a_method()).to(equal(RETURN_VALUE)) with context('when using nested contexts'): with it('uses methods defined inside its parent'): expect(self.a_method()).to(equal(RETURN_VALUE))
# -*- coding: utf-8 -* from mamba import describe, context from expects import expect from expects.testing import failure with describe("true"): def it_should_pass_if_actual_is_true(): expect(True).to.be.true def it_should_fail_if_actual_is_false(): with failure(False, "to be True"): expect(False).to.be.true with context("#negated"): def it_should_pass_if_actual_is_not_true(): expect(False).not_to.be.true def it_should_fail_if_actual_is_true(): with failure(True, "not to be True"): expect(True).not_to.be.true
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!'))
def it_adds_failed_example_when_example_failed(): _.reporter.example_failed(_.example) expect(_.example).to.be.within(_.reporter.failed_examples) def it_notifies_event_example_pending_to_listeners(): _.reporter.example_pending(_.example) assert_that(_.formatter.example_pending, called().with_args(_.example)) def it_increases_pending_counter_when_example_started(): _.reporter.example_pending(_.example) expect(_.reporter.pending_count).to.be.equal(1) with context('when reporting events for an example group'): @before.each def creates_example_group(): _.example_group = an_example_group() def it_notifies_event_example_group_started_to_listeners(): _.reporter.example_group_started(_.example_group) assert_that(_.formatter.example_group_started, called().with_args(_.example_group)) def it_notifies_event_example_group_finished_to_listeners(): _.reporter.example_group_finished(_.example_group) assert_that(_.formatter.example_group_finished, called().with_args(_.example_group)) def it_notifies_event_example_group_pending_to_listeners():
def should_return_an_error_with_no_files(): execution = _.env.run(*_.cmd + ['push'], expect_error=True) expect(execution.stderr).to.have('Usage') def should_log_files_sent_to_the_ipod(): execution = _.env.run(*_.cmd + ['push'] + _.song_paths) expect(execution.stdout.count('Sending')).to.be(len(_.songs)) def should_find_files_within_a_given_directory(): execution = _.env.run(*_.cmd + ['push', _.fixtures_path]) expect(execution.stdout.count('ending')).to.be(len(_.songs)) with context('with songs already in the iPod'): def should_refuse_to_duplicate_a_song(): populate_ipod(_.mountpoint_path, _.songs) execution = _.env.run(*_.cmd + ['push'] + _.song_paths) expect(execution.stdout.count('Not sending')).to.be(len(_.songs)) with context('with --force option'): def should_not_mind_duplicating_songs_already_in_the_ipod(): number_of_added_songs = sum( 1 for path in _.execution.files_created if 'iPod_Control/Music' in path and path.endswith('mp3')) expect(number_of_added_songs).to.be(2)
from mamba import description, context, it from expects import expect, equal import file_extractor import regex_project_type with description('File Extractor'): with context('for a python project'): with context('given a list of files'): with it('gets the python files'): python_regex = regex_project_type.RegexProjectGenerator( ['python']).regex()[0] test_file_list = ['foo.py', 'foo.txt'] _file_extractor = file_extractor.FileExtractorFromRegex( python_regex) result = _file_extractor.process(test_file_list) expect(result).to(equal(['foo.py']))
from mamba import describe, it, context from unittest.mock import MagicMock from crowd_anki.export.anki_exporter_wrapper import AnkiJsonExporterWrapper DUMMY_EXPORT_DIRECTORY = "/tmp" TEST_DECK_ID = 1 with describe(AnkiJsonExporterWrapper) as self: with context("user is trying to export dynamic deck"): with it("should warn and exit without initiating export"): exporter_mock = MagicMock() notifier_mock = MagicMock() collection_mock = MagicMock() collection_mock.decks.get.return_value = {'dyn': True} subject = AnkiJsonExporterWrapper(collection_mock, TEST_DECK_ID, exporter_mock, notifier_mock) subject.exportInto(DUMMY_EXPORT_DIRECTORY) notifier_mock.warning.assert_called_once() exporter_mock.export_to_directory.assert_not_called()
first_context.old_subject = first_context.subject def it_should_be_a_new_instance_every_time(): expect(first_context).to.have.property('subject').to.not_be.equal(first_context.old_subject) with describe(SubjectWithBeforeHook) as second_context: @before.each def also_execute_before_hook(): second_context.executed_hook = True def it_should_execute_instance_creation_and_hook(): expect(second_context).to.have.property('subject').to.be.a(SubjectWithBeforeHook) expect(second_context).to.have.property('executed_hook').to.be.true with context('when acessing subject in before hook'): @before.each def access_to_subject_in_hook(): second_context.subject.was_accessed = True def it_should_execute_first_instance_creation(): expect(second_context.subject).to.have.property('was_accessed').to.be.true with describe(SubjectWithArguments) as third_context: def it_should_be_not_be_instantiated(): expect(third_context).to.not_have.property('subject') with describe(SubjectWithArgumentsAndBeforeEachHook) as __: @before.each
'l2tpBlockConfiguredParams' : l2tpblkcfg } ) def control_pppox(self, control, handles, mode, dis_or_not, port): global pppox_mset_name disconnectl2tp = True ppp_mset = get_port_msg_set(self, pppox_mset_name, port) assert control in controlType assert mode in ipcpMode if dis_or_not.upper() != 'DISCONNECT': disconnectl2tp = False self.response = ppp_mset.sendMessageGetResponse('ControlCommand', {"blockHandleMap": handles, "controlCmd": controlType[control], "ipcpMode": ipcpMode[mode], "l2tpSessionDisconnect": disconnectl2tp}) with context('when a chassis/slot/port is given,'): with context('connects to the chassis and reserves the ports,'): with before.all: # Don't use multiple before.all/after.all(or .each) in different contexts, see https://github.com/nestorsalceda/mamba/issues/130 for details global protocol # using the first chassis/slot/port, in case you need more than 1 port self.msg_set_name = 'PPP_1' # need 2 ports self.chassis = ['172.18.0.2', '172.18.0.3'] self.slot = ['1', '1'] self.port = ['1', '1'] self.TotalCount = 1 self.portcount = 2 #self.capture_mode = None # Get setup from env if os.environ.has_key('CSP1'): (self.chassis[0], self.slot[0], self.port[0]) = get_csp_info('CSP1')
from mamba import description, it, context from expects import expect, equal RETURN_VALUE = '42' with description('Refactoring goodies') as self: def a_method(self, return_value=RETURN_VALUE): return return_value with it('uses methods defined inside its context'): expect(self.a_method()).to(equal(RETURN_VALUE)) with context('when using nested contexts'): with it('uses methods defined inside its parent'): expect(self.a_method()).to(equal(RETURN_VALUE)) with describe('Execution context of methods'): with context('When the value is defined in a before all hook of the same context'): def method_with_context(self): return self.context_value with before.all: self.context_value = RETURN_VALUE with it('returns the value defined in the before all hook'): expect(self.method_with_context()).to(equal(RETURN_VALUE))
# -*- coding: utf-8 -*- from expects import expect from mamba import describe, context, before from ipodio.cli import Router class MockCommand(object): def __init__(self, key, handler): self.key = frozenset(key) self.hanlder = handler with describe(Router) as _: with context("the commands property"): def should_be_a_dictionary_of_commands_by_key(): expect(_.router.commands).to.be.equal(_.commands_by_key) with context("the get_command method"): def should_return_a_command_by_its_key_sequence(): command = _.router.get_command(_.key_sequence) expect(command.key).to.have(*_.key_sequence) expect(command.key).to.have.length(len(_.key_sequence)) def should_raise_KeyError_for_any_unknown_key(): call = lambda: _.router.get_command(_.unknown_key)
def should_return_an_error_with_no_files(): execution = _.env.run(*_.cmd + ['push'], expect_error=True) expect(execution.stderr).to.have('Usage') def should_log_files_sent_to_the_ipod(): execution = _.env.run(*_.cmd + ['push'] + _.song_paths) expect(execution.stdout.count('Sending')).to.be(len(_.songs)) def should_find_files_within_a_given_directory(): execution = _.env.run(*_.cmd + ['push', _.fixtures_path]) expect(execution.stdout.count('ending')).to.be(len(_.songs)) with context('with songs already in the iPod'): def should_refuse_to_duplicate_a_song(): populate_ipod(_.mountpoint_path, _.songs) execution = _.env.run(*_.cmd + ['push'] + _.song_paths) expect(execution.stdout.count('Not sending')).to.be(len(_.songs)) with context('with --force option'): def should_not_mind_duplicating_songs_already_in_the_ipod(): number_of_added_songs = sum(1 for path in _.execution.files_created if 'iPod_Control/Music' in path and path.endswith('mp3')) expect(number_of_added_songs).to.be(2) def should_log_same_output_as_if_when_pushing_normally(): expect(_.execution.stdout.count('Sending')).to.be(len(_.songs))
from mamba import description, context, it, before from expects import expect, be_a, raise_error, equal, be from doublex_expects import have_been_called_with from doublex import Spy from amadeus import Client from os import environ from logging import Logger, getLogger with description('Mixins/Validator') as self: with before.all: self.valid_params = {'client_id': '1234', 'client_secret': '4546'} with context('Client.__init__'): with it('should create a new client with direct variables'): client = Client(**self.valid_params) expect(client).to(be_a(Client)) with it('should create a new client with environment variables'): environ['AMADEUS_CLIENT_ID'] = '123' environ['AMADEUS_CLIENT_SECRET'] = '234' expect(Client()).to(be_a(Client)) del environ['AMADEUS_CLIENT_ID'] del environ['AMADEUS_CLIENT_SECRET'] with context('with missing parameters'): with it('should refuse to create a new client without client_id'): del self.valid_params['client_id'] expect(lambda: Client(**self.valid_params)).to(
import requests import time import configuration from mamba import description, context, it from expects import expect, be_true, have_length, equal, be_a, have_property, be_none headers = {'content-type': 'application/json', 'accept': 'application/json'} with description('Zipkin tracing functionality'): with before.all: #Read Config file configuration.setenv(self) with context('Deploy Zipkin and make sure port forwarded to localhost'): with it('Bookinfo Zipkin tracing feature'): for _ in range(10): r = requests.get(self.url) r.status_code expect(r.status_code).to(equal(200)) r1 = requests.get(self.zipkin) r1.status_code expect(r1.status_code).to(equal(200)) if 'productpage' in r1.text: expect(0).to(equal(0)) else: expect(0).not_to(equal(0)) configuration.generate_request(self)
class DummyCommand(object): pass class DummyEvent(object): pass with describe('FakeBus') as _: @before.each def create_fake_bus(): _.bus = FakeBus() with context('registering handlers'): def it_registers_the_first_handler_for_a_command_or_event(): _.bus.register_handler(IRRELEVANT_EVENT_TYPE, IRRELEVANT_HANDLER1) expect(_.bus.routes).to.have.key(IRRELEVANT_EVENT_TYPE) expect(_.bus.routes.get(IRRELEVANT_EVENT_TYPE)).to.be.equal([IRRELEVANT_HANDLER1]) def it_registers_more_than_one_handler_per_command_or_event(): _.bus.register_handler(IRRELEVANT_EVENT_TYPE, IRRELEVANT_HANDLER1) _.bus.register_handler(IRRELEVANT_EVENT_TYPE, IRRELEVANT_HANDLER2) expect(_.bus.routes).to.have.key(IRRELEVANT_EVENT_TYPE) expect(_.bus.routes.get(IRRELEVANT_EVENT_TYPE)).to.be.equal([IRRELEVANT_HANDLER1, IRRELEVANT_HANDLER2]) with context('sending commands'): @before.each def create_command(): _.command = DummyCommand()
from collections import deque from multiprocessing import Queue from queue import PriorityQueue import array import heapq class Car: def __init__(self, color, mileage, automatic): self.color = color self.mileage = mileage self.automatic = automatic with description('Chapter05') as self: with context('dicts'): with it('fast lookup'): phonebook: Dict[str, int] = { 'bob': 7387, 'alice': 3719, 'jack': 7052, } assert phonebook['alice'] == 3719 squares = {x: x * x for x in range(6)} assert len(squares.keys()) == 6 with context('ordered dict'): with it('keeps keys in order'): d = OrderedDict(one=1, two=2, three=3) assert d['two'] == 2
def it_can_be_created_with_an_empty_constructor(): expect(InventoryItem()).to.be.an('simplecqrs.inventory.InventoryItem') def it_has_an_id(): expect(_.item.id).to.be.equal(IRRELEVANT_ID) def it_has_a_name(): expect(_.item.name).to.be.equal(IRRELEVANT_NAME) def it_has_no_items(): expect(_.item.count).to.equal(0) def it_is_active(): expect(_.item.is_active).to.be.true with context('creating'): def it_stores_an_item_created_event(): expect(_.item.uncommitted_changes.pop()).to.be.a('simplecqrs.inventory.InventoryItemCreated') with context('renaming'): def it_can_be_renamed_if_the_new_name_is_valid(): _.item.rename(OTHER_NAME) expect(_.item.name).to.be.equal(OTHER_NAME) def it_cannot_be_renamed_if_the_new_name_is_invalid(): expect(_.item.rename).when.called_with(None).to.throw(ValueError) expect(_.item.rename).when.called_with('').to.throw(ValueError) def it_stores_an_item_rename_event(): _.item.rename(OTHER_NAME) expect(_.item.uncommitted_changes.pop()).to.be.a('simplecqrs.inventory.InventoryItemRenamed')