<commit_before>"""Unittest of command entry point."""
#  Copyright 2015 Masayuki Yamamoto
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.

import argparse
import unittest
import unittest.mock as mock

import yanico
import yanico.command

class TestCreateMainParser(unittest.TestCase):
    """yanico.command.create_main_parser() test."""

    def test_version(self):
        """Parse '--version' option."""
        parser = yanico.command.create_main_parser()
        with mock.patch.object(parser, '_print_message') as print_message:
            self.assertRaises(SystemExit, parser.parse_args, ['--version'])
        print_message.assert_called_once_with('yanico version ' +
                                              yanico.__version__ + '\n',
                                              mock.ANY)

    def test_help_long(self):
        """Parse '--help' option."""
        parser = yanico.command.create_main_parser()
        with mock.patch.object(parser, 'print_help') as print_help:
            self.assertRaises(SystemExit, parser.parse_args, ['--help'])
        print_help.assert_called_once_with()

    def test_help_short(self):
        """Parse '-h' option."""
        parser = yanico.command.create_main_parser()
        with mock.patch.object(parser, 'print_help') as print_help:
            self.assertRaises(SystemExit, parser.parse_args, ['-h'])
        print_help.assert_called_once_with()

    @staticmethod
    def test_without_argments():
        """Expect 'run' method that showing help."""
        parser = yanico.command.create_main_parser()
        args = parser.parse_args([])
        with mock.patch.object(parser, 'print_help') as print_help:
            args.run(args)
        print_help.assert_called_once_with()

class TestBuildSubparsers(unittest.TestCase):
    """yanico.command.build_subparsers() test."""

    @staticmethod
    def _init_stub_command():
        """Return entry point having stub command."""
        def run(args):
            """Command body."""
            return args.n * 2

        def register(command_name, subparsers):
            """Command registrant."""
            parser = subparsers.add_parser(command_name)
            parser.add_argument('n', type=int)
            parser.set_defaults(run=run)

        entry_point = mock.Mock()
        entry_point.name = 'stub'
        entry_point.load.return_value = register
        return entry_point

    @mock.patch('pkg_resources.iter_entry_points')
    def test_stub_command(self, iter_entry_points):
        """Register command returning two times numbers."""
        iter_entry_points.return_value = [self._init_stub_command()]

        parser = argparse.ArgumentParser()
        yanico.command.build_subparsers(parser)
        args = parser.parse_args(['stub', '21'])
        self.assertEqual(args.run(args), 42)
        iter_entry_points.assert_called_once_with('yanico.commands')

    @mock.patch('pkg_resources.iter_entry_points')
    def test_without_arguments(self, iter_entry_points):
        """Expect 'run' method that showing help."""
        iter_entry_points.return_value = [self._init_stub_command()]

        parser = yanico.command.create_main_parser()
        yanico.command.build_subparsers(parser)
        args = parser.parse_args([])
        with mock.patch.object(parser, 'print_help') as print_help:
            args.run(args)
        print_help.assert_called_once_with()
        iter_entry_points.assert_called_once_with('yanico.commands')

class TestMain(unittest.TestCase):
    """yanico.command.main() test."""
<commit_msg>Add stub parser for entry point test<commit_after>"""Unittest of command entry point."""
#  Copyright 2015 Masayuki Yamamoto
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.

import argparse
import unittest
import unittest.mock as mock

import yanico
import yanico.command

class TestCreateMainParser(unittest.TestCase):
    """yanico.command.create_main_parser() test."""

    def test_version(self):
        """Parse '--version' option."""
        parser = yanico.command.create_main_parser()
        with mock.patch.object(parser, '_print_message') as print_message:
            self.assertRaises(SystemExit, parser.parse_args, ['--version'])
        print_message.assert_called_once_with('yanico version ' +
                                              yanico.__version__ + '\n',
                                              mock.ANY)

    def test_help_long(self):
        """Parse '--help' option."""
        parser = yanico.command.create_main_parser()
        with mock.patch.object(parser, 'print_help') as print_help:
            self.assertRaises(SystemExit, parser.parse_args, ['--help'])
        print_help.assert_called_once_with()

    def test_help_short(self):
        """Parse '-h' option."""
        parser = yanico.command.create_main_parser()
        with mock.patch.object(parser, 'print_help') as print_help:
            self.assertRaises(SystemExit, parser.parse_args, ['-h'])
        print_help.assert_called_once_with()

    @staticmethod
    def test_without_argments():
        """Expect 'run' method that showing help."""
        parser = yanico.command.create_main_parser()
        args = parser.parse_args([])
        with mock.patch.object(parser, 'print_help') as print_help:
            args.run(args)
        print_help.assert_called_once_with()

class TestBuildSubparsers(unittest.TestCase):
    """yanico.command.build_subparsers() test."""

    @staticmethod
    def _init_stub_command():
        """Return entry point having stub command."""
        def run(args):
            """Command body."""
            return args.n * 2

        def register(command_name, subparsers):
            """Command registrant."""
            parser = subparsers.add_parser(command_name)
            parser.add_argument('n', type=int)
            parser.set_defaults(run=run)

        entry_point = mock.Mock()
        entry_point.name = 'stub'
        entry_point.load.return_value = register
        return entry_point

    @mock.patch('pkg_resources.iter_entry_points')
    def test_stub_command(self, iter_entry_points):
        """Register command returning two times numbers."""
        iter_entry_points.return_value = [self._init_stub_command()]

        parser = argparse.ArgumentParser()
        yanico.command.build_subparsers(parser)
        args = parser.parse_args(['stub', '21'])
        self.assertEqual(args.run(args), 42)
        iter_entry_points.assert_called_once_with('yanico.commands')

    @mock.patch('pkg_resources.iter_entry_points')
    def test_without_arguments(self, iter_entry_points):
        """Expect 'run' method that showing help."""
        iter_entry_points.return_value = [self._init_stub_command()]

        parser = yanico.command.create_main_parser()
        yanico.command.build_subparsers(parser)
        args = parser.parse_args([])
        with mock.patch.object(parser, 'print_help') as print_help:
            args.run(args)
        print_help.assert_called_once_with()
        iter_entry_points.assert_called_once_with('yanico.commands')

class TestMain(unittest.TestCase):
    """yanico.command.main() test."""

    @staticmethod
    def _init_stub_parser():
        """Return parser having command that returns integer."""
        parser = argparse.ArgumentParser()
        subparsers = parser.add_subparsers()
        stub_parser = subparsers.add_parser('stub')
        stub_parser.add_argument('n', type=int)
        stub_parser.set_defaults(run=lambda args: args.n)
        return parser
<|endoftext|>


<commit_before>from testkit.context import *

def test_context_user():
    from contextlib import contextmanager
    test_dict = dict(value='before')
    @contextmanager
    def test_context(test_dict):
        test_dict['value'] = 'during'
        yield 'test'
        test_dict['value'] = 'after'
    ctx = ContextUser(test_context(test_dict))
    assert test_dict['value'] == 'before'
    ctx.enter()
    assert test_dict['value'] == 'during'
    ctx.exit()
    assert test_dict['value'] == 'after'

class my_context(ContextDecorator):
    def before(self):
        self.hello = 'hello'
        self.done = False

    def after(self):
        self.done = True

def test_context_decorator_as_decorator():
    as_decorator = my_context()
    @as_decorator
    def hello(context):
        assert context.hello == 'hello'
    hello()
    assert as_decorator.done == True

def test_context_decorator_as_decorator_exception():
    as_decorator = my_context()
    fake_message = 'A fake error!'
    @as_decorator
    def hello(context):
        raise Exception(fake_message)
    try:
        hello()
    except Exception, e:
        assert e.message == fake_message
    assert as_decorator.done == True

def test_context_decorator_as_context():
    as_context = my_context()
    with as_context as context:
        assert context.hello == 'hello'
        assert context.done == False
    assert context.done == True

def test_context_decorator_as_context_exception():
    as_context = my_context()
    fake_message = 'error!'
    try:
        with as_context as context:
            raise Exception(fake_message)
    except Exception, e:
        assert e.message == fake_message
    assert context.done == True

class my_other_context(ContextDecorator):
    def before(self):
        self.hello = 'hello'
        self.done = False
        return self.hello

    def after(self):
        self.done = True

def test_context_decorator_before_returns_custom_context():
    as_context = my_other_context()
    with as_context as hello:
        assert hello == 'hello'
<commit_msg>PEP8 fixes<commit_after>from testkit.context import *

def test_context_user():
    from contextlib import contextmanager
    test_dict = dict(value='before')

    @contextmanager
    def test_context(test_dict):
        test_dict['value'] = 'during'
        yield 'test'
        test_dict['value'] = 'after'
    ctx = ContextUser(test_context(test_dict))
    assert test_dict['value'] == 'before'
    ctx.enter()
    assert test_dict['value'] == 'during'
    ctx.exit()
    assert test_dict['value'] == 'after'

class my_context(ContextDecorator):
    def before(self):
        self.hello = 'hello'
        self.done = False

    def after(self):
        self.done = True

def test_context_decorator_as_decorator():
    as_decorator = my_context()

    @as_decorator
    def hello(context):
        assert context.hello == 'hello'
    hello()
    assert as_decorator.done == True

def test_context_decorator_as_decorator_exception():
    as_decorator = my_context()
    fake_message = 'A fake error!'

    @as_decorator
    def hello(context):
        raise Exception(fake_message)

    try:
        hello()
    except Exception, e:
        assert e.message == fake_message
    assert as_decorator.done == True

def test_context_decorator_as_context():
    as_context = my_context()
    with as_context as context:
        assert context.hello == 'hello'
        assert context.done == False
    assert context.done == True

def test_context_decorator_as_context_exception():
    as_context = my_context()
    fake_message = 'error!'
    try:
        with as_context as context:
            raise Exception(fake_message)
    except Exception, e:
        assert e.message == fake_message
    assert context.done == True

class my_other_context(ContextDecorator):
    def before(self):
        self.hello = 'hello'
        self.done = False
        return self.hello

    def after(self):
        self.done = True

def test_context_decorator_before_returns_custom_context():
    as_context = my_other_context()
    with as_context as hello:
        assert hello == 'hello'
<|endoftext|>


<commit_before>import os
from nose.tools import assert_raises, with_setup, assert_equals
from nose import SkipTest
from webassets import Bundle, Environment
from webassets.filter import Filter, get_filter, register_filter
from helpers import BuildTestHelper

