Ejemplo n.º 1
0
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
Ejemplo n.º 2
0
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
Ejemplo n.º 3
0
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
Ejemplo n.º 4
0
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"])
Ejemplo n.º 5
0
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']
Ejemplo n.º 6
0
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"])
Ejemplo n.º 7
0
def runtests():
    tests = Tests(
        [
            runner_unit,
            utils_unit,
            tree_unit,
            pkg_unit,
        ],
    )
    tests.run()
Ejemplo n.º 8
0
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
Ejemplo n.º 9
0
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
Ejemplo n.º 10
0
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
Ejemplo n.º 11
0
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
Ejemplo n.º 12
0
def tests(args):
    all_tests = Tests(
        [
            common.common_unit(),
            listfetch.listfetch_unit(noweb=args.noweb),
            jikenparser.jikenparser_unit(noweb=args.noweb),
        ],
    )
    return all_tests
Ejemplo n.º 13
0
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
Ejemplo n.º 14
0
def flask_tests():
    tests = Tests()

    @tests.context
    def request_context():
        app = create_app()
        with app.test_request_context():
            yield dict(name='Rudolf')

    return tests
Ejemplo n.º 15
0
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
Ejemplo n.º 16
0
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
Ejemplo n.º 17
0
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']
Ejemplo n.º 18
0
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]
Ejemplo n.º 19
0
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
Ejemplo n.º 20
0
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
Ejemplo n.º 21
0
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
Ejemplo n.º 22
0
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
Ejemplo n.º 23
0
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
Ejemplo n.º 24
0
from attest import Tests

from acrylamid.specs import (lib, readers, filters, filters_builtin, helpers,
                             imprt, views, utils, entry, content, core, search)


testsuite = Tests()
testsuite.register(lib.TestHTMLParser)
testsuite.register(readers.tt)
testsuite.register(filters.TestFilterlist)
testsuite.register(filters.TestFilterTree)
testsuite.register(filters_builtin.tt)
testsuite.register(filters_builtin.Hyphenation)
testsuite.register(helpers.Helpers)
testsuite.register(imprt.Import)
testsuite.register(imprt.RSS)
testsuite.register(imprt.Atom)
testsuite.register(imprt.WordPress)
testsuite.register(views.Tag)
testsuite.register(utils.TestMetadata)
testsuite.register(entry.TestEntry)
testsuite.register(content.SingleEntry)
testsuite.register(content.MultipleEntries)
testsuite.register(core.Cache)
testsuite.register(search.tt)
Ejemplo n.º 25
0
from attest import Tests
from . import resource, image, color


tests = Tests()
tests.register(resource.tests)
tests.register(image.tests)
tests.register(color.tests)

Ejemplo n.º 26
0
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',
Ejemplo n.º 27
0
    :copyright: 2010-2011 by Daniel Neuhäuser
    :license: BSD, see LICENSE.rst for details
"""
import sys

from attest import Tests, TestBase, test, test_if, Assert

from brownie.proxies import as_proxy, get_wrapped, LazyProxy
from brownie.datastructures import missing


GE_PYTHON_26 = sys.version_info >= (2, 6)


tests = Tests()


class TestAsProxy(TestBase):
    @test
    def default_repr(self):
        proxy_cls = as_proxy(type('FooProxy', (object, ), {}))
        Assert(repr(proxy_cls(1))) == '1'

    @test
    def setting_repr(self):
        class FooProxy(object):
            def repr(self, proxied):
                return 'FooProxy(%s)' % repr(proxied)
        FooProxy = as_proxy(FooProxy)
Ejemplo n.º 28
0
        return self.post('/login', data=dict(
            username=username,
            password=password
        ), follow_redirects=True)

    def logout(self):
        return self.get('/logout', follow_redirects=True)


@request_context
def testapp():
    flaskr.app.test_client_class = FlaskrClient
    yield flaskr.app


app = Tests(contexts=[testapp])

@app.context
def tempdb():
    """Before each test, set up a blank database"""
    fd, flaskr.app.config['DATABASE'] = tempfile.mkstemp()
    flaskr.init_db()
    try:
        yield
    finally:
        os.close(fd)
        os.unlink(flaskr.app.config['DATABASE'])


@app.test
@get('/')
Ejemplo n.º 29
0
    ~~~~~~~~~~~~~~~~~~~~~~~~

    Tests for :mod:`brownie.functional`.

    :copyright: 2010-2011 by Daniel Neuhäuser
    :license: BSD, see LICENSE.rst for details
"""
from __future__ import with_statement

from attest import Tests, Assert, TestBase, test

