<commit_before># -*- coding: utf-8 -*-
"""
    Tests for tipfyext.jinja2
"""
import os
import sys
import unittest

from jinja2 import FileSystemLoader, Environment

from tipfy import RequestHandler, Request, Response, Tipfy
from tipfy.app import local
from tipfyext.jinja2 import Jinja2, Jinja2Mixin

current_dir = os.path.abspath(os.path.dirname(__file__))
templates_dir = os.path.join(current_dir, 'resources', 'templates')
templates_compiled_target = os.path.join(current_dir, 'resources', 'templates_compiled')

class TestJinja2(unittest.TestCase):
    def tearDown(self):
        local.__release_local__()

    def test_render_template(self):
        app = Tipfy(config={'tipfyext.jinja2': {'templates_dir': templates_dir}})
        request = Request.from_values()
        local.current_handler = handler = RequestHandler(app, request)
        jinja2 = Jinja2(app)

        message = 'Hello, World!'
        res = jinja2.render_template(local.current_handler, 'template1.html', message=message)
        self.assertEqual(res, message)

    def test_render_template_with_i18n(self):
        app = Tipfy(config={
            'tipfyext.jinja2': {
                'templates_dir': templates_dir,
                'environment_args': dict(
                    autoescape=True,
                    extensions=['jinja2.ext.autoescape', 'jinja2.ext.with_', 'jinja2.ext.i18n'],
                ),
            },
            'tipfy.sessions': {
                'secret_key': 'secret',
            },
        })
        request = Request.from_values()
        local.current_handler = handler = RequestHandler(app, request)
        jinja2 = Jinja2(app)

        message = 'Hello, i18n World!'
        res = jinja2.render_template(local.current_handler, 'template2.html', message=message)
        self.assertEqual(res, message)

    def test_render_response(self):
        app = Tipfy(config={'tipfyext.jinja2': {'templates_dir': templates_dir}})
        request = Request.from_values()
        local.current_handler = handler = RequestHandler(app, request)
        jinja2 = Jinja2(app)

        message = 'Hello, World!'
        response = jinja2.render_response(local.current_handler, 'template1.html', message=message)
        self.assertEqual(isinstance(response, Response), True)
        self.assertEqual(response.mimetype, 'text/html')
        self.assertEqual(response.data, message)

    def test_render_response_force_compiled(self):
        app = Tipfy(config={
            'tipfyext.jinja2': {
                'templates_compiled_target': templates_compiled_target,
                'force_use_compiled': True,
            }
        }, debug=False)
        request = Request.from_values()
        local.current_handler = handler = RequestHandler(app, request)
        jinja2 = Jinja2(app)

        message = 'Hello, World!'
        response = jinja2.render_response(local.current_handler, 'template1.html', message=message)
        self.assertEqual(isinstance(response, Response), True)
        self.assertEqual(response.mimetype, 'text/html')
        self.assertEqual(response.data, message)

    def test_jinja2_mixin_render_template(self):
        class MyHandler(RequestHandler, Jinja2Mixin):
            def __init__(self, app, request):
                self.app = app
                self.request = request
                self.context = {}

        app = Tipfy(config={'tipfyext.jinja2': {'templates_dir': templates_dir}})
        request = Request.from_values()
        local.current_handler = handler = MyHandler(app, request)
        jinja2 = Jinja2(app)
        message = 'Hello, World!'

        response = handler.render_template('template1.html', message=message)
        self.assertEqual(response, message)

    def test_jinja2_mixin_render_response(self):
        class MyHandler(RequestHandler, Jinja2Mixin):
            def __init__(self, app, request):
                self.app = app
                self.request = request
                self.context = {}

        app = Tipfy(config={'tipfyext.jinja2': {'templates_dir': templates_dir}})
        request = Request.from_values()
        local.current_handler = handler = MyHandler(app, request)
        jinja2 = Jinja2(app)
        message = 'Hello, World!'

        response = handler.render_response('template1.html', message=message)
        self.assertEqual(isinstance(response, Response), True)
        self.assertEqual(response.mimetype, 'text/html')
        self.assertEqual(response.data, message)

    def test_get_template_attribute(self):
        app = Tipfy(config={'tipfyext.jinja2': {'templates_dir': templates_dir}})
        request = Request.from_values()
        local.current_handler = handler = RequestHandler(app, request)
        jinja2 = Jinja2(app)

        hello = jinja2.get_template_attribute('hello.html', 'hello')
        self.assertEqual(hello('World'), 'Hello, World!')

    def test_engine_factory(self):
        def get_jinja2_env():
            app = local.current_handler.app
            cfg = app.get_config('tipfyext.jinja2')

            loader = FileSystemLoader(cfg.get( 'templates_dir'))

            return Environment(loader=loader)

        app = Tipfy(config={'tipfyext.jinja2': {
            'templates_dir': templates_dir,
            'engine_factory': get_jinja2_env,
        }})
        request = Request.from_values()
        local.current_handler = handler = RequestHandler(app, request)
        jinja2 = Jinja2(app)

        message = 'Hello, World!'
        res = jinja2.render_template(local.current_handler, 'template1.html', message=message)
        self.assertEqual(res, message)

    def test_engine_factory2(self):
        old_sys_path = sys.path[:]
        sys.path.insert(0, current_dir)

        app = Tipfy(config={'tipfyext.jinja2': {
            'templates_dir': templates_dir,
            'engine_factory': 'resources.get_jinja2_env',
        }})
        request = Request.from_values()
        local.current_handler = handler = RequestHandler(app, request)
        jinja2 = Jinja2(app)

        message = 'Hello, World!'
        res = jinja2.render_template(local.current_handler, 'template1.html', message=message)
        self.assertEqual(res, message)

        sys.path = old_sys_path

    def test_engine_factory3(self):
        app = Tipfy()
        request = Request.from_values()
        local.current_handler = handler = RequestHandler(app, request)
        _globals = {'message': 'Hey there!'}
        filters = {'ho': lambda e: e + ' Ho!'}
        jinja2 = Jinja2(app, _globals=_globals, filters=filters)

        template = jinja2.environment.from_string("""{{ message|ho }}""")

        self.assertEqual(template.render(), 'Hey there! Ho!')

    def test_after_environment_created(self):
        def after_creation(environment):
            environment.filters['ho'] = lambda x: x + ', Ho!'

        app = Tipfy(config={'tipfyext.jinja2': {'after_environment_created': after_creation}})
        request = Request.from_values()
        local.current_handler = handler = RequestHandler(app, request)
        jinja2 = Jinja2(app)

        template = jinja2.environment.from_string("""{{ 'Hey'|ho }}""")
        self.assertEqual(template.render(), 'Hey, Ho!')

    def test_after_environment_created_using_string(self):
        app = Tipfy(config={'tipfyext.jinja2': {'after_environment_created': 'resources.jinja2_after_environment_created.after_creation'}})
        request = Request.from_values()
        local.current_handler = handler = RequestHandler(app, request)
        jinja2 = Jinja2(app)

        template = jinja2.environment.from_string("""{{ 'Hey'|ho }}""")
        self.assertEqual(template.render(), 'Hey, Ho!')

<commit_msg>Added a test for new_style translations.<commit_after># -*- coding: utf-8 -*-
"""
    Tests for tipfyext.jinja2
"""
import os
import sys
import unittest

from jinja2 import FileSystemLoader, Environment

from tipfy import RequestHandler, Request, Response, Tipfy
from tipfy.app import local
from tipfyext.jinja2 import Jinja2, Jinja2Mixin

current_dir = os.path.abspath(os.path.dirname(__file__))
templates_dir = os.path.join(current_dir, 'resources', 'templates')
templates_compiled_target = os.path.join(current_dir, 'resources', 'templates_compiled')

class TestJinja2(unittest.TestCase):
    def tearDown(self):
        local.__release_local__()

    def test_render_template(self):
        app = Tipfy(config={'tipfyext.jinja2': {'templates_dir': templates_dir}})
        request = Request.from_values()
        local.current_handler = handler = RequestHandler(app, request)
        jinja2 = Jinja2(app)

        message = 'Hello, World!'
        res = jinja2.render_template(local.current_handler, 'template1.html', message=message)
        self.assertEqual(res, message)

    def test_render_template_with_i18n(self):
        app = Tipfy(config={
            'tipfyext.jinja2': {
                'templates_dir': templates_dir,
                'environment_args': dict(
                    autoescape=True,
                    extensions=['jinja2.ext.autoescape', 'jinja2.ext.with_', 'jinja2.ext.i18n'],
                ),
            },
            'tipfy.sessions': {
                'secret_key': 'secret',
            },
        })
        request = Request.from_values()
        local.current_handler = handler = RequestHandler(app, request)
        jinja2 = Jinja2(app)

        message = 'Hello, i18n World!'
        res = jinja2.render_template(local.current_handler, 'template2.html', message=message)
        self.assertEqual(res, message)

    def test_render_response(self):
        app = Tipfy(config={'tipfyext.jinja2': {'templates_dir': templates_dir}})
        request = Request.from_values()
        local.current_handler = handler = RequestHandler(app, request)
        jinja2 = Jinja2(app)

        message = 'Hello, World!'
        response = jinja2.render_response(local.current_handler, 'template1.html', message=message)
        self.assertEqual(isinstance(response, Response), True)
        self.assertEqual(response.mimetype, 'text/html')
        self.assertEqual(response.data, message)

    def test_render_response_force_compiled(self):
        app = Tipfy(config={
            'tipfyext.jinja2': {
                'templates_compiled_target': templates_compiled_target,
                'force_use_compiled': True,
            }
        }, debug=False)
        request = Request.from_values()
        local.current_handler = handler = RequestHandler(app, request)
        jinja2 = Jinja2(app)

        message = 'Hello, World!'
        response = jinja2.render_response(local.current_handler, 'template1.html', message=message)
        self.assertEqual(isinstance(response, Response), True)
        self.assertEqual(response.mimetype, 'text/html')
        self.assertEqual(response.data, message)

    def test_jinja2_mixin_render_template(self):
        class MyHandler(RequestHandler, Jinja2Mixin):
            def __init__(self, app, request):
                self.app = app
                self.request = request
                self.context = {}

        app = Tipfy(config={'tipfyext.jinja2': {'templates_dir': templates_dir}})
        request = Request.from_values()
        local.current_handler = handler = MyHandler(app, request)
        jinja2 = Jinja2(app)
        message = 'Hello, World!'

        response = handler.render_template('template1.html', message=message)
        self.assertEqual(response, message)

    def test_jinja2_mixin_render_response(self):
        class MyHandler(RequestHandler, Jinja2Mixin):
            def __init__(self, app, request):
                self.app = app
                self.request = request
                self.context = {}

        app = Tipfy(config={'tipfyext.jinja2': {'templates_dir': templates_dir}})
        request = Request.from_values()
        local.current_handler = handler = MyHandler(app, request)
        jinja2 = Jinja2(app)
        message = 'Hello, World!'

        response = handler.render_response('template1.html', message=message)
        self.assertEqual(isinstance(response, Response), True)
        self.assertEqual(response.mimetype, 'text/html')
        self.assertEqual(response.data, message)

    def test_get_template_attribute(self):
        app = Tipfy(config={'tipfyext.jinja2': {'templates_dir': templates_dir}})
        request = Request.from_values()
        local.current_handler = handler = RequestHandler(app, request)
        jinja2 = Jinja2(app)

        hello = jinja2.get_template_attribute('hello.html', 'hello')
        self.assertEqual(hello('World'), 'Hello, World!')

    def test_engine_factory(self):
        def get_jinja2_env():
            app = local.current_handler.app
            cfg = app.get_config('tipfyext.jinja2')

            loader = FileSystemLoader(cfg.get( 'templates_dir'))

            return Environment(loader=loader)

        app = Tipfy(config={'tipfyext.jinja2': {
            'templates_dir': templates_dir,
            'engine_factory': get_jinja2_env,
        }})
        request = Request.from_values()
        local.current_handler = handler = RequestHandler(app, request)
        jinja2 = Jinja2(app)

        message = 'Hello, World!'
        res = jinja2.render_template(local.current_handler, 'template1.html', message=message)
        self.assertEqual(res, message)

    def test_engine_factory2(self):
        old_sys_path = sys.path[:]
        sys.path.insert(0, current_dir)

        app = Tipfy(config={'tipfyext.jinja2': {
            'templates_dir': templates_dir,
            'engine_factory': 'resources.get_jinja2_env',
        }})
        request = Request.from_values()
        local.current_handler = handler = RequestHandler(app, request)
        jinja2 = Jinja2(app)

        message = 'Hello, World!'
        res = jinja2.render_template(local.current_handler, 'template1.html', message=message)
        self.assertEqual(res, message)

        sys.path = old_sys_path

    def test_engine_factory3(self):
        app = Tipfy()
        request = Request.from_values()
        local.current_handler = handler = RequestHandler(app, request)
        _globals = {'message': 'Hey there!'}
        filters = {'ho': lambda e: e + ' Ho!'}
        jinja2 = Jinja2(app, _globals=_globals, filters=filters)

        template = jinja2.environment.from_string("""{{ message|ho }}""")

        self.assertEqual(template.render(), 'Hey there! Ho!')

    def test_after_environment_created(self):
        def after_creation(environment):
            environment.filters['ho'] = lambda x: x + ', Ho!'

        app = Tipfy(config={'tipfyext.jinja2': {'after_environment_created': after_creation}})
        request = Request.from_values()
        local.current_handler = handler = RequestHandler(app, request)
        jinja2 = Jinja2(app)

        template = jinja2.environment.from_string("""{{ 'Hey'|ho }}""")
        self.assertEqual(template.render(), 'Hey, Ho!')

    def test_after_environment_created_using_string(self):
        app = Tipfy(config={'tipfyext.jinja2': {'after_environment_created': 'resources.jinja2_after_environment_created.after_creation'}})
        request = Request.from_values()
        local.current_handler = handler = RequestHandler(app, request)
        jinja2 = Jinja2(app)

        template = jinja2.environment.from_string("""{{ 'Hey'|ho }}""")
        self.assertEqual(template.render(), 'Hey, Ho!')

    def test_translations(self):
        app = Tipfy(config={
            'tipfyext.jinja2': {
                'environment_args': {
                    'extensions': ['jinja2.ext.i18n',],
                },
            },
            'tipfy.sessions': {
                'secret_key': 'foo',
            },
        })
        request = Request.from_values()
        local.current_handler = handler = RequestHandler(app, request)
        jinja2 = Jinja2(app)

        template = jinja2.environment.from_string("""{{ _('foo = %(bar)s', bar='foo') }}""")
        self.assertEqual(template.render(), 'foo = foo')