class TestFilter:
    """Test the API ``Filter`` provides to descendants.
    """

    def test_auto_name(self):
        """Test the automatic generation of the filter name.
        """
        assert type('Foo', (Filter,), {}).name == 'foo'
        assert type('FooFilter', (Filter,), {}).name == 'foo'
        assert type('FooBarFilter', (Filter,), {}).name == 'foobar'

        assert type('Foo', (Filter,), {'name': 'custom'}).name == 'custom'
        assert type('Foo', (Filter,), {'name': None}).name == None

    def test_get_config(self):
        """Test the ``get_config`` helper.
        """
        m = Environment(None, None)
        f = Filter()
        f.set_environment(m)
        get_config = f.get_config

        # For the purposes of the following tests, we use two test
        # names which we expect to be undefined in both settings
        # and environment.
        NAME = 'FOO%s' % id(object())
        NAME2 = 'FOO%s' % id(NAME)
        assert NAME != NAME2
        assert not NAME in os.environ and not NAME2 in os.environ
        assert not NAME in m._config and not NAME2 in m._config

        try:
            # Test raising of error, and test not raising it.
            assert_raises(EnvironmentError, get_config, NAME)
            assert get_config(NAME, require=False) == None

            # Start with only the environment variable set.
            os.environ[NAME] = 'bar'
            assert get_config(NAME) == 'bar'
            assert get_config(env=NAME, setting=False) == 'bar'
            assert_raises(EnvironmentError, get_config, setting=NAME, env=False)

            # Set the value in the environment as well.
            m.set_config(NAME, 'foo')
            # Ensure that settings take precedence.
            assert_equals(get_config(NAME), 'foo')
            # Two different names can be supplied.
            assert not NAME2 in m._config
            assert get_config(setting=NAME2, env=NAME) == 'bar'

            # Unset the env variable, now with only the setting.
            del os.environ[NAME]
            assert get_config(NAME) == 'foo'
            assert get_config(setting=NAME, env=False) == 'foo'
            assert_raises(EnvironmentError, get_config, env=NAME)
        finally:
            if NAME in os.environ:
                del os.environ[NAME]
            del m._config[NAME.lower()]

    def test_equality(self):
        """Test the ``unique`` method used to determine equality.
        """
        class TestFilter(Filter):
            def unique(self):
                return getattr(self, 'token', 'bar')
        f1 = TestFilter();
        f2 = TestFilter();

        # As long as the two tokens are equal, the filters are
        # considered to be the same.
        assert f1 == f2
        f1.token = 'foo'
        assert f1 != f2
        f2.token = 'foo'
        assert f1 == f2

        # However, unique() is only per class; two different filter
        # classes will never match...
        class AnotherFilter(TestFilter):
            # ...provided they have a different name.
            name = TestFilter.name + '_2'
            def unique(self):
                return 'foo'
        g = AnotherFilter()
        assert f1 != g

def test_register_filter():
    """Test registration of custom filters.
    """
    # Needs to be a ``Filter`` subclass.
    assert_raises(ValueError, register_filter, object)

    # A name is required.
    class MyFilter(Filter):
        name = None
        def output(self, *a, **kw): pass
    assert_raises(ValueError, register_filter, MyFilter)

    # The same filter cannot be registered under multiple names.
    MyFilter.name = 'foo'
    register_filter(MyFilter)
    MyFilter.name = 'bar'
    register_filter(MyFilter)

    # But the same name cannot be registered multiple times.
    assert_raises(KeyError, register_filter, MyFilter)

    # A filter needs to have at least one of the input or output methods.
    class BrokenFilter(Filter):
        name = 'broken'
    assert_raises(TypeError, register_filter, BrokenFilter)

def test_get_filter():
    """Test filter resolving.
    """
    # By name - here using one of the builtins.
    assert isinstance(get_filter('jsmin'), Filter)
    assert_raises(ValueError, get_filter, 'notafilteractually')

    # By class.
    class MyFilter(Filter): pass
    assert isinstance(get_filter(MyFilter), MyFilter)
    assert_raises(ValueError, get_filter, object())

    # Passing an instance doesn't do anything.
    f = MyFilter()
    assert id(get_filter(f)) == id(f)

    # Passing a lone callable will give us a a filter back as well.
    assert hasattr(get_filter(lambda: None), 'output')

    # Arguments passed to get_filter are used for instance creation.
    assert get_filter('sass', scss=True).use_scss == True
    # However, this is not allowed when a filter instance is passed directly,
    # or a callable object.
    assert_raises(AssertionError, get_filter, f, 'test')
    assert_raises(AssertionError, get_filter, lambda: None, 'test')

class TestBuiltinFilters(BuildTestHelper):
    """
    TODO: Add tests for all the builtin filters.
    """

    default_files = {
        'foo.css': """
            h1  {
                font-family: "Verdana"  ;
                color: #FFFFFF;
            }
        """,
        'foo.sass': '''h1
            font-family: "Verdana"
            color: #FFFFFF
        '''}

    def test_cssmin(self):
        try:
            self.mkbundle('foo.css', filters='cssmin', output='out.css').build()
            assert self.get('out.css') == """h1{font-family:"Verdana";color:#FFF}"""
        except EnvironmentError:
            # cssmin is not installed, that's ok.
            pass

    def test_compass(self):
        # As long as http://github.com/chriseppstein/compass/issues#issue/129
        # remains unfixed, the Compass filter doesn't actually work.
        raise SkipTest()
        #self.mkbundle('foo.sass', filters='compass', output='out.css').build()
        #assert self.get('out.css') == """/* line 1, in.sass */\nh1 {\n  font-family: "Verdana";\n  color: white;\n}\n"""

    def test_sass(self):
        sass = get_filter('sass', debug_info=False)
        self.mkbundle('foo.sass', filters=sass, output='out.css').build()
        assert self.get('out.css') == """/* line 1 */\nh1 {\n  font-family: "Verdana";\n  color: white;\n}\n"""

    def test_sass_import(self):
        """Test referencing other files in sass.
        """
        sass = get_filter('sass', debug_info=False)
        self.create_files({'import-test.sass': '''@import foo.sass'''})
        self.mkbundle('import-test.sass', filters=sass, output='out.css').build()
        assert self.get('out.css') == """/* line 1, ./foo.sass */\nh1 {\n  font-family: "Verdana";\n  color: white;\n}\n"""

    def test_scss(self):
        # SCSS is a CSS superset, should be able to compile the CSS file just fine
        scss = get_filter('scss', debug_info=False)
        self.mkbundle('foo.css', filters=scss, output='out.css').build()
        assert self.get('out.css') == """/* line 2 */\nh1 {\n  font-family: "Verdana";\n  color: #FFFFFF;\n}\n"""<commit_msg>Now that we can create an empty, fresh "environment" of our own, rather than relying on the one provided Django, it's really unnecessary to play it quite as safe when testing Filter.get_config().<commit_after>import os
from nose.tools import assert_raises, with_setup, assert_equals
from nose import SkipTest
from webassets import Bundle, Environment
from webassets.filter import Filter, get_filter, register_filter
from helpers import BuildTestHelper

class TestFilter:
    """Test the API ``Filter`` provides to descendants.
    """

    def test_auto_name(self):
        """Test the automatic generation of the filter name.
        """
        assert type('Foo', (Filter,), {}).name == 'foo'
        assert type('FooFilter', (Filter,), {}).name == 'foo'
        assert type('FooBarFilter', (Filter,), {}).name == 'foobar'

        assert type('Foo', (Filter,), {'name': 'custom'}).name == 'custom'
        assert type('Foo', (Filter,), {'name': None}).name == None

    def test_get_config(self):
        """Test the ``get_config`` helper.
        """
        m = Environment(None, None)
        f = Filter()
        f.set_environment(m)
        get_config = f.get_config

        # For the purposes of the following tests, we use two test
        # names which we expect to be undefined in os.env.
        NAME = 'FOO%s' % id(object())
        NAME2 = 'FOO%s' % id(NAME)
        assert NAME != NAME2
        assert not NAME in os.environ and not NAME2 in os.environ

        try:
            # Test raising of error, and test not raising it.
            assert_raises(EnvironmentError, get_config, NAME)
            assert get_config(NAME, require=False) == None

            # Start with only the environment variable set.
            os.environ[NAME] = 'bar'
            assert get_config(NAME) == 'bar'
            assert get_config(env=NAME, setting=False) == 'bar'
            assert_raises(EnvironmentError, get_config, setting=NAME, env=False)

            # Set the value in the environment as well.
            m.set_config(NAME, 'foo')
            # Ensure that settings take precedence.
            assert_equals(get_config(NAME), 'foo')
            # Two different names can be supplied.
            assert get_config(setting=NAME2, env=NAME) == 'bar'

            # Unset the env variable, now with only the setting.
            del os.environ[NAME]
            assert get_config(NAME) == 'foo'
            assert get_config(setting=NAME, env=False) == 'foo'
            assert_raises(EnvironmentError, get_config, env=NAME)
        finally:
            if NAME in os.environ:
                del os.environ[NAME]

    def test_equality(self):
        """Test the ``unique`` method used to determine equality.
        """
        class TestFilter(Filter):
            def unique(self):
                return getattr(self, 'token', 'bar')
        f1 = TestFilter();
        f2 = TestFilter();

        # As long as the two tokens are equal, the filters are
        # considered to be the same.
        assert f1 == f2
        f1.token = 'foo'
        assert f1 != f2
        f2.token = 'foo'
        assert f1 == f2

        # However, unique() is only per class; two different filter
        # classes will never match...
        class AnotherFilter(TestFilter):
            # ...provided they have a different name.
            name = TestFilter.name + '_2'
            def unique(self):
                return 'foo'
        g = AnotherFilter()
        assert f1 != g

def test_register_filter():
    """Test registration of custom filters.
    """
    # Needs to be a ``Filter`` subclass.
    assert_raises(ValueError, register_filter, object)

    # A name is required.
    class MyFilter(Filter):
        name = None
        def output(self, *a, **kw): pass
    assert_raises(ValueError, register_filter, MyFilter)

    # The same filter cannot be registered under multiple names.
    MyFilter.name = 'foo'
    register_filter(MyFilter)
    MyFilter.name = 'bar'
    register_filter(MyFilter)

    # But the same name cannot be registered multiple times.
    assert_raises(KeyError, register_filter, MyFilter)

    # A filter needs to have at least one of the input or output methods.
    class BrokenFilter(Filter):
        name = 'broken'
    assert_raises(TypeError, register_filter, BrokenFilter)

def test_get_filter():
    """Test filter resolving.
    """
    # By name - here using one of the builtins.
    assert isinstance(get_filter('jsmin'), Filter)
    assert_raises(ValueError, get_filter, 'notafilteractually')

    # By class.
    class MyFilter(Filter): pass
    assert isinstance(get_filter(MyFilter), MyFilter)
    assert_raises(ValueError, get_filter, object())

    # Passing an instance doesn't do anything.
    f = MyFilter()
    assert id(get_filter(f)) == id(f)

    # Passing a lone callable will give us a a filter back as well.
    assert hasattr(get_filter(lambda: None), 'output')

    # Arguments passed to get_filter are used for instance creation.
    assert get_filter('sass', scss=True).use_scss == True
    # However, this is not allowed when a filter instance is passed directly,
    # or a callable object.
    assert_raises(AssertionError, get_filter, f, 'test')
    assert_raises(AssertionError, get_filter, lambda: None, 'test')

class TestBuiltinFilters(BuildTestHelper):
    """
    TODO: Add tests for all the builtin filters.
    """

    default_files = {
        'foo.css': """
            h1  {
                font-family: "Verdana"  ;
                color: #FFFFFF;
            }
        """,
        'foo.sass': '''h1
            font-family: "Verdana"
            color: #FFFFFF
        '''}

    def test_cssmin(self):
        try:
            self.mkbundle('foo.css', filters='cssmin', output='out.css').build()
            assert self.get('out.css') == """h1{font-family:"Verdana";color:#FFF}"""
        except EnvironmentError:
            # cssmin is not installed, that's ok.
            pass

    def test_compass(self):
        # As long as http://github.com/chriseppstein/compass/issues#issue/129
        # remains unfixed, the Compass filter doesn't actually work.
        raise SkipTest()
        #self.mkbundle('foo.sass', filters='compass', output='out.css').build()
        #assert self.get('out.css') == """/* line 1, in.sass */\nh1 {\n  font-family: "Verdana";\n  color: white;\n}\n"""

    def test_sass(self):
        sass = get_filter('sass', debug_info=False)
        self.mkbundle('foo.sass', filters=sass, output='out.css').build()
        assert self.get('out.css') == """/* line 1 */\nh1 {\n  font-family: "Verdana";\n  color: white;\n}\n"""

    def test_sass_import(self):
        """Test referencing other files in sass.
        """
        sass = get_filter('sass', debug_info=False)
        self.create_files({'import-test.sass': '''@import foo.sass'''})
        self.mkbundle('import-test.sass', filters=sass, output='out.css').build()
        assert self.get('out.css') == """/* line 1, ./foo.sass */\nh1 {\n  font-family: "Verdana";\n  color: white;\n}\n"""

    def test_scss(self):
        # SCSS is a CSS superset, should be able to compile the CSS file just fine
        scss = get_filter('scss', debug_info=False)
        self.mkbundle('foo.css', filters=scss, output='out.css').build()
        assert self.get('out.css') == """/* line 2 */\nh1 {\n  font-family: "Verdana";\n  color: #FFFFFF;\n}\n"""<|endoftext|>


