# -*- coding: utf-8 -*- 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 push') as _: @before.all def setup_all(): update_environment(_) bootstrap_ipod(_.mountpoint_path) @after.each def cleanup(): empty_ipod(_.mountpoint_path) 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():
# -*- coding: utf-8 -*- from mamba import describe, before from expects import expect from spec.helpers import failure with describe('helpers') as _: with describe('failure'): def it_should_have_failure_message(): message = failure(_.actual, _.message).message expect(message).to.equal('Expected {} {}'.format( repr(_.actual), _.message)) def it_should_pass_if_assertion_error_raised_with_message(): def callback(): fail = failure(_.actual, _.message) with fail: raise AssertionError(fail.message) expect(callback).not_to.raise_error(AssertionError) def it_should_pass_if_assertion_error_raised_and_matchs_pattern(): fail = failure(_.actual, _.pattern) with fail: raise AssertionError(failure(_.actual, _.message).message)
# -*- 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
# -*- coding: utf-8 -* from mamba import describe, context from expects import expect from expects.testing import failure with describe('above'): def it_should_pass_if_actual_is_above_expected(): expect(5).to.be.above(4) def it_should_fail_if_actual_is_not_above_expected(): with failure(1, 'to be above 4'): expect(1).to.be.above(4) with context('#negated'): def it_should_pass_if_actual_is_not_above_expected(): expect(1).not_to.be.above(4) def it_should_fail_if_actual_is_above_expected(): with failure(5, 'not to be above 4'): expect(5).not_to.be.above(4)
from mamba import shared_context, included_context, describe, it SHARED_CONTEXT = 'Shared Context' with shared_context(SHARED_CONTEXT): with it('shared example'): pass with describe('Real tests'): with included_context(SHARED_CONTEXT): with it('added example'): pass
from mamba import describe, context, before, pending from sure import expect from doublex import * 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))
# -*- coding: utf-8 -*- import re import os import shutil 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 pull') as _: @before.all def setup_all(): update_environment(_) bootstrap_ipod(_.mountpoint_path) populate_ipod(_.mountpoint_path, _.songs) _.execution = _.env.run(*_.cmd + ['pull']) @after.all def cleanup(): shutil.rmtree(_.env_path) def should_copy_selected_songs_to_the_current_directory(): copied_songs = [ path for path in _.execution.files_created if path.endswith('.mp3') ] expect(copied_songs).to.have.length(2)
# -*- coding: utf-8 -*- 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])
def __init__(self, key, handler): 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)
self.fail = False 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)
# pylint: disable=no-member import json from mamba import before, describe, it from expects import contain, equal, expect, have_keys, have_length from src.app import app with describe("App") as self: with before.each: self.app = app self.app.config['TESTING'] = True self.client = self.app.test_client() with describe("/search") as self: with before.each: self.response = self.client.get('/search') with it("returns list of metrics"): expect(json.loads(self.response.data)).to( contain('Germany:confirmed', 'Germany:deaths', 'Germany:recovered')) with describe("/query") as self: with before.each: post_params_header = {"Content-Type": "application/json"} post_params_body = { "range": { "from": "2020-01-22T00:00:00.000Z",
# -*- coding: utf-8 -*- from expects import expect from mamba import describe, context, before from spec.ui._ipod_helpers import * from spec.ui._fixture import update_environment 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'):
# -*- 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)
# -*- 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():
from mamba import describe, it from expects import expect, be from python_sample.python_sample import my_sample with describe(my_sample): with it("does"): result = my_sample("b") expect(result).to(be("b"))
# -*- coding: utf-8 -* from mamba import describe, context from expects import expect from expects.testing import failure with describe('false'): def it_should_pass_if_actual_is_false(): expect(False).to.be.false def it_should_fail_if_actual_is_true(): with failure(True, 'to be False'): expect(True).to.be.false with context('#negated'): def it_should_pass_if_actual_is_not_false(): expect(True).not_to.be.false def it_should_fail_if_actual_is_false(): with failure(False, 'not to be False'): expect(False).not_to.be.false
from mamba import context, describe, it, _it from expects import expect, equal from unittest.mock import patch from app import concatx def concat(x, y): return x + y with describe('Função de concatenar') as self: with context('Juntar coisas'): with it('Deve juntar strings'): expect(concat('a', 'a')).to(equal('aa')) with it('Deve juntar listar'): expect(concat([0], [1])).to(equal([0, 1])) with context('Somar coisas'): with it('Deve somar números inteiros'): expect(concat(0, 1)).to(equal(1)) with context('mockar'): with it('Deve somar números inteiros'): with patch('app.concats', return_value=10) as xpto: expect(concatx(0, 1)).to(equal(10)) xpto.assert_called()
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()
import sys from unittest.mock import patch import toml from mamba import context, describe, it from poetry_githooks import helpers with describe("Helpers"): with context("#execute_script"): with it("should execute a script without arguments"): with patch("subprocess.call") as call_mock, patch("sys.exit") as exit_mock: helpers.execute_script("ls") call_mock.assert_called_with("ls", shell=True) with it("should execute a script with static arguments"): with patch("subprocess.call") as call_mock, patch("sys.exit") as exit_mock: helpers.execute_script("ls -l") call_mock.assert_called_with("ls -l", shell=True) with it( "should execute a script with dynamic arguments and escape them if necessary" ): with patch("subprocess.call") as call_mock, patch("sys.exit") as exit_mock: helpers.execute_script("ls", ["-l", "somefile; rm -rf ~"]) call_mock.assert_called_with("ls -l 'somefile; rm -rf ~'", shell=True) with context("#read_config"): with it("should exit if the config is not present"): with patch("os.path.isfile", return_value=False) as isfile_mock, patch( "sys.exit" ) as exit_mock, patch("toml.load") as toml_mock: helpers.read_config() args, kwargs = exit_mock.call_args assert args[0] == 1
from doublex import * from spec.constants import * from simplecqrs.fake_bus import FakeBus from simplecqrs.errors import InvalidOperationError 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)
# -*- 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(): track = spy(_.track)
# -*- coding: utf-8 -* from mamba import describe, before from expects import expect from expects.expectations import Expectation with describe(Expectation) as _: def it_should_return_class_if_accessed_from_class(): expect(_.cls.expectation).to.be(Expectation) def it_should_return_instance_if_accesed_from_instance(): expect(_.obj.expectation).to.be.an(Expectation) @before.all def fixtures(): class Foo(object): expectation = Expectation _.cls = Foo _.obj = _.cls()
from mamba import describe, included_context, it NEW_EXPORTED_CONTEXT = 'New Exported Context' with describe('Real tests'): with included_context(NEW_EXPORTED_CONTEXT): with it('added example'): pass
# -*- coding: utf-8 -*- from mamba import describe, context, before from spec.fixtures import Foo from expects import expect from expects.testing import failure with describe('properties') as _: def it_should_pass_if_actual_has_properties_in_args(): expect(_.obj).to.have.properties('bar', 'baz') def it_should_pass_if_actual_has_properties_in_kwargs(): expect(_.obj).to.have.properties(bar=0, baz=1) def it_should_pass_if_actual_has_properties_in_args_and_kwargs(): expect(_.obj).to.have.properties('bar', baz=1) def it_should_pass_if_actual_has_properties_in_dict(): expect(_.obj).to.have.properties({'bar': 0, 'baz': 1}) def it_should_fail_if_actual_does_not_have_property_in_args(): with failure(_.obj, "to have property 'foo'"): expect(_.obj).to.have.properties('bar', 'foo') def it_should_fail_if_actual_does_not_have_property_in_kwargs(): with failure(_.obj, "to have property 'foo'"): expect(_.obj).to.have.properties(bar=0, foo=1)
# -*- 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)
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()
from mamba import describe, it, context from expects import expect, contain def concat(x, y): return x + y sanduiche = 'sanduiche com queijo' with describe(sanduiche) as self: with it('tem queijo'): expect(sanduiche).to(contain('queijo')) with it('é um sanduiche'): expect(sanduiche).to(contain('sanduiche')) with context('Sanduiche vegano'): with it('Não tem Bacon'): expect(sanduiche).to_not(contain('bacon'))
# -*- coding: utf-8 -*- import shutil 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 list') as _: @before.all def setup_all(): update_environment(_) bootstrap_ipod(_.mountpoint_path) with context('given a bad expression'): def should_print_an_error(): execution = _.env.run(*_.cmd + ['list', _.bad_expression], expect_error=True) expect(execution.stdout).to.have("Error: Invalid expression") with context('with an empty iPod'): def should_print_nothing(): execution = _.env.run(*_.cmd + ['list']) expect(execution.stdout).to.be.empty with context('with songs in the iPod'):
from mamba import context, describe, it from expects import expect, equal, be_false, be_true, have_property from bee import Bee from position import Position from environment import Environment with describe(Environment) as self: with it("has default size"): expect(Environment()).to(have_property("width", 10)) expect(Environment()).to(have_property("height", 10)) with it("checks positions within given size"): expect(Environment(5, 5).check(Position(0, 0))).to(be_true) expect(Environment(10, 10).check(Position(10, 10))).to(be_false) expect(Environment(11, 11).check(Position(10, 10))).to(be_true) with it("gives information about known flowers"): flowers = [ (5, 5), (7, 3), ] positions = [Position(*coords) for coords in flowers] env = Environment(flowers=positions) expect(env.is_flower(positions[0])).to(be_true) expect(env.is_flower(Position(0, 0))).to(be_false) with describe(Bee) as self:
# -*- coding: utf-8 -*- from mamba import describe, before from expects import expect from expects.testing import failure with describe('failure') as _: def it_should_pass_if_assertion_error_raised_and_message_matches(): def callback(): with failure(_.actual, _.message): raise AssertionError('Expected {!r} {}'.format(_.actual, _.message)) expect(callback).not_to.raise_error(AssertionError) def it_should_pass_if_assertion_error_raised_and_pattern_matches(): def callback(): with failure(_.actual, _.pattern): raise AssertionError('Expected {!r} {}'.format(_.actual, _.message)) expect(callback).not_to.raise_error(AssertionError) def it_should_pass_if_assertion_error_raised_with_plugin_name_in_message(): def callback(): with failure(_.actual, _.pattern): raise AssertionError('Expected plugin {!r} {}'.format(_.actual, _.message)) expect(callback).not_to.raise_error(AssertionError) def it_should_fail_if_assertion_error_not_raised():
# -*- coding: utf-8 -* from mamba import describe, context, before from expects import expect from expects.testing import failure with describe('keys') as _: def it_should_pass_if_actual_has_keys_in_args(): expect(_.dct).to.have.keys('bar', 'baz') def it_should_pass_if_actual_has_keys_in_kwargs(): expect(_.dct).to.have.keys(bar=0, baz=1) def it_should_pass_if_actual_has_keys_in_args_and_kwargs(): expect(_.dct).to.have.keys('bar', baz=1) def it_should_pass_if_actual_has_keys_in_dict(): expect(_.dct).to.have.keys({'bar': 0, 'baz': 1}) def it_should_fail_if_actual_does_not_have_key_in_args(): with failure(_.dct, "to have key 'foo'"): expect(_.dct).to.have.keys('bar', 'foo') def it_should_fail_if_actual_does_not_have_key_in_kwargs(): with failure(_.dct, "to have key 'foo'"): expect(_.dct).to.have.keys(bar=0, foo=1) def it_should_fail_if_actual_has_key_without_value_in_kwargs(): with failure(_.dct, "to have key 'bar' with value 1 but was 0"):
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 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 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))
# -*- coding: utf-8 -*- from expects import expect from mamba import describe, context, before from spec.ui._ipod_helpers import * from spec.ui._fixture import update_environment 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.")
# -*- coding: utf-8 -*- 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 push') as _: @before.all def setup_all(): update_environment(_) bootstrap_ipod(_.mountpoint_path) @after.each def cleanup(): empty_ipod(_.mountpoint_path) 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])
# -*- coding: utf-8 -* import re from mamba import describe, before from spec.helpers import failure from spec.fixtures import Foo from expects import expect with describe(expect) as _: with describe('to'): with describe('equal'): def it_should_pass_if_actual_equals_expected(): expect(1).to.equal(1) def it_should_fail_if_actual_does_not_equal_expected(): with failure(1, 'to equal 2'): expect(1).to.equal(2) with describe('match'): def it_should_pass_if_actual_matches_expected_regexp(): expect(_.str).to.match(r'My \w+ string') def it_should_pass_if_actual_matches_expected_regexp_with_re_flags( ): expect(_.str).to.match(r'my [A-Z]+ strinG', re.I) def it_should_fail_if_actual_does_not_match_expected_regexp():
# -*- 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)
# -*- coding: utf-8 -* from mamba import describe, context from expects import expect from expects.testing import failure with describe("none"): def it_should_pass_if_actual_is_none(): expect(None).to.be.none def it_should_fail_if_actual_is_not_none(): with failure(True, "to be None"): expect(True).to.be.none with context("#negated"): def it_should_pass_if_actual_is_not_none(): expect("foo").not_to.be.none def it_should_fail_if_actual_is_none(): with failure(None, "not to be None"): expect(None).not_to.be.none
from expects import expect, be, equal from mamba import describe, it from genyrator.entities.Column import ForeignKey from genyrator.entities.entity.create_entity_from_type_dict import create_entity_from_type_dict with describe('create from type dict'): with it('converts identifier column'): result = create_entity_from_type_dict( class_name='Book', identifier_column_name='book_identifier', type_dict={ 'bookIdentifier': 'str', }) expect(result.identifier_column.python_name).to( equal('book_identifier')) with it('converts type? to a nullable column'): result = create_entity_from_type_dict( class_name='Book', identifier_column_name='book_identifier', type_dict={ 'bookIdentifier': 'str', 'rating': 'float?', 'name': 'str', }) expect(result.columns[1].nullable).to(be(True)) expect(result.columns[1].python_type.value).to(be('float')) expect(result.columns[2].nullable).to(be(False))
# -*- coding: utf-8 -*- from expects import expect from mamba import describe, context, before from spec.ui._ipod_helpers import * from spec.ui._fixture import update_environment 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_():
#-*- 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, pending with describe('Fixture#with_pending_decorator'): @pending def pending_spec(): pass with pending(context('when pending context')): pass
# -*- coding: utf-8 -* from mamba import describe, context, before from expects import expect from expects.testing import failure with describe('raise_error') as _: def it_should_pass_if_actual_raises_expected_exception(): def callback(): raise AttributeError() expect(callback).to.raise_error(AttributeError) def it_should_fail_if_actual_does_not_raise_expected_exception(): def callback(): raise KeyError() with failure(callback, 'to raise AttributeError but KeyError raised'): expect(callback).to.raise_error(AttributeError) def it_should_fail_if_actual_does_not_raise_exception(): callback = lambda: None with failure(callback, 'to raise AttributeError but not raised'): expect(callback).to.raise_error(AttributeError) def it_should_pass_if_actual_raises_with_message(): def callback(): raise AttributeError(_.message)
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, before from sure import * from doublex import * from spec.constants import * from simplecqrs.view_model import ReadModel with describe('ReadModel') as _: @before.each def creat_read_model(): _.db = Stub() _.read_model = ReadModel(_.db) def it_returns_all_the_inventory_items(): dtos = [IRRELEVANT_INVENTORY_ITEM_DTO1, IRRELEVANT_INVENTORY_ITEM_DTO2] with _.db as db: db.inventory_items = dtos expect(_.read_model.get_inventory_items()).to.be.equal(dtos) def it_returns_the_details_of_a_particular_inventory_item(): dto = IRRELEVANT_INVENTORY_ITEM_DETAILS_DTO with _.db as db: db.get_inventory_item_details(IRRELEVANT_ID).returns(dto) expect(_.read_model.get_inventory_item_details(IRRELEVANT_ID)).to.be.equal(dto)
# -*- coding: utf-8 -*- 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 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])
# -*- 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 describe, context, before from sure import expect from doublex import * from spec.object_mother import * from mamba import reporter, formatters, example, example_group with describe(reporter.Reporter) as _: @before.each def create_reporter_and_attach_formatter(): _.example = an_example(_) _.formatter = Spy(formatters.Formatter) _.reporter = reporter.Reporter(_.formatter) _.reporter.start() def it_notifies_event_example_started_to_listeners(): _.reporter.example_started(_.example) assert_that(_.formatter.example_started, called().with_args(_.example)) def it_increases_example_counter_when_example_started(): _.reporter.example_started(_.example) expect(_.reporter.example_count).to.be.equal(1) def it_notifies_event_example_passed_to_listeners(): _.reporter.example_passed(_.example)
# -*- coding: utf-8 -*- 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 rename') as _: @before.all def setup_all(): update_environment(_) bootstrap_ipod(_.mountpoint_path) @after.each def cleanup(): empty_ipod(_.mountpoint_path) def should_return_an_error_when_rename_with_bad_expressions(): execution = _.env.run( *_.cmd + ['rm', _.bad_expression, _.bad_expression], expect_error=True) expect(execution.stdout).to.have("Error: Invalid expression") def should_show_an_error_when_called_without_arguments(): execution = _.env.run(*_.cmd + ['rename'], expect_error=True) expect(execution.stderr).to.have('Usage')
# -*- coding: utf-8 -* from mamba import describe, context from expects import expect from expects.testing import failure 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)
# -*- coding: utf-8 -* from mamba import describe, context, before from expects import expect from expects.testing import failure with describe('have') as _: def it_should_pass_if_list_have_expected_item(): expect(_.lst).to.have('bar') def it_should_pass_if_list_has_expected_items(): expect(_.lst).to.have('bar', 'baz') def it_should_pass_if_iterable_of_dicts_has_dict(): # https://github.com/jaimegildesagredo/expects/issues/8 expect([{'foo': 1}, 'bar']).to.have({'foo': 1}) def it_should_pass_if_iterable_has_expected_item(): expect(_.itr).to.have('bar') def it_should_pass_if_iterable_has_expected_items(): expect(_.itr).to.have('bar', 'baz') def it_should_fail_if_list_does_not_have_expected_item(): with failure(_.lst, "to have 'foo'"): expect(_.lst).to.have('bar', 'foo') def it_should_fail_if_iterable_does_not_have_expected_item():
class SubjectWithBeforeHook(object): pass class SubjectWithArguments(object): def __init__(self, argument): pass class SubjectWithArgumentsAndBeforeEachHook(object): def __init__(self, argument): pass with describe(Subject) as first_context: def it_should_be_instantiated_automatically(): expect(first_context).to.have.property('subject').to.be.a(Subject) 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)
from expects import equal, expect from mamba import describe, it from src.handlers.hello.app import say_hello STATUS_OK = 200 with describe(say_hello): with it('is ok'): response = say_hello(event={}) expect(response['statusCode']).to(equal(STATUS_OK))
#-*- 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
from mamba import describe, context, it from expects import expect, equal from roman_numbers import to_roman with describe("Roman numbers"): with context("once digit numbers"): with it("converts 1 to I"): expect(to_roman(1)).to(equal("I")) with it("converts 2 to II"): expect(to_roman(2)).to(equal("II")) with it("converts 3 to III"): expect(to_roman(3)).to(equal("III")) with it("converts 5 to V"): expect(to_roman(5)).to(equal("V")) with it("converts 6 to VI"): expect(to_roman(6)).to(equal("VI")) with it("converts 4 to IV"): expect(to_roman(4)).to(equal("IV")) with context("two digit numbers"): with it("converts 10 to X"): expect(to_roman(10)).to(equal("X"))