<|endoftext|>


<commit_before>#!/usr/bin/env python

from __future__ import print_function

import unittest

try:
    from unittest import mock
except ImportError:
    import mock

try:
    import builtins
except ImportError:
    import __builtin__ as builtins

import string
import sys

try:
    from StringIO import StringIO
except ImportError:
    from io import StringIO

import eztemplate

class TestArgumentParser(unittest.TestCase):

    def test_empty_arguments(self):
        args = eztemplate.parse_args([])
        self.assertDictEqual(vars(args), {
                'args':         [{}],
                'concatenate':  False,
                'delete_empty': False,
                'engine':       'string.Template',
                'infiles':      [sys.stdin],
                'outfiles':     [sys.stdout],
                'tolerant':     False,
                'vary':         None,
            })

    def test_one_argument_and_output_delete_empty(self):
        args = eztemplate.parse_args([
                '--outfile=template2',
                '--delete-empty',
                'template1',
            ])
        self.assertDictEqual(vars(args), {
                'args':         [{}],
                'concatenate':  False,
                'delete_empty': True,
                'engine':       'string.Template',
                'infiles':      ['template1'],
                'outfiles':     ['template2'],
                'tolerant':     False,
                'vary':         None,
            })

    def test_engine_tolerant_stdout_concatenate_args_multiple_files(self):
        args = eztemplate.parse_args([
                '-e', 'string.Template',
                '--tolerant',
                '--stdout',
                '--concatenate',
                '-a', 'beilage=Kartoffeln',
                '--arg', 'essen=Szegediner Gulasch',
                'template1',
                'template2',
            ])
        self.assertDictEqual(vars(args), {
                'args':         [{
                                    'beilage': 'Kartoffeln',
                                    'essen':   'Szegediner Gulasch',
                                }],
                'concatenate':  True,
                'delete_empty': False,
                'engine':       'string.Template',
                'infiles':      [
                                    'template1',
                                    'template2',
                                ],
                'outfiles':     [sys.stdout],
                'tolerant':     True,
                'vary':         None,
            })

class TestCheckEngine(unittest.TestCase):

    def test_help(self):
        mock_dump_engines = mock.Mock()
        with mock.patch('eztemplate.dump_engines', mock_dump_engines):
            try:
                eztemplate.check_engine('help')
            except SystemExit as e:
                self.assertEqual(e.args[0], 0, "didn't exit with return code 0")
            else:
                self.fail("didn't exit")

        mock_dump_engines.assert_called_once_with()

    def test_unavailable_engine(self):
        mock_stderr = StringIO()
        with mock.patch('sys.stderr', mock_stderr):
            try:
                eztemplate.check_engine('<NONEXISTENT_ENGINE>')
            except SystemExit as e:
                self.assertEqual(e.args[0], 1, "didn't exit with return code 1")
            else:
                self.fail("didn't exit")

        self.assertEqual(mock_stderr.getvalue().strip(),
                         'Engine "<NONEXISTENT_ENGINE>" is not available.')

    def test_built_in_engines(self):
        for engine in ('string.Template',):
            eztemplate.check_engine(engine)

if __name__ == '__main__':
    unittest.main()
<commit_msg>Add parser test for argument separators.<commit_after>#!/usr/bin/env python

from __future__ import print_function

import unittest

try:
    from unittest import mock
except ImportError:
    import mock

try:
    import builtins
except ImportError:
    import __builtin__ as builtins

import string
import sys

try:
    from StringIO import StringIO
except ImportError:
    from io import StringIO

import eztemplate

class TestArgumentParser(unittest.TestCase):

    def test_empty_arguments(self):
        args = eztemplate.parse_args([])
        self.assertDictEqual(vars(args), {
                'args':         [{}],
                'concatenate':  False,
                'delete_empty': False,
                'engine':       'string.Template',
                'infiles':      [sys.stdin],
                'outfiles':     [sys.stdout],
                'tolerant':     False,
                'vary':         None,
            })

    def test_one_argument_and_output_delete_empty(self):
        args = eztemplate.parse_args([
                '--outfile=template2',
                '--delete-empty',
                'template1',
            ])
        self.assertDictEqual(vars(args), {
                'args':         [{}],
                'concatenate':  False,
                'delete_empty': True,
                'engine':       'string.Template',
                'infiles':      ['template1'],
                'outfiles':     ['template2'],
                'tolerant':     False,
                'vary':         None,
            })

    def test_engine_tolerant_stdout_concatenate_args_multiple_files(self):
        args = eztemplate.parse_args([
                '-e', 'string.Template',
                '--tolerant',
                '--stdout',
                '--concatenate',
                '-a', 'beilage=Kartoffeln',
                '--arg', 'essen=Szegediner Gulasch',
                'template1',
                'template2',
            ])
        self.assertDictEqual(vars(args), {
                'args':         [{
                                    'beilage': 'Kartoffeln',
                                    'essen':   'Szegediner Gulasch',
                                }],
                'concatenate':  True,
                'delete_empty': False,
                'engine':       'string.Template',
                'infiles':      [
                                    'template1',
                                    'template2',
                                ],
                'outfiles':     [sys.stdout],
                'tolerant':     True,
                'vary':         None,
            })

    def test_engine_separator_template_separator_args(self):
        args = eztemplate.parse_args([
                '--engine', 'string.Template',
                '--',
                'template',
                '--',
                'beilage=Kartoffeln',
                'essen=Szegediner Gulasch',
            ])
        self.assertDictEqual(vars(args), {
                'args':         [{
                                    'beilage': 'Kartoffeln',
                                    'essen':   'Szegediner Gulasch',
                                }],
                'concatenate':  False,
                'delete_empty': False,
                'engine':       'string.Template',
                'infiles':      ['template'],
                'outfiles':     [sys.stdout],
                'tolerant':     False,
                'vary':         None,
            })

class TestCheckEngine(unittest.TestCase):

    def test_help(self):
        mock_dump_engines = mock.Mock()
        with mock.patch('eztemplate.dump_engines', mock_dump_engines):
            try:
                eztemplate.check_engine('help')
            except SystemExit as e:
                self.assertEqual(e.args[0], 0, "didn't exit with return code 0")
            else:
                self.fail("didn't exit")

        mock_dump_engines.assert_called_once_with()

    def test_unavailable_engine(self):
        mock_stderr = StringIO()
        with mock.patch('sys.stderr', mock_stderr):
            try:
                eztemplate.check_engine('<NONEXISTENT_ENGINE>')
            except SystemExit as e:
                self.assertEqual(e.args[0], 1, "didn't exit with return code 1")
            else:
                self.fail("didn't exit")

        self.assertEqual(mock_stderr.getvalue().strip(),
                         'Engine "<NONEXISTENT_ENGINE>" is not available.')

    def test_built_in_engines(self):
        for engine in ('string.Template',):
            eztemplate.check_engine(engine)

if __name__ == '__main__':
    unittest.main()
<|endoftext|>


<commit_before>#!/usr/bin/python
from finaLib import finaImport
import unittest, os, pandas

class testImport(unittest.TestCase):
  '''Tests for importing a CSV file'''

  def setUp(self):
    toeFile = open(os.path.join("data", "toe"), "w+")
    toeFile.write('hi, bye')
    toeFile.write('1,2')
    toeFile.write('3,4')

    emptyFile = open(os.path.join("data", "empty"), "w+")

  def tearDown(self):
    os.remove(os.path.join("data", "toe"))
    os.remove(os.path.join("data", "empty"))

  def testDataDirExists(self):
    '''Test that the data directory exists'''
    self.assertTrue(os.path.exists("data"))

  def testImportCSV(self):
    ''' Test a good file and make sure importCSV returns a csv reader object '''
    self.assertIsInstance(finaImport.importCSV("toe"), pandas.core.frame.DataFrame)

  def testImportBadFile(self):
    ''' Test a non-existant file '''
    self.assertEquals(finaImport.importCSV("testopesto"), "File not found!")

  def testImportEmptyFile(self):
    '''Test an empty file import'''
    self.assertEquals(finaImport.importCSV("empty"), "Bad csv file!")