<commit_before>"""
Unit tests for hxl_proxy.filters module
David Megginson
March 2015

License: Public Domain
"""

import unittest
import sys

from hxl.io import ArrayInput, HXLReader
from hxl_proxy.filters import *

DATA = [
    ['#org', '#sector', '#country'],
    ['Org A', 'WASH', 'Country A'],
    ['Org B', 'Health', 'Country B'],
    ['Org C', 'Protection', 'Country A']
]

class TestPipelineFunctions(unittest.TestCase):

    def setUp(self):
        self.input = ArrayInput(DATA)
        self.source = HXLReader(self.input)

    def test_add_add_filter(self):
        """Test constructing a hxl.filters.AddFilter from HTTP parameters."""
        args = {
            'add-tag05': '#country',
            'add-header05': 'Country name',
            'add-value05': 'Mali',
            'add-before05': 'on'
        }
        filter = add_add_filter(self.source, args, 5)
        self.assertEqual('AddFilter', filter.__class__.__name__)
        self.assertEqual(self.source, filter.source)
        self.assertEqual(args['add-tag05'], filter.values[0][0].tag)
        self.assertEqual(args['add-value05'], filter.values[0][1])
        self.assertTrue(filter.before)

    def test_add_clean_filter(self):
        """Test constructing a hxl.filters.CleanFilter from HTTP parameters."""
        args = {
            'clean-whitespace-tags07': 'adm1,sector-cluster',
            'clean-upper-tags07': 'adm1_id,sector_id',
            'clean-lower-tags07': 'org_id,agesex_id',
            'clean-date-tags07': 'from_date,to_date',
            'clean-number-tags07': 'aff_num+idp,targeted_num'
        }
        filter = add_clean_filter(self.source, args, 7)
        self.assertEqual('CleanFilter', filter.__class__.__name__)
        self.assertEqual(['#adm1', '#sector-cluster'], [str(p) for p in filter.whitespace])
        self.assertEqual(['#adm1_id', '#sector_id'], [str(p) for p in filter.upper])
        self.assertEqual(['#org_id', '#agesex_id'], [str(p) for p in filter.lower])
        self.assertEqual(['#from_date', '#to_date'], [str(p) for p in filter.date])
        self.assertEqual(['#aff_num+idp', '#targeted_num'], [str(p) for p in filter.number])

    def test_add_count_filter(self):
        """Test constructing a hxl.filters.CountFilter from HTTP parameters."""
        args = {
            'count-tags03': 'country,adm1,adm2+ocha',
            'count-aggregate-tag03': 'targeted_num+f'
        }
        filter = add_count_filter(self.source, args, 3)
        self.assertEqual('CountFilter', filter.__class__.__name__)
        self.assertEqual(['#country', '#adm1', '#adm2+ocha'], [str(p) for p in filter.count_tags])
        self.assertEqual('#targeted_num+f', str(filter.aggregate_tag))

# end
<commit_msg>Added unit tests for adding a cut filter.<commit_after>"""
Unit tests for hxl_proxy.filters module
David Megginson
March 2015

License: Public Domain
"""

import unittest
import sys

from hxl.io import ArrayInput, HXLReader
from hxl_proxy.filters import *

DATA = [
    ['#org', '#sector', '#country'],
    ['Org A', 'WASH', 'Country A'],
    ['Org B', 'Health', 'Country B'],
    ['Org C', 'Protection', 'Country A']
]

class TestPipelineFunctions(unittest.TestCase):

    def setUp(self):
        self.input = ArrayInput(DATA)
        self.source = HXLReader(self.input)

    def test_add_add_filter(self):
        """Test constructing a hxl.filters.AddFilter from HTTP parameters."""
        args = {
            'add-tag05': '#country',
            'add-header05': 'Country name',
            'add-value05': 'Mali',
            'add-before05': 'on'
        }
        filter = add_add_filter(self.source, args, 5)
        self.assertEqual('AddFilter', filter.__class__.__name__)
        self.assertEqual(self.source, filter.source)
        self.assertEqual(args['add-tag05'], filter.values[0][0].tag)
        self.assertEqual(args['add-value05'], filter.values[0][1])
        self.assertTrue(filter.before)

    def test_add_clean_filter(self):
        """Test constructing a hxl.filters.CleanFilter from HTTP parameters."""
        args = {
            'clean-whitespace-tags07': 'adm1,sector-cluster',
            'clean-upper-tags07': 'adm1_id,sector_id',
            'clean-lower-tags07': 'org_id,agesex_id',
            'clean-date-tags07': 'from_date,to_date',
            'clean-number-tags07': 'aff_num+idp,targeted_num'
        }
        filter = add_clean_filter(self.source, args, 7)
        self.assertEqual('CleanFilter', filter.__class__.__name__)
        self.assertEqual(self.source, filter.source)
        self.assertEqual(['#adm1', '#sector-cluster'], [str(p) for p in filter.whitespace])
        self.assertEqual(['#adm1_id', '#sector_id'], [str(p) for p in filter.upper])
        self.assertEqual(['#org_id', '#agesex_id'], [str(p) for p in filter.lower])
        self.assertEqual(['#from_date', '#to_date'], [str(p) for p in filter.date])
        self.assertEqual(['#aff_num+idp', '#targeted_num'], [str(p) for p in filter.number])

    def test_add_count_filter(self):
        """Test constructing a hxl.filters.CountFilter from HTTP parameters."""
        args = {
            'count-tags03': 'country,adm1,adm2+ocha',
            'count-aggregate-tag03': 'targeted_num+f'
        }
        filter = add_count_filter(self.source, args, 3)
        self.assertEqual('CountFilter', filter.__class__.__name__)
        self.assertEqual(self.source, filter.source)
        self.assertEqual(['#country', '#adm1', '#adm2+ocha'], [str(p) for p in filter.count_tags])
        self.assertEqual('#targeted_num+f', str(filter.aggregate_tag))

    def test_add_cut_filter(self):
        args = {
            'cut-include-tags01': 'org,adm1,adm2+pcode',
            'cut-exclude-tags01': 'email+external,name-ngo'
        }
        filter = add_cut_filter(self.source, args, 1)
        self.assertEqual('CutFilter', filter.__class__.__name__)
        self.assertEqual(self.source, filter.source)
        self.assertEqual(['#org', '#adm1', '#adm2+pcode'], [str(p) for p in filter.include_tags])
        self.assertEqual(['#email+external', '#name-ngo'], [str(p) for p in filter.exclude_tags])

# end
<|endoftext|>


<commit_before>import json
import unittest
import responses
from unittest import mock

import kairos_face

class KairosApiGalleryTest(unittest.TestCase):
    def setUp(self):
        kairos_face.settings.app_id = 'app_id'
        kairos_face.settings.app_key = 'app_key'

    def test_throws_exception_when_app_id_is_not_set(self):
        kairos_face.settings.app_id = None

        with self.assertRaises(kairos_face.SettingsNotPresentException):
            kairos_face.get_gallery(gallery_name='gallery')

    def test_throws_exception_when_app_key_is_not_set(self):
        kairos_face.settings.app_key = None

        with self.assertRaises(kairos_face.SettingsNotPresentException):
            kairos_face.get_gallery(gallery_name='gallery')

    @mock.patch('kairos_face.requests.post')
    def test_passes_app_id_and_key_in_post_header(self, post_mock):
        post_mock.return_value.status_code = 200

        kairos_face.get_gallery(gallery_name='gallery')

        _, kwargs = post_mock.call_args
        expected_headers = {
            'app_id': 'app_id',
            'app_key': 'app_key'
        }
        self.assertTrue('headers' in kwargs)
        self.assertEqual(expected_headers, kwargs['headers'])

    @mock.patch('kairos_face.requests.post')
    def test_payload_with_gallery_name_is_passed_in_request(self, post_mock):
        post_mock.return_value.status_code = 200

        kairos_face.get_gallery(gallery_name='gallery')

        _, kwargs = post_mock.call_args
        expected_payload = {
            'gallery_name': 'gallery'
        }
        self.assertTrue('json' in kwargs)
        self.assertEqual(expected_payload, kwargs['json'])

    @responses.activate
    def test_getting_non_existing_gallery_raises_an_exception(self):
        response_body = {"Errors": [{"ErrCode": 5004, "Message": "gallery name not found"}]}
        responses.add(responses.POST, 'https://api.kairos.com/gallery/view',
                      status=200,
                      body=json.dumps(response_body))

        with self.assertRaises(kairos_face.ServiceRequestError):
            kairos_face.get_gallery('non-existing-gallery')

    @responses.activate
    def test_returned_gallery_has_gallery_name(self):
        response_body = {
            "time": 0.00991,
            "status": "Complete",
            "subject_ids": [
                "subject1"
            ]
        }
        responses.add(responses.POST, 'https://api.kairos.com/gallery/view',
                      status=200,
                      body=json.dumps(response_body))

        gallery = kairos_face.get_gallery('a-gallery')

        self.assertEqual('a-gallery', gallery.name)

    @responses.activate
    def test_returned_gallery_has_face_subjects_list(self):
        response_body = {
              "time": 0.00991,
              "status": "Complete",
              "subject_ids": [
                "subject1",
                "subject2",
                "subject3"
              ]
        }
        responses.add(responses.POST, 'https://api.kairos.com/gallery/view',
                      status=200,
                      body=json.dumps(response_body))

        gallery = kairos_face.get_gallery('a-gallery')

        self.assertEqual(3, len(gallery.subjects))
        self.assertTrue('subject1' in gallery.subjects)
        self.assertTrue('subject2' in gallery.subjects)
        self.assertTrue('subject3' in gallery.subjects)

class KairosApiGetGalleriesListTest(unittest.TestCase):
    def setUp(self):
        kairos_face.settings.app_id = 'app_id'
        kairos_face.settings.app_key = 'app_key'

    def test_throws_exception_when_app_id_is_not_set(self):
        kairos_face.settings.app_id = None

        with self.assertRaises(kairos_face.SettingsNotPresentException):
            kairos_face.get_galleries_names_list()

    def test_throws_exception_when_app_key_is_not_set(self):
        kairos_face.settings.app_key = None

        with self.assertRaises(kairos_face.SettingsNotPresentException):
            kairos_face.get_galleries_names_list()

    @responses.activate
    def test_returns_empty_list_when_no_galleries_are_present(self):
        response_body = {
            "time": 0.00991,
            "status": "Complete",
            "gallery_names": []
        }
        responses.add(responses.POST, 'https://api.kairos.com/gallery/list_all',
                      status=200,
                      body=json.dumps(response_body))

        galleries_list = kairos_face.get_galleries_names_list()

        self.assertEqual(0, len(galleries_list))

    @responses.activate
    def test_returns_availables_galleries_names(self):
        response_body = {
            "time": 0.00991,
            "status": "Complete",
            "gallery_ids": [
                'gallery1',
                'gallery2'
            ]
        }
        responses.add(responses.POST, 'https://api.kairos.com/gallery/list_all',
                      status=200,
                      body=json.dumps(response_body))

        galleries_list = kairos_face.get_galleries_names_list()

        self.assertEqual(2, len(galleries_list))
        self.assertTrue('gallery1' in galleries_list)
        self.assertTrue('gallery2' in galleries_list)
<commit_msg>Fixing type in test name<commit_after>import json
import unittest
import responses
from unittest import mock

import kairos_face

