def unittest(): """Compatibility with Python's unittest package""" signals = set() example = Tests() @example.test def simple(): signals.add("one") class Test(TestBase): @test def simple(self): signals.add("two") Test = example.register(Test) # Python 2.5 # unittest.TestCase TestCase = example.test_case() TestCase("test_simple").debug() assert signals == set(["one"]) # unittest.TestSuite test_suite = example.test_suite() signals.clear() test_suite.debug() assert signals == set(["one", "two"])
def testcase_naming(): example = Tests() @example.test def simple(): pass @example.test def simple(): """Duplicate name, should have ``_2`` appended.""" class Test(TestBase): @test def simple(): """Another duplicate, should have ``_3`` appended.""" Test = example.register(Test) # Python 2.5 @example.test def test_something(): """Already prepended with ``test_`` - should be used verbatim.""" example.test(lambda self: None) TestCase = example.test_case() assert TestCase.test_simple assert TestCase.test_simple_2 assert TestCase.test_simple_3 assert TestCase.test_something assert TestCase.test_lambda
def decorative_conditional(): """@Tests().register_if(condition)(TestBase)""" col = Tests() class IncludedTest(TestBase): @test def foo(self): pass @test def bar(self): pass class ExcludedTest(TestBase): @test def spam(self): pass @test def eggs(self): pass col.register_if(True)(IncludedTest) col.register_if(False)(ExcludedTest) assert len(col) == 2 assert sorted(test.__name__ for test in col) == ['bar', 'foo']
def run(): """Tests().run""" col = Tests() @col.test def fail(): assert 1 == 2 @col.test def succeed(): assert 1 == 1 @col.test def exit(): raise SystemExit result = TestReporter() with Assert.not_raising(SystemExit): col.run(result) assert len(result.failed) == 2 assert len(result.succeeded) == 1 assert result.failed[0].test.__wrapped__ is fail assert result.failed[0].exc_info[0] is TestFailure assert result.succeeded[0].test.__wrapped__ is succeed
def tests(args): all_tests = Tests( [ common.common_unit(), listfetch.listfetch_unit(noweb=args.noweb), jikenparser.jikenparser_unit(noweb=args.noweb), ], ) return all_tests
def flask_tests(): tests = Tests() @tests.context def request_context(): app = create_app() with app.test_request_context(): yield dict(name='Rudolf') return tests
def listfetch_unit(noweb=False): tests = Tests() tests.test(detect_jiken_url) tests.test(detect_en_jiken_url) tests.test(get_hanreiid) tests.test(get_en_hanreiid) tests.test(detect_all_jiken_urls) tests.test(detect_all_en_jiken_urls) if not noweb: tests.test(fetch_jiken_page) return tests
def class_context(): """TestBase().__context__""" instance = Contextual() col = Tests([instance]) result = TestReporter() col.run(result) assert hasattr(instance, 'two') == False assert len(result.failed) == 0 assert len(result.succeeded) == 1
def decorator(): """@Tests().test""" col = Tests() @col.test def one(): pass @col.test def two(): pass assert len(col) == 2 assert [func.__wrapped__ for func in col] == [one, two]
def conditional(): """@Tests().test_if(condition)""" col = Tests(replace_tests=True) @col.test_if(True) def include(): pass @col.test_if(False) def exclude(): pass assert include in col assert exclude not in col
def response_proxy_suite(): proxy = Tests() class Response(object): pass @proxy.context def prepare_new_proxy(): yield ResponseProxy(Response) @proxy.test def is_instance_of_the_target(proxy): assert isinstance(proxy, Response) return proxy
def jikenparser_unit(noweb=False): tests = Tests() tests.test(parse_single_attribute) tests.test(parse_single_attribute_from_en_table) tests.test(detect_all_hanrei_attrs) tests.test(detect_all_en_hanrei_attrs) tests.test(create_hanrei_struct) tests.test(create_en_hanrei_struct) tests.test(fetch_full_text) if not noweb: tests.test(full_text_from_web) tests.test(create_hanrei_elem) tests.test(create_hanrei_xml) tests.test(create_en_hanrei_xml) tests.test(en_attr_conversions) return tests
def classbased_test_runs(): """Tests().register(TestBase())""" instance = Classy() col = Tests([instance]) assert len(col) == 2 assert list(col)[0] == instance.fail result = TestReporter() col.run(result) assert len(result.succeeded) == 1 assert len(result.failed) == 1 assert result.failed[0].test == instance.fail assert result.failed[0].exc_info[0] is TestFailure
def response_stack_suite(): stack = Tests() @stack.context def prepare_new_stack(): yield ResponseStack() @stack.test def pop_returns_the_removed_item(stack): stack.push(1) assert stack.pop() == 1 assert len(stack) == 0 @stack.test def top_is_null_if_stack_is_empty(stack): assert stack.top() is None return stack
def decorative(): """@Tests().register(TestBase)""" col = Tests() assert len(col) == 0 class DecoratedTest(TestBase): @test def noop(self): pass @test def nothing(self): pass DecoratedTest = col.register(DecoratedTest) assert issubclass(DecoratedTest, TestBase) == True assert len(col) == 2
def conditional(): """@test_if(condition)""" col = Tests() class TestClass(TestBase): @test def foo(self): pass @test_if(True) def bar(self): pass @test_if(False) def baz(self): assert False col.register(TestClass) result = TestReporter() col.run(result) assert len(result.failed) == 0 assert len(result.succeeded) == 2
@test def peek(self): iterator = PeekableIterator(range(10)) with Assert.raises(ValueError): iterator.peek(0) with Assert.raises(ValueError): iterator.peek(-1) Assert(iterator.peek(11)) == range(10) Assert(iterator.peek(10)) == range(10) for item, expected in zip(iterator, range(10)): Assert(item) == expected iterator = PeekableIterator(range(10)) Assert(iterator.peek()) == iterator.peek() Assert(iterator.peek()) == [0] Assert(iterator.peek(10)) == range(10) Assert(iterator.peek(5)) == range(5) @test def repr(self): original = iter(xrange(10)) iterator = PeekableIterator(original) Assert(repr(iterator)) == 'PeekableIterator(%r)' % iter(original) tests = Tests([TestPeekableIterator])
Tests for mod:`brownie.abstract`. :copyright: 2010-2011 by Daniel Neuhäuser :license: BSD, see LICENSE.rst for details """ import sys from attest import Tests, TestBase, test_if, test, Assert from brownie.itools import product from brownie.abstract import VirtualSubclassMeta, ABCMeta, AbstractClassMeta GE_PYTHON_26 = sys.version_info >= (2, 6) tests = Tests() @tests.test_if(GE_PYTHON_26) def test_virtual_subclass_meta(): from abc import ABCMeta class Foo(object): __metaclass__ = ABCMeta class Bar(object): __metaclass__ = ABCMeta class Simple(object): __metaclass__ = VirtualSubclassMeta virtual_superclasses = [Foo, Bar]
# coding: utf-8 """Test the core table functionality.""" from __future__ import absolute_import, unicode_literals from attest import assert_hook, raises, Tests, warns import copy from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator import django_tables2 as tables from django_tables2.tables import DeclarativeColumnsMetaclass import six import itertools core = Tests() class UnorderedTable(tables.Table): i = tables.Column() alpha = tables.Column() beta = tables.Column() class OrderedTable(UnorderedTable): class Meta: order_by = 'alpha' MEMORY_DATA = [ { 'i': 2, 'alpha': 'b', 'beta': 'b' },
from __future__ import with_statement import inspect from contextlib import contextmanager from attest import Tests, assert_hook, utils, disable_imports, raises import attest from attest.utils import import_dotted_name suite = Tests() @suite.test def terminal_size(): size = utils.get_terminal_size() assert type(size) is tuple assert len(size) == 2 assert type(size[0]) is int assert type(size[1]) is int with disable_imports('fcntl', 'termios'): size = utils.get_terminal_size() assert size == (80, 24) size = utils.get_terminal_size((1, 2)) assert size == (1, 2) @suite.test def string_importing(): assert import_dotted_name('attest') is attest assert import_dotted_name('attest.tests') is attest.tests assert import_dotted_name('attest.utils') is utils assert import_dotted_name('attest.utils:import_dotted_name') \
# -*- coding: utf-8 -*- from attest import assert_hook, raises, Tests import django_tables2 as tables from django_tables2 import utils rows = Tests() @rows.test def bound_rows(): class SimpleTable(tables.Table): name = tables.Column() data = [ { 'name': 'Bradley' }, { 'name': 'Chris' }, { 'name': 'Peter' }, ] table = SimpleTable(data) # iteration records = [] for row in table.rows: records.append(row.record)
from contextlib import contextmanager import json from flask import (Flask, session, get_flashed_messages, url_for, request, signals_available) from flask.views import MethodView from flask.ext.login import ( encode_cookie, decode_cookie, make_next_param, login_url, LoginManager, login_user, logout_user, current_user, login_required, LoginRequiredMixin, LOGIN_MESSAGE, confirm_login, UserMixin, AnonymousUser, make_secure_token, user_logged_in, user_logged_out, user_loaded_from_cookie, user_login_confirmed, user_unauthorized, user_needs_refresh, session_protected, fresh_login_required, _create_identifier) from werkzeug.exceptions import Unauthorized from werkzeug.utils import parse_cookie login = Tests() # utilities class User(UserMixin): def __init__(self, name, id, active=True): self.id = id self.name = name self.active = active def is_active(self): return self.active def get_auth_token(self): return make_secure_token(self.name, key="deterministic")
from __future__ import absolute_import, unicode_literals import os os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.app.settings' from attest import Tests import django_attest from .columns import columns from .config import config from .core import core from .models import models from .rows import rows from .templates import templates from .utils import utils loader = django_attest.FancyReporter.test_loader everything = Tests([columns, config, core, models, rows, templates, utils]) # ----------------------------------------------------------------------------- junit = Tests() @junit.test def make_junit_output(): import xmlrunner runner = xmlrunner.XMLTestRunner(output=b'reports') runner.run(everything.test_suite()) # -----------------------------------------------------------------------------
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with CSjark. If not, see <http://www.gnu.org/licenses/>. """ Module for testing the config module. """ import sys, os from attest import Tests, assert_hook import config from config import Options # Test that configuration support range rules. range_rule = Tests() @range_rule.context def create_ranges(): """Create range rules for testing.""" text = ''' Structs: - name: test ranges: - member: percent min: 10 max: 30 - type: int max: 15.5 '''
# You should have received a copy of the GNU General Public License # along with CSjark. If not, see <http://www.gnu.org/licenses/>. """ Module for testing the csjark module. Especially command line interface. """ import sys, os from attest import Tests, assert_hook, contexts import csjark import config import cparser import dissector # Tests for the command line interface. cli = Tests() @cli.context def create_cli(): """Create Cli as a context to reset it afterwards.""" c = config.Options defaults = c.verbose, c.debug, c.use_cpp, c.output_dir, c.output_file yield c c.verbose, c.debug, c.use_cpp, c.output_dir, c.output_file = defaults @cli.test def cli_headerfile1(cli): """Test the default commandline interface flags""" header = os.path.join(os.path.dirname(__file__), 'cpp.h')
def context(): """@Tests().context""" col = Tests(replace_tests=True) @col.test def test(calculated): assert calculated == 2 @col.context def context(): calculated = 1 + 1 yield calculated @col.test def noctx(): pass test() noctx() col2 = Tests() @col2.context def empty(): yield @col2.test def test2(): pass test2() col3 = Tests(replace_tests=True) @col3.context def multiple(): yield 1, 2, 3 @col3.test def test3(one, two, three): assert one == 1 assert two == 2 assert three == 3 @col3.test def test3_2(one, two): assert one == 1 assert two == 2 test3() test3_2() col4 = Tests(replace_tests=True) @col4.context def nested(): yield 1 @col4.context def nested(): yield @col4.context def nested(): yield 2 @col4.test def test4(one, two): assert one == 1 assert two == 2 test4() from contextlib import contextmanager @contextmanager def context5(): yield 1 col5 = Tests(contexts=[context5], replace_tests=True) @col5.test def test5(one): assert one == 1 test5()
# coding: utf-8 from attest import assert_hook, Tests # pylint: disable=W0611 import itertools from django_attest import TestContext import django_tables2 as tables from .app.models import Person, Occupation models = Tests() models.context(TestContext()) class PersonTable(tables.Table): first_name = tables.Column() last_name = tables.Column() occupation = tables.Column() @models.test def boundrows_iteration(): occupation = Occupation.objects.create(name='Programmer') Person.objects.create(first_name='Bradley', last_name='Ayers', occupation=occupation) Person.objects.create(first_name='Chris', last_name='Doble', occupation=occupation) table = PersonTable(Person.objects.all()) records = [row.record for row in table.rows] expecteds = Person.objects.all() for expected, actual in itertools.izip(expecteds, records):
from .app.models import Person, Region def parse(html): return lxml.html.fromstring(html) def attrs(xml): """ Helper function that returns a dict of XML attributes, given an element. """ return lxml.html.fromstring(xml).attrib database = contextmanager(TestContext()) templates = Tests() class CountryTable(tables.Table): name = tables.Column() capital = tables.Column(orderable=False, verbose_name=ugettext_lazy("capital")) population = tables.Column(verbose_name='population size') currency = tables.Column(visible=False) tld = tables.Column(visible=False, verbose_name='domain') calling_code = tables.Column(accessor='cc', verbose_name='phone ext.') MEMORY_DATA = [{ 'name': 'Germany', 'capital': 'Berlin',
hello | wo\\nrld ------+-------- foo | bar spam | eggs """) with Assert.raises(ValueError): self.writer.table([]) with Assert.raises(ValueError): self.writer.table([['foo', 'bar'], ['spam']]) with Assert.raises(ValueError): self.writer.table([['foo', 'bar']], ['spam']) self.set_writer(stream=FlushStream()) self.writer.table(content) Assert(len(self.stream.contents)) == 2 Assert.isinstance(self.stream.contents[0], basestring) Assert(self.stream.contents[1]) == True @test def repr(self): Assert(repr(self.writer)) == ( 'TerminalWriter(' '%r, %r, %r, %r, %r, %r)') % ( self.stream, self.writer.fallback_encoding, self.writer.prefix, self.writer.indent_string, self.writer.autoescape, self.writer.ignore_options) tests = Tests([progress.tests, TestTerminalWriter])
# coding: utf-8 from attest import assert_hook, raises, Tests from django_tables2.utils import (Accessor, AttributeDict, computed_values, OrderByTuple, OrderBy, segment) import itertools import six utils = Tests() @utils.test def orderbytuple(): obt = OrderByTuple(('a', 'b', 'c')) assert obt == (OrderBy('a'), OrderBy('b'), OrderBy('c')) # indexing assert obt[0] == OrderBy('a') assert obt['b'] == OrderBy('b') with raises(KeyError): obt['d'] with raises(TypeError): obt[('tuple', )] # .get sentinel = object() assert obt.get('b', sentinel) is obt['b'] # keying assert obt.get('-', sentinel) is sentinel assert obt.get(0, sentinel) is obt['a'] # indexing assert obt.get(3, sentinel) is sentinel