<commit_msg>change the tests to use the new method name<commit_after>#!/usr/bin/python
from finaLib import finaImport
import unittest, os, pandas

class testImport(unittest.TestCase):
  '''Tests for importing a CSV file'''

  def setUp(self):
    toeFile = open(os.path.join("data", "toe"), "w+")
    toeFile.write('hi, bye')
    toeFile.write('1,2')
    toeFile.write('3,4')

    emptyFile = open(os.path.join("data", "empty"), "w+")

  def tearDown(self):
    os.remove(os.path.join("data", "toe"))
    os.remove(os.path.join("data", "empty"))

  def testDataDirExists(self):
    '''Test that the data directory exists'''
    self.assertTrue(os.path.exists("data"))

  def testImportCSV(self):
    ''' Test a good file and make sure importCSV returns a csv reader object '''
    self.assertIsInstance(finaImport.importOFX("toe"), pandas.core.frame.DataFrame)

  def testImportBadFile(self):
    ''' Test a non-existant file '''
    self.assertEquals(finaImport.importOFX("testopesto"), "File not found!")

  def testImportEmptyFile(self):
    '''Test an empty file import'''
    self.assertEquals(finaImport.importOFX("empty"), "Bad csv file!")
<|endoftext|>


<commit_before>import unittest

from symbolic.functional import Function, Parameters, inject_constants
from symbolic.core import where

_GLOBAL = 'GLOBAL'

class TestWhere(unittest.TestCase):
    def test_where_class_statement(self):
        obtained = (1, 2) &where(PI=3.14)
        expected = [{'PI': 3.14}, (1, 2)]
        self.assertEqual(obtained, expected)
        self.assertTrue(isinstance(obtained[0], where))

    def test_inject_constants_function(self):
        generator = ((x + a, y + b, z + c) for (x, y, z) in [[1, 2, 3]])
        expanded = inject_constants(generator, a=1, b=2, c=3)
        self.assertEqual((2, 4, 6), next(expanded))

class TestFunction(unittest.TestCase):
    def setUp(self):
        self.function = Function(x for x in Parameters)

    def test_instance(self):
        self.assertTrue(isinstance(self.function, Function))

    def test_basic_source_code(self):
        expected = "def function(x):\n"\
                   "    yield x"
        self.assertEqual(self.function.__source__, expected)

    def test_source_code_with_many_variables(self):
        function = Function((x, y, z) for (x, y, z) in Parameters)
        expected = "def function(x, y, z):\n"\
                   "    yield (x, y, z)"
        self.assertEqual(function.__source__, expected)

    def test_source_code_with_some_operations(self):
        function = Function(-x*y**z for (x, y, z) in Parameters)
        expected = "def function(x, y, z):\n"\
                   "    yield -(x)*(y**(z))"
        self.assertEqual(function.__source__, expected)

    def test_where_class(self):
        function = Function((PI*r**2) &where(PI=3.14) for r in Parameters)
        expected = "def function(r):\n"\
                   "    yield (3.14)*r**(2)"
        self.assertEqual(function.__source__, expected)

    def test_where_class_with_two_constants(self):
        function = Function(
            PI*r**two
        &where (
            PI = 3.14,
            two = 2
        ) for r in Parameters)
        expected = "def function(r):\n"\
                   "    yield (3.14)*r**(2)"
        self.assertEqual(function.__source__, expected)

    def test_where_class_with_global_var(self):
        function = Function(
            _GLOBAL
        &where(
            _GLOBAL='where_GLOBAL'
        ) for void in Parameters)

        expected = "def function(void):\n"\
                   "    yield 'where_GLOBAL'"
        self.assertEqual(function.__source__, expected)

    def test_where_class_with_local_var(self):
        a_local = 'a'
        b_local = 'b'

        function = Function(
            a_local+b_local
            &where (
                a_local = 'AA',
                b_local = 'BB',
            ) for x in Parameters)

        expected = "def function(x):\n"\
                   "    yield 'AABB'"
        self.assertEqual(function.__source__, expected)

    def test_where_class_with_non_local_variables(self):
        # NOTE: the value of this variable should be different than the name
        non_local = '_nnnnnnn'
        function = Function(non_local for _ in Parameters)

        expected = "def function(_):\n"\
                   "    yield '_nnnnnnn'"
        self.assertEqual(function.__source__, expected)

    @unittest.skip('unimplemented')
    def test_where_class_in_the_begining_of_the_expression(self):
        """Should raise an SintaxError if
        where is placed in the begining."""

    @unittest.skip('unimplemented')
    def test_where_class_in_the_middle_of_the_expression(self):
        """Should raise an SintaxError if
        where is placed in the middle."""

    @unittest.skip('unimplemented')
    def test_where_class_with_unary_operator(self):
        """Should raise an SintaxError if
        where have an unary operator."""

    @unittest.skip('unimplemented')
    def test_where_class_with_binary_left_operator(self):
        """Should raise an SintaxError if where is used
        with an binary operator placed in the left."""

    @unittest.skip('unimplemented')
    def test_where_class_with_binary_right_operator(self):
        """Should raise an SintaxError if where have
        an binary operator in the right side."""

    @unittest.skip('unimplemented')
    def test_CalledObject_instances_wrapped_with_next_method(self):
        """All `CalledObject` instances should be
        wrapped with the next() built-in method."""

if __name__ == '__main__':
    unittest.main()
<commit_msg>improve test coverage for the where class<commit_after>import unittest

from symbolic.functional import Function, Parameters, inject_constants
from symbolic.core import where

_GLOBAL = 'GLOBAL'
_GLOBAL_2 = 9999

class TestWhere(unittest.TestCase):
    def test_where_class_statement(self):
        obtained = (1, 2) &where(PI=3.14)
        expected = [{'PI': 3.14}, (1, 2)]
        self.assertEqual(obtained, expected)
        self.assertTrue(isinstance(obtained[0], where))

    def test_inject_constants_function(self):
        generator = ((x + a, y + b, z + c) for (x, y, z) in [[1, 2, 3]])
        expanded = inject_constants(generator, a=1, b=2, c=3)
        self.assertEqual((2, 4, 6), next(expanded))

class TestFunction(unittest.TestCase):
    def setUp(self):
        self.function = Function(x for x in Parameters)

    def test_instance(self):
        self.assertTrue(isinstance(self.function, Function))

    def test_basic_source_code(self):
        expected = "def function(x):\n"\
                   "    yield x"
        self.assertEqual(self.function.__source__, expected)

    def test_source_code_with_many_variables(self):
        function = Function((x, y, z) for (x, y, z) in Parameters)
        expected = "def function(x, y, z):\n"\
                   "    yield (x, y, z)"
        self.assertEqual(function.__source__, expected)

    def test_source_code_with_some_operations(self):
        function = Function(-x*y**z for (x, y, z) in Parameters)
        expected = "def function(x, y, z):\n"\
                   "    yield -(x)*(y**(z))"
        self.assertEqual(function.__source__, expected)

    def test_where_class(self):
        function = Function((PI*r**2) &where(PI=3.14) for r in Parameters)
        expected = "def function(r):\n"\
                   "    yield (3.14)*r**(2)"
        self.assertEqual(function.__source__, expected)

    def test_where_class_with_two_constants(self):
        function = Function(
            PI*r**two
        &where (
            PI = 3.14,
            two = 2
        ) for r in Parameters)
        expected = "def function(r):\n"\
                   "    yield (3.14)*r**(2)"
        self.assertEqual(function.__source__, expected)

    def test_where_class_with_global_var(self):
        function = Function(
            _GLOBAL
        &where(
            _GLOBAL='where_GLOBAL'
        ) for void in Parameters)

        expected = "def function(void):\n"\
                   "    yield 'where_GLOBAL'"
        self.assertEqual(function.__source__, expected)

    def test_where_class_with_local_var(self):
        a_local = 'a'
        b_local = 'b'

        function = Function(
            a_local+b_local
            &where (
                a_local = 'AA',
                b_local = 'BB',
            ) for x in Parameters)

        expected = "def function(x):\n"\
                   "    yield 'AABB'"
        self.assertEqual(function.__source__, expected)

    def test_where_class_with_non_local_variables(self):
        # NOTE: the value of this variable should be different than the name
        non_local = '_nnnnnnn'
        function = Function(non_local for _ in Parameters)

        expected = "def function(_):\n"\
                   "    yield '_nnnnnnn'"
        self.assertEqual(function.__source__, expected)

    def test_where_class_with_non_local_global_and_local_variables(self):
        # NOTE: the value of this variable should be different than the name
        non_local = '_nnnnnnn'
        local = '_lllllll'
        function_1 = Function(
            non_local+_GLOBAL+local
            &where(
                local = '_local'
            ) for _ in Parameters)

        expected_1 = "def function(_):\n"\
                   "    yield '_nnnnnnnGLOBAL_local'"
        non_local = 1111
        local = 2222
        function_2 = Function(
            non_local+_GLOBAL_2+local
            &where(
                local = 3333
            ) for _ in Parameters)

        expected_2 = "def function(_):\n"\
                   "    yield 14443"
        self.assertEqual(function_1.__source__, expected_1)
        self.assertEqual(function_2.__source__, expected_2)

    @unittest.skip('unimplemented')
    def test_where_class_in_the_begining_of_the_expression(self):
        """Should raise an SintaxError if
        where is placed in the begining."""

    @unittest.skip('unimplemented')
    def test_where_class_in_the_middle_of_the_expression(self):
        """Should raise an SintaxError if
        where is placed in the middle."""

    @unittest.skip('unimplemented')
    def test_where_class_with_unary_operator(self):
        """Should raise an SintaxError if
        where have an unary operator."""

    @unittest.skip('unimplemented')
    def test_where_class_with_binary_left_operator(self):
        """Should raise an SintaxError if where is used
        with an binary operator placed in the left."""

    @unittest.skip('unimplemented')
    def test_where_class_with_binary_right_operator(self):
        """Should raise an SintaxError if where have
        an binary operator in the right side."""

    @unittest.skip('unimplemented')
    def test_CalledObject_instances_wrapped_with_next_method(self):
        """All `CalledObject` instances should be
        wrapped with the next() built-in method."""

if __name__ == '__main__':
    unittest.main()
<|endoftext|>


<commit_before>import unittest

from jarn.viewdoc.viewdoc import DocumentationViewer

from jarn.viewdoc.testing import JailSetup
from jarn.viewdoc.testing import quiet

