def test_should_fail_if_inputs_do_not_have_the_same_type(self):
     testf = lambda: timestamp.compare(self.TESTS[0][0],
                                       datetime.datetime.utcnow())
     expect(testf).to(raise_error(ValueError))
     testf = lambda: timestamp.compare(self.TESTS[0],
                                       datetime.datetime.utcnow())
     expect(testf).to(raise_error(ValueError))
Example #2
0
 def test_should_fail_if_service_is_bad(self):
     testfs = [
         lambda: self._get_registry(),
         lambda: service.MethodRegistry(None),
         lambda: service.MethodRegistry(object()),
     ]
     for f in testfs:
         expect(f).to(raise_error(ValueError))
 def test_should_fail_for_delta_metrics_with_unmergable_types(self):
     no_init = metric_value.create()
     unmergeables = [
         metric_value.create(stringValue='a test string'),
         metric_value.create(boolValue=False),
     ]
     for mv in unmergeables:
         testf = lambda: metric_value.merge(MetricKind.DELTA, mv, mv)
         expect(testf).to(raise_error(ValueError))
Example #4
0
    def test_bad_commandname_raises_error(self):

        parser = argparse.ArgumentParser()
        JustOneCommandGroup().build(parser.add_subparsers())

        def parse():
            parser.parse_args(['demo' 'nosuchcommand'])

        expect(parse).to(raise_error(SystemExit))
Example #5
0
def test_setup_should_raise_exception_when_invalid_route_configuration_provided(
):
    # given
    # when
    def call():
        return RouteInfo('AB5, C4D, DE6')

    # then
    expect(call).to(raise_error(InvalidRouteConfiguration))
Example #6
0
 def test_should_fail_for_delta_metrics_with_unmergable_types(self):
     no_init = metric_value.create()
     unmergeables = [
         metric_value.create(stringValue='a test string'),
         metric_value.create(boolValue=False),
     ]
     for mv in unmergeables:
         testf = lambda: metric_value.merge(MetricKind.DELTA, mv, mv)
         expect(testf).to(raise_error(ValueError))
Example #7
0
 def test_should_fail_if_non_money_is_used(self):
     testfs = [
         lambda: money.add(self._SOME_YEN, object()),
         lambda: money.add(object(), self._SOME_USD),
         lambda: money.add(None, self._SOME_USD),
         lambda: money.add(self._SOME_YEN, None),
     ]
     for testf in testfs:
         expect(testf).to(raise_error(ValueError))
Example #8
0
 def test_should_fail_on_dissimilar_bucket_options(self):
     explicit = _make_explicit_dist()
     linear = _make_linear_dist()
     exponential = _make_exponential_dist()
     pairs = ((explicit, linear), (explicit, exponential), (linear,
                                                            exponential))
     for p in pairs:
         testf = lambda: distribution.merge(*p)
         expect(testf).to(raise_error(ValueError))
    def test_object_is_mutable(self):
        thing = MutableObject()
        name = "ximinez"
        value = 77

        def attempt():
            setattr(thing, name, value)

        expect(attempt).not_to(raise_error(AttributeError))
        expect(getattr(thing, name)).to(equal(value))
    def test_does_not_raise_exception_from_subscriber(self):
        def bad_subscriber(**kwargs):
            raise Exception("intentional walrus")

        event = "spamorama"
        EventBroker.subscribe(event=event, func=bad_subscriber)

        def attempt():
            EventBroker.publish(event=event)

        expect(attempt).not_to(raise_error(Exception))
Example #11
0
def test_setup_should_raise_no_such_route_for_invalid_route_query():
    # given
    setup = RouteInfo('AB5, CD4, DE6')

    # when

    def call():
        return setup.get_route_distance('A-C')

    # then
    expect(call).to(raise_error(NoSuchRoute))