from brownie.functional import compose, flip, curried, fmap
from brownie.tests.functional import signature


tests = Tests([signature.tests])


@tests.test
def test_compose():
    with Assert.raises(TypeError):
        compose()
    add_one = lambda x: x + 1
    mul_two = lambda x: x * 2
    Assert(compose(add_one, mul_two)(1)) == 3

    func = lambda: None
    Assert(compose(func)).is_(func)


@tests.test
Ejemplo n.º 30
0
    table = SequencedTable([], exclude=('c', ))
    table.as_html()


@general.test
def bound_columns_should_support_indexing():
    class SimpleTable(tables.Table):
        a = tables.Column()
        b = tables.Column()

    table = SimpleTable([])
    Assert('b') == table.columns[1].name
    Assert('b') == table.columns['b'].name


linkcolumn = Tests()
linkcolumn.context(TransactionTestContext())

@linkcolumn.test
def unicode():
    """Test LinkColumn"""
    # test unicode values + headings
    class UnicodeTable(tables.Table):
        first_name = tables.LinkColumn('person', args=[A('pk')])
        last_name = tables.LinkColumn('person', args=[A('pk')], verbose_name=u'äÚ¨´ˆÁ˜¨ˆ˜˘Ú…Ò˚ˆπ∆ˆ´')

    dataset = [
        {'pk': 1, 'first_name': u'Brädley', 'last_name': u'∆yers'},
        {'pk': 2, 'first_name': u'Chr…s', 'last_name': u'DÒble'},
    ]
Ejemplo n.º 31
0
import blake2
from attest import Tests

tests = Tests()


@tests.test
def blake2b():
    """Test blake2s results"""
    assert blake2.blake2("blake2", key="blake2") == 'b202b477a797e984e6a2b976ca4cb7d3944004b3ef6cde80341c7853a2dd7e2f9e08cda6d7372812cf75e8c7741fb656cec3a119772e2e715cebc76433fafd4d'
    assert blake2.blake2("hello world", key="hello world") == '45589476ec87eec2e35a20817e822ec894a3c35116dfb8a35b2b966a7193deafbb65684f102a8dee449d75065251e7d8fe71c05b4d2452329caf6c5bb48d66f9'
    assert blake2.blake2("hello world", hashSize=32, key="hello world") == '177a8d7754e0aaa6645179c6c9933c3c57a4880e91223f56ded5d3e3cd7144dd'
    assert blake2.blake2("hello world", hashSize=16, key="hello world") == '8fe7d57f5c53d8afd00f552269502b81'
    assert blake2.blake2("hello world", hashSize=4, key="hello world") == 'bbd7cc6e'
    assert blake2.blake2(None) == None


@tests.test
def blake2s():
    """Test blake2s results"""
    assert blake2.blake2s("blake2", key="blake2") == '9b2c152a9567b530af1dc6549e1f8b67a278b710a1512c92dca5236d27309f87'
    assert blake2.blake2s("hello world", key="hello world") == '846d7f4e70f94df2b07e2f5d59d271d5b4627ab64cc0fc376f411448528bee49'
    assert blake2.blake2s("hello world", hashSize=16, key="hello world") == '4e989fc7739d052dd93ec88962137c08'
    assert blake2.blake2s("hello world", hashSize=4, key="hello world") == 'fef7f902'
    assert blake2.blake2(None) == None



if __name__ == '__main__':
    tests.run()
Ejemplo n.º 32
0
# coding: utf-8
from attest import assert_hook, Tests
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):
        assert expected == actual

Ejemplo n.º 33
0
# -*- 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)
Ejemplo n.º 34
0
# 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):
Ejemplo n.º 35
0
import datetime
import numbers
import re

from attest import Tests

from wand.version import (MAGICK_VERSION, MAGICK_VERSION_INFO,
                          MAGICK_VERSION_NUMBER, MAGICK_RELEASE_DATE,
                          MAGICK_RELEASE_DATE_STRING)
from . import color, image, resource


tests = Tests()
tests.register(resource.tests)  # it must be the first
tests.register(color.tests)
tests.register(image.tests)


@tests.test
def version():
    """Test version strings."""
    match = re.match('^ImageMagick\s+\d+\.\d+\.\d+(?:-\d+)?', MAGICK_VERSION)
    assert match
    assert isinstance(MAGICK_VERSION_INFO, tuple)
    assert (len(MAGICK_VERSION_INFO) ==
            match.group(0).count('.') + match.group(0).count('-') + 1)
    assert all(isinstance(v, int) for v in MAGICK_VERSION_INFO)
    assert isinstance(MAGICK_VERSION_NUMBER, numbers.Integral)
    assert isinstance(MAGICK_RELEASE_DATE, datetime.date)
    assert (MAGICK_RELEASE_DATE_STRING ==
            MAGICK_RELEASE_DATE.strftime('%Y-%m-%d'))