class GetOptionsTests(JailSetup):

    def test_defaults(self):
        self.mkfile('my.cfg', """\
[viewdoc]
""")
        dv = DocumentationViewer(['-c', 'my.cfg'])
        dv.parse_options(dv.args)
        self.assertEqual(dv.defaults.version, '1.8')
        self.assertEqual(dv.defaults.browser, 'default')
        self.assertEqual(dv.defaults.known_styles, {})
        self.assertEqual(dv.defaults.default_style, '')
        self.assertEqual(dv.defaults.styles, '')
        self.assertEqual(dv.browser, 'default')
        self.assertEqual(dv.styles, '')

    @quiet
    def test_quiet(self):
        print('Should not be visible')

    def test_empty_defaults(self):
        self.mkfile('my.cfg', """\
[viewdoc]
version =
browser =
style =

[styles]
pypi =
""")
        dv = DocumentationViewer(['-c', 'my.cfg'])
        dv.parse_options(dv.args)
        self.assertEqual(dv.defaults.version, '1.8')
        self.assertEqual(dv.defaults.browser, 'default')
        self.assertEqual(dv.defaults.known_styles, {'pypi': ''})
        self.assertEqual(dv.defaults.default_style, '')
        self.assertEqual(dv.defaults.styles, '')
        self.assertEqual(dv.browser, 'default')
        self.assertEqual(dv.styles, '')

    def test_read_defaults(self):
        self.mkfile('my.cfg', """\
[viewdoc]
version = 2.0
browser = safari
style = pypi

[styles]
pypi = <style></style>
""")
        dv = DocumentationViewer(['-c', 'my.cfg'])
        dv.parse_options(dv.args)
        self.assertEqual(dv.defaults.version, '2.0')
        self.assertEqual(dv.defaults.browser, 'safari')
        self.assertEqual(dv.defaults.known_styles, {'pypi': '<style></style>'})
        self.assertEqual(dv.defaults.default_style, 'pypi')
        self.assertEqual(dv.defaults.styles, '<style></style>')
        self.assertEqual(dv.browser, 'safari')
        self.assertEqual(dv.styles, '<style></style>')

    def test_newline_in_defaults(self):
        self.mkfile('my.cfg', """\
[viewdoc]
version =
    2.0
browser =
    safari
style =
    pypi

[styles]
pypi =
    <style>
    </style>

plain =
""")
        dv = DocumentationViewer(['-c', 'my.cfg'])
        dv.parse_options(dv.args)
        self.assertEqual(dv.defaults.version, '2.0')
        self.assertEqual(dv.defaults.browser, 'safari')
        self.assertEqual(dv.defaults.known_styles, {'pypi': '<style>\n</style>', 'plain': ''})
        self.assertEqual(dv.defaults.default_style, 'pypi')
        self.assertEqual(dv.defaults.styles, '<style>\n</style>')
        self.assertEqual(dv.browser, 'safari')
        self.assertEqual(dv.styles, '<style>\n</style>')

    def test_unknown_style(self):
        self.mkfile('my.cfg', """\
[viewdoc]
style = foo

[styles]
pypi = <style></style>
""")
        dv = DocumentationViewer(['-c', 'my.cfg'])
        dv.parse_options(dv.args)
        self.assertEqual(dv.defaults.known_styles, {'pypi': '<style></style>'})
        self.assertEqual(dv.defaults.default_style, 'foo')
        self.assertEqual(dv.defaults.styles, '')
        self.assertEqual(dv.browser, 'default')
        self.assertEqual(dv.styles, '')

    def test_command_line(self):
        self.mkfile('my.cfg', """\
[viewdoc]
browser = safari
style = pypi

[styles]
pypi = <style>1</style>
small  = <style>2</style>
""")
        dv = DocumentationViewer(['-c', 'my.cfg', '-s', 'small', '-b', 'firefox'])
        dv.parse_options(dv.args)
        self.assertEqual(dv.defaults.browser, 'safari')
        self.assertEqual(dv.defaults.known_styles, {'pypi': '<style>1</style>', 'small': '<style>2</style>'})
        self.assertEqual(dv.defaults.default_style, 'pypi')
        self.assertEqual(dv.defaults.styles, '<style>1</style>')
        self.assertEqual(dv.browser, 'firefox')
        self.assertEqual(dv.styles, '<style>2</style>')

<commit_msg>Fix tests broken by --no-color.<commit_after>import unittest

from jarn.viewdoc.viewdoc import DocumentationViewer

from jarn.viewdoc.testing import JailSetup
from jarn.viewdoc.testing import quiet

class GetOptionsTests(JailSetup):

    def test_defaults(self):
        self.mkfile('my.cfg', """\
[viewdoc]
""")
        dv = DocumentationViewer(['-c', 'my.cfg'])
        dv.set_defaults('my.cfg')
        dv.parse_options(dv.args)
        self.assertEqual(dv.defaults.version, '1.8')
        self.assertEqual(dv.defaults.browser, 'default')
        self.assertEqual(dv.defaults.known_styles, {})
        self.assertEqual(dv.defaults.default_style, '')
        self.assertEqual(dv.defaults.styles, '')
        self.assertEqual(dv.browser, 'default')
        self.assertEqual(dv.styles, '')

    @quiet
    def test_quiet(self):
        print('Should not be visible')

    def test_empty_defaults(self):
        self.mkfile('my.cfg', """\
[viewdoc]
version =
browser =
style =

[styles]
pypi =
""")
        dv = DocumentationViewer(['-c', 'my.cfg'])
        dv.set_defaults('my.cfg')
        dv.parse_options(dv.args)
        self.assertEqual(dv.defaults.version, '1.8')
        self.assertEqual(dv.defaults.browser, 'default')
        self.assertEqual(dv.defaults.known_styles, {'pypi': ''})
        self.assertEqual(dv.defaults.default_style, '')
        self.assertEqual(dv.defaults.styles, '')
        self.assertEqual(dv.browser, 'default')
        self.assertEqual(dv.styles, '')

    def test_read_defaults(self):
        self.mkfile('my.cfg', """\
[viewdoc]
version = 2.0
browser = safari
style = pypi

[styles]
pypi = <style></style>
""")
        dv = DocumentationViewer(['-c', 'my.cfg'])
        dv.set_defaults('my.cfg')
        dv.parse_options(dv.args)
        self.assertEqual(dv.defaults.version, '2.0')
        self.assertEqual(dv.defaults.browser, 'safari')
        self.assertEqual(dv.defaults.known_styles, {'pypi': '<style></style>'})
        self.assertEqual(dv.defaults.default_style, 'pypi')
        self.assertEqual(dv.defaults.styles, '<style></style>')
        self.assertEqual(dv.browser, 'safari')
        self.assertEqual(dv.styles, '<style></style>')

    def test_newline_in_defaults(self):
        self.mkfile('my.cfg', """\
[viewdoc]
version =
    2.0
browser =
    safari
style =
    pypi

[styles]
pypi =
    <style>
    </style>

plain =
""")
        dv = DocumentationViewer(['-c', 'my.cfg'])
        dv.set_defaults('my.cfg')
        dv.parse_options(dv.args)
        self.assertEqual(dv.defaults.version, '2.0')
        self.assertEqual(dv.defaults.browser, 'safari')
        self.assertEqual(dv.defaults.known_styles, {'pypi': '<style>\n</style>', 'plain': ''})
        self.assertEqual(dv.defaults.default_style, 'pypi')
        self.assertEqual(dv.defaults.styles, '<style>\n</style>')
        self.assertEqual(dv.browser, 'safari')
        self.assertEqual(dv.styles, '<style>\n</style>')

    def test_unknown_style(self):
        self.mkfile('my.cfg', """\
[viewdoc]
style = foo

[styles]
pypi = <style></style>
""")
        dv = DocumentationViewer(['-c', 'my.cfg'])
        dv.set_defaults('my.cfg')
        dv.parse_options(dv.args)
        self.assertEqual(dv.defaults.known_styles, {'pypi': '<style></style>'})
        self.assertEqual(dv.defaults.default_style, 'foo')
        self.assertEqual(dv.defaults.styles, '')
        self.assertEqual(dv.browser, 'default')
        self.assertEqual(dv.styles, '')

    def test_command_line(self):
        self.mkfile('my.cfg', """\
[viewdoc]
browser = safari
style = pypi

[styles]
pypi = <style>1</style>
small  = <style>2</style>
""")
        dv = DocumentationViewer(['-c', 'my.cfg', '-s', 'small', '-b', 'firefox'])
        dv.set_defaults('my.cfg')
        dv.parse_options(dv.args)
        self.assertEqual(dv.defaults.browser, 'safari')
        self.assertEqual(dv.defaults.known_styles, {'pypi': '<style>1</style>', 'small': '<style>2</style>'})
        self.assertEqual(dv.defaults.default_style, 'pypi')
        self.assertEqual(dv.defaults.styles, '<style>1</style>')
        self.assertEqual(dv.browser, 'firefox')
        self.assertEqual(dv.styles, '<style>2</style>')

<|endoftext|>


<commit_before>import time
import pytest
import numpy as np

from flare import gp_algebra, gp_algebra_multi
from flare.env import AtomicEnvironment
from flare.struc import Structure
from flare.mc_simple import two_plus_three_body_mc, \
        two_plus_three_body_mc_grad
from flare.mc_sephyps import two_plus_three_body_mc \
        as two_plus_three_body_mc_multi
from flare.mc_sephyps import two_plus_three_body_mc_grad \
        as two_plus_three_body_mc_grad_multi
from flare.gp_algebra import get_like_grad_from_mats

def get_random_training_set(nenv):
    """Create a random training_set array with parameters """

    np.random.seed(0)

    cutoffs = np.array([0.8, 0.8])
    hyps = np.ones(5, dtype=float)
    kernel = (two_plus_three_body_mc, two_plus_three_body_mc_grad)
    kernel_m = (two_plus_three_body_mc_multi, two_plus_three_body_mc_grad_multi)
    hyps_mask = {'nspec': 2,
                 'spec_mask': np.zeros(118, dtype=int),
                 'nbond': 2,
                 'bond_mask': np.array([0, 1]),
                 'ntriplet': 2,
                 'triplet_mask': np.array([0, 1])}
    hyps_mask['spec_mask'][2] = 1

    # create test data
    cell = np.eye(3)
    unique_species = [2, 1]
    noa = 5

    training_data = []
    training_labels = []
    for idenv in range(nenv):
        positions = np.random.uniform(-1, 1, [noa,3])
        species = np.random.randint(0, len(unique_species), noa)
        struc = Structure(cell, species, positions)
        training_data += [AtomicEnvironment(struc, 1, cutoffs)]
        training_labels += [np.random.uniform(-1, 1, 3)]
    training_labels = np.hstack(training_labels)

    return hyps, training_data, training_labels, kernel, cutoffs, \
           kernel_m, hyps_mask

def test_ky_mat():

    hyps, training_data, training_labels, kernel, cutoffs, \
            kernel_m, hyps_mask = \
            get_random_training_set(50)

    func = [gp_algebra.get_ky_mat,
            gp_algebra.get_ky_mat_par,
            gp_algebra_multi.get_ky_mat,
            gp_algebra_multi.get_ky_mat_par]

    # get the reference
    # timer0 = time.time()
    ky_mat0 = func[0](hyps, training_data,
                      kernel[0], cutoffs)
    # print("linear", time.time()-timer0)

    # parallel version
    ky_mat = func[1](hyps, training_data,
                     kernel[0], cutoffs,
                     ncpus=2, nsample=20)
    diff = (np.max(np.abs(ky_mat-ky_mat0)))
    assert (diff==0), "parallel implementation is wrong"

    # this part of the code can be use for timing the parallel performance
    # for n in [10, 50, 100]:
    #     timer0 = time.time()
    #     ky_mat = func[1](hyps, training_data,
    #                      kernel[0], cutoffs,
    #                      ncpus=8, nsample=n)
    #     diff = (np.max(np.abs(ky_mat-ky_mat0)))
    #     print("parallel", n, time.time()-timer0, diff)
    #     assert (diff==0), "parallel implementation is wrong"

    hyps = np.ones(9, dtype=float)
    # check multi hyps implementation
    ky_mat = func[2](hyps, training_data,
                      kernel_m[0], cutoffs, hyps_mask)
    diff = (np.max(np.abs(ky_mat-ky_mat0)))
    assert (diff==0), "multi hyps parameter implementation is wrong"

    # check multi hyps parallel implementation
    ky_mat = func[3](hyps, training_data,
                     kernel_m[0],
                     cutoffs, hyps_mask, ncpus=2, nsample=20)
    diff = (np.max(np.abs(ky_mat-ky_mat0)))
    assert (diff==0), "multi hyps parameter parallel "\
            "implementation is wrong"