Example #12
0
def validate_field(model, field_name, raises_error=True):
    """
    Raises Validation error for provided field name.

    :param django.db.models.Model model:
    :param String field_name:
    :param raises_error: true - if field validation raises error, false - otherwise
    :return:
    """
    expect_to = getattr(expect(lambda: model.clean_fields()),
                        'to' if raises_error else 'not_to')
    expect_to(raise_error(ValidationError, have_key(field_name)))
 def test_should_fail_on_dissimilar_bucket_options(self):
     explicit = _make_explicit_dist()
     linear = _make_linear_dist()
     exponential = _make_exponential_dist()
     pairs = (
         (explicit, linear),
         (explicit, exponential),
         (linear, exponential)
     )
     for p in pairs:
         testf = lambda: distribution.merge(*p)
         expect(testf).to(raise_error(ValueError))
    def test_it_raises_exception_when_no_mr_in_report_header(self):
        wrong_header = (
            'Random data\n'
            'Some other header data\n'
        )
        free_text = (
            'Free text body, full of important data and\n'
            'annotations that we should save.\n'
            'We hope this report is good news for patient :)\n'
        )

        expect(lambda: AnonymizeTxtFile().do(
            file_content=f'{wrong_header}\n{free_text}',
            repository=FakeReportRepository()
        )).to(raise_error(WrongFileStructureException))
    def test_handles_test_failed_event_without_exception_gracefully(self):
        name = "susan"
        start_suite()
        start_test(name)

        def attempt():
            EventBroker.publish(event=TestEvent.test_failed,
                                test_name=name,
                                exception=RuntimeError())

        expect(attempt).not_to(raise_error(Exception))
        end_test(name)
        end_suite()
        results = self.retrieve_results()
        expect(results.tests).to(have_length(1))
        expect(results.tests[0].status).to(equal(TestStatus.failed))
Example #16
0
    def test_missing_arg_raises_error(self):
        class DemoGroup(CommandGroup):
            name = 'demo'

            @command('callme')
            @command_arg('arg1')
            def maybe(self, arg1):
                return arg1

        parser = argparse.ArgumentParser()
        DemoGroup().build(parser.add_subparsers())

        def parse():
            parser.parse_args(['demo', 'callme'])

        expect(parse).to(raise_error(SystemExit))
 def test_should_fail_as_report_request_on_incomplete_info(self):
     timer = _DateTimeTimer()
     incomplete = report_request.Info()  # has no service_name
     rules = report_request.ReportingRules()
     testf = lambda: incomplete.as_report_request(rules, timer=timer)
     expect(testf).to(raise_error(ValueError))
 def test_should_fail_if_req_is_bad(self):
     testf = lambda: self.agg.check(object())
     expect(testf).to(raise_error(ValueError))
     testf = lambda: self.agg.check(None)
     expect(testf).to(raise_error(ValueError))
 def test_should_fail_if_there_are_matching_bounds(self):
     testf = lambda: distribution.create_explicit([0.0, 0.1, 0.1])
     expect(testf).to(raise_error(ValueError))
 def test_should_raise_if_constructed_with_a_bad_protocol(self):
     testf = lambda: report_request.Info(protocol=object())
     # not a report_request.ReportedProtocols
     expect(testf).to(raise_error(ValueError))
from co import factory, errors

from expects import expect, be_true, raise_error

with description('Register user'):

    with before.each:
        self.nickname = '@foolano'
        self.service = factory.create_users_service()

    with it('registers a new user'):
        self.service.register(self.nickname)

        expect(self.service.is_registered(self.nickname)).to(be_true)

    with context('when user already exists'):
        with it('raises error'):
            self.service.register(self.nickname)

            expect(lambda: self.service.register(self.nickname)).to(raise_error(errors.UserAlreadyRegisteredError))

 def test_should_fail_if_num_finite_buckets_is_bad(self):
     testf = lambda: distribution.create_linear(0, 1.1, 0.1)
     expect(testf).to(raise_error(ValueError))
 def test_should_raise_if_constructed_with_a_bad_error_cause(self):
     testf = lambda: report_request.Info(error_cause=object())
     expect(testf).to(raise_error(ValueError))
 def test_should_fail_if_check_request_is_missing(self):
     req = messages.ServicecontrolServicesReportRequest(
         serviceName=self.SERVICE_NAME)
     testf = lambda: self.agg.report(req)
     expect(testf).to(raise_error(ValueError))
Example #25
0
 def test_should_fail_when_the_units_and_nanos_are_mismatched(self):
     for m in self._MISMATCHED_UNITS:
         expect(lambda: money.check_valid(m)).to(raise_error(ValueError))
Example #26
0
 def test_should_fail_when_nanos_are_oob(self):
     expect(lambda: money.check_valid(self._NANOS_OOB)).to(
         raise_error(ValueError))
Example #27
0
 def test_should_fail_when_the_currency_is_bad(self):
     expect(lambda: money.check_valid(self._BAD_CURRENCY)).to(
         raise_error(ValueError))
Example #28
0
 def test_should_fail_when_no_currency_is_set(self):
     expect(lambda: money.check_valid(messages.Money())).to(
         raise_error(ValueError))
Example #29
0
 def test_should_fail_if_not_really_money(self):
     expect(lambda: money.check_valid(object())).to(raise_error(ValueError))
     expect(lambda: money.check_valid(None)).to(raise_error(ValueError))
 def test_should_fail_if_operation_is_missing(self):
     req = messages.ServicecontrolServicesCheckRequest(
         serviceName=self.SERVICE_NAME,
         checkRequest=messages.CheckRequest())
     testf = lambda: self.agg.check(req)
     expect(testf).to(raise_error(ValueError))