class KairosApiGalleryTest(unittest.TestCase):
    def setUp(self):
        kairos_face.settings.app_id = 'app_id'
        kairos_face.settings.app_key = 'app_key'

    def test_throws_exception_when_app_id_is_not_set(self):
        kairos_face.settings.app_id = None

        with self.assertRaises(kairos_face.SettingsNotPresentException):
            kairos_face.get_gallery(gallery_name='gallery')

    def test_throws_exception_when_app_key_is_not_set(self):
        kairos_face.settings.app_key = None

        with self.assertRaises(kairos_face.SettingsNotPresentException):
            kairos_face.get_gallery(gallery_name='gallery')

    @mock.patch('kairos_face.requests.post')
    def test_passes_app_id_and_key_in_post_header(self, post_mock):
        post_mock.return_value.status_code = 200

        kairos_face.get_gallery(gallery_name='gallery')

        _, kwargs = post_mock.call_args
        expected_headers = {
            'app_id': 'app_id',
            'app_key': 'app_key'
        }
        self.assertTrue('headers' in kwargs)
        self.assertEqual(expected_headers, kwargs['headers'])

    @mock.patch('kairos_face.requests.post')
    def test_payload_with_gallery_name_is_passed_in_request(self, post_mock):
        post_mock.return_value.status_code = 200

        kairos_face.get_gallery(gallery_name='gallery')

        _, kwargs = post_mock.call_args
        expected_payload = {
            'gallery_name': 'gallery'
        }
        self.assertTrue('json' in kwargs)
        self.assertEqual(expected_payload, kwargs['json'])

    @responses.activate
    def test_getting_non_existing_gallery_raises_an_exception(self):
        response_body = {"Errors": [{"ErrCode": 5004, "Message": "gallery name not found"}]}
        responses.add(responses.POST, 'https://api.kairos.com/gallery/view',
                      status=200,
                      body=json.dumps(response_body))

        with self.assertRaises(kairos_face.ServiceRequestError):
            kairos_face.get_gallery('non-existing-gallery')

    @responses.activate
    def test_returned_gallery_has_gallery_name(self):
        response_body = {
            "time": 0.00991,
            "status": "Complete",
            "subject_ids": [
                "subject1"
            ]
        }
        responses.add(responses.POST, 'https://api.kairos.com/gallery/view',
                      status=200,
                      body=json.dumps(response_body))

        gallery = kairos_face.get_gallery('a-gallery')

        self.assertEqual('a-gallery', gallery.name)

    @responses.activate
    def test_returned_gallery_has_face_subjects_list(self):
        response_body = {
              "time": 0.00991,
              "status": "Complete",
              "subject_ids": [
                "subject1",
                "subject2",
                "subject3"
              ]
        }
        responses.add(responses.POST, 'https://api.kairos.com/gallery/view',
                      status=200,
                      body=json.dumps(response_body))

        gallery = kairos_face.get_gallery('a-gallery')

        self.assertEqual(3, len(gallery.subjects))
        self.assertTrue('subject1' in gallery.subjects)
        self.assertTrue('subject2' in gallery.subjects)
        self.assertTrue('subject3' in gallery.subjects)

class KairosApiGetGalleriesListTest(unittest.TestCase):
    def setUp(self):
        kairos_face.settings.app_id = 'app_id'
        kairos_face.settings.app_key = 'app_key'

    def test_throws_exception_when_app_id_is_not_set(self):
        kairos_face.settings.app_id = None

        with self.assertRaises(kairos_face.SettingsNotPresentException):
            kairos_face.get_galleries_names_list()

    def test_throws_exception_when_app_key_is_not_set(self):
        kairos_face.settings.app_key = None

        with self.assertRaises(kairos_face.SettingsNotPresentException):
            kairos_face.get_galleries_names_list()

    @responses.activate
    def test_returns_empty_list_when_no_galleries_are_present(self):
        response_body = {
            "time": 0.00991,
            "status": "Complete",
            "gallery_names": []
        }
        responses.add(responses.POST, 'https://api.kairos.com/gallery/list_all',
                      status=200,
                      body=json.dumps(response_body))

        galleries_list = kairos_face.get_galleries_names_list()

        self.assertEqual(0, len(galleries_list))

    @responses.activate
    def test_returns_available_galleries_names(self):
        response_body = {
            "time": 0.00991,
            "status": "Complete",
            "gallery_ids": [
                'gallery1',
                'gallery2'
            ]
        }
        responses.add(responses.POST, 'https://api.kairos.com/gallery/list_all',
                      status=200,
                      body=json.dumps(response_body))

        galleries_list = kairos_face.get_galleries_names_list()

        self.assertEqual(2, len(galleries_list))
        self.assertTrue('gallery1' in galleries_list)
        self.assertTrue('gallery2' in galleries_list)
<|endoftext|>


<commit_before>from os import path
from datetime import datetime
import six

import pytest
from flaky import flaky
import requests

from Robinhood import Robinhood
import helpers
if six.PY2:
    from Robinhood import RH_exception

HERE = path.abspath(path.dirname(__file__))
ROOT = path.dirname(HERE)

CONFIG_FILENAME = path.join(HERE, 'test_config.cfg')

CONFIG = helpers.get_config(CONFIG_FILENAME)

TEST_QUOTE = {}

TESTABLE_KEYS = [
    'previous_close_date',
    'symbol',
    'trading_halted',
    'previous_close',
    'last_trade_price_source',
    'instrument'
]
@pytest.mark.incremental
class TestQuoteHelpers:
    """wrapper to test quote architecture in order"""
    test_ticker = CONFIG.get('FETCH', 'test_ticker')
    fake_ticker = CONFIG.get('FETCH', 'fake_ticker')
    rh_obj = Robinhood()
    def test_quote_endpoint(self, config=CONFIG):
        """get raw data from Robinhood to test against"""
        global TEST_QUOTE

        TEST_QUOTE = helpers.fetch_REST_directly(
            'quotes',
            self.test_ticker,
            config
        )

    def test_validate_quote(self):
        """validate fetcher"""
        data = self.rh_obj.quote_data(self.test_ticker)
        if data['updated_at'] == TEST_QUOTE['updated_at']:
            assert data == TEST_QUOTE
        else:
            for key in data.keys(): #SKIP PRICE DATA
                if key in TESTABLE_KEYS:
                    assert data[key] == TEST_QUOTE[key]

    def test_validate_fail_quote(self):
        """validate bad-path exception"""
        with pytest.raises(NameError):
            data = self.rh_obj.quote_data(self.fake_ticker)

    def test_validate_get_quote(self):
        """validate `get_quote` call"""
        data = self.rh_obj.get_quote(self.test_ticker)
        assert data == TEST_QUOTE['symbol']

    @flaky
    def test_validate_ask_price(self):
        """validate `ask_price` call"""
        data = self.rh_obj.ask_price(self.test_ticker)
        quote = self.rh_obj.quote_data(self.test_ticker)

        assert data == quote['ask_price']

    @flaky
    def test_validate_ask_size(self):
        """validate `ask_size` call"""
        data = self.rh_obj.ask_size(self.test_ticker)
        quote = self.rh_obj.quote_data(self.test_ticker)

        assert data == quote['ask_size']

    @flaky
    def test_validate_bid_price(self):
        """validate `bid_price` call"""
        data = self.rh_obj.bid_price(self.test_ticker)
        quote = self.rh_obj.quote_data(self.test_ticker)

        assert data == quote['bid_price']

    @flaky
    def test_validate_bid_size(self):
        """validate `bid_size` call"""
        data = self.rh_obj.bid_size(self.test_ticker)
        quote = self.rh_obj.quote_data(self.test_ticker)

        assert data == quote['bid_size']

    @flaky
    def test_validate_last_trade_price(self):
        """validate `last_trade_price` call"""
        data = self.rh_obj.last_trade_price(self.test_ticker)
        quote = self.rh_obj.quote_data(self.test_ticker)

        assert data == quote['last_trade_price']

    def test_validate_previous_close(self):
        """validate `previous_close` call"""
        data = self.rh_obj.previous_close(self.test_ticker)

        assert data == TEST_QUOTE['previous_close']

    def test_validate_previous_close_date(self):
        """validate `previous_close_date` call"""
        data = self.rh_obj.previous_close_date(self.test_ticker)

        assert data == TEST_QUOTE['previous_close_date']

    def test_validate_adjusted_previous_close(self):
        """validate `adjusted_previous_close` call"""
        data = self.rh_obj.adjusted_previous_close(self.test_ticker)

        assert data == TEST_QUOTE['adjusted_previous_close']

    def test_validate_symbol(self):
        """validate `symbol` call"""
        data = self.rh_obj.symbol(self.test_ticker)

        assert data == TEST_QUOTE['symbol']

    @flaky
    def test_validate_last_updated_at(self):
        """validate `last_updated_at` call"""
        data = self.rh_obj.last_updated_at(self.test_ticker)
        quote = self.rh_obj.quote_data(self.test_ticker)

        assert data == quote['updated_at']

TEST_FUNDAMENTAL = {}
@pytest.mark.incremental
class TestFundamentalsHelpers:
    """wrapper to test fundamental architecture in order"""
    test_ticker = CONFIG.get('FETCH', 'test_ticker')
    fake_ticker = CONFIG.get('FETCH', 'fake_ticker')
    rh_obj = Robinhood()
    def test_fundamental_endpoint(self, config=CONFIG):
        """get raw data from Robinhood to test against"""
        global TEST_FUNDAMENTAL

        TEST_FUNDAMENTAL = helpers.fetch_REST_directly(
            'fundamentals',
            self.test_ticker,
            config
        )
    @flaky
    def test_validate_fundamental(self):
        """validate fetcher"""
        data = self.rh_obj.get_fundamentals(self.test_ticker)
        assert data == TEST_FUNDAMENTAL

    def test_validate_fail_fundamental(self):
        """validate bad-path exception"""
        with pytest.raises(NameError):
            data = self.rh_obj.get_fundamentals(self.fake_ticker)

    def test_validate_fundamental_wrapper(self):
        main_data = self.rh_obj.fundamentals(self.test_ticker)
        wrapped_data = self.rh_obj.fundamentals(self.test_ticker)

        assert wrapped_data == main_data
        assert wrapped_data == TEST_FUNDAMENTAL

TEST_URL_RESULT = {}
@pytest.mark.incremental
class TestURLWrapper:
    """make sure get_url returns expected behavior"""
    base_url = 'https://api.robinhood.com/'
    rh_obj = Robinhood()
    def test_url_endpoint(self):
        """fetch url directly"""
        global TEST_URL_RESULT

        req = requests.get(self.base_url)
        req.raise_for_status()

        TEST_URL_RESULT = req.json()

    def test_get_url(self):
        """fetch url with get_url"""
        data = self.rh_obj.get_url(self.base_url)
        assert data == TEST_URL_RESULT

<commit_msg>adding test for news fetcher<commit_after>from os import path
from datetime import datetime
import six

import pytest
from flaky import flaky
import requests

from Robinhood import Robinhood
import helpers
if six.PY2:
    from Robinhood import RH_exception

HERE = path.abspath(path.dirname(__file__))
ROOT = path.dirname(HERE)

CONFIG_FILENAME = path.join(HERE, 'test_config.cfg')

CONFIG = helpers.get_config(CONFIG_FILENAME)

TEST_QUOTE = {}