def test_ky_mat_update():

    hyps, training_data, training_labels, kernel, cutoffs, \
            kernel_m, hyps_mask = \
            get_random_training_set(50)

    func = [gp_algebra.get_ky_mat,
            gp_algebra.get_ky_mat_update,
            gp_algebra.get_ky_mat_update_par,
            gp_algebra_multi.get_ky_mat_update,
            gp_algebra_multi.get_ky_mat_update_par]

    # get the reference
    # timer0 = time.time()
    ky_mat0 = func[0](hyps, training_data,
                       kernel[0], cutoffs)
    n = 20
    ky_mat_old = func[0](hyps, training_data[:n],
                       kernel[0], cutoffs)
    # print("linear", time.time()-timer0)

    # parallel version
    ky_mat = func[1](ky_mat_old, hyps, training_data,
                     kernel[0], cutoffs)
    diff = (np.max(np.abs(ky_mat-ky_mat0)))
    assert (diff<1e-12), "update function is wrong"

    ky_mat = func[2](ky_mat_old, hyps, training_data,
                     kernel[0], cutoffs,
                     ncpus=2, nsample=20)
    diff = (np.max(np.abs(ky_mat-ky_mat0)))
    assert (diff<1e-12), "parallel implementation is wrong"

    hyps = np.ones(9, dtype=float)
    # check multi hyps implementation
    ky_mat = func[3](ky_mat_old, hyps, training_data,
                     kernel_m[0], cutoffs, hyps_mask)
    diff = (np.max(np.abs(ky_mat-ky_mat0)))
    assert (diff<1e-12), "multi hyps parameter implementation is wrong"

    # check multi hyps parallel implementation
    ky_mat = func[4](ky_mat_old, hyps, training_data,
                     kernel_m[0], cutoffs,
                     hyps_mask, ncpus=2, nsample=20)
    diff = (np.max(np.abs(ky_mat-ky_mat0)))
    assert (diff<1e-12), "multi hyps parameter parallel "\
            "implementation is wrong"

def test_ky_and_hyp():

    hyps, training_data, training_labels, \
            kernel, cutoffs, \
            kernel_m, hyps_mask = \
            get_random_training_set(10)

    func = [gp_algebra.get_ky_and_hyp,
            gp_algebra.get_ky_and_hyp_par,
            gp_algebra_multi.get_ky_and_hyp,
            gp_algebra_multi.get_ky_and_hyp_par]

    hypmat_0, ky_mat0 = func[0](hyps, training_data,
                       kernel[1], cutoffs)

    # parallel version
    hypmat, ky_mat = func[1](hyps, training_data,
                     kernel[1], cutoffs, ncpus=2)
    diff = (np.max(np.abs(ky_mat-ky_mat0)))
    assert (diff==0), "parallel implementation is wrong"

    hyps = np.ones(9, dtype=float)
    # check multi hyps implementation
    hypmat, ky_mat = func[2](hyps, training_data,
                      kernel_m[1], cutoffs, hyps_mask)
    diff = (np.max(np.abs(ky_mat-ky_mat0)))
    assert (diff==0), "multi hyps parameter implementation is wrong"

    # check multi hyps parallel implementation
    hypmat, ky_mat = func[3](hyps, training_data,
                     kernel_m[1], cutoffs, hyps_mask,
                     ncpus=2)
    diff = (np.max(np.abs(ky_mat-ky_mat0)))
    assert (diff==0), "multi hyps parameter parallel "\
            "implementation is wrong"

def test_ky_hyp_grad():

    hyps, training_data, training_labels, \
            kernel, cutoffs, \
            kernel_m, hyps_mask = \
            get_random_training_set(10)

    func = gp_algebra.get_ky_and_hyp

    hyp_mat, ky_mat = func(hyps, training_data,
                       kernel[1], cutoffs)

    print(hyp_mat.shape, ky_mat.shape, len(training_labels), training_labels[0])

    like, like_grad = \
                     get_like_grad_from_mats(ky_mat, hyp_mat, training_labels)
    delta = 0.001
    for i in range(len(hyps)):
        newhyps = np.copy(hyps)
        newhyps[i] += delta
        hyp_mat_p, ky_mat_p = func(newhyps, training_data,
                           kernel[1], cutoffs)
        like_p, like_grad_p = \
                         get_like_grad_from_mats(ky_mat_p, hyp_mat_p, training_labels)
        newhyps[i] -= 2*delta
        hyp_mat_m, ky_mat_m = func(newhyps, training_data,
                           kernel[1], cutoffs)
        like_m, like_grad_m = \
                         get_like_grad_from_mats(ky_mat_m, hyp_mat_m, training_labels)
        diff = np.abs(like_grad[i]-(like_p-like_m)/2./delta)
        assert (diff < 1e-3), "wrong calculation of hyp_mat"

<commit_msg>get test_gp_algebra.py<commit_after>import time
import pytest
import numpy as np

from flare import gp_algebra, gp_algebra_multi, gp_algebra_origin
from flare.env import AtomicEnvironment
from flare.struc import Structure
from flare.mc_simple import two_plus_three_body_mc, \
        two_plus_three_body_mc_grad
from flare.mc_sephyps import two_plus_three_body_mc \
        as two_plus_three_body_mc_multi
from flare.mc_sephyps import two_plus_three_body_mc_grad \
        as two_plus_three_body_mc_grad_multi
from flare.gp_algebra import get_like_grad_from_mats

def get_random_training_set(nenv):
    """Create a random training_set array with parameters """

    np.random.seed(0)

    cutoffs = np.array([0.8, 0.8])
    hyps = np.ones(5, dtype=float)
    kernel = (two_plus_three_body_mc, two_plus_three_body_mc_grad)
    kernel_m = (two_plus_three_body_mc_multi, two_plus_three_body_mc_grad_multi)

    hyps_mask1 = {'nspec': 2,
                 'spec_mask': np.zeros(118, dtype=int),
                 'nbond': 2,
                 'bond_mask': np.array([0, 1, 1, 1]),
                 'triplet_mask': np.array([0, 1, 1, 1, 1, 1, 1, 1]),
                 'ntriplet': 2}
    hyps_mask1['spec_mask'][2] = 1
    hyps1 = np.ones(9, dtype=float)

    hyps_mask2 = {'nspec': 2,
                 'spec_mask': np.zeros(118, dtype=int),
                 'nbond': 2,
                 'bond_mask': np.array([0, 1, 1, 1]),
                 'ntriplet': 2,
                 'triplet_mask': np.array([0, 1, 1, 1, 1, 1, 1, 1]),
                 'train_noise':True,
                 'map':[0,2,4,6,8],
                 'original':np.array([1, 1, 1, 1, 1, 1, 1, 1, 1])}
    hyps_mask2['spec_mask'][2] = 1
    hyps2 = np.ones(5, dtype=float)

    hyps_mask3 = {'nspec': 2,
                 'spec_mask': np.zeros(118, dtype=int),
                 'nbond': 2,
                 'bond_mask': np.array([0, 1, 1, 1]),
                 'ntriplet': 2,
                 'triplet_mask': np.array([0, 1, 1, 1, 1, 1, 1, 1]),
                 'train_noise':False,
                 'map':[0,2,4,6],
                 'original':np.array([1, 1, 1, 1, 1, 1, 1, 1, 1])}
    hyps_mask3['spec_mask'][2] = 1
    hyps3 = np.ones(4, dtype=float)

    hyps_mask4 = {'nspec': 1,
                 'spec_mask': np.zeros(118, dtype=int),
                 'nbond': 1,
                 'bond_mask': np.array([0]),
                 'ntriplet': 1,
                 'triplet_mask': np.array([0])}
    hyps4 = np.ones(5, dtype=float)

    # create test data
    cell = np.eye(3)
    unique_species = [2, 1]
    noa = 5

    training_data = []
    training_labels = []
    for idenv in range(nenv):
        positions = np.random.uniform(-1, 1, [noa,3])
        species = np.random.randint(0, len(unique_species), noa)
        struc = Structure(cell, species, positions)
        training_data += [AtomicEnvironment(struc, 1, cutoffs)]
        training_labels += [np.random.uniform(-1, 1, 3)]
    training_labels = np.hstack(training_labels)
    hyps_list = [hyps1, hyps2, hyps3, hyps4, hyps]
    hyps_mask_list = [hyps_mask1, hyps_mask2, hyps_mask3, hyps_mask4, None]

    return hyps, training_data, training_labels, kernel, cutoffs, \
           kernel_m, hyps_list, hyps_mask_list

def test_ky_mat():

    hyps, training_data, training_labels, kernel, cutoffs, \
            kernel_m, hyps_list, hyps_mask_list = \
            get_random_training_set(10)

    func = [gp_algebra_origin.get_ky_mat,
            gp_algebra.get_ky_mat_par,
            gp_algebra_multi.get_ky_mat,
            gp_algebra_multi.get_ky_mat_par]

    # get the reference
    # timer0 = time.time()
    ky_mat0 = func[0](hyps, training_data,
                      training_labels,
                      kernel[0], cutoffs)

    # print("linear", time.time()-timer0)

    # parallel version
    ky_mat = func[1](hyps, training_data,
                     kernel[0], cutoffs,
                     ncpus=2, nsample=20)
    diff = (np.max(np.abs(ky_mat-ky_mat0)))
    assert (diff==0), "parallel implementation is wrong"

    # this part of the code can be use for timing the parallel performance
    # for n in [10, 50, 100]:
    #     timer0 = time.time()
    #     ky_mat = func[1](hyps, training_data,
    #                      kernel[0], cutoffs,
    #                      ncpus=8, nsample=n)
    #     diff = (np.max(np.abs(ky_mat-ky_mat0)))
    #     print("parallel", n, time.time()-timer0, diff)
    #     assert (diff==0), "parallel implementation is wrong"

    # check multi hyps implementation
    # for all cases
    for i in range(len(hyps_list)):
        hyps = hyps_list[i]
        hyps_mask = hyps_mask_list[i]

        if hyps_mask is None:
            ker = kernel[0]
        else:
            ker = kernel_m[0]
        # serial implementation
        ky_mat = func[2](hyps, training_data,
                          ker, cutoffs, hyps_mask)
        diff = (np.max(np.abs(ky_mat-ky_mat0)))
        assert (diff==0), "multi hyps parameter implementation is wrong"

        # parallel implementation
        ky_mat = func[3](hyps, training_data,
                         ker,
                         cutoffs, hyps_mask, ncpus=2, nsample=20)
        diff = (np.max(np.abs(ky_mat-ky_mat0)))
        assert (diff==0), "multi hyps parameter parallel "\
                "implementation is wrong"