Example #31
0
 def test_should_fail_on_currency_mismatch(self):
     testf = lambda: money.add(self._SOME_YEN, self._SOME_USD)
     expect(testf).to(raise_error(ValueError))
 def test_should_fail_on_invalid_input(self):
     testf = lambda: check_request.sign(None)
     expect(testf).to(raise_error(ValueError))
     testf = lambda: check_request.sign(object())
     expect(testf).to(raise_error(ValueError))
Example #33
0
 def test_should_fail_on_unallowed_negative_overflows(self):
     testf = lambda: money.add(self._SOME_YEN_DEBT, self._LARGE_YEN_DEBT)
     expect(testf).to(raise_error(OverflowError))
Example #34
0
 def test_should_fail_if_bad_options_are_used(self):
     should_fail = [
         lambda: caches.create(object()),
     ]
     for testf in should_fail:
         expect(testf).to(raise_error(ValueError))
Example #35
0
from expects import expect, raise_error
from bankbarcode.bankbarcode import BankBarcode

with description('BankBarcode'):
    with it('doesn\'t have code generation method'):
        error = 'This method is not implemented!'

        def callback():
            return BankBarcode().code()

        expect(callback).to(raise_error(NotImplementedError, error))

    with it('can\'t create barcode without code generation method'):
        path = '/tmp/mybarcode'
        error = 'This method is not implemented!'

        def callback():
            return BankBarcode().save(path)

        expect(callback).to(raise_error(NotImplementedError, error))

    with it('can\'t create SVG without code generation method'):
        error = 'This method is not implemented!'

        def callback():
            return BankBarcode().svg()

        expect(callback).to(raise_error(NotImplementedError, error))
 def test_should_fail_if_req_is_bad(self):
     testf = lambda: self.agg.report(object())
     expect(testf).to(raise_error(ValueError))
     testf = lambda: self.agg.report(None)
     expect(testf).to(raise_error(ValueError))
Example #37
0
 def test_should_fail_if_bad_options_are_used(self):
     should_fail = [
         lambda: caches.create(object()),
     ]
     for testf in should_fail:
         expect(testf).to(raise_error(ValueError))
 def test_should_fail_if_growth_factor_is_bad(self):
     testf = lambda: distribution.create_linear(1, -0.1, 0.1)
     expect(testf).to(raise_error(ValueError))
Example #39
0
 def test_constructor_should_fail_on_bad_deques(self):
     testf = lambda: caches.DequeOutTTLCache(_TEST_NUM_ENTRIES, _TEST_TTL,
                                             out_deque=object())
     expect(testf).to(raise_error(ValueError))