TESTABLE_KEYS = [
    'previous_close_date',
    'symbol',
    'trading_halted',
    'previous_close',
    'last_trade_price_source',
    'instrument'
]
@pytest.mark.incremental
class TestQuoteHelpers:
    """wrapper to test quote architecture in order"""
    test_ticker = CONFIG.get('FETCH', 'test_ticker')
    fake_ticker = CONFIG.get('FETCH', 'fake_ticker')
    rh_obj = Robinhood()
    def test_quote_endpoint(self, config=CONFIG):
        """get raw data from Robinhood to test against"""
        global TEST_QUOTE

        TEST_QUOTE = helpers.fetch_REST_directly(
            'quotes',
            self.test_ticker,
            config
        )

    def test_validate_quote(self):
        """validate fetcher"""
        data = self.rh_obj.quote_data(self.test_ticker)
        if data['updated_at'] == TEST_QUOTE['updated_at']:
            assert data == TEST_QUOTE
        else:
            for key in data.keys(): #SKIP PRICE DATA
                if key in TESTABLE_KEYS:
                    assert data[key] == TEST_QUOTE[key]

    def test_validate_fail_quote(self):
        """validate bad-path exception"""
        with pytest.raises(NameError):
            data = self.rh_obj.quote_data(self.fake_ticker)

    def test_validate_get_quote(self):
        """validate `get_quote` call"""
        data = self.rh_obj.get_quote(self.test_ticker)
        assert data == TEST_QUOTE['symbol']

    @flaky
    def test_validate_ask_price(self):
        """validate `ask_price` call"""
        data = self.rh_obj.ask_price(self.test_ticker)
        quote = self.rh_obj.quote_data(self.test_ticker)

        assert data == quote['ask_price']

    @flaky
    def test_validate_ask_size(self):
        """validate `ask_size` call"""
        data = self.rh_obj.ask_size(self.test_ticker)
        quote = self.rh_obj.quote_data(self.test_ticker)

        assert data == quote['ask_size']

    @flaky
    def test_validate_bid_price(self):
        """validate `bid_price` call"""
        data = self.rh_obj.bid_price(self.test_ticker)
        quote = self.rh_obj.quote_data(self.test_ticker)

        assert data == quote['bid_price']

    @flaky
    def test_validate_bid_size(self):
        """validate `bid_size` call"""
        data = self.rh_obj.bid_size(self.test_ticker)
        quote = self.rh_obj.quote_data(self.test_ticker)

        assert data == quote['bid_size']

    @flaky
    def test_validate_last_trade_price(self):
        """validate `last_trade_price` call"""
        data = self.rh_obj.last_trade_price(self.test_ticker)
        quote = self.rh_obj.quote_data(self.test_ticker)

        assert data == quote['last_trade_price']

    def test_validate_previous_close(self):
        """validate `previous_close` call"""
        data = self.rh_obj.previous_close(self.test_ticker)

        assert data == TEST_QUOTE['previous_close']

    def test_validate_previous_close_date(self):
        """validate `previous_close_date` call"""
        data = self.rh_obj.previous_close_date(self.test_ticker)

        assert data == TEST_QUOTE['previous_close_date']

    def test_validate_adjusted_previous_close(self):
        """validate `adjusted_previous_close` call"""
        data = self.rh_obj.adjusted_previous_close(self.test_ticker)

        assert data == TEST_QUOTE['adjusted_previous_close']

    def test_validate_symbol(self):
        """validate `symbol` call"""
        data = self.rh_obj.symbol(self.test_ticker)

        assert data == TEST_QUOTE['symbol']

    @flaky
    def test_validate_last_updated_at(self):
        """validate `last_updated_at` call"""
        data = self.rh_obj.last_updated_at(self.test_ticker)
        quote = self.rh_obj.quote_data(self.test_ticker)

        assert data == quote['updated_at']

TEST_FUNDAMENTAL = {}
@pytest.mark.incremental
class TestFundamentalsHelpers:
    """wrapper to test fundamental architecture in order"""
    test_ticker = CONFIG.get('FETCH', 'test_ticker')
    fake_ticker = CONFIG.get('FETCH', 'fake_ticker')
    rh_obj = Robinhood()
    def test_fundamental_endpoint(self, config=CONFIG):
        """get raw data from Robinhood to test against"""
        global TEST_FUNDAMENTAL

        TEST_FUNDAMENTAL = helpers.fetch_REST_directly(
            'fundamentals',
            self.test_ticker,
            config
        )

    @flaky
    def test_validate_fundamental(self):
        """validate fetcher"""
        data = self.rh_obj.get_fundamentals(self.test_ticker)
        assert data == TEST_FUNDAMENTAL

    def test_validate_fail_fundamental(self):
        """validate bad-path exception"""
        with pytest.raises(NameError):
            data = self.rh_obj.get_fundamentals(self.fake_ticker)

    @flaky
    def test_validate_fundamental_wrapper(self):
        main_data = self.rh_obj.fundamentals(self.test_ticker)
        wrapped_data = self.rh_obj.fundamentals(self.test_ticker)

        assert wrapped_data == main_data
        assert wrapped_data == TEST_FUNDAMENTAL

TEST_URL_RESULT = {}
@pytest.mark.incremental
class TestURLWrapper:
    """make sure get_url returns expected behavior"""
    base_url = 'https://api.robinhood.com/'
    rh_obj = Robinhood()
    def test_url_endpoint(self):
        """fetch url directly"""
        global TEST_URL_RESULT

        req = requests.get(self.base_url)
        req.raise_for_status()

        TEST_URL_RESULT = req.json()

    def test_get_url(self):
        """fetch url with get_url"""
        data = self.rh_obj.get_url(self.base_url)
        assert data == TEST_URL_RESULT

def test_get_news(config=CONFIG):
    """test `get_news` endpoint"""
    test_ticker = CONFIG.get('FETCH', 'test_ticker')
    raw_news = helpers.fetch_REST_directly(
        'news',
        test_ticker,
        config
    )
    get_news = Robinhood().get_news(test_ticker)

    assert get_news == raw_news
<|endoftext|>


<commit_before># -*- Mode: Python -*-

import unittest

import gobject
import testhelper

class TestGObjectAPI(unittest.TestCase):
    def testGObjectModule(self):
        obj = gobject.GObject()
        self.assertEquals(obj.__module__,
                          'gobject._gobject')

class TestReferenceCounting(unittest.TestCase):
    def testRegularObject(self):
        obj = gobject.GObject()
        self.assertEquals(obj.__grefcount__, 1)

        obj = gobject.new(gobject.GObject)
        self.assertEquals(obj.__grefcount__, 1)

    def testFloatingWithSinkFunc(self):
        obj = testhelper.FloatingWithSinkFunc()
        self.assertEquals(obj.__grefcount__, 1)

        obj = gobject.new(testhelper.FloatingWithSinkFunc)
        self.assertEquals(obj.__grefcount__, 1)

    def testFloatingWithoutSinkFunc(self):
        obj = testhelper.FloatingWithoutSinkFunc()
        self.assertEquals(obj.__grefcount__, 1)

        obj = gobject.new(testhelper.FloatingWithoutSinkFunc)
        self.assertEquals(obj.__grefcount__, 1)

    def testOwnedByLibrary(self):
        # Upon creation, the refcount of the object should be 2:
        # - someone already has a reference on the new object.
        # - the python wrapper should hold its own reference.
        obj = testhelper.OwnedByLibrary()
        self.assertEquals(obj.__grefcount__, 2)

        # We ask the library to release its reference, so the only
        # remaining ref should be our wrapper's. Once the wrapper
        # will run out of scope, the object will get finalized.
        obj.release()
        self.assertEquals(obj.__grefcount__, 1)

    def testOwnedByLibraryOutOfScope(self):
        obj = testhelper.OwnedByLibrary()
        self.assertEquals(obj.__grefcount__, 2)

        # We are manually taking the object out of scope. This means
        # that our wrapper has been freed, and its reference dropped. We
        # cannot check it but the refcount should now be 1 (the ref held
        # by the library is still there, we didn't call release()
        obj = None

        # When we get the object back from the lib, the wrapper is
        # re-created, so our refcount will be 2 once again.
        obj = testhelper.owned_by_library_get_instance_list()[0]
        self.assertEquals(obj.__grefcount__, 2)

        obj.release()
        self.assertEquals(obj.__grefcount__, 1)

    def testOwnedByLibraryUsingGObjectNew(self):
        # Upon creation, the refcount of the object should be 2:
        # - someone already has a reference on the new object.
        # - the python wrapper should hold its own reference.
        obj = gobject.new(testhelper.OwnedByLibrary)
        self.assertEquals(obj.__grefcount__, 2)

        # We ask the library to release its reference, so the only
        # remaining ref should be our wrapper's. Once the wrapper
        # will run out of scope, the object will get finalized.
        obj.release()
        self.assertEquals(obj.__grefcount__, 1)

    def testOwnedByLibraryOutOfScopeUsingGobjectNew(self):
        obj = gobject.new(testhelper.OwnedByLibrary)
        self.assertEquals(obj.__grefcount__, 2)

        # We are manually taking the object out of scope. This means
        # that our wrapper has been freed, and its reference dropped. We
        # cannot check it but the refcount should now be 1 (the ref held
        # by the library is still there, we didn't call release()
        obj = None

        # When we get the object back from the lib, the wrapper is
        # re-created, so our refcount will be 2 once again.
        obj = testhelper.owned_by_library_get_instance_list()[0]
        self.assertEquals(obj.__grefcount__, 2)

        obj.release()
        self.assertEquals(obj.__grefcount__, 1)

    def testFloatingAndSunk(self):
        # Upon creation, the refcount of the object should be 2:
        # - someone already has a reference on the new object.
        # - the python wrapper should hold its own reference.
        obj = testhelper.FloatingAndSunk()
        self.assertEquals(obj.__grefcount__, 2)

        # We ask the library to release its reference, so the only
        # remaining ref should be our wrapper's. Once the wrapper
        # will run out of scope, the object will get finalized.
        obj.release()
        self.assertEquals(obj.__grefcount__, 1)

    def testFloatingAndSunkOutOfScope(self):
        obj = testhelper.FloatingAndSunk()
        self.assertEquals(obj.__grefcount__, 2)

        # We are manually taking the object out of scope. This means
        # that our wrapper has been freed, and its reference dropped. We
        # cannot check it but the refcount should now be 1 (the ref held
        # by the library is still there, we didn't call release()
        obj = None

        # When we get the object back from the lib, the wrapper is
        # re-created, so our refcount will be 2 once again.
        obj = testhelper.floating_and_sunk_get_instance_list()[0]
        self.assertEquals(obj.__grefcount__, 2)

        obj.release()
        self.assertEquals(obj.__grefcount__, 1)

    def testFloatingAndSunkUsingGObjectNew(self):
        # Upon creation, the refcount of the object should be 2:
        # - someone already has a reference on the new object.
        # - the python wrapper should hold its own reference.
        obj = gobject.new(testhelper.FloatingAndSunk)
        self.assertEquals(obj.__grefcount__, 2)

        # We ask the library to release its reference, so the only
        # remaining ref should be our wrapper's. Once the wrapper
        # will run out of scope, the object will get finalized.
        obj.release()
        self.assertEquals(obj.__grefcount__, 1)

    def testFloatingAndSunkOutOfScopeUsingGObjectNew(self):
        obj = gobject.new(testhelper.FloatingAndSunk)
        self.assertEquals(obj.__grefcount__, 2)

        # We are manually taking the object out of scope. This means
        # that our wrapper has been freed, and its reference dropped. We
        # cannot check it but the refcount should now be 1 (the ref held
        # by the library is still there, we didn't call release()
        obj = None

        # When we get the object back from the lib, the wrapper is
        # re-created, so our refcount will be 2 once again.
        obj = testhelper.floating_and_sunk_get_instance_list()[0]
        self.assertEquals(obj.__grefcount__, 2)

        obj.release()
        self.assertEquals(obj.__grefcount__, 1)
<commit_msg>Add some tests for the number of python refs held at creation time<commit_after># -*- Mode: Python -*-

import unittest

import gobject
import sys
import testhelper

class TestGObjectAPI(unittest.TestCase):
    def testGObjectModule(self):
        obj = gobject.GObject()
        self.assertEquals(obj.__module__,
                          'gobject._gobject')