def test_ky_mat_update():

    hyps, training_data, training_labels, kernel, cutoffs, \
            kernel_m, hyps_list, hyps_mask_list = \
            get_random_training_set(10)

    func = [gp_algebra.get_ky_mat,
            gp_algebra.get_ky_mat_update,
            gp_algebra.get_ky_mat_update_par,
            gp_algebra_multi.get_ky_mat_update,
            gp_algebra_multi.get_ky_mat_update_par]

    # get the reference
    # timer0 = time.time()
    ky_mat0 = func[0](hyps, training_data,
                       kernel[0], cutoffs)
    n = 5
    ky_mat_old = func[0](hyps, training_data[:n],
                       kernel[0], cutoffs)
    # print("linear", time.time()-timer0)

    # parallel version
    ky_mat = func[1](ky_mat_old, hyps, training_data,
                     kernel[0], cutoffs)
    diff = (np.max(np.abs(ky_mat-ky_mat0)))
    assert (diff<1e-12), "update function is wrong"

    ky_mat = func[2](ky_mat_old, hyps, training_data,
                     kernel[0], cutoffs,
                     ncpus=2, nsample=20)
    diff = (np.max(np.abs(ky_mat-ky_mat0)))
    assert (diff<1e-12), "parallel implementation is wrong"

    # check multi hyps implementation
    # for all cases
    for i in range(len(hyps_list)):

        hyps = hyps_list[i]
        hyps_mask = hyps_mask_list[i]

        if hyps_mask is None:
            ker = kernel[0]
        else:
            ker = kernel_m[0]

        # serial implementation
        ky_mat = func[3](ky_mat_old, hyps, training_data,
                         ker, cutoffs, hyps_mask)
        diff = (np.max(np.abs(ky_mat-ky_mat0)))
        assert (diff<1e-12), "multi hyps parameter implementation is wrong"

        # parallel implementation
        ky_mat = func[4](ky_mat_old, hyps, training_data,
                         ker, cutoffs,
                         hyps_mask, ncpus=2, nsample=20)
        diff = (np.max(np.abs(ky_mat-ky_mat0)))
        assert (diff<1e-12), "multi hyps parameter parallel "\
                "implementation is wrong"

def test_ky_and_hyp():

    hyps, training_data, training_labels, kernel, cutoffs, \
            kernel_m, hyps_list, hyps_mask_list = \
            get_random_training_set(10)

    func = [gp_algebra_origin.get_ky_and_hyp,
            gp_algebra.get_ky_and_hyp_par,
            gp_algebra_multi.get_ky_and_hyp,
            gp_algebra_multi.get_ky_and_hyp_par]

    hypmat_0, ky_mat0 = func[0](hyps, training_data,
                       training_labels,
                       kernel[1], cutoffs)

    # parallel version
    hypmat, ky_mat = func[1](hyps, training_data,
                     kernel[1], cutoffs, ncpus=2)
    diff = (np.max(np.abs(ky_mat-ky_mat0)))
    assert (diff==0), "parallel implementation is wrong"

    hypmat_list = [[]]
    # check all cases
    for i in range(len(hyps_list)):
        hyps = hyps_list[i]
        hyps_mask = hyps_mask_list[i]

        if hyps_mask is None:
            ker = kernel[1]
        else:
            ker = kernel_m[1]

        # serial implementation
        hypmat, ky_mat = func[2](hyps, training_data,
                          ker, cutoffs, hyps_mask)
        hypmat_list += [hypmat]
        diff = (np.max(np.abs(ky_mat-ky_mat0)))
        assert (diff==0), "multi hyps parameter implementation is wrong"

        # 9 5 4 5 5
        # compare to no hyps_mask version
        diff = 0
        print(i, hypmat.shape)
        print(i, hypmat_0.shape)
        if (i==1):
            diff = (np.max(np.abs(hypmat-hypmat_0)))
        elif (i==2):
            diff = (np.max(np.abs(hypmat-hypmat_0[:-1, :, :])))
        elif (i==3):
            diff = (np.max(np.abs(hypmat-hypmat_0)))
        elif (i==4):
            diff = (np.max(np.abs(hypmat-hypmat_0)))
        assert (diff==0), "multi hyps implementation is wrong"\
                          f"in case {i}"

        # parallel implementation
        hypmat_par, ky_mat_par = func[3](hyps, training_data,
                         ker, cutoffs, hyps_mask,
                         ncpus=2)

        # compare to serial implementation
        diff = (np.max(np.abs(ky_mat-ky_mat_par)))
        assert (diff==0), f"multi hyps parallel "\
                f"implementation is wrong in case {i}"

        diff = (np.max(np.abs(hypmat_par-hypmat)))
        assert (diff==0), f"multi hyps parallel implementation is wrong"\
                f" in case{i}"

def test_grad():

    hyps, training_data, training_labels, kernel, cutoffs, \
            kernel_m, hyps_list, hyps_mask_list = \
            get_random_training_set(10)

    # obtain reference
    func = gp_algebra_origin.get_ky_and_hyp
    hyp_mat, ky_mat = func(hyps, training_data,
                       training_labels,
                       kernel[1], cutoffs)
    like0, like_grad0 = \
                     get_like_grad_from_mats(ky_mat, hyp_mat, training_labels)

    # serial implementation
    func = gp_algebra.get_ky_and_hyp
    hyp_mat, ky_mat = func(hyps, training_data,
                       kernel[1], cutoffs)
    like, like_grad = \
                     get_like_grad_from_mats(ky_mat, hyp_mat, training_labels)

    assert (like==like0), "wrong likelihood"
    assert np.max(np.abs(like_grad-like_grad0))==0, "wrong likelihood"

    func = gp_algebra_multi.get_ky_and_hyp

    # check all cases for multi hyps
    for i in range(len(hyps_list)):
        hyps = hyps_list[i]
        hyps_mask = hyps_mask_list[i]

        if hyps_mask is None:
            ker = kernel[1]
        else:
            ker = kernel_m[1]

        hyp_mat, ky_mat = func(hyps, training_data,
                          ker, cutoffs, hyps_mask)
        like, like_grad = \
                         get_like_grad_from_mats(ky_mat, hyp_mat, training_labels)
        print(like, like0)
        assert (like==like0), "wrong likelihood"

        print(like_grad, like_grad0)

        diff = 0
        if (i==1):
            diff = (np.max(np.abs(like_grad-like_grad0)))
        elif (i==2):
            diff = (np.max(np.abs(like_grad-like_grad0[:-1])))
        elif (i==3):
            diff = (np.max(np.abs(like_grad-like_grad0)))
        elif (i==4):
            diff = (np.max(np.abs(like_grad-like_grad0)))
        assert (diff==0), "multi hyps implementation is wrong"\
                          f"in case {i}"

def test_ky_hyp_grad():

    hyps, training_data, training_labels, kernel, cutoffs, \
            kernel_m, hyps_list, hyps_mask_list = \
            get_random_training_set(10)

    func = gp_algebra.get_ky_and_hyp

    hyp_mat, ky_mat = func(hyps, training_data,
                       kernel[1], cutoffs)

    print(hyp_mat.shape, ky_mat.shape, len(training_labels), training_labels[0])

    like, like_grad = \
                     get_like_grad_from_mats(ky_mat, hyp_mat, training_labels)
    delta = 0.001
    for i in range(len(hyps)):
        newhyps = np.copy(hyps)
        newhyps[i] += delta
        hyp_mat_p, ky_mat_p = func(newhyps, training_data,
                           kernel[1], cutoffs)
        like_p, like_grad_p = \
                         get_like_grad_from_mats(ky_mat_p, hyp_mat_p, training_labels)
        newhyps[i] -= 2*delta
        hyp_mat_m, ky_mat_m = func(newhyps, training_data,
                           kernel[1], cutoffs)
        like_m, like_grad_m = \
                         get_like_grad_from_mats(ky_mat_m, hyp_mat_m, training_labels)
        diff = np.abs(like_grad[i]-(like_p-like_m)/2./delta)
        assert (diff < 1e-3), "wrong calculation of hyp_mat"

<|endoftext|>


<commit_before>import os
from textwrap import dedent

import sublime

from unittesting import DeferrableTestCase
from GitSavvy.tests.mockito import unstub, when

from GitSavvy.core.commands.log_graph import (
    GsLogGraphCurrentBranch,
    GsLogGraphRefreshCommand,
    GsLogGraphCursorListener
)
from GitSavvy.core.commands.show_commit_info import GsShowCommitInfoCommand
from GitSavvy.core.settings import GitSavvySettings

if os.name == 'nt':
    # On Windows, `find_all_results` returns pseudo linux paths
    # E.g. `/C/not/here/README.md`
    def cleanup_fpath(fpath):
        return fpath[2:]
else:
    def cleanup_fpath(fpath):
        return fpath

THIS_DIRNAME = os.path.dirname(os.path.realpath(__file__))
COMMIT_1 = 'This is commit fec0aca'
COMMIT_2 = 'This is commit f461ea1'

def fixture(name):
    with open(os.path.join(THIS_DIRNAME, 'fixtures', name)) as f:
        return f.read()