Example #40
0
        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'))

    with it('is not created when expiration date is before today'):
        yesterday = date.today() - timedelta(days=1)
        auction = lambda: auction_with(price=600, expiration_date=yesterday)

        expect(auction).to(
            raise_error(AuctionError,
                        'expiration date cannot be before today'))

    with it('accepts purchase of the item by its selling_price'):
        expected_price = 600
        auction = Auction.rebuild([{
            'type': Auction.AUCTION_CREATED_TYPE,
            'auction_id': AN_AUCTION_ID,
            'auctioneer': AN_AUCTIONEER_ID,
 def test_should_raise_if_constructed_with_a_bad_protocol(self):
     testf = lambda: report_request.Info(protocol=object())
     # not a report_request.ReportedProtocols
     expect(testf).to(raise_error(ValueError))
 def test_should_raise_if_constructed_with_a_bad_error_cause(self):
     testf = lambda: report_request.Info(error_cause=object())
     expect(testf).to(raise_error(ValueError))
Example #43
0
 def it_should_raise_an_error(self):
     expect(self.callback).to(raise_error(TypeError))
 def test_should_fail_if_check_request_is_missing(self):
     req = messages.ServicecontrolServicesReportRequest(
         serviceName=self.SERVICE_NAME)
     testf = lambda: self.agg.report(req)
     expect(testf).to(raise_error(ValueError))
from expects import expect, equal, raise_error
from bankbarcode.cuaderno57 import Recibo507

with description('Recibo507 with due date of cuaderno57'):
    with it('Validate than suffix is less than 500'):
        def callback():
            entity = '01234567'
            suffix = '023'
            ref = '12345678901'
            notice = '123456'
            amount = '6543.21'
            due_date = datetime(2015, 11, 01)
            recibo = Recibo507(entity, suffix, ref, notice, amount, due_date)
        expect(callback).to(
            raise_error(ValueError,
                        'suffix with due date must be bigger than 499'))

    with it('Overwrites introduced notice for due date DDMMAA'):
        entity = '22350466'
        suffix = '501'
        ref = '00000000015'
        notice = '300815'
        amount = '53.98'
        due_date = datetime(2015, 11, 01)
        recibo = Recibo507(entity, suffix, ref, notice, amount, due_date)
        expect(recibo.notice).not_to(equal(notice))
        expect(recibo.notice).to(equal(due_date.strftime('%d%m%y')))

    with it('accomplish the example of cuaderno57 with due date Datetime'):
        entity = '22350466'
        suffix = '501'
 def test_should_fail_if_service_name_does_not_match(self):
     req = _make_test_request(self.SERVICE_NAME + '-will-not-match')
     testf = lambda: self.agg.check(req)
     expect(testf).to(raise_error(ValueError))
 def test_should_fail_if_operation_has_no_operation_name(self):
     op = messages.Operation(consumerId=_TEST_CONSUMER_ID)
     testf = lambda: check_request.sign(messages.CheckRequest(operation=op))
     expect(testf).to(raise_error(ValueError))
 def test_should_fail_if_operation_is_not_set(self):
     testf = lambda: check_request.sign(messages.CheckRequest())
     expect(testf).to(raise_error(ValueError))
Example #49
0
def it_raises_an_invalidserversettings_error(context):
    expect(context.validate).to(raise_error(InvalidSettings))
    return
 def test_should_fail_as_check_request_on_incomplete_info(self):
     timer = _DateTimeTimer()
     for info in _INCOMPLETE_INFO_TESTS:
         testf = lambda: info.as_check_request(timer=timer)
         expect(testf).to(raise_error(ValueError))
 def test_should_fail_if_service_name_does_not_match(self):
     req = _make_test_request(self.SERVICE_NAME + u'-will-not-match')
     testf = lambda: self.agg.report(req)
     expect(testf).to(raise_error(ValueError))
 def test_should_fail_if_operation_has_no_consumer_id(self):
     op = messages.Operation(operationName=_TEST_OP_NAME)
     testf = lambda: check_request.sign(messages.CheckRequest(operation=op))
     expect(testf).to(raise_error(ValueError))
 def test_should_fail_if_no_buckets_are_set(self):
     testf = lambda: distribution.add_sample(_UNDERFLOW_SAMPLE,
                                             self.NOTHING_SET)
     expect(testf).to(raise_error(ValueError))
Example #54
0
    def test_retrieve_a_not_exists_attribute_raises_expection(
            self, simple_dict):
        def mock_for_retrieve_attr():
            simple_dict.d

        expect(mock_for_retrieve_attr).to(raise_error(AttributeError))
 def test_should_fail_on_dissimilar_bucket_counts(self):
     for _, d2, d3 in self.merge_triples:
         testf = lambda: distribution.merge(d2, d3)
         expect(testf).to(raise_error(ValueError))
Example #56
0
 def test_constructor_should_fail_on_bad_deques(self):
     testf = lambda: caches.DequeOutTTLCache(_TEST_NUM_ENTRIES, _TEST_TTL,
                                             out_deque=object())
     expect(testf).to(raise_error(ValueError))
 def test_should_fail_if_scale_is_bad(self):
     testf = lambda: distribution.create_exponential(1, 1.1, -0.1)
     expect(testf).to(raise_error(ValueError))
Example #58
0
            dict2: Dict[str, int] = {'three': 3, 'four': 4}
            chain = ChainMap(dict1, dict2)
            assert chain['three'] == 3
            assert chain['one'] == 1

    with context('MappingProxyType'):
        with it('is a read-only dictionary'):
            writable = {'one': 1, 'two': 2}
            read_only = MappingProxyType(writable)
            assert read_only['one'] == 1

            def set_item(x):
                read_only['two'] = x

            expect(lambda: set_item(42)).to(
                raise_error(TypeError))

    with context('Lists'):
        with it('is mutable'):
            arr: List[str] = ['one', 'two', 'three']
            assert len(arr) == 3

            arr[1] = 'hello'
            assert arr == ['one', 'hello', 'three']

            del arr[1]
            assert arr == ['one', 'three']

            arr.append('ok')
            assert arr == ['one', 'three', 'ok']
 def test_should_fail_as_report_request_on_incomplete_info(self):
     timer = _DateTimeTimer()
     incomplete = report_request.Info()  # has no service_name
     rules = report_request.ReportingRules()
     testf = lambda: incomplete.as_report_request(rules, timer=timer)
     expect(testf).to(raise_error(ValueError))