class TestReferenceCounting(unittest.TestCase):
    def testRegularObject(self):
        obj = gobject.GObject()
        self.assertEquals(obj.__grefcount__, 1)

        obj = gobject.new(gobject.GObject)
        self.assertEquals(obj.__grefcount__, 1)

    def testFloatingWithSinkFunc(self):
        obj = testhelper.FloatingWithSinkFunc()
        self.assertEquals(obj.__grefcount__, 1)

        obj = gobject.new(testhelper.FloatingWithSinkFunc)
        self.assertEquals(obj.__grefcount__, 1)

    def testFloatingWithoutSinkFunc(self):
        obj = testhelper.FloatingWithoutSinkFunc()
        self.assertEquals(obj.__grefcount__, 1)

        obj = gobject.new(testhelper.FloatingWithoutSinkFunc)
        self.assertEquals(obj.__grefcount__, 1)

    def testOwnedByLibrary(self):
        # Upon creation, the refcount of the object should be 2:
        # - someone already has a reference on the new object.
        # - the python wrapper should hold its own reference.
        obj = testhelper.OwnedByLibrary()
        self.assertEquals(obj.__grefcount__, 2)

        # We ask the library to release its reference, so the only
        # remaining ref should be our wrapper's. Once the wrapper
        # will run out of scope, the object will get finalized.
        obj.release()
        self.assertEquals(obj.__grefcount__, 1)

    def testOwnedByLibraryOutOfScope(self):
        obj = testhelper.OwnedByLibrary()
        self.assertEquals(obj.__grefcount__, 2)

        # We are manually taking the object out of scope. This means
        # that our wrapper has been freed, and its reference dropped. We
        # cannot check it but the refcount should now be 1 (the ref held
        # by the library is still there, we didn't call release()
        obj = None

        # When we get the object back from the lib, the wrapper is
        # re-created, so our refcount will be 2 once again.
        obj = testhelper.owned_by_library_get_instance_list()[0]
        self.assertEquals(obj.__grefcount__, 2)

        obj.release()
        self.assertEquals(obj.__grefcount__, 1)

    def testOwnedByLibraryUsingGObjectNew(self):
        # Upon creation, the refcount of the object should be 2:
        # - someone already has a reference on the new object.
        # - the python wrapper should hold its own reference.
        obj = gobject.new(testhelper.OwnedByLibrary)
        self.assertEquals(obj.__grefcount__, 2)

        # We ask the library to release its reference, so the only
        # remaining ref should be our wrapper's. Once the wrapper
        # will run out of scope, the object will get finalized.
        obj.release()
        self.assertEquals(obj.__grefcount__, 1)

    def testOwnedByLibraryOutOfScopeUsingGobjectNew(self):
        obj = gobject.new(testhelper.OwnedByLibrary)
        self.assertEquals(obj.__grefcount__, 2)

        # We are manually taking the object out of scope. This means
        # that our wrapper has been freed, and its reference dropped. We
        # cannot check it but the refcount should now be 1 (the ref held
        # by the library is still there, we didn't call release()
        obj = None

        # When we get the object back from the lib, the wrapper is
        # re-created, so our refcount will be 2 once again.
        obj = testhelper.owned_by_library_get_instance_list()[0]
        self.assertEquals(obj.__grefcount__, 2)

        obj.release()
        self.assertEquals(obj.__grefcount__, 1)

    def testFloatingAndSunk(self):
        # Upon creation, the refcount of the object should be 2:
        # - someone already has a reference on the new object.
        # - the python wrapper should hold its own reference.
        obj = testhelper.FloatingAndSunk()
        self.assertEquals(obj.__grefcount__, 2)

        # We ask the library to release its reference, so the only
        # remaining ref should be our wrapper's. Once the wrapper
        # will run out of scope, the object will get finalized.
        obj.release()
        self.assertEquals(obj.__grefcount__, 1)

    def testFloatingAndSunkOutOfScope(self):
        obj = testhelper.FloatingAndSunk()
        self.assertEquals(obj.__grefcount__, 2)

        # We are manually taking the object out of scope. This means
        # that our wrapper has been freed, and its reference dropped. We
        # cannot check it but the refcount should now be 1 (the ref held
        # by the library is still there, we didn't call release()
        obj = None

        # When we get the object back from the lib, the wrapper is
        # re-created, so our refcount will be 2 once again.
        obj = testhelper.floating_and_sunk_get_instance_list()[0]
        self.assertEquals(obj.__grefcount__, 2)

        obj.release()
        self.assertEquals(obj.__grefcount__, 1)

    def testFloatingAndSunkUsingGObjectNew(self):
        # Upon creation, the refcount of the object should be 2:
        # - someone already has a reference on the new object.
        # - the python wrapper should hold its own reference.
        obj = gobject.new(testhelper.FloatingAndSunk)
        self.assertEquals(obj.__grefcount__, 2)

        # We ask the library to release its reference, so the only
        # remaining ref should be our wrapper's. Once the wrapper
        # will run out of scope, the object will get finalized.
        obj.release()
        self.assertEquals(obj.__grefcount__, 1)

    def testFloatingAndSunkOutOfScopeUsingGObjectNew(self):
        obj = gobject.new(testhelper.FloatingAndSunk)
        self.assertEquals(obj.__grefcount__, 2)

        # We are manually taking the object out of scope. This means
        # that our wrapper has been freed, and its reference dropped. We
        # cannot check it but the refcount should now be 1 (the ref held
        # by the library is still there, we didn't call release()
        obj = None

        # When we get the object back from the lib, the wrapper is
        # re-created, so our refcount will be 2 once again.
        obj = testhelper.floating_and_sunk_get_instance_list()[0]
        self.assertEquals(obj.__grefcount__, 2)

        obj.release()
        self.assertEquals(obj.__grefcount__, 1)

class A(gobject.GObject):
    def __init__(self):
        super(A, self).__init__()

class TestPythonReferenceCounting(unittest.TestCase):
    # Newly created instances should alwayshave two references: one for
    # the GC, and one for the bound variable in the local scope.

    def testNewInstanceHasTwoRefs(self):
        obj = gobject.GObject()
        self.assertEquals(sys.getrefcount(obj), 2)

    def testNewInstanceHasTwoRefsUsingGObjectNew(self):
        obj = gobject.new(gobject.GObject)
        self.assertEquals(sys.getrefcount(obj), 2)

    def testNewSubclassInstanceHasTwoRefs(self):
        obj = A()
        self.assertEquals(sys.getrefcount(obj), 2)
<|endoftext|>


<commit_before># -*- Mode: Python -*-

import unittest

import gobject
import testhelper

class TestGObjectAPI(unittest.TestCase):
    def testGObjectModule(self):
        obj = gobject.GObject()
        self.assertEquals(obj.__module__,
                          'gobject._gobject')
        self.assertEquals(obj.__grefcount__, 1)

class TestFloating(unittest.TestCase):
    def testFloatingWithSinkFunc(self):
        obj = testhelper.FloatingWithSinkFunc()
        self.assertEquals(obj.__grefcount__, 1)

        obj = gobject.new(testhelper.FloatingWithSinkFunc)
        self.assertEquals(obj.__grefcount__, 1)

    def testFloatingWithoutSinkFunc(self):
        obj = testhelper.FloatingWithoutSinkFunc()
        self.assertEquals(obj.__grefcount__, 1)

        obj = gobject.new(testhelper.FloatingWithoutSinkFunc)
        self.assertEquals(obj.__grefcount__, 1)
<commit_msg>Add a test to check for regular object reference count<commit_after># -*- Mode: Python -*-

import unittest

import gobject
import testhelper

class TestGObjectAPI(unittest.TestCase):
    def testGObjectModule(self):
        obj = gobject.GObject()
        self.assertEquals(obj.__module__,
                          'gobject._gobject')

class TestReferenceCounting(unittest.TestCase):
    def testRegularObject(self):
        obj = gobject.GObject()
        self.assertEquals(obj.__grefcount__, 1)

        obj = gobject.new(gobject.GObject)
        self.assertEquals(obj.__grefcount__, 1)

    def testFloatingWithSinkFunc(self):
        obj = testhelper.FloatingWithSinkFunc()
        self.assertEquals(obj.__grefcount__, 1)

        obj = gobject.new(testhelper.FloatingWithSinkFunc)
        self.assertEquals(obj.__grefcount__, 1)

    def testFloatingWithoutSinkFunc(self):
        obj = testhelper.FloatingWithoutSinkFunc()
        self.assertEquals(obj.__grefcount__, 1)

        obj = gobject.new(testhelper.FloatingWithoutSinkFunc)
        self.assertEquals(obj.__grefcount__, 1)
<|endoftext|>


<commit_before>from viper.lexer import lex_line, lex_lines
from viper.parser import *
from viper.parser.ast.ast_to_string import ast_to_string

import viper.lexer as vl
import viper.parser.ast.nodes as ns

import pytest

from typing import List

def run_test(rule: str, tree: AST, lexemes: List[vl.Lexeme], prepend: List[vl.Lexeme], append: List[vl.Lexeme]):
    parse = GRAMMAR.parse_rule(rule, prepend + lexemes + append)
    try:
        assert isinstance(parse, SingleParse)
    except AssertionError:
        print(f"lexemes: {lexemes}")
        print(f"parse: {parse}")
        print(f"ast: {tree}")
        print(f"rule: {rule}")
        raise
    try:
        assert tree == parse.ast
    except AssertionError:
        print(f"Got AST:\n{ast_to_string(parse.ast)}")
        print()
        print(f"Wanted AST:\n{ast_to_string(tree)}")
        raise

@pytest.mark.parametrize('line,tree', [
    ('foo',
     ns.NameAtom(vl.Name('foo'))),
    ('42',
     ns.NumberAtom(vl.Number('42'))),
    ('...',
     ns.EllipsisAtom()),
    ('()',
     ns.ParenAtom([])),
    ('(foo)',
     ns.ParenAtom([ns.OpExpr(None, ns.AtomExpr(ns.NameAtom(vl.Name('foo')), []), [], None)])),
])
def test_atom(line: str, tree: AST):
    lexemes = lex_line(line)
    run_test('atom', tree, lexemes, [], [])

@pytest.mark.parametrize('line,tree', [
    ('foo',
     ns.AtomExpr(ns.NameAtom(vl.Name('foo')), [])),
    ('foo.bar',
     ns.AtomExpr(ns.NameAtom(vl.Name('foo')), [ns.Field(vl.Name('bar'))])),
    ('foo.bar.baz',
     ns.AtomExpr(ns.NameAtom(vl.Name('foo')), [ns.Field(vl.Name('bar')), ns.Field(vl.Name('baz'))])),
    ('foo.bar(baz)',
     ns.AtomExpr(ns.NameAtom(vl.Name('foo')), [ns.Field(vl.Name('bar')),
                                               ns.Call([ns.AtomExpr(ns.NameAtom(vl.Name('baz')), [])])])),
    ('foo.bar(baz, qux)',
     ns.AtomExpr(ns.NameAtom(vl.Name('foo')), [
         ns.Field(vl.Name('bar')),
         ns.Call([ns.AtomExpr(ns.NameAtom(vl.Name('baz')), []), ns.AtomExpr(ns.NameAtom(vl.Name('qux')), [])])
     ])),
    ('foo.bar(baz, qux.quum())',
     ns.AtomExpr(ns.NameAtom(vl.Name('foo')), [
         ns.Field(vl.Name('bar')),
         ns.Call([
             ns.AtomExpr(ns.NameAtom(vl.Name('baz')), []),
             ns.AtomExpr(ns.NameAtom(vl.Name('qux')), [ns.Field(vl.Name('quum')), ns.Call([])])
         ])
     ])),
    ('2.foo',
     ns.AtomExpr(ns.NumberAtom(vl.Number('2')), [ns.Field(vl.Name('foo'))])),
])
def test_expr(line: str, tree: AST):
    lexemes = lex_line(line)
    run_test('atom_expr', tree, lexemes, [], [])