class TestDiffViewInteractionWithCommitInfoPanel(DeferrableTestCase):
    @classmethod
    def setUpClass(cls):
        # make sure we have a window to work with
        original_window_id = sublime.active_window().id()
        sublime.run_command("new_window")

        yield lambda: sublime.active_window().id() != original_window_id

        cls.window = sublime.active_window()

        s = sublime.load_settings("Preferences.sublime-settings")
        s.set("close_windows_when_empty", False)

    @classmethod
    def tearDownClass(cls):
        cls.window.run_command('close_window')

    def setUp(self):
        self.create_new_view()

    def tearDown(self):
        self.do_cleanup()
        unstub()

    # `addCleanup` doesn't work either in Sublime at all or
    # with the DeferrableTestCase so we do a quick implementation
    # here.
    def add_cleanup(self, fn, *args, **kwargs):
        self._cleanups.append((fn, args, kwargs))

    def do_cleanup(self):
        while self._cleanups:
            fn, args, kwrags = self._cleanups.pop()
            try:
                fn(*args, **kwrags)
            except Exception:
                pass

    def await_string_in_view(self, view, needle):
        yield lambda: view.find(needle, 0, sublime.LITERAL)

    def await_active_panel_to_be(self, name):
        yield lambda: self.window.active_panel() == 'output.show_commit_info'

    def create_new_view(self, window=None):
        view = (window or sublime.active_window()).new_file()
        self.add_cleanup(self.close_view, view)
        return view

    def close_view(self, view):
        if view:
            view.set_scratch(True)
            view.close()

    def set_global_setting(self, key, value):
        settings = GitSavvySettings()
        original_value = settings.get(key)
        settings.set(key, value)
        self.add_cleanup(settings.set, key, original_value)

    def enable_commit_info(self, info):
        self.set_global_setting('graph_show_more_commit_info', True)
        for sha1, info in info.items():
            when(GsShowCommitInfoCommand).show_commit(sha1, ...).thenReturn(info)

    def create_graph_view_async(self, repo_path, log, wait_for):
        when(GsLogGraphRefreshCommand).git('log', ...).thenReturn(log)
        cmd = GsLogGraphCurrentBranch(self.window)
        when(cmd).get_repo_path().thenReturn(repo_path)
        cmd.run()
        yield lambda: self.window.active_view().settings().get('git_savvy.log_graph_view') is True
        log_view = self.window.active_view()
        yield from self.await_string_in_view(log_view, wait_for)

        return log_view

    def setup_graph_view_async(self):
        REPO_PATH = '/not/there'
        LOG = fixture('log_graph_1.txt')

        self.enable_commit_info({
            'fec0aca': COMMIT_1,
            'f461ea1': COMMIT_2
        })

        log_view = yield from self.create_graph_view_async(
            REPO_PATH, LOG,
            wait_for='0c2dd28 Guard updating state using a lock'
        )
        yield from self.await_active_panel_to_be('output.show_commit_info')
        return log_view

    def test_open_info_panel_after_create(self):
        log_view = yield from self.setup_graph_view_async()

        actual = self.window.active_panel()
        expected = 'output.show_commit_info'
        self.assertEqual(actual, expected)

    def test_info_panel_shows_first_commit_initially(self):
        log_view = yield from self.setup_graph_view_async()
        panel = self.window.find_output_panel('show_commit_info')

        yield from self.await_string_in_view(panel, COMMIT_1)

        # `yield condition` will continue after a timeout so we need
        # to actually assert here
        actual = panel.find(COMMIT_1, 0, sublime.LITERAL)
        self.assertTrue(actual)

    def test_info_panel_shows_second_commit_after_navigate(self):
        log_view = yield from self.setup_graph_view_async()
        panel = self.window.find_output_panel('show_commit_info')

        log_view.run_command('gs_log_graph_navigate')
        yield from self.await_string_in_view(panel, COMMIT_2)

        actual = panel.find(COMMIT_2, 0, sublime.LITERAL)
        self.assertTrue(actual)

    def test_info_panel_shows_second_commit_after_cursor_moves(self):
        log_view = yield from self.setup_graph_view_async()
        panel = self.window.find_output_panel('show_commit_info')

        log_view.sel().clear()
        log_view.sel().add(log_view.text_point(1, 14))
        GsLogGraphCursorListener().on_selection_modified_async(log_view)
        yield from self.await_string_in_view(panel, COMMIT_2)

        actual = panel.find(COMMIT_2, 0, sublime.LITERAL)
        self.assertTrue(actual)

    def test_if_the_user_issues_our_toggle_command_close_the_panel_and_keep_it(self):
        log_view = yield from self.setup_graph_view_async()

        self.window.run_command('gs_log_graph_toggle_more_info')
        actual = self.window.active_panel()
        expected = None
        self.assertEqual(actual, expected)

        # Ensure it doesn't open on navigate
        log_view.run_command('gs_log_graph_navigate')

        yield 500  # ?

        actual = self.window.active_panel()
        expected = None
        self.assertEqual(actual, expected)

    def test_if_the_user_opens_another_panel_dont_fight(self):
        window = self.window
        log_view = yield from self.setup_graph_view_async()
        active_group = window.active_group()

        window.run_command('show_panel', {'panel': 'console'})
        # We need both to get the cursor back
        window.focus_group(active_group)
        window.focus_view(log_view)
        log_view.run_command('gs_log_graph_navigate')

        yield 500  # ?

        actual = self.window.active_panel()
        expected = 'console'
        self.assertEqual(actual, expected)

    def test_if_the_user_closes_the_panel_accept_it(self):
        log_view = yield from self.setup_graph_view_async()

        self.window.run_command('hide_panel')
        log_view.run_command('gs_log_graph_navigate')

        yield 500  # ?

        actual = self.window.active_panel()
        expected = None
        self.assertEqual(actual, expected)

    def test_show_correct_info_if_user_moves_around_and_then_toggles_panel(self):
        log_view = yield from self.setup_graph_view_async()
        panel = self.window.find_output_panel('show_commit_info')
        # close panel
        self.window.run_command('gs_log_graph_toggle_more_info')

        # move around
        log_view.sel().clear()
        log_view.sel().add(log_view.text_point(1, 14))
        GsLogGraphCursorListener().on_selection_modified_async(log_view)

        # show panel
        self.window.run_command('gs_log_graph_toggle_more_info')

        yield from self.await_string_in_view(panel, COMMIT_2)

        actual = panel.find(COMMIT_2, 0, sublime.LITERAL)
        self.assertTrue(actual)

    def test_show_correct_info_if_user_moves_around_and_then_opens_panel(self):
        log_view = yield from self.setup_graph_view_async()
        panel = self.window.find_output_panel('show_commit_info')
        # close panel
        self.window.run_command('gs_log_graph_toggle_more_info')

        # move around
        log_view.sel().clear()
        log_view.sel().add(log_view.text_point(1, 14))
        GsLogGraphCursorListener().on_selection_modified_async(log_view)

        # show panel e.g. via mouse
        self.window.run_command('show_panel', {'panel': 'output.show_commit_info'})

        yield from self.await_string_in_view(panel, COMMIT_2)

        actual = panel.find(COMMIT_2, 0, sublime.LITERAL)
        self.assertTrue(actual)

    def _test_afocus_info_panel(self):
        log_view = yield from self.setup_graph_view_async()

        yield 2500

    def _test(self):
        panel = self.window.find_output_panel('show_commit_info')

        self.window.focus_view(panel)

        log_view.run_command('gs_log_graph_navigate')
        log_view.run_command('gs_log_graph_navigate')
        yield 2000