Ejemplo n.º 36
0
    confirm_login,
    UserMixin,
    AnonymousUser,
    make_secure_token,
    user_logged_in,
    user_logged_out,
    user_login_confirmed,
    user_unauthorized,
    user_needs_refresh,
    session_protected,
    fresh_login_required,
)
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")
Ejemplo n.º 37
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""CodinGame: Onboarding Test"""

from attest import Tests
import onboarding

TESTS = Tests()


@TESTS.test
def detect():
    """Test the functionality of the detect method."""
    dictionary_default = {
        'name': '',
        'distance': -1
    }
    assert onboarding.detect() == dictionary_default
    dictionary_defined = {
        'name': 'defined',
        'distance': 42
    }
    assert (onboarding.detect(dictionary_defined['name'],
                              dictionary_defined['distance']) ==
            dictionary_defined)
 

@TESTS.test
def choose():
    assert False 
Ejemplo n.º 38
0
import itertools
from django.conf import settings
from django.test.client import RequestFactory
from django.template import Template, Context
import django_tables2 as tables
from django_attest import TransactionTestContext
from attest import Tests, Assert
from .testapp.models import Person, Occupation


models = Tests()
models.context(TransactionTestContext())


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):
        Assert(expected) == actual
Ejemplo n.º 39
0
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")
Ejemplo n.º 40
0
try:
    import cStringIO as StringIO
except ImportError:
    import StringIO
import warnings

from attest import Tests, raises

from wand.image import ClosedImageError, Image
from wand.color import Color
from wand.exceptions import MissingDelegateError
from wand.font import Font

skip_slow_tests = bool(os.environ.get('WANDTESTS_SKIP_SLOW_TESTS'))

tests = Tests()


def asset(*path):
    return os.path.join(os.path.dirname(__file__), 'assets', *path)


@tests.test
def empty_image():
    with Image() as img:
        assert img.size == (0, 0)


@tests.test
def blank_image():
    gray = Color('#ccc')
Ejemplo n.º 41
0
    brownie.tests.caching
    ~~~~~~~~~~~~~~~~~~~~~

    Tests for :mod:`brownie.caching`.

    :copyright: 2010-2011 by Daniel Neuhäuser
    :license: BSD, see LICENSE.rst for details
"""
import time

from attest import Tests, Assert, TestBase, test

from brownie.caching import cached_property, LRUCache, LFUCache, memoize


tests = Tests()


@tests.test
def test_cached_property():
    class Foo(object):
        def __init__(self):
            self.counter = 0

        @cached_property
        def spam(self):
            self.counter += 1
            return self.counter

    Assert(Foo.spam).is_(Foo.spam)