@pytest.mark.parametrize('line,tree', [
    ('foo',
     ns.OpExpr(None, ns.AtomExpr(ns.NameAtom(vl.Name('foo')), []), [], None)),
    ('++ foo',
     ns.OpExpr(vl.Operator('++'), ns.AtomExpr(ns.NameAtom(vl.Name('foo')), []), [], None)),
    ('++ foo --',
     ns.OpExpr(vl.Operator('++'), ns.AtomExpr(ns.NameAtom(vl.Name('foo')), []), [], vl.Operator('--'))),
    ('++ foo || bar --',
     ns.OpExpr(
         vl.Operator('++'),
         ns.AtomExpr(ns.NameAtom(vl.Name('foo')), []),
         [ns.SubOpExpr(
             vl.Operator('||'),
             ns.AtomExpr(ns.NameAtom(vl.Name('bar')), [])
         )],
         vl.Operator('--')
     )),
    ('++ foo ** bar || baz // qux',
     ns.OpExpr(
         vl.Operator('++'),
         ns.AtomExpr(ns.NameAtom(vl.Name('foo')), []),
         [
             ns.SubOpExpr(vl.Operator('**'), ns.AtomExpr(ns.NameAtom(vl.Name('bar')), [])),
             ns.SubOpExpr(vl.Operator('||'), ns.AtomExpr(ns.NameAtom(vl.Name('baz')), [])),
             ns.SubOpExpr(vl.Operator('//'), ns.AtomExpr(ns.NameAtom(vl.Name('qux')), []))
         ],
         None
     )),
])
def test_op_expr(line: str, tree: AST):
    lexemes = lex_line(line)
    run_test('op_expr', tree, lexemes, [], [])

@pytest.mark.parametrize('line,tree', [
    ('pass',
     ns.SimpleStmtBlock(ns.SimpleStmt(ns.EmptyStmt()))),
    ('return',
     ns.SimpleStmtBlock(ns.SimpleStmt(ns.ReturnStmt([])))),
    ('return foo',
     ns.SimpleStmtBlock(ns.SimpleStmt(ns.ReturnStmt([
         ns.OpExpr(None,
                   ns.AtomExpr(ns.NameAtom(vl.Name('foo')), []),
                   [],
                   None)])))),
    ('return foo, ~bar, baz !',
     ns.SimpleStmtBlock(ns.SimpleStmt(ns.ReturnStmt([
         ns.OpExpr(None, ns.AtomExpr(ns.NameAtom(vl.Name('foo')), []), [], None),
         ns.OpExpr(vl.Operator('~'), ns.AtomExpr(ns.NameAtom(vl.Name('bar')), []), [], None),
         ns.OpExpr(None, ns.AtomExpr(ns.NameAtom(vl.Name('baz')), []), [], vl.Operator('!'))
     ])))),
])
def test_stmt_block(line: str, tree: AST):
    lexemes = lex_line(line)
    run_test('stmt_block', tree, lexemes, [], [vl.NEWLINE])

@pytest.mark.parametrize('line,tree', [
    ('foo bar: Baz',
     ns.Parameter(vl.Name('foo'), vl.Name('bar'), vl.Class('Baz'))),
    ('bar: Baz',
     ns.Parameter(None, vl.Name('bar'), vl.Class('Baz'))),
])
def test_parameter(line: str, tree: AST):
    lexemes = lex_line(line)
    run_test('parameter', tree, lexemes, [], [])

@pytest.mark.parametrize('line,tree', [
    ('def foo() -> Bar: pass',
     ns.FuncDef(vl.Name('foo'), [], vl.Class('Bar'), ns.SimpleStmtBlock(ns.SimpleStmt(ns.EmptyStmt())))),
    ('def foo(bar: Baz) -> Qux: pass',
     ns.FuncDef(vl.Name('foo'),
                [
                    ns.Parameter(None, vl.Name('bar'), vl.Class('Baz'))
                ],
                vl.Class('Qux'),
                ns.SimpleStmtBlock(ns.SimpleStmt(ns.EmptyStmt())))),
    ('def foo(a b: C, d: E, f g: H) -> I: pass',
     ns.FuncDef(vl.Name('foo'),
                [
                    ns.Parameter(vl.Name('a'), vl.Name('b'), vl.Class('C')),
                    ns.Parameter(None, vl.Name('d'), vl.Class('E')),
                    ns.Parameter(vl.Name('f'), vl.Name('g'), vl.Class('H'))
                ],
                vl.Class('I'),
                ns.SimpleStmtBlock(ns.SimpleStmt(ns.EmptyStmt())))),
])
def test_func_def(line: str, tree: AST):
    lexemes = lex_line(line)
    run_test('func_def', tree, lexemes, [], [vl.NEWLINE])

@pytest.mark.parametrize('line,tree', [
    ('class Foo: pass',
     ns.ClassDef(vl.Class('Foo'), None, ns.SimpleStmtBlock(ns.SimpleStmt(ns.EmptyStmt())))),
])
def test_class_def(line: str, tree: AST):
    lexemes = lex_line(line)
    run_test('class_def', tree, lexemes, [], [vl.NEWLINE])

@pytest.mark.parametrize('lines,tree', [
    ([
        'if x == y:',
        '    return 42'
     ],
     ns.IfStmt(
         ns.TestExpr(ns.OrTestExpr([ns.AndTestExpr([ns.NotTestExpr([
             ns.OpExpr(None,
                       ns.AtomExpr(ns.NameAtom(vl.Name('x')), []),
                       [ns.SubOpExpr(vl.Operator('=='),
                                     ns.AtomExpr(ns.NameAtom(vl.Name('y')), []))],
                       None)])])])),
         ns.CompoundStmtBlock([ns.SimpleStmt(ns.ReturnStmt([
             ns.OpExpr(None,
                       ns.AtomExpr(ns.NumberAtom(vl.Number('42')), []),
                       [],
                       None)]))]),
         [],
         None)),
    ([
        'if x == y:',
        '    if x == z:',
        '        return 42'
     ],
     ns.IfStmt(
         ns.TestExpr(ns.OrTestExpr([ns.AndTestExpr([ns.NotTestExpr([
             ns.OpExpr(None,
                       ns.AtomExpr(ns.NameAtom(vl.Name('x')), []),
                       [ns.SubOpExpr(vl.Operator('=='),
                                     ns.AtomExpr(ns.NameAtom(vl.Name('y')), []))],
                       None)])])])),
         ns.CompoundStmtBlock([
             ns.IfStmt(
                 ns.TestExpr(ns.OrTestExpr([ns.AndTestExpr([ns.NotTestExpr([
                     ns.OpExpr(None,
                               ns.AtomExpr(ns.NameAtom(vl.Name('x')), []),
                               [ns.SubOpExpr(vl.Operator('=='),
                                             ns.AtomExpr(ns.NameAtom(vl.Name('z')), []))],
                               None)])])])),
                 ns.CompoundStmtBlock([ns.SimpleStmt(ns.ReturnStmt([
                     ns.OpExpr(None,
                               ns.AtomExpr(ns.NumberAtom(vl.Number('42')), []),
                               [],
                               None)]))]),
                 [],
                 None)]),
         [],
         None)),
    ([
        'if x == y:',
        '    pass',
        'else:',
        '    return 42'
     ],
     ns.IfStmt(
         ns.TestExpr(ns.OrTestExpr([ns.AndTestExpr([ns.NotTestExpr([
             ns.OpExpr(None,
                       ns.AtomExpr(ns.NameAtom(vl.Name('x')), []),
                       [ns.SubOpExpr(vl.Operator('=='),
                                     ns.AtomExpr(ns.NameAtom(vl.Name('y')), []))],
                       None)])])])),
         ns.CompoundStmtBlock([ns.SimpleStmt(ns.EmptyStmt())]),
         [],
         ns.ElseStmt(ns.CompoundStmtBlock([ns.SimpleStmt(ns.ReturnStmt([
             ns.OpExpr(None,
                       ns.AtomExpr(ns.NumberAtom(vl.Number('42')), []),
                       [],
                       None)]))])))),
])
def test_if_stmt(lines: List[str], tree: AST):
    lexemes = lex_lines('\n'.join(lines))[:-1]
    run_test('if_stmt', tree, lexemes, [], [])
<commit_msg>Implement more if-stmt/if-expr tests<commit_after>from viper.lexer import lex_line, lex_lines
from viper.parser import *
from viper.parser.ast.ast_to_string import ast_to_string

import viper.lexer as vl
import viper.parser.ast.nodes as ns

import pytest

from typing import List

def run_test(rule: str, tree: AST, lexemes: List[vl.Lexeme], prepend: List[vl.Lexeme], append: List[vl.Lexeme]):
    parse = GRAMMAR.parse_rule(rule, prepend + lexemes + append)
    try:
        assert isinstance(parse, SingleParse)
    except AssertionError:
        print(f"lexemes: {lexemes}")
        print(f"parse: {parse}")
        print(f"ast: {tree}")
        print(f"rule: {rule}")
        raise
    try:
        assert tree == parse.ast
    except AssertionError:
        print(f"Got AST:\n{ast_to_string(parse.ast)}")
        print()
        print(f"Wanted AST:\n{ast_to_string(tree)}")
        raise

@pytest.mark.parametrize('line,tree', [
    ('foo',
     ns.NameAtom(vl.Name('foo'))),
    ('42',
     ns.NumberAtom(vl.Number('42'))),
    ('...',
     ns.EllipsisAtom()),
    ('()',
     ns.ParenAtom([])),
    ('(foo)',
     ns.ParenAtom([ns.OpExpr(None, ns.AtomExpr(ns.NameAtom(vl.Name('foo')), []), [], None)])),
])
def test_atom(line: str, tree: AST):
    lexemes = lex_line(line)
    run_test('atom', tree, lexemes, [], [])

@pytest.mark.parametrize('line,tree', [
    ('foo',
     ns.AtomExpr(ns.NameAtom(vl.Name('foo')), [])),
    ('foo.bar',
     ns.AtomExpr(ns.NameAtom(vl.Name('foo')), [ns.Field(vl.Name('bar'))])),
    ('foo.bar.baz',
     ns.AtomExpr(ns.NameAtom(vl.Name('foo')), [ns.Field(vl.Name('bar')), ns.Field(vl.Name('baz'))])),
    ('foo.bar(baz)',
     ns.AtomExpr(ns.NameAtom(vl.Name('foo')), [ns.Field(vl.Name('bar')),
                                               ns.Call([ns.AtomExpr(ns.NameAtom(vl.Name('baz')), [])])])),
    ('foo.bar(baz, qux)',
     ns.AtomExpr(ns.NameAtom(vl.Name('foo')), [
         ns.Field(vl.Name('bar')),
         ns.Call([ns.AtomExpr(ns.NameAtom(vl.Name('baz')), []), ns.AtomExpr(ns.NameAtom(vl.Name('qux')), [])])
     ])),
    ('foo.bar(baz, qux.quum())',
     ns.AtomExpr(ns.NameAtom(vl.Name('foo')), [
         ns.Field(vl.Name('bar')),
         ns.Call([
             ns.AtomExpr(ns.NameAtom(vl.Name('baz')), []),
             ns.AtomExpr(ns.NameAtom(vl.Name('qux')), [ns.Field(vl.Name('quum')), ns.Call([])])
         ])
     ])),
    ('2.foo',
     ns.AtomExpr(ns.NumberAtom(vl.Number('2')), [ns.Field(vl.Name('foo'))])),
])
def test_expr(line: str, tree: AST):
    lexemes = lex_line(line)
    run_test('atom_expr', tree, lexemes, [], [])