<commit_msg>Add test cases for log graph view not showing the panel initially (#1068)<commit_after>import os
from textwrap import dedent

import sublime

from unittesting import DeferrableTestCase
from GitSavvy.tests.mockito import unstub, when

from GitSavvy.core.commands.log_graph import (
    GsLogGraphCurrentBranch,
    GsLogGraphRefreshCommand,
    GsLogGraphCursorListener
)
from GitSavvy.core.commands.show_commit_info import GsShowCommitInfoCommand
from GitSavvy.core.settings import GitSavvySettings

if os.name == 'nt':
    # On Windows, `find_all_results` returns pseudo linux paths
    # E.g. `/C/not/here/README.md`
    def cleanup_fpath(fpath):
        return fpath[2:]
else:
    def cleanup_fpath(fpath):
        return fpath

THIS_DIRNAME = os.path.dirname(os.path.realpath(__file__))
COMMIT_1 = 'This is commit fec0aca'
COMMIT_2 = 'This is commit f461ea1'

def fixture(name):
    with open(os.path.join(THIS_DIRNAME, 'fixtures', name)) as f:
        return f.read()

class TestDiffViewInteractionWithCommitInfoPanel(DeferrableTestCase):
    @classmethod
    def setUpClass(cls):
        s = sublime.load_settings("Preferences.sublime-settings")
        s.set("close_windows_when_empty", False)

    def setUp(self):
        self.window = window = self.create_new_window()
        self.create_new_view(window)

    def tearDown(self):
        self.do_cleanup()
        unstub()

    # `addCleanup` doesn't work either in Sublime at all or
    # with the DeferrableTestCase so we do a quick implementation
    # here.
    def add_cleanup(self, fn, *args, **kwargs):
        self._cleanups.append((fn, args, kwargs))

    def do_cleanup(self):
        while self._cleanups:
            fn, args, kwrags = self._cleanups.pop()
            try:
                fn(*args, **kwrags)
            except Exception:
                pass

    def await_string_in_view(self, view, needle):
        yield lambda: view.find(needle, 0, sublime.LITERAL)

    def await_active_panel_to_be(self, name):
        yield lambda: self.window.active_panel() == 'output.show_commit_info'

    def create_new_window(self):
        sublime.run_command("new_window")
        window = sublime.active_window()
        self.addCleanup(lambda: window.run_command('close_window'))
        return window

    def create_new_view(self, window=None):
        view = (window or sublime.active_window()).new_file()
        self.add_cleanup(self.close_view, view)
        return view

    def close_view(self, view):
        if view:
            view.set_scratch(True)
            view.close()

    def set_global_setting(self, key, value):
        settings = GitSavvySettings()
        original_value = settings.get(key)
        settings.set(key, value)
        self.add_cleanup(settings.set, key, original_value)

    def register_commit_info(self, info):
        for sha1, info in info.items():
            when(GsShowCommitInfoCommand).show_commit(sha1, ...).thenReturn(info)

    def create_graph_view_async(self, repo_path, log, wait_for):
        when(GsLogGraphRefreshCommand).git('log', ...).thenReturn(log)
        cmd = GsLogGraphCurrentBranch(self.window)
        when(cmd).get_repo_path().thenReturn(repo_path)
        cmd.run()
        yield lambda: self.window.active_view().settings().get('git_savvy.log_graph_view') is True
        log_view = self.window.active_view()
        yield from self.await_string_in_view(log_view, wait_for)

        return log_view

    def setup_graph_view_async(self, show_commit_info_setting=True):
        REPO_PATH = '/not/there'
        LOG = fixture('log_graph_1.txt')

        self.set_global_setting('graph_show_more_commit_info', show_commit_info_setting)
        self.register_commit_info({
            'fec0aca': COMMIT_1,
            'f461ea1': COMMIT_2
        })

        log_view = yield from self.create_graph_view_async(
            REPO_PATH, LOG,
            wait_for='0c2dd28 Guard updating state using a lock'
        )
        if show_commit_info_setting:
            yield from self.await_active_panel_to_be('output.show_commit_info')

        return log_view

    def test_hidden_info_panel_after_create(self):
        log_view = yield from self.setup_graph_view_async(show_commit_info_setting=False)

        actual = self.window.active_panel()
        expected = None
        self.assertEqual(actual, expected)

    def test_if_the_user_issues_our_toggle_command_open_the_panel(self):
        log_view = yield from self.setup_graph_view_async(show_commit_info_setting=False)

        self.window.run_command('gs_log_graph_toggle_more_info')
        yield from self.await_active_panel_to_be('output.show_commit_info')

        actual = self.window.active_panel()
        expected = 'output.show_commit_info'
        self.assertEqual(actual, expected)

    def test_open_info_panel_after_create(self):
        log_view = yield from self.setup_graph_view_async()

        actual = self.window.active_panel()
        expected = 'output.show_commit_info'
        self.assertEqual(actual, expected)

    def test_info_panel_shows_first_commit_initially(self):
        log_view = yield from self.setup_graph_view_async()
        panel = self.window.find_output_panel('show_commit_info')

        yield from self.await_string_in_view(panel, COMMIT_1)

        # `yield condition` will continue after a timeout so we need
        # to actually assert here
        actual = panel.find(COMMIT_1, 0, sublime.LITERAL)
        self.assertTrue(actual)

    def test_info_panel_shows_second_commit_after_navigate(self):
        log_view = yield from self.setup_graph_view_async()
        panel = self.window.find_output_panel('show_commit_info')

        log_view.run_command('gs_log_graph_navigate')
        yield from self.await_string_in_view(panel, COMMIT_2)

        actual = panel.find(COMMIT_2, 0, sublime.LITERAL)
        self.assertTrue(actual)

    def test_info_panel_shows_second_commit_after_cursor_moves(self):
        log_view = yield from self.setup_graph_view_async()
        panel = self.window.find_output_panel('show_commit_info')

        log_view.sel().clear()
        log_view.sel().add(log_view.text_point(1, 14))
        GsLogGraphCursorListener().on_selection_modified_async(log_view)
        yield from self.await_string_in_view(panel, COMMIT_2)

        actual = panel.find(COMMIT_2, 0, sublime.LITERAL)
        self.assertTrue(actual)

    def test_if_the_user_issues_our_toggle_command_close_the_panel_and_keep_it(self):
        log_view = yield from self.setup_graph_view_async()

        self.window.run_command('gs_log_graph_toggle_more_info')
        actual = self.window.active_panel()
        expected = None
        self.assertEqual(actual, expected)

        # Ensure it doesn't open on navigate
        log_view.run_command('gs_log_graph_navigate')

        yield 500  # ?

        actual = self.window.active_panel()
        expected = None
        self.assertEqual(actual, expected)

    def test_if_the_user_opens_another_panel_dont_fight(self):
        window = self.window
        log_view = yield from self.setup_graph_view_async()
        active_group = window.active_group()

        window.run_command('show_panel', {'panel': 'console'})
        # We need both to get the cursor back
        window.focus_group(active_group)
        window.focus_view(log_view)
        log_view.run_command('gs_log_graph_navigate')

        yield 500  # ?

        actual = self.window.active_panel()
        expected = 'console'
        self.assertEqual(actual, expected)

    def test_if_the_user_closes_the_panel_accept_it(self):
        log_view = yield from self.setup_graph_view_async()

        self.window.run_command('hide_panel')
        log_view.run_command('gs_log_graph_navigate')

        yield 500  # ?

        actual = self.window.active_panel()
        expected = None
        self.assertEqual(actual, expected)

    def test_show_correct_info_if_user_moves_around_and_then_toggles_panel(self):
        log_view = yield from self.setup_graph_view_async()
        panel = self.window.find_output_panel('show_commit_info')
        # close panel
        self.window.run_command('gs_log_graph_toggle_more_info')

        # move around
        log_view.sel().clear()
        log_view.sel().add(log_view.text_point(1, 14))
        GsLogGraphCursorListener().on_selection_modified_async(log_view)

        # show panel
        self.window.run_command('gs_log_graph_toggle_more_info')

        yield from self.await_string_in_view(panel, COMMIT_2)

        actual = panel.find(COMMIT_2, 0, sublime.LITERAL)
        self.assertTrue(actual)

    def test_show_correct_info_if_user_moves_around_and_then_opens_panel(self):
        log_view = yield from self.setup_graph_view_async()
        panel = self.window.find_output_panel('show_commit_info')
        # close panel
        self.window.run_command('gs_log_graph_toggle_more_info')

        # move around
        log_view.sel().clear()
        log_view.sel().add(log_view.text_point(1, 14))
        GsLogGraphCursorListener().on_selection_modified_async(log_view)

        # show panel e.g. via mouse
        self.window.run_command('show_panel', {'panel': 'output.show_commit_info'})

        yield from self.await_string_in_view(panel, COMMIT_2)

        actual = panel.find(COMMIT_2, 0, sublime.LITERAL)
        self.assertTrue(actual)

    def _test_afocus_info_panel(self):
        log_view = yield from self.setup_graph_view_async()

        yield 2500

    def _test(self):
        panel = self.window.find_output_panel('show_commit_info')

        self.window.focus_view(panel)

        log_view.run_command('gs_log_graph_navigate')
        log_view.run_command('gs_log_graph_navigate')
        yield 2000
<|endoftext|>


<commit_before>import great_expectations as ge
import great_expectations.jupyter_ux as jux
from great_expectations.profile.basic_dataset_profiler import BasicDatasetProfiler

def test_styling_elements_exist():
    assert "<link" in jux.bootstrap_link_element
    assert "bootstrap" in jux.bootstrap_link_element

    assert jux.cooltip_style_element[:23] == '

        naturals

is a required field.

values must be unique.

"""

def test_display_column_evrs_as_section():
    #TODO: We should add a fixture that contains EVRs
    df = ge.read_csv("./tests/test_sets/Titanic.csv")
    df.profile(BasicDatasetProfiler)
    evrs = df.validate(result_format="SUMMARY")  # ["results"]

    html_to_display = jux.display_column_evrs_as_section(
        evrs,
        "Name",
        include_styling=False,
        return_without_displaying=True
    )
    print(html_to_display)

    #FIXME: This snapshot test is brittle, since it depends on the behavior of the profiler, renderer, and view.
    # At the very least, we can take the profiler out of the loop by creating a new fixture for it.
    # Next time this snapshot test fails, please do that.
    assert html_to_display == """\

        Name

        Properties

            Distinct (n)	1310

            Distinct (%)	99.8%

            Missing (n)	0

            Missing (%)	0.0%

        Example values

        Carlsson, Mr Frans Olof
        Connolly, Miss Kate
        Kelly, Mr James
        Allen, Miss Elisabeth Walton
        Allison, Master Hudson Trevor
        Allison, Miss Helen Loraine
        Allison, Mr Hudson Joshua Creighton
        Allison, Mrs Hudson JC (Bessie Waldo Daniels)
        Anderson, Mr Harry
        Andrews, Miss Kornelia Theodosia
        Andrews, Mr Thomas, jr
        Appleton, Mrs Edward Dale (Charlotte Lamson)
        Artagaveytia, Mr Ramon
        Astor, Colonel John Jacob
        Astor, Mrs John Jacob (Madeleine Talmadge Force)
        Aubert, Mrs Leontine Pauline
        Barkworth, Mr Algernon H
        Baumann, Mr John D
        Baxter, Mr Quigg Edmond
        Baxter, Mrs James (Helene DeLaudeniere Chaput)

        Expectation types

expect_column_values_to_be_in_type_list True

expect_column_unique_value_count_to_be_between True

expect_column_proportion_of_unique_values_to_be_between True

expect_column_values_to_not_be_null True

expect_column_values_to_be_in_set False

expect_column_values_to_not_match_regex False

"""<commit_msg>Replace snapshot test with narrower test<commit_after>import great_expectations as ge
import great_expectations.jupyter_ux as jux
from great_expectations.profile.basic_dataset_profiler import BasicDatasetProfiler

def test_styling_elements_exist():
    assert "<link" in jux.bootstrap_link_element
    assert "bootstrap" in jux.bootstrap_link_element

    assert jux.cooltip_style_element[:23] == '

        naturals

is a required field.

values must be unique.

"""

def test_display_column_evrs_as_section():
    #TODO: We should add a fixture that contains EVRs
    df = ge.read_csv("./tests/test_sets/Titanic.csv")
    df.profile(BasicDatasetProfiler)
    evrs = df.validate(result_format="SUMMARY")  # ["results"]

    html_to_display = jux.display_column_evrs_as_section(
        evrs,
        "Name",
        include_styling=False,
        return_without_displaying=True
    )
    print(html_to_display)

    #FIXME: This isn't a full snapshot test.
    assert '
' in html_to_display
    assert 'Carlsson, Mr Frans Olof' in html_to_display
    assert '
expect_column_values_to_be_in_type_list True
' in html_to_display
<|endoftext|>


<commit_before>import unittest

from distance.levelinfos import LevelInfos
from distance.bytes import DstBytes, PrintContext

class Version0LevelsTest(unittest.TestCase):

    def setUp(self):
        self.file = open("tests/in/levelinfos/LevelInfos.bytes", 'rb')
        self.dbytes = DstBytes(self.file)
        self.infos = LevelInfos(self.dbytes)
        self.levels = self.infos.levels

    def tearDown(self):
        self.file.close()

    def test_length(self):
        self.assertEqual(len(self.levels), 2)

    def test_names(self):
        self.assertEqual('Lost Fortress', self.levels[0].level_name)
        self.assertEqual('Main Menu Datastream', self.levels[1].level_name)

    def test_paths(self):
        self.assertEqual('MyLevels/lost fortress.bytes', self.levels[0].level_path)
        self.assertEqual('MyLevels/main menu datastream.bytes', self.levels[1].level_path)

    def test_basename(self):
        self.assertEqual('lost fortress', self.levels[0].level_basename)
        self.assertEqual('main menu datastream', self.levels[1].level_basename)

    def test_modes(self):
        self.assertEqual({1: 1, 2: 0, 3: 0, 5: 0, 8: 0, 10: 0}, self.levels[0].modes)
        self.assertEqual({1: 0, 2: 0, 5: 0, 8: 0, 13: 1}, self.levels[1].modes)

    def test_times(self):
        exp = [240000, 180000, 135000, 90000]
        for i, time in enumerate(self.levels[0].medal_times):
            self.assertAlmostEqual(exp[i], time)
        exp = [-1, -1, -1, -1]
        for i, time in enumerate(self.levels[1].medal_times):
            self.assertAlmostEqual(exp[i], time)

    def test_scores(self):
        self.assertEqual([0, 0, 0, 0], self.levels[0].medal_scores)
        self.assertEqual([-1, -1, -1, -1], self.levels[1].medal_scores)

    def test_printing_works(self):
        p = PrintContext.for_test()
        p.print_data_of(self.infos)

# vim:set sw=4 ts=8 sts=4 et sr ft=python fdm=marker tw=0:
<commit_msg>test: use more implicit DstBytes constructor<commit_after>import unittest

from distance.levelinfos import LevelInfos
from distance.printing import PrintContext

class Version0LevelsTest(unittest.TestCase):

    def setUp(self):
        self.infos = LevelInfos("tests/in/levelinfos/LevelInfos.bytes")
        self.levels = self.infos.levels

    def test_length(self):
        self.assertEqual(len(self.levels), 2)

    def test_names(self):
        self.assertEqual('Lost Fortress', self.levels[0].level_name)
        self.assertEqual('Main Menu Datastream', self.levels[1].level_name)

    def test_paths(self):
        self.assertEqual('MyLevels/lost fortress.bytes', self.levels[0].level_path)
        self.assertEqual('MyLevels/main menu datastream.bytes', self.levels[1].level_path)

    def test_basename(self):
        self.assertEqual('lost fortress', self.levels[0].level_basename)
        self.assertEqual('main menu datastream', self.levels[1].level_basename)

    def test_modes(self):
        self.assertEqual({1: 1, 2: 0, 3: 0, 5: 0, 8: 0, 10: 0}, self.levels[0].modes)
        self.assertEqual({1: 0, 2: 0, 5: 0, 8: 0, 13: 1}, self.levels[1].modes)

    def test_times(self):
        exp = [240000, 180000, 135000, 90000]
        for i, time in enumerate(self.levels[0].medal_times):
            self.assertAlmostEqual(exp[i], time)
        exp = [-1, -1, -1, -1]
        for i, time in enumerate(self.levels[1].medal_times):
            self.assertAlmostEqual(exp[i], time)

    def test_scores(self):
        self.assertEqual([0, 0, 0, 0], self.levels[0].medal_scores)
        self.assertEqual([-1, -1, -1, -1], self.levels[1].medal_scores)

    def test_printing_works(self):
        p = PrintContext.for_test()
        p.print_data_of(self.infos)

# vim:set sw=4 ts=8 sts=4 et sr ft=python fdm=marker tw=0:
<|endoftext|>