Ejemplo n.º 42
0
# 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
    '''
Ejemplo n.º 43
0
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') \
Ejemplo n.º 44
0
from response import get, post, request, response, \
                     ResponseStack, ResponseProxy


if 'HTTPBIN_URL' not in os.environ:
    os.environ['HTTPBIN_URL'] = 'http://httpbin.org/'

HTTPBIN_URL = os.environ.get('HTTPBIN_URL')


def httpbin(*suffix):
    """Returns url for HTTPBIN resource."""
    return HTTPBIN_URL + '/'.join(suffix)


suite = Tests()


@apply
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
Ejemplo n.º 45
0
# 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'
    },
Ejemplo n.º 46
0
# 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
Ejemplo n.º 47
0
from attest import Tests
from controlers import shortener, click_info
import requests
import helper

generate = Tests()
code = Tests()
load = Tests()


@generate.test
def gen():
    for i in range(5,10):
        str = helper._id_generator(i)
        assert i == len(str)


@code.test
def chek():
    server_url = 'http://0.0.0.0:8080/'
    url = shortener.short_it('nic.to')
    print url
    r = requests.get(server_url+url, allow_redirects=False)
    assert r.status_code == 301     


@load.test
def chek():
    server_url = 'http://0.0.0.0:8080/'
    url = shortener.short_it('http://www.google.com.ua/')
    for i in range(1000):
Ejemplo n.º 48
0
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()
Ejemplo n.º 49
0
    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]
Ejemplo n.º 50
0
# 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')
Ejemplo n.º 51
0
    @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])
Ejemplo n.º 52
0
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.app.settings'

from attest import Tests
from django_attest import TestContext, FancyReporter
from django_revisionfield.models import Revision
from .app.models import Company, Person


loader = FancyReporter.test_loader
everything = Tests()
everything.context(TestContext())


@everything.test
def creating_model_instance_should_use_new_revision():
    current_revision = Revision.next()
    person = Person.objects.create(name="Brad")
    assert person.revision > current_revision


@everything.test
def saving_model_should_increment_revision():
    person = Person.objects.create(name="Brad")
    revision = person.revision
    person.name = "Sunny"
    person.save()
    assert person.revision > revision
Ejemplo n.º 53
0
# encoding: utf-8
from attest import Tests
from stream import ImageStream
from drive.keys import *
from drive.mbr import ClassicalMBR


mbr = Tests()

@mbr.context
def instantiate_stream():
    stream = ImageStream('d:/edt.raw')
    c = ClassicalMBR.parse_stream(stream)

    yield c

    stream.close()

@mbr.test
def test_mbr(c):
    assert '\x33\xc0\x8e\xd0\xbc' in c[k_bootstrap_code]


@mbr.test
def test_partition_entry(c):
    partition_entry_0 = c[k_PartitionEntries][0]
    assert partition_entry_0[k_status] == 0x80
    assert partition_entry_0[k_starting_chs_address] == (0, 1, 1)
    assert partition_entry_0[k_partition_type] == k_FAT32
    assert partition_entry_0[k_ending_chs_address] == (652, 254, 63)
    assert partition_entry_0[k_first_sector_address] == 63
Ejemplo n.º 54
0
    Tests for :mod:`brownie.parallel`.

    :copyright: 2010 by Daniel Neuhäuser
    :license: BSD, see LICENSE.rst for details
"""
from __future__ import with_statement
import time
from threading import Thread

from attest import Tests, Assert, TestBase, test

from brownie.parallel import get_cpu_count, AsyncResult, TimeoutError


tests = Tests()


@tests.test
def test_get_cpu_count():
    try:
        Assert(get_cpu_count()) > 0
        Assert(get_cpu_count()) == get_cpu_count()
    except NotImplementedError:
        # make sure default is returned if the number of processes cannot be
        # determined
        Assert(get_cpu_count(2)) == 2


class TestAsyncResult(TestBase):
    @test
Ejemplo n.º 55
0
    # return classes of an element as a set
    assert "sortable" in classes(root.findall(".//thead/tr/th")[0])
    assert "asc" in classes(root.findall(".//thead/tr/th")[0])
    assert "sortable" not in classes(root.findall(".//thead/tr/th")[1])


@general.test
def empty_values_triggers_default():
    class Table(tables.Table):
        a = tables.Column(empty_values=(1, 2), default="--")

    table = Table([{"a": 1}, {"a": 2}, {"a": 3}, {"a": 4}])
    assert [x["a"] for x in table.rows] == ["--", "--", 3, 4]


linkcolumn = Tests()
linkcolumn.context(TestContext())


@linkcolumn.test
def unicode():
    """Test LinkColumn"""
    # test unicode values + headings
    class UnicodeTable(tables.Table):
        first_name = tables.LinkColumn("person", args=[A("pk")])
        last_name = tables.LinkColumn("person", args=[A("pk")], verbose_name=u"äÚ¨´ˆÁ˜¨ˆ˜˘Ú…Ò˚ˆπ∆ˆ´")

    dataset = [
        {"pk": 1, "first_name": u"Brädley", "last_name": u"∆yers"},
        {"pk": 2, "first_name": u"Chr…s", "last_name": u"DÒble"},
    ]
Ejemplo n.º 56
0
from __future__ import absolute_import
from attest import Tests
from . import transaction, unit


tests = Tests()
tests.register(transaction.tests)
tests.register(unit.tests)
Ejemplo n.º 57
0
            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])
Ejemplo n.º 58
0
# coding: utf-8
from .app.models import Region
from attest import assert_hook, Tests
from django_attest import TestContext
import django_tables2 as tables
from django_tables2.utils import build_request


views = Tests()
views.context(TestContext())
USING_CBV = hasattr(tables, "SingleTableView")


class DispatchHookMixin(object):
    """
    Returns a response *and* reference to the view.
    """

    def dispatch(self, *args, **kwargs):
        return super(DispatchHookMixin, self).dispatch(*args, **kwargs), self


class SimpleTable(tables.Table):
    class Meta:
        model = Region


@views.test_if(USING_CBV)
def view_should_support_pagination_options():
    for name in ("Queensland", "New South Wales", "Victoria", "Tasmania"):
        Region.objects.create(name=name)