@pytest.mark.parametrize('line,tree', [
    ('foo',
     ns.OpExpr(None, ns.AtomExpr(ns.NameAtom(vl.Name('foo')), []), [], None)),
    ('++ foo',
     ns.OpExpr(vl.Operator('++'), ns.AtomExpr(ns.NameAtom(vl.Name('foo')), []), [], None)),
    ('++ foo --',
     ns.OpExpr(vl.Operator('++'), ns.AtomExpr(ns.NameAtom(vl.Name('foo')), []), [], vl.Operator('--'))),
    ('++ foo || bar --',
     ns.OpExpr(
         vl.Operator('++'),
         ns.AtomExpr(ns.NameAtom(vl.Name('foo')), []),
         [ns.SubOpExpr(
             vl.Operator('||'),
             ns.AtomExpr(ns.NameAtom(vl.Name('bar')), [])
         )],
         vl.Operator('--')
     )),
    ('++ foo ** bar || baz // qux',
     ns.OpExpr(
         vl.Operator('++'),
         ns.AtomExpr(ns.NameAtom(vl.Name('foo')), []),
         [
             ns.SubOpExpr(vl.Operator('**'), ns.AtomExpr(ns.NameAtom(vl.Name('bar')), [])),
             ns.SubOpExpr(vl.Operator('||'), ns.AtomExpr(ns.NameAtom(vl.Name('baz')), [])),
             ns.SubOpExpr(vl.Operator('//'), ns.AtomExpr(ns.NameAtom(vl.Name('qux')), []))
         ],
         None
     )),
])
def test_op_expr(line: str, tree: AST):
    lexemes = lex_line(line)
    run_test('op_expr', tree, lexemes, [], [])

@pytest.mark.parametrize('line,tree', [
    ('pass',
     ns.SimpleStmtBlock(ns.SimpleStmt(ns.EmptyStmt()))),
    ('return',
     ns.SimpleStmtBlock(ns.SimpleStmt(ns.ReturnStmt([])))),
    ('return foo',
     ns.SimpleStmtBlock(ns.SimpleStmt(ns.ReturnStmt([
         ns.OpExpr(None,
                   ns.AtomExpr(ns.NameAtom(vl.Name('foo')), []),
                   [],
                   None)])))),
    ('return foo, ~bar, baz !',
     ns.SimpleStmtBlock(ns.SimpleStmt(ns.ReturnStmt([
         ns.OpExpr(None, ns.AtomExpr(ns.NameAtom(vl.Name('foo')), []), [], None),
         ns.OpExpr(vl.Operator('~'), ns.AtomExpr(ns.NameAtom(vl.Name('bar')), []), [], None),
         ns.OpExpr(None, ns.AtomExpr(ns.NameAtom(vl.Name('baz')), []), [], vl.Operator('!'))
     ])))),
])
def test_stmt_block(line: str, tree: AST):
    lexemes = lex_line(line)
    run_test('stmt_block', tree, lexemes, [], [vl.NEWLINE])

@pytest.mark.parametrize('line,tree', [
    ('foo bar: Baz',
     ns.Parameter(vl.Name('foo'), vl.Name('bar'), vl.Class('Baz'))),
    ('bar: Baz',
     ns.Parameter(None, vl.Name('bar'), vl.Class('Baz'))),
])
def test_parameter(line: str, tree: AST):
    lexemes = lex_line(line)
    run_test('parameter', tree, lexemes, [], [])

@pytest.mark.parametrize('line,tree', [
    ('def foo() -> Bar: pass',
     ns.FuncDef(vl.Name('foo'), [], vl.Class('Bar'), ns.SimpleStmtBlock(ns.SimpleStmt(ns.EmptyStmt())))),
    ('def foo(bar: Baz) -> Qux: pass',
     ns.FuncDef(vl.Name('foo'),
                [
                    ns.Parameter(None, vl.Name('bar'), vl.Class('Baz'))
                ],
                vl.Class('Qux'),
                ns.SimpleStmtBlock(ns.SimpleStmt(ns.EmptyStmt())))),
    ('def foo(a b: C, d: E, f g: H) -> I: pass',
     ns.FuncDef(vl.Name('foo'),
                [
                    ns.Parameter(vl.Name('a'), vl.Name('b'), vl.Class('C')),
                    ns.Parameter(None, vl.Name('d'), vl.Class('E')),
                    ns.Parameter(vl.Name('f'), vl.Name('g'), vl.Class('H'))
                ],
                vl.Class('I'),
                ns.SimpleStmtBlock(ns.SimpleStmt(ns.EmptyStmt())))),
])
def test_func_def(line: str, tree: AST):
    lexemes = lex_line(line)
    run_test('func_def', tree, lexemes, [], [vl.NEWLINE])

@pytest.mark.parametrize('line,tree', [
    ('class Foo: pass',
     ns.ClassDef(vl.Class('Foo'), None, ns.SimpleStmtBlock(ns.SimpleStmt(ns.EmptyStmt())))),
])
def test_class_def(line: str, tree: AST):
    lexemes = lex_line(line)
    run_test('class_def', tree, lexemes, [], [vl.NEWLINE])

@pytest.mark.parametrize('lines,tree', [
    ([
        'if x == y:',
        '    return 42'
     ],
     ns.IfStmt(
         ns.TestExpr(ns.OrTestExpr([ns.AndTestExpr([ns.NotTestExpr([
             ns.OpExpr(None,
                       ns.AtomExpr(ns.NameAtom(vl.Name('x')), []),
                       [ns.SubOpExpr(vl.Operator('=='),
                                     ns.AtomExpr(ns.NameAtom(vl.Name('y')), []))],
                       None)])])])),
         ns.CompoundStmtBlock([ns.SimpleStmt(ns.ReturnStmt([
             ns.OpExpr(None,
                       ns.AtomExpr(ns.NumberAtom(vl.Number('42')), []),
                       [],
                       None)]))]),
         [],
         None)),
    ([
        'if x == y:',
        '    if x == z:',
        '        return 42'
     ],
     ns.IfStmt(
         ns.TestExpr(ns.OrTestExpr([ns.AndTestExpr([ns.NotTestExpr([
             ns.OpExpr(None,
                       ns.AtomExpr(ns.NameAtom(vl.Name('x')), []),
                       [ns.SubOpExpr(vl.Operator('=='),
                                     ns.AtomExpr(ns.NameAtom(vl.Name('y')), []))],
                       None)])])])),
         ns.CompoundStmtBlock([
             ns.IfStmt(
                 ns.TestExpr(ns.OrTestExpr([ns.AndTestExpr([ns.NotTestExpr([
                     ns.OpExpr(None,
                               ns.AtomExpr(ns.NameAtom(vl.Name('x')), []),
                               [ns.SubOpExpr(vl.Operator('=='),
                                             ns.AtomExpr(ns.NameAtom(vl.Name('z')), []))],
                               None)])])])),
                 ns.CompoundStmtBlock([ns.SimpleStmt(ns.ReturnStmt([
                     ns.OpExpr(None,
                               ns.AtomExpr(ns.NumberAtom(vl.Number('42')), []),
                               [],
                               None)]))]),
                 [],
                 None)]),
         [],
         None)),
    ([
        'if x == y:',
        '    pass',
        'else:',
        '    return 42'
     ],
     ns.IfStmt(
         ns.TestExpr(ns.OrTestExpr([ns.AndTestExpr([ns.NotTestExpr([
             ns.OpExpr(None,
                       ns.AtomExpr(ns.NameAtom(vl.Name('x')), []),
                       [ns.SubOpExpr(vl.Operator('=='),
                                     ns.AtomExpr(ns.NameAtom(vl.Name('y')), []))],
                       None)])])])),
         ns.CompoundStmtBlock([ns.SimpleStmt(ns.EmptyStmt())]),
         [],
         ns.ElseStmt(ns.CompoundStmtBlock([ns.SimpleStmt(ns.ReturnStmt([
             ns.OpExpr(None,
                       ns.AtomExpr(ns.NumberAtom(vl.Number('42')), []),
                       [],
                       None)]))])))),
    ([
        'if x == y: pass',
        'else:',
        '    return 42'
     ],
     ns.IfStmt(
         ns.TestExpr(ns.OrTestExpr([ns.AndTestExpr([ns.NotTestExpr([
             ns.OpExpr(None,
                       ns.AtomExpr(ns.NameAtom(vl.Name('x')), []),
                       [ns.SubOpExpr(vl.Operator('=='),
                                     ns.AtomExpr(ns.NameAtom(vl.Name('y')), []))],
                       None)])])])),
         ns.SimpleStmtBlock(ns.SimpleStmt(ns.EmptyStmt())),
         [],
         ns.ElseStmt(ns.CompoundStmtBlock([ns.SimpleStmt(ns.ReturnStmt([
             ns.OpExpr(None,
                       ns.AtomExpr(ns.NumberAtom(vl.Number('42')), []),
                       [],
                       None)]))])))),
    ([
        'if x == y: pass',
        'else: return 42'
     ],
     ns.IfStmt(
         ns.TestExpr(ns.OrTestExpr([ns.AndTestExpr([ns.NotTestExpr([
             ns.OpExpr(None,
                       ns.AtomExpr(ns.NameAtom(vl.Name('x')), []),
                       [ns.SubOpExpr(vl.Operator('=='),
                                     ns.AtomExpr(ns.NameAtom(vl.Name('y')), []))],
                       None)])])])),
         ns.SimpleStmtBlock(ns.SimpleStmt(ns.EmptyStmt())),
         [],
         ns.ElseStmt(ns.SimpleStmtBlock(ns.SimpleStmt(ns.ReturnStmt([
             ns.OpExpr(None,
                       ns.AtomExpr(ns.NumberAtom(vl.Number('42')), []),
                       [],
                       None)])))))),
])
def test_if_stmt(lines: List[str], tree: AST):
    lexemes = lex_lines('\n'.join(lines))[:-1]
    run_test('if_stmt', tree, lexemes, [], [])

@pytest.mark.parametrize('lines,tree', [
    ([
        'if x == y:',
        '    42'
     ],
     ns.IfExpr(
         ns.TestExpr(ns.OrTestExpr([ns.AndTestExpr([ns.NotTestExpr([
             ns.OpExpr(None,
                       ns.AtomExpr(ns.NameAtom(vl.Name('x')), []),
                       [ns.SubOpExpr(vl.Operator('=='),
                                     ns.AtomExpr(ns.NameAtom(vl.Name('y')), []))],
                       None)])])])),
         ns.IndentedExprBlock(ns.TestExpr(ns.OrTestExpr([ns.AndTestExpr([ns.NotTestExpr([
             ns.OpExpr(None,
                       ns.AtomExpr(ns.NumberAtom(vl.Number('42')), []),
                       [],
                       None)])])]))),
         [],
         None)),
    ([
        'if x == y: 42'
     ],
     ns.IfExpr(
         ns.TestExpr(ns.OrTestExpr([ns.AndTestExpr([ns.NotTestExpr([
             ns.OpExpr(None,
                       ns.AtomExpr(ns.NameAtom(vl.Name('x')), []),
                       [ns.SubOpExpr(vl.Operator('=='),
                                     ns.AtomExpr(ns.NameAtom(vl.Name('y')), []))],
                       None)])])])),
         ns.SimpleExprBlock(ns.TestExpr(ns.OrTestExpr([ns.AndTestExpr([ns.NotTestExpr([
             ns.OpExpr(None,
                       ns.AtomExpr(ns.NumberAtom(vl.Number('42')), []),
                       [],
                       None)])])]))),
         [],
         None)),
])
def test_if_expr(lines: List[str], tree: AST):
    lexemes = lex_lines('\n'.join(lines))[:-1]
    run_test('if_expr', tree, lexemes, [], [])
<|endoftext|>