<commit_before># -*- coding: utf8 -*-
# This file is part of PyBossa.
#
# Copyright (C) 2013 SF Isle of Man Limited
#
# PyBossa is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# PyBossa is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with PyBossa.  If not, see <http://www.gnu.org/licenses/>.

import json

from base import Fixtures
from helper import web as web_helper
from pybossa.hateoas import Hateoas

class TestHateoas(web_helper.Helper):
    url = "/app/%s/tasks/export" % Fixtures.app_short_name

    hateoas = Hateoas()

    def setUp(self):
        super(TestHateoas, self).setUp()
        Fixtures.create()

    # Tests

    def test_00_link_object(self):
        """Test HATEOAS object link is created when"""
        # For app
        res = self.app.get("/api/app/1", follow_redirects=True)
        output = json.loads(res.data)
        err_msg = "There should be a Link with the object URI"
        assert output['link'] is not None, err_msg

        err_msg = "There should be a Links list with the category URI"
        assert output['links'] is not None, err_msg
        assert len(output['links']) == 1, err_msg
        app_link = self.hateoas.link(rel='category', title='category',
                                     href='http://localhost/api/category/1')
        assert app_link == output['links'][0], err_msg

        app_link = self.hateoas.link(rel='self', title='app',
                                     href='http://localhost/api/app/1')
        err_msg = "The object link is wrong: %s" % output['link']
        assert app_link == output['link'], err_msg

        # For task
        res = self.app.get("/api/task/1", follow_redirects=True)
        output = json.loads(res.data)
        err_msg = "There should be a Link with the object URI"
        assert output['link'] is not None, err_msg
        task_link = self.hateoas.link(rel='self', title='task',
                                      href='http://localhost/api/task/1')
        err_msg = "The object link is wrong: %s" % output['link']
        assert task_link == output['link'], err_msg
        err_msg = "There should be one parent link: app"
        assert output.get('links') is not None, err_msg
        assert len(output.get('links')) == 1, err_msg
        err_msg = "The parent link is wrong"
        app_link = self.hateoas.link(rel='parent', title='app',
                                     href='http://localhost/api/app/1')
        assert output.get('links')[0] == app_link, err_msg

        # For taskrun
        res = self.app.get("/api/taskrun/1", follow_redirects=True)
        output = json.loads(res.data)
        err_msg = "There should be a Link with the object URI"
        assert output['link'] is not None, err_msg
        task_link = self.hateoas.link(rel='self', title='taskrun',
                                      href='http://localhost/api/taskrun/1')
        err_msg = "The object link is wrong: %s" % output['link']
        assert task_link == output['link'], err_msg
        err_msg = "There should be two parent links: app and task"
        assert output.get('links') is not None, err_msg
        assert len(output.get('links')) == 2, err_msg
        err_msg = "The parent app link is wrong"
        app_link = self.hateoas.link(rel='parent', title='app',
                                     href='http://localhost/api/app/1')
        assert output.get('links')[0] == app_link, err_msg

        err_msg = "The parent task link is wrong"
        app_link = self.hateoas.link(rel='parent', title='task',
                                     href='http://localhost/api/task/1')
        assert output.get('links')[1] == app_link, err_msg

    def test_01_link_object(self):
        """Test HATEOAS object link is created"""
        # For app
        res = self.app.get("/api/app", follow_redirects=True)
        output = json.loads(res.data)[0]
        err_msg = "There should be a Link with the object URI"
        assert output['link'] is not None, err_msg
        app_link = self.hateoas.link(rel='self', title='app',
                                     href='http://localhost/api/app/1')

        err_msg = "The object link is wrong: %s" % output['link']
        assert app_link == output['link'], err_msg

        err_msg = "There should be a Links list with the category URI"
        assert output['links'] is not None, err_msg
        assert len(output['links']) == 1, err_msg
        app_link = self.hateoas.link(rel='category', title='category',
                                     href='http://localhost/api/category/1')
        assert app_link == output['links'][0], err_msg

        # For task
        res = self.app.get("/api/task", follow_redirects=True)
        output = json.loads(res.data)[0]
        err_msg = "There should be a Link with the object URI"
        assert output['link'] is not None, err_msg
        task_link = self.hateoas.link(rel='self', title='task',
                                      href='http://localhost/api/task/1')
        err_msg = "The object link is wrong: %s" % output['link']
        assert task_link == output['link'], err_msg
        err_msg = "There should be one parent link: app"
        assert output.get('links') is not None, err_msg
        assert len(output.get('links')) == 1, err_msg
        err_msg = "The parent link is wrong"
        app_link = self.hateoas.link(rel='parent', title='app',
                                     href='http://localhost/api/app/1')
        assert output.get('links')[0] == app_link, err_msg

        # For taskrun
        res = self.app.get("/api/taskrun", follow_redirects=True)
        output = json.loads(res.data)[0]
        err_msg = "There should be a Link with the object URI"
        assert output['link'] is not None, err_msg
        task_link = self.hateoas.link(rel='self', title='taskrun',
                                      href='http://localhost/api/taskrun/1')
        err_msg = "The object link is wrong: %s" % output['link']
        assert task_link == output['link'], err_msg
        err_msg = "There should be two parent links: app and task"
        assert output.get('links') is not None, err_msg
        assert len(output.get('links')) == 2, err_msg
        err_msg = "The parent app link is wrong"
        app_link = self.hateoas.link(rel='parent', title='app',
                                     href='http://localhost/api/app/1')
        assert output.get('links')[0] == app_link, err_msg

        err_msg = "The parent task link is wrong"
        app_link = self.hateoas.link(rel='parent', title='task',
                                     href='http://localhost/api/task/1')
        assert output.get('links')[1] == app_link, err_msg<commit_msg>fixed typo<commit_after># -*- coding: utf8 -*-
# This file is part of PyBossa.
#
# Copyright (C) 2013 SF Isle of Man Limited
#
# PyBossa is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# PyBossa is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with PyBossa.  If not, see <http://www.gnu.org/licenses/>.

import json

from base import Fixtures
from helper import web as web_helper
from pybossa.hateoas import Hateoas

class TestHateoas(web_helper.Helper):
    url = "/app/%s/tasks/export" % Fixtures.app_short_name

    hateoas = Hateoas()

    def setUp(self):
        super(TestHateoas, self).setUp()
        Fixtures.create()

    # Tests

    def test_00_link_object(self):
        """Test HATEOAS object link is created"""
        # For app
        res = self.app.get("/api/app/1", follow_redirects=True)
        output = json.loads(res.data)
        err_msg = "There should be a Link with the object URI"
        assert output['link'] is not None, err_msg

        err_msg = "There should be a Links list with the category URI"
        assert output['links'] is not None, err_msg
        assert len(output['links']) == 1, err_msg
        app_link = self.hateoas.link(rel='category', title='category',
                                     href='http://localhost/api/category/1')
        assert app_link == output['links'][0], err_msg

        app_link = self.hateoas.link(rel='self', title='app',
                                     href='http://localhost/api/app/1')
        err_msg = "The object link is wrong: %s" % output['link']
        assert app_link == output['link'], err_msg

        # For task
        res = self.app.get("/api/task/1", follow_redirects=True)
        output = json.loads(res.data)
        err_msg = "There should be a Link with the object URI"
        assert output['link'] is not None, err_msg
        task_link = self.hateoas.link(rel='self', title='task',
                                      href='http://localhost/api/task/1')
        err_msg = "The object link is wrong: %s" % output['link']
        assert task_link == output['link'], err_msg
        err_msg = "There should be one parent link: app"
        assert output.get('links') is not None, err_msg
        assert len(output.get('links')) == 1, err_msg
        err_msg = "The parent link is wrong"
        app_link = self.hateoas.link(rel='parent', title='app',
                                     href='http://localhost/api/app/1')
        assert output.get('links')[0] == app_link, err_msg

        # For taskrun
        res = self.app.get("/api/taskrun/1", follow_redirects=True)
        output = json.loads(res.data)
        err_msg = "There should be a Link with the object URI"
        assert output['link'] is not None, err_msg
        task_link = self.hateoas.link(rel='self', title='taskrun',
                                      href='http://localhost/api/taskrun/1')
        err_msg = "The object link is wrong: %s" % output['link']
        assert task_link == output['link'], err_msg
        err_msg = "There should be two parent links: app and task"
        assert output.get('links') is not None, err_msg
        assert len(output.get('links')) == 2, err_msg
        err_msg = "The parent app link is wrong"
        app_link = self.hateoas.link(rel='parent', title='app',
                                     href='http://localhost/api/app/1')
        assert output.get('links')[0] == app_link, err_msg

        err_msg = "The parent task link is wrong"
        app_link = self.hateoas.link(rel='parent', title='task',
                                     href='http://localhost/api/task/1')
        assert output.get('links')[1] == app_link, err_msg

    def test_01_link_object(self):
        """Test HATEOAS object link is created"""
        # For app
        res = self.app.get("/api/app", follow_redirects=True)
        output = json.loads(res.data)[0]
        err_msg = "There should be a Link with the object URI"
        assert output['link'] is not None, err_msg
        app_link = self.hateoas.link(rel='self', title='app',
                                     href='http://localhost/api/app/1')

        err_msg = "The object link is wrong: %s" % output['link']
        assert app_link == output['link'], err_msg

        err_msg = "There should be a Links list with the category URI"
        assert output['links'] is not None, err_msg
        assert len(output['links']) == 1, err_msg
        app_link = self.hateoas.link(rel='category', title='category',
                                     href='http://localhost/api/category/1')
        assert app_link == output['links'][0], err_msg

        # For task
        res = self.app.get("/api/task", follow_redirects=True)
        output = json.loads(res.data)[0]
        err_msg = "There should be a Link with the object URI"
        assert output['link'] is not None, err_msg
        task_link = self.hateoas.link(rel='self', title='task',
                                      href='http://localhost/api/task/1')
        err_msg = "The object link is wrong: %s" % output['link']
        assert task_link == output['link'], err_msg
        err_msg = "There should be one parent link: app"
        assert output.get('links') is not None, err_msg
        assert len(output.get('links')) == 1, err_msg
        err_msg = "The parent link is wrong"
        app_link = self.hateoas.link(rel='parent', title='app',
                                     href='http://localhost/api/app/1')
        assert output.get('links')[0] == app_link, err_msg

        # For taskrun
        res = self.app.get("/api/taskrun", follow_redirects=True)
        output = json.loads(res.data)[0]
        err_msg = "There should be a Link with the object URI"
        assert output['link'] is not None, err_msg
        task_link = self.hateoas.link(rel='self', title='taskrun',
                                      href='http://localhost/api/taskrun/1')
        err_msg = "The object link is wrong: %s" % output['link']
        assert task_link == output['link'], err_msg
        err_msg = "There should be two parent links: app and task"
        assert output.get('links') is not None, err_msg
        assert len(output.get('links')) == 2, err_msg
        err_msg = "The parent app link is wrong"
        app_link = self.hateoas.link(rel='parent', title='app',
                                     href='http://localhost/api/app/1')
        assert output.get('links')[0] == app_link, err_msg

        err_msg = "The parent task link is wrong"
        app_link = self.hateoas.link(rel='parent', title='task',
                                     href='http://localhost/api/task/1')
        assert output.get('links')[1] == app_link, err_msg
<|endoftext|>


<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-

import re

import py.test
from mock import Mock
from docutils import nodes
from sphinx.addnodes import pending_xref

from sphinxcontrib import issuetracker

def pytest_funcarg__issue_info(request):
    return dict(uri='http://example.com/issues/10', closed=False)

def pytest_funcarg__get_issue_information(request):
    get_issue_information = Mock()
    info = request.getfuncargvalue('issue_info')
    get_issue_information.return_value = info
    return get_issue_information

def pytest_funcarg__resolver(request):
    return issuetracker.make_issue_reference_resolver(
        request.getfuncargvalue('get_issue_information'))

def pytest_funcarg__config(request):
    config = Mock()
    config.project = 'issuetracker'
    config.issuetracker = 'spamtracker'
    config.issuetracker_user = 'foobar'
    config.issuetracker_project = None
    config.issuetracker_issue_pattern = re.compile(r'#(\d+)')
    return config

def pytest_funcarg__app(request):
    app = Mock()
    app.config = request.getfuncargvalue('config')
    return app

def pytest_funcarg__env(request):
    env = Mock()
    env.config = request.getfuncargvalue('config')
    return env

def pytest_funcarg__node(request):
    node = pending_xref()
    node['reftype'] = 'issue'
    node['reftarget'] = '10'
    node.append(nodes.Text('#10'))
    return node

def pytest_funcarg__doc(request):
    doc = nodes.paragraph()
    doc.append(nodes.Text('foo #1 bar'))
    em = nodes.emphasis()
    em.append(nodes.Text('see #2 if you are #abc brave'))
    doc.append(em)
    doc.settings = Mock()
    doc.settings.language_code = ''
    doc.settings.env = request.getfuncargvalue('env')
    return doc

def test_get_github_issue_information(env):
    info = issuetracker.get_github_issue_information(
        'pyudev', 'lunaryorn', '2', env)
    assert info == {'closed': True,
                    'uri': 'http://github.com/lunaryorn/pyudev/issues/2'}

def test_get_bitbucket_issue_information_resolved(env):
    info = issuetracker.get_bitbucket_issue_information(
        'synaptiks', 'lunar', '22', env)
    assert info == {'closed': True,
                    'uri': 'http://bitbucket.org/lunar/synaptiks/issue/22/'}

def test_get_bitbucket_issue_information_invalid(env):
    info = issuetracker.get_bitbucket_issue_information(
        'synaptiks', 'lunar', '36', env)
    assert info == {'closed': True,
                    'uri': 'http://bitbucket.org/lunar/synaptiks/issue/36/'}

def test_get_bitbucket_issue_information_duplicate(env):
    info = issuetracker.get_bitbucket_issue_information(
        'synaptiks', 'lunar', '42', env)
    assert info == {'closed': True,
                    'uri': 'http://bitbucket.org/lunar/synaptiks/issue/42/'}

def test_get_google_code_issue_information_fixed(env):
    info = issuetracker.get_google_code_issue_information(
        'pytox', None, '2', env)
    assert info == {
        'closed': True,
        'uri': 'http://code.google.com/p/pytox/issues/detail?id=2'}

def test_get_google_code_issue_information_invalid(env):
    info = issuetracker.get_google_code_issue_information(
        'pytox', None, '5', env)
    assert info == {
        'closed': True,
        'uri': 'http://code.google.com/p/pytox/issues/detail?id=5'}

def test_get_google_code_issue_information_wontfix(env):
    info = issuetracker.get_google_code_issue_information(
        'pytox', None, '6', env)
    assert info == {
        'closed': True,
        'uri': 'http://code.google.com/p/pytox/issues/detail?id=6'}

def test_make_isssue_reference_resolver_invalid_reftype(
    app, env, resolver, node):
    node['reftype'] = 'spam'
    assert resolver(app, env, node, node[0]) is None

def test_make_issue_reference_resolver_no_issue(
    app, env, resolver, node, get_issue_information):
    get_issue_information.return_value = None
    assert resolver(app, env, node, node[0]) is None

def test_make_issue_reference_resolver_no_uri(
    app, env, resolver, node, issue_info):
    del issue_info['uri']
    assert resolver(app, env, node, node[0]) is None

def test_make_issue_reference_resolver_open_issue(
    app, env, resolver, node, issue_info):
    contnode = node[0]
    node = resolver(app, env, node, node[0])
    assert isinstance(node, nodes.reference)
    assert node[0] is contnode
    assert node['refuri'] == issue_info['uri']
    assert 'reference-issue' in node['classes']
    assert 'issue-closed' not in node['classes']

def test_make_issue_reference_resolver_closed_issue(
    app, env, resolver, node, issue_info):
    issue_info['closed'] = True
    contnode = node[0]
    node = resolver(app, env, node, node[0])
    assert isinstance(node, nodes.reference)
    assert node[0] is contnode
    assert node['refuri'] == issue_info['uri']
    assert 'reference-issue' in node['classes']
    assert 'issue-closed' in node['classes']

def test_get_issue_information_called(
    app, env, resolver, node, get_issue_information):
    resolver(app, env, node, node[0])
    get_issue_information.assert_called_with(
        'issuetracker', 'foobar', '10', env)
    app.config.issuetracker_project = 'spam with eggs'
    resolver(app, env, node, node[0])
    get_issue_information.assert_called_with(
        'spam with eggs', 'foobar', '10', env)

def test_builtin_issue_trackers():
    for tracker in ('github', 'bitbucket',
                    'launchpad', 'google code'):
        assert tracker in issuetracker.BUILTIN_ISSUE_TRACKERS

def _assert_text(node, text):
    assert isinstance(node, nodes.Text)
    assert node.astext() == text

def _assert_xref(node, target):
    assert isinstance(node, pending_xref)
    _assert_text(node[0], '#%s' % target)
    assert node['reftype'] == 'issue'
    assert node['reftarget'] == target

def test_issues_references(doc):
    transformer = issuetracker.IssuesReferences(doc)
    transformer.apply()
    assert isinstance(doc, nodes.paragraph)
    assert doc.astext() == 'foo #1 barsee #2 if you are #abc brave'
    _assert_text(doc[0], 'foo ')
    _assert_xref(doc[1], '1')
    _assert_text(doc[2], ' bar')
    em = doc[3]
    assert isinstance(em, nodes.emphasis)
    _assert_text(em[0], 'see ')
    _assert_xref(em[1], '2')
    _assert_text(em[2], ' if you are #abc brave')

def test_auto_connect_builtin_issue_resolvers_known_tracker(app):
    app.config.issuetracker = 'bitbucket'
    issuetracker.auto_connect_builtin_issue_resolvers(app)
    assert app.connect.called

def test_auto_connect_builtin_issue_resolvers_unknown_tracker(app):
    app.config.issuetracker = 'spamtracker'
    with py.test.raises(KeyError):
        issuetracker.auto_connect_builtin_issue_resolvers(app)

def test_auto_connect_builtin_issue_resolvers_no_tracker(app):
    app.config.issuetracker = None
    issuetracker.auto_connect_builtin_issue_resolvers(app)
    assert not app.connect.called

def test_add_stylesheet(app):
    issuetracker.add_stylesheet(app)
    app.add_stylesheet.assert_called_with('issuetracker.css')

def test_setup(app):
    issuetracker.setup(app)
    app.require_sphinx.assert_called_with('1.0')
    app.add_transform.assert_called_with(issuetracker.IssuesReferences)
    app.connect.call_args_list = [
        (('builder-inited',
          issuetracker.auto_connect_builtin_issue_resolvers), {}),
        (('builder-inited', issuetracker.add_stylesheet), {}),
        (('build-finished', issuetracker.copy_stylesheet), {})]
    app.add_config_value.call_args_list = [
        (('issuetracker_issue_pattern', re.compile(r'#(\d+)'), 'env'), {}),
        (('issuetracker_user', None, 'env'), {}),
        (('issuetracker_project', None, 'env'), {}),
        (('issuetracker', None, 'env'), {})]

def main():
    import py
    py.cmdline.pytest()

if __name__ == '__main__':
    main()
<commit_msg>Test error message when using a pattern with too many groups<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-

import re

import py.test
from mock import Mock
from docutils import nodes
from sphinx.addnodes import pending_xref

from sphinxcontrib import issuetracker

def pytest_funcarg__issue_info(request):
    return dict(uri='http://example.com/issues/10', closed=False)

def pytest_funcarg__get_issue_information(request):
    get_issue_information = Mock()
    info = request.getfuncargvalue('issue_info')
    get_issue_information.return_value = info
    return get_issue_information

def pytest_funcarg__resolver(request):
    return issuetracker.make_issue_reference_resolver(
        request.getfuncargvalue('get_issue_information'))

def pytest_funcarg__config(request):
    config = Mock()
    config.project = 'issuetracker'
    config.issuetracker = 'spamtracker'
    config.issuetracker_user = 'foobar'
    config.issuetracker_project = None
    config.issuetracker_issue_pattern = re.compile(r'#(\d+)')
    return config

def pytest_funcarg__app(request):
    app = Mock()
    app.config = request.getfuncargvalue('config')
    return app

def pytest_funcarg__env(request):
    env = Mock()
    env.config = request.getfuncargvalue('config')
    return env

def pytest_funcarg__node(request):
    node = pending_xref()
    node['reftype'] = 'issue'
    node['reftarget'] = '10'
    node.append(nodes.Text('#10'))
    return node

def pytest_funcarg__doc(request):
    doc = nodes.paragraph()
    doc.append(nodes.Text('foo #1 bar'))
    em = nodes.emphasis()
    em.append(nodes.Text('see #2 if you are #abc brave'))
    doc.append(em)
    doc.settings = Mock()
    doc.settings.language_code = ''
    doc.settings.env = request.getfuncargvalue('env')
    return doc

def test_get_github_issue_information(env):
    info = issuetracker.get_github_issue_information(
        'pyudev', 'lunaryorn', '2', env)
    assert info == {'closed': True,
                    'uri': 'http://github.com/lunaryorn/pyudev/issues/2'}

def test_get_bitbucket_issue_information_resolved(env):
    info = issuetracker.get_bitbucket_issue_information(
        'synaptiks', 'lunar', '22', env)
    assert info == {'closed': True,
                    'uri': 'http://bitbucket.org/lunar/synaptiks/issue/22/'}

def test_get_bitbucket_issue_information_invalid(env):
    info = issuetracker.get_bitbucket_issue_information(
        'synaptiks', 'lunar', '36', env)
    assert info == {'closed': True,
                    'uri': 'http://bitbucket.org/lunar/synaptiks/issue/36/'}

def test_get_bitbucket_issue_information_duplicate(env):
    info = issuetracker.get_bitbucket_issue_information(
        'synaptiks', 'lunar', '42', env)
    assert info == {'closed': True,
                    'uri': 'http://bitbucket.org/lunar/synaptiks/issue/42/'}

def test_get_google_code_issue_information_fixed(env):
    info = issuetracker.get_google_code_issue_information(
        'pytox', None, '2', env)
    assert info == {
        'closed': True,
        'uri': 'http://code.google.com/p/pytox/issues/detail?id=2'}

def test_get_google_code_issue_information_invalid(env):
    info = issuetracker.get_google_code_issue_information(
        'pytox', None, '5', env)
    assert info == {
        'closed': True,
        'uri': 'http://code.google.com/p/pytox/issues/detail?id=5'}

def test_get_google_code_issue_information_wontfix(env):
    info = issuetracker.get_google_code_issue_information(
        'pytox', None, '6', env)
    assert info == {
        'closed': True,
        'uri': 'http://code.google.com/p/pytox/issues/detail?id=6'}

def test_make_isssue_reference_resolver_invalid_reftype(
    app, env, resolver, node):
    node['reftype'] = 'spam'
    assert resolver(app, env, node, node[0]) is None

def test_make_issue_reference_resolver_no_issue(
    app, env, resolver, node, get_issue_information):
    get_issue_information.return_value = None
    assert resolver(app, env, node, node[0]) is None

def test_make_issue_reference_resolver_no_uri(
    app, env, resolver, node, issue_info):
    del issue_info['uri']
    assert resolver(app, env, node, node[0]) is None

def test_make_issue_reference_resolver_open_issue(
    app, env, resolver, node, issue_info):
    contnode = node[0]
    node = resolver(app, env, node, node[0])
    assert isinstance(node, nodes.reference)
    assert node[0] is contnode
    assert node['refuri'] == issue_info['uri']
    assert 'reference-issue' in node['classes']
    assert 'issue-closed' not in node['classes']

def test_make_issue_reference_resolver_closed_issue(
    app, env, resolver, node, issue_info):
    issue_info['closed'] = True
    contnode = node[0]
    node = resolver(app, env, node, node[0])
    assert isinstance(node, nodes.reference)
    assert node[0] is contnode
    assert node['refuri'] == issue_info['uri']
    assert 'reference-issue' in node['classes']
    assert 'issue-closed' in node['classes']

def test_get_issue_information_called(
    app, env, resolver, node, get_issue_information):
    resolver(app, env, node, node[0])
    get_issue_information.assert_called_with(
        'issuetracker', 'foobar', '10', env)
    app.config.issuetracker_project = 'spam with eggs'
    resolver(app, env, node, node[0])
    get_issue_information.assert_called_with(
        'spam with eggs', 'foobar', '10', env)

def test_builtin_issue_trackers():
    for tracker in ('github', 'bitbucket',
                    'launchpad', 'google code'):
        assert tracker in issuetracker.BUILTIN_ISSUE_TRACKERS

def _assert_text(node, text):
    assert isinstance(node, nodes.Text)
    assert node.astext() == text

def _assert_xref(node, target):
    assert isinstance(node, pending_xref)
    _assert_text(node[0], '#%s' % target)
    assert node['reftype'] == 'issue'
    assert node['reftarget'] == target

def test_issues_references(doc):
    transformer = issuetracker.IssuesReferences(doc)
    transformer.apply()
    assert isinstance(doc, nodes.paragraph)
    assert doc.astext() == 'foo #1 barsee #2 if you are #abc brave'
    _assert_text(doc[0], 'foo ')
    _assert_xref(doc[1], '1')
    _assert_text(doc[2], ' bar')
    em = doc[3]
    assert isinstance(em, nodes.emphasis)
    _assert_text(em[0], 'see ')
    _assert_xref(em[1], '2')
    _assert_text(em[2], ' if you are #abc brave')

def test_issues_references_too_many_groups(doc, config):
    config.issuetracker_issue_pattern = r'(#)(\d+)'
    transformer = issuetracker.IssuesReferences(doc)
    with py.test.raises(ValueError) as exc_info:
        transformer.apply()
    error = exc_info.value
    assert str(error) == ('issuetracker_issue_pattern must have '
                          'exactly one group: %r' % ((u'#', u'1'),))

def test_auto_connect_builtin_issue_resolvers_known_tracker(app):
    app.config.issuetracker = 'bitbucket'
    issuetracker.auto_connect_builtin_issue_resolvers(app)
    assert app.connect.called

def test_auto_connect_builtin_issue_resolvers_unknown_tracker(app):
    app.config.issuetracker = 'spamtracker'
    with py.test.raises(KeyError):
        issuetracker.auto_connect_builtin_issue_resolvers(app)

def test_auto_connect_builtin_issue_resolvers_no_tracker(app):
    app.config.issuetracker = None
    issuetracker.auto_connect_builtin_issue_resolvers(app)
    assert not app.connect.called

def test_add_stylesheet(app):
    issuetracker.add_stylesheet(app)
    app.add_stylesheet.assert_called_with('issuetracker.css')

def test_setup(app):
    issuetracker.setup(app)
    app.require_sphinx.assert_called_with('1.0')
    app.add_transform.assert_called_with(issuetracker.IssuesReferences)
    app.connect.call_args_list = [
        (('builder-inited',
          issuetracker.auto_connect_builtin_issue_resolvers), {}),
        (('builder-inited', issuetracker.add_stylesheet), {}),
        (('build-finished', issuetracker.copy_stylesheet), {})]
    app.add_config_value.call_args_list = [
        (('issuetracker_issue_pattern', re.compile(r'#(\d+)'), 'env'), {}),
        (('issuetracker_user', None, 'env'), {}),
        (('issuetracker_project', None, 'env'), {}),
        (('issuetracker', None, 'env'), {})]

def main():
    import py
    py.cmdline.pytest()

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


<commit_before>import logging
import time
import unittest
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.queryinspect import QueryInspect

log = logging.getLogger(__name__)

class TestQueryInspect(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        logging.basicConfig(format='%(asctime)-15s %(levelname)s %(message)s')
        logging.getLogger('flask_queryinspect').setLevel(logging.DEBUG)
        logging.getLogger('test_queryinspect').setLevel(logging.DEBUG)

        cls.app = Flask(__name__)
        cls.app.config['TESTING'] = True

        cls.app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://'
        #cls.app.config['SQLALCHEMY_ECHO'] = True
        db = SQLAlchemy(cls.app)
        cls.db = db
        cls.qi = QueryInspect(cls.app)

        class TestModel(db.Model):
            id = db.Column(db.Integer, primary_key=True)
            foo = db.Column(db.Unicode(10))

            def __init__(self, foo):
                self.foo = foo

        db.create_all(app=cls.app)
        for i in range(10):
            db.session.add(TestModel('test_%d' % i))
        db.session.commit()

        @cls.app.route('/')
        def index():
            return u'No Queries'

        @cls.app.route('/mix')
        def mix():
            t = TestModel.query.first()
            t.foo = 'bar'
            db.session.commit()
            return u'Reads and writes'

        @cls.app.route('/slow')
        def slow():
            time.sleep(.1)
            return u'Slow request'

    def test_noqueries(self):
        with self.app.test_client() as c:
            res = c.get('/')
            log.debug(res.headers)
            self.assertTrue(res.headers['X-QueryInspect-Combined'].startswith('reads=0,writes=0,conns=0'))

    def test_mix(self):
        with self.app.test_client() as c:
            res = c.get('/mix')
            log.debug(res.headers)
            self.assertTrue(res.headers['X-QueryInspect-Combined'].startswith('reads=1,writes=1'))

    def test_rtime(self):
        self.app.config['QUERYINSPECT_HEADERS_COMBINED'] = False
        with self.app.test_client() as c:
            res = c.get('/slow')
            r_time = res.headers['X-QueryInspect-Total-Request-Time']
            self.assertTrue(90 < r_time > 110)
        self.app.config['QUERYINSPECT_HEADERS_COMBINED'] = True
<commit_msg>python 3<commit_after>import logging
import time
import unittest
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.queryinspect import QueryInspect

log = logging.getLogger(__name__)

class TestQueryInspect(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        logging.basicConfig(format='%(asctime)-15s %(levelname)s %(message)s')
        logging.getLogger('flask_queryinspect').setLevel(logging.DEBUG)
        logging.getLogger('test_queryinspect').setLevel(logging.DEBUG)

        cls.app = Flask(__name__)
        cls.app.config['TESTING'] = True

        cls.app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://'
        #cls.app.config['SQLALCHEMY_ECHO'] = True
        db = SQLAlchemy(cls.app)
        cls.db = db
        cls.qi = QueryInspect(cls.app)

        class TestModel(db.Model):
            id = db.Column(db.Integer, primary_key=True)
            foo = db.Column(db.Unicode(10))

            def __init__(self, foo):
                self.foo = foo

        db.create_all(app=cls.app)
        for i in range(10):
            db.session.add(TestModel('test_%d' % i))
        db.session.commit()

        @cls.app.route('/')
        def index():
            return u'No Queries'

        @cls.app.route('/mix')
        def mix():
            t = TestModel.query.first()
            t.foo = 'bar'
            db.session.commit()
            return u'Reads and writes'

        @cls.app.route('/slow')
        def slow():
            time.sleep(.1)
            return u'Slow request'

    def test_noqueries(self):
        with self.app.test_client() as c:
            res = c.get('/')
            log.debug(res.headers)
            self.assertTrue(res.headers['X-QueryInspect-Combined'].startswith('reads=0,writes=0,conns=0'))

    def test_mix(self):
        with self.app.test_client() as c:
            res = c.get('/mix')
            log.debug(res.headers)
            self.assertTrue(res.headers['X-QueryInspect-Combined'].startswith('reads=1,writes=1'))

    def test_rtime(self):
        self.app.config['QUERYINSPECT_HEADERS_COMBINED'] = False
        with self.app.test_client() as c:
            res = c.get('/slow')
            r_time = float(res.headers['X-QueryInspect-Total-Request-Time'])
            self.assertTrue(90.0 < r_time > 110.0)
        self.app.config['QUERYINSPECT_HEADERS_COMBINED'] = True
<|endoftext|>


<commit_before>import os

from django.conf import settings
from django.core.management.commands.loaddata import Command
from django.db import connections, DEFAULT_DB_ALIAS
from django.db.backends.creation import TEST_DATABASE_PREFIX
from django.db.backends.mysql import creation as mysql

import django_nose

# Monkey-patch loaddata to ignore foreign key checks.
_old_handle = Command.handle
def _new_handle(self, *fixture_labels, **options):
    using = options.get('database', DEFAULT_DB_ALIAS)
    commit = options.get('commit', True)
    connection = connections[using]

    cursor = connection.cursor()
    cursor.execute('SET foreign_key_checks = 0')

    _old_handle(self, *fixture_labels, **options)

    cursor = connection.cursor()
    cursor.execute('SET foreign_key_checks = 1')

    if commit:
        connection.close()
Command.handle = _new_handle

# XXX: hard-coded to mysql.
class SkipDatabaseCreation(mysql.DatabaseCreation):

    def _create_test_db(self, verbosity, autoclobber):
        ### Oh yes, let's copy from django/db/backends/creation.py
        suffix = self.sql_table_creation_suffix()

        if self.connection.settings_dict['TEST_NAME']:
            test_database_name = self.connection.settings_dict['TEST_NAME']
        else:
            test_database_name = TEST_DATABASE_PREFIX + self.connection.settings_dict['NAME']
        qn = self.connection.ops.quote_name

        # Create the test database and connect to it. We need to autocommit
        # if the database supports it because PostgreSQL doesn't allow
        # CREATE/DROP DATABASE statements within transactions.
        cursor = self.connection.cursor()
        self.set_autocommit()

        ### That's enough copying.

        # If we couldn't create the test db, assume it already exists.
        try:
            cursor.execute("CREATE DATABASE %s %s" %
                           (qn(test_database_name), suffix))
        except Exception, e:
            print '...Skipping setup of %s!' % test_database_name
            print '...Try FORCE_DB=true if you need fresh databases.'
            return test_database_name

        # Drop the db we just created, then do the normal setup.
        cursor.execute("DROP DATABASE %s" % qn(test_database_name))
        return super(SkipDatabaseCreation, self)._create_test_db(
            verbosity, autoclobber)

class RadicalTestSuiteRunner(django_nose.NoseTestSuiteRunner):
    """
    This is a test runner that monkeypatches connection.creation to skip
    database creation if it appears that the db already exists.  Your tests
    will run much faster.

    To force the normal database creation, define the environment variable
    ``FORCE_DB``.  It doesn't really matter what the value is, we just check to
    see if it's there.
    """

    def setup_databases(self):
        if not os.getenv('FORCE_DB'):
            for alias in connections:
                connection = connections[alias]
                connection.creation.__class__ = SkipDatabaseCreation
        return super(RadicalTestSuiteRunner, self).setup_databases()

    def teardown_databases(self, old_config):
        if os.getenv('FORCE_DB'):
            super(RadicalTestSuiteRunner, self).teardown_databases(old_config)

    def setup_test_environment(self, **kwargs):
        super(RadicalTestSuiteRunner, self).setup_test_environment(**kwargs)

        # If we have a settings_test.py let's roll it into our settings.
        try:
            import settings_test
            settings.__dict__.update(settings_test.__dict__)
        except ImportError:
            pass

<commit_msg>Uses setattr to update Django's proxies.  This allows settings to be reset.<commit_after>import os

from django.conf import settings
from django.core.management.commands.loaddata import Command
from django.db import connections, DEFAULT_DB_ALIAS
from django.db.backends.creation import TEST_DATABASE_PREFIX
from django.db.backends.mysql import creation as mysql

import django_nose

# Monkey-patch loaddata to ignore foreign key checks.
_old_handle = Command.handle
def _new_handle(self, *fixture_labels, **options):
    using = options.get('database', DEFAULT_DB_ALIAS)
    commit = options.get('commit', True)
    connection = connections[using]

    cursor = connection.cursor()
    cursor.execute('SET foreign_key_checks = 0')

    _old_handle(self, *fixture_labels, **options)

    cursor = connection.cursor()
    cursor.execute('SET foreign_key_checks = 1')

    if commit:
        connection.close()
Command.handle = _new_handle

# XXX: hard-coded to mysql.
class SkipDatabaseCreation(mysql.DatabaseCreation):

    def _create_test_db(self, verbosity, autoclobber):
        ### Oh yes, let's copy from django/db/backends/creation.py
        suffix = self.sql_table_creation_suffix()

        if self.connection.settings_dict['TEST_NAME']:
            test_database_name = self.connection.settings_dict['TEST_NAME']
        else:
            test_database_name = TEST_DATABASE_PREFIX + self.connection.settings_dict['NAME']
        qn = self.connection.ops.quote_name

        # Create the test database and connect to it. We need to autocommit
        # if the database supports it because PostgreSQL doesn't allow
        # CREATE/DROP DATABASE statements within transactions.
        cursor = self.connection.cursor()
        self.set_autocommit()

        ### That's enough copying.

        # If we couldn't create the test db, assume it already exists.
        try:
            cursor.execute("CREATE DATABASE %s %s" %
                           (qn(test_database_name), suffix))
        except Exception, e:
            print '...Skipping setup of %s!' % test_database_name
            print '...Try FORCE_DB=true if you need fresh databases.'
            return test_database_name

        # Drop the db we just created, then do the normal setup.
        cursor.execute("DROP DATABASE %s" % qn(test_database_name))
        return super(SkipDatabaseCreation, self)._create_test_db(
            verbosity, autoclobber)

class RadicalTestSuiteRunner(django_nose.NoseTestSuiteRunner):
    """
    This is a test runner that monkeypatches connection.creation to skip
    database creation if it appears that the db already exists.  Your tests
    will run much faster.

    To force the normal database creation, define the environment variable
    ``FORCE_DB``.  It doesn't really matter what the value is, we just check to
    see if it's there.
    """

    def setup_databases(self):
        if not os.getenv('FORCE_DB'):
            for alias in connections:
                connection = connections[alias]
                connection.creation.__class__ = SkipDatabaseCreation
        return super(RadicalTestSuiteRunner, self).setup_databases()

    def teardown_databases(self, old_config):
        if os.getenv('FORCE_DB'):
            super(RadicalTestSuiteRunner, self).teardown_databases(old_config)

    def setup_test_environment(self, **kwargs):
        super(RadicalTestSuiteRunner, self).setup_test_environment(**kwargs)

        # If we have a settings_test.py let's roll it into our settings.
        try:
            import settings_test
            # Use setattr to update Django's proxies:
            for k in dir(settings_test):
                setattr(settings, k, getattr(settings_test, k))
        except ImportError:
            pass

<|endoftext|>


<commit_before>import os
import warnings

from django.conf import settings
from django.core.management.commands.loaddata import Command
from django.db import connections, DEFAULT_DB_ALIAS
from django.db.backends.creation import TEST_DATABASE_PREFIX
from django.db.backends.mysql import creation as mysql

import django_nose

def uses_mysql(connection):
    return 'mysql' in connection.settings_dict['ENGINE']

_old_handle = Command.handle
def _new_handle(self, *fixture_labels, **options):
    """Wrap the the stock loaddata to ignore foreign key checks.

    This is monkeypatched into place in setup_databases().

    """
    using = options.get('database', DEFAULT_DB_ALIAS)
    commit = options.get('commit', True)
    connection = connections[using]

    if uses_mysql(connection):
        cursor = connection.cursor()
        cursor.execute('SET foreign_key_checks = 0')

    _old_handle(self, *fixture_labels, **options)

    if uses_mysql(connection):
        cursor = connection.cursor()
        cursor.execute('SET foreign_key_checks = 1')

        if commit:
            connection.close()

# XXX: hard-coded to mysql.
class SkipDatabaseCreation(mysql.DatabaseCreation):

    def _create_test_db(self, verbosity, autoclobber):
        ### Oh yes, let's copy from django/db/backends/creation.py
        suffix = self.sql_table_creation_suffix()

        if self.connection.settings_dict['TEST_NAME']:
            test_database_name = self.connection.settings_dict['TEST_NAME']
        else:
            test_database_name = TEST_DATABASE_PREFIX + self.connection.settings_dict['NAME']
        qn = self.connection.ops.quote_name

        # Create the test database and connect to it. We need to autocommit
        # if the database supports it because PostgreSQL doesn't allow
        # CREATE/DROP DATABASE statements within transactions.
        cursor = self.connection.cursor()
        self.set_autocommit()

        ### That's enough copying.

        # If we couldn't create the test db, assume it already exists.
        try:
            cursor.execute("CREATE DATABASE %s %s" %
                           (qn(test_database_name), suffix))
        except Exception, e:
            print '...Skipping setup of %s!' % test_database_name
            print '...Try FORCE_DB=true if you need fresh databases.'
            return test_database_name

        # Drop the db we just created, then do the normal setup.
        cursor.execute("DROP DATABASE %s" % qn(test_database_name))
        return super(SkipDatabaseCreation, self)._create_test_db(
            verbosity, autoclobber)

class RadicalTestSuiteRunner(django_nose.NoseTestSuiteRunner):
    """This is a test runner that monkeypatches connection.creation to skip
    database creation if it appears that the db already exists.  Your tests
    will run much faster.

    To force the normal database creation, define the environment variable
    ``FORCE_DB``.  It doesn't really matter what the value is, we just check to
    see if it's there.

    """
    def setup_databases(self):
        using_mysql = False
        for alias in connections:
            connection = connections[alias]
            if not os.getenv('FORCE_DB'):
                if uses_mysql(connection):
                    connection.creation.__class__ = SkipDatabaseCreation
                else:
                    warnings.warn('NOT skipping db creation for %s' %
                                  connection.settings_dict['ENGINE'])

        Command.handle = _new_handle
        return super(RadicalTestSuiteRunner, self).setup_databases()

    def teardown_databases(self, old_config):
        if os.getenv('FORCE_DB'):
            super(RadicalTestSuiteRunner, self).teardown_databases(old_config)

    def setup_test_environment(self, **kwargs):
        # If we have a settings_test.py let's roll it into our settings.
        try:
            import settings_test
            # Use setattr to update Django's proxies:
            for k in dir(settings_test):
                setattr(settings, k, getattr(settings_test, k))
        except ImportError:
            pass
        super(RadicalTestSuiteRunner, self).setup_test_environment(**kwargs)

<commit_msg>Cut test run startup time from 15 seconds (worst case) to 3.<commit_after>import os

from django.conf import settings
from django.core.management.color import no_style
from django.core.management.commands.loaddata import Command
from django.db import connections, DEFAULT_DB_ALIAS
from django.db.backends.mysql import creation as mysql

import django_nose

def uses_mysql(connection):
    return 'mysql' in connection.settings_dict['ENGINE']

_old_handle = Command.handle
def _foreign_key_ignoring_handle(self, *fixture_labels, **options):
    """Wrap the the stock loaddata to ignore foreign key checks so we can load
    circular references from fixtures.

    This is monkeypatched into place in setup_databases().

    """
    using = options.get('database', DEFAULT_DB_ALIAS)
    commit = options.get('commit', True)
    connection = connections[using]

    if uses_mysql(connection):
        cursor = connection.cursor()
        cursor.execute('SET foreign_key_checks = 0')

    _old_handle(self, *fixture_labels, **options)

    if uses_mysql(connection):
        cursor = connection.cursor()
        cursor.execute('SET foreign_key_checks = 1')

        if commit:
            connection.close()

class SkipDatabaseCreation(mysql.DatabaseCreation):
    """Database creation class that skips both creation and flushing

    The idea is to re-use the perfectly good test DB already created by an
    earlier test run, cutting the time spent before any tests run from 5-13
    (depending on your I/O luck) down to 3.

    """
    def create_test_db(self, verbosity=1, autoclobber=False):
        # Notice that the DB supports transactions. Originally, this was done
        # in the method this overrides.
        self.connection.features.confirm()
        return self._get_test_db_name()

class RadicalTestSuiteRunner(django_nose.NoseTestSuiteRunner):
    """This is a test runner that monkeypatches connection.creation to skip
    database creation if it appears that the DB already exists.  Your tests
    will run much faster.

    To force the normal database creation, define the environment variable
    ``FORCE_DB``.  It doesn't really matter what the value is, we just check to
    see if it's there.

    """
    def setup_databases(self):
        def should_create_database(connection):
            """Return whether we should recreate the given DB.

            This is true if the DB doesn't exist or if the FORCE_DB env var is
            truthy.

            """
            # TODO: Notice when the Model classes change and return True. Worst
            # case, we can generate sqlall and hash it, though it's a bit slow
            # (2 secs) and hits the DB for no good reason. Until we find a
            # faster way, I'm inclined to keep making people explicitly saying
            # FORCE_DB if they want a new DB.

            # Notice whether the DB exists, and create it if it doesn't:
            try:
                connection.cursor()
            except StandardError:  # TODO: Be more discerning but still DB
                                   # agnostic.
                return True
            return not not os.getenv('FORCE_DB')

        def sql_reset_sequences(connection):
            """Return a list of SQL statements needed to reset all sequences
            for Django tables."""
            # TODO: This is MySQL-specific--see below. It should also work with
            # SQLite but not Postgres. :-(
            tables = connection.introspection.django_table_names(
                only_existing=True)
            flush_statements = connection.ops.sql_flush(
                no_style(), tables, connection.introspection.sequence_list())

            # connection.ops.sequence_reset_sql() is not implemented for MySQL,
            # and the base class just returns []. TODO: Implement it by pulling
            # the relevant bits out of sql_flush().
            return [s for s in flush_statements if s.startswith('ALTER')]
            # Being overzealous and resetting the sequences on non-empty tables
            # like django_content_type seems to be fine in MySQL: adding a row
            # afterward does find the correct sequence number rather than
            # crashing into an existing row.

        for alias in connections:
            connection = connections[alias]
            creation = connection.creation
            test_db_name = creation._get_test_db_name()

            # Mess with the DB name so other things operate on a test DB
            # rather than the real one. This is done in create_test_db when
            # we don't monkeypatch it away with SkipDatabaseCreation.
            orig_db_name = connection.settings_dict['NAME']
            connection.settings_dict['NAME'] = test_db_name

            if not should_create_database(connection):
                print ('Reusing old database "%s". Set env var FORCE_DB=1 if '
                       'you need fresh DBs.' % test_db_name)

                # Reset auto-increment sequences. Apparently, SUMO's tests are
                # horrid and coupled to certain numbers.
                cursor = connection.cursor()
                for statement in sql_reset_sequences(connection):
                    cursor.execute(statement)
                connection.commit_unless_managed()  # which it is

                creation.__class__ = SkipDatabaseCreation
            else:
                # We're not using SkipDatabaseCreation, so put the DB name
                # back.
                connection.settings_dict['NAME'] = orig_db_name

        Command.handle = _foreign_key_ignoring_handle

        # With our class patch, does nothing but return some connection
        # objects:
        return super(RadicalTestSuiteRunner, self).setup_databases()

    def teardown_databases(self, old_config, **kwargs):
        """Leave those poor, reusable databases alone."""

    def setup_test_environment(self, **kwargs):
        # If we have a settings_test.py let's roll it into our settings.
        try:
            import settings_test
            # Use setattr to update Django's proxies:
            for k in dir(settings_test):
                setattr(settings, k, getattr(settings_test, k))
        except ImportError:
            pass
        super(RadicalTestSuiteRunner, self).setup_test_environment(**kwargs)
<|endoftext|>


<commit_before>import contextlib
import json
import os
import shutil
import sys
import tempfile

__all__ = ['MockCommand', 'assert_calls']

pkgdir = os.path.dirname(__file__)

commands_dir = None
recording_dir = None

def prepend_to_path(dir):
    os.environ['PATH'] = dir + os.pathsep + os.environ['PATH']

def remove_from_path(dir):
    path_dirs = os.environ['PATH'].split(os.pathsep)
    path_dirs.remove(dir)
    os.environ['PATH'] = os.pathsep.join(path_dirs)

_record_run = """#!{python}
import os, sys
import json

with open({recording_file!r}, 'a') as f:
    json.dump({{'env': dict(os.environ),
               'argv': sys.argv,
               'cwd': os.getcwd()}},
              f)
    f.write('\\x1e') # ASCII record separator
"""

# TODO: Overlapping calls to the same command may interleave writes.

class MockCommand(object):
    """Context manager to mock a system command.

    The mock command will be written to a directory at the front of $PATH,
    taking precedence over any existing command with the same name.

    By specifying content as a string, you can determine what running the
    command will do. The default content records each time the command is
    called and exits: you can access these records with mockcmd.get_calls().

    On Windows, the specified content will be run by the Python interpreter in
    use. On Unix, it should start with a shebang (``#!/path/to/interpreter``).
    """
    def __init__(self, name, content=None):
        global recording_dir
        self.name = name
        self.content = content

        if recording_dir is None:
            recording_dir = tempfile.mkdtemp()
        fd, self.recording_file = tempfile.mkstemp(dir=recording_dir,
                                                prefix=name, suffix='.json')
        os.close(fd)

    def _copy_exe(self):
        bitness = '32' if (sys.maxsize > 2**32) else '64'
        src = os.path.join(pkgdir, 'cli-%s.exe' % bitness)
        dst = os.path.join(commands_dir, self.name+'.exe')
        shutil.copy(src, dst)

    @property
    def _cmd_path(self):
        # Can only be used once commands_dir has been set
        p = os.path.join(commands_dir, self.name)
        if os.name == 'nt':
            p += '-script.py'
        return p

    def __enter__(self):
        global commands_dir
        if commands_dir is None:
            commands_dir = tempfile.mkdtemp()

        if os.path.isfile(self._cmd_path):
            raise EnvironmentError("Command %r already exists at %s" %
                                            (self.name, self._cmd_path))

        if commands_dir not in os.environ['PATH'].split(os.pathsep):
            prepend_to_path(commands_dir)

        if self.content is None:
            self.content = _record_run.format(python=sys.executable,
                                             recording_file=self.recording_file)

        with open(self._cmd_path, 'w') as f:
            f.write(self.content)

        if os.name == 'nt':
            self._copy_exe()
        else:
            os.chmod(self._cmd_path, 0o755) # Set executable bit

        return self

    def __exit__(self, etype, evalue, tb):
        os.remove(self._cmd_path)
        if os.name == 'nt':
            os.remove(os.path.join(commands_dir, self.name+'.exe'))
        if not os.listdir(commands_dir):
            remove_from_path(commands_dir)

    def get_calls(self):
        """Get a list of calls made to this mocked command.

        This relies on the default script content, so it will return an
        empty list if you specified a different content parameter.

        For each time the command was run, the list will contain a dictionary
        with keys argv, env and cwd.
        """
        if recording_dir is None:
            return []
        if not os.path.isfile(self.recording_file):
            return []

        with open(self.recording_file, 'r') as f:
            # 1E is ASCII record separator, last chunk is empty
            chunks = f.read().split('\x1e')[:-1]

        return [json.loads(c) for c in chunks]

@contextlib.contextmanager
def assert_calls(cmd, args=None):
    """Assert that a block of code runs the given command.

    If args is passed, also check that it was called at least once with the
    given arguments (not including the command name).

    Use as a context manager, e.g.::

        with assert_calls('git'):
            some_function_wrapping_git()

        with assert_calls('git', ['add', myfile]):
            some_other_function()
    """
    with MockCommand(cmd) as mc:
        yield

    calls = mc.get_calls()
    assert calls != [], "Command %r was not called" % cmd

    if args is not None:
        if not any(args == c['argv'][1:] for c in calls):
            msg = ["Command %r was not called with specified args (%r)" %
                            (cmd, args),
                   "It was called with these arguments: "]
            for c in calls:
                msg.append('  %r' % c['argv'][1:])
            raise AssertionError('\n'.join(msg))
<commit_msg>Separate command dir for each MockCommand<commit_after>import contextlib
import json
import os
import shutil
import sys
import tempfile

__all__ = ['MockCommand', 'assert_calls']

pkgdir = os.path.dirname(__file__)

recording_dir = None

def prepend_to_path(dir):
    os.environ['PATH'] = dir + os.pathsep + os.environ['PATH']

def remove_from_path(dir):
    path_dirs = os.environ['PATH'].split(os.pathsep)
    path_dirs.remove(dir)
    os.environ['PATH'] = os.pathsep.join(path_dirs)

_record_run = """#!{python}
import os, sys
import json

with open({recording_file!r}, 'a') as f:
    json.dump({{'env': dict(os.environ),
               'argv': sys.argv,
               'cwd': os.getcwd()}},
              f)
    f.write('\\x1e') # ASCII record separator
"""

# TODO: Overlapping calls to the same command may interleave writes.

class MockCommand(object):
    """Context manager to mock a system command.

    The mock command will be written to a directory at the front of $PATH,
    taking precedence over any existing command with the same name.

    By specifying content as a string, you can determine what running the
    command will do. The default content records each time the command is
    called and exits: you can access these records with mockcmd.get_calls().

    On Windows, the specified content will be run by the Python interpreter in
    use. On Unix, it should start with a shebang (``#!/path/to/interpreter``).
    """
    def __init__(self, name, content=None):
        global recording_dir
        self.name = name
        self.content = content

        if recording_dir is None:
            recording_dir = tempfile.mkdtemp()
        fd, self.recording_file = tempfile.mkstemp(dir=recording_dir,
                                                prefix=name, suffix='.json')
        self.command_dir = tempfile.mkdtemp()
        os.close(fd)

    def _copy_exe(self):
        bitness = '32' if (sys.maxsize > 2**32) else '64'
        src = os.path.join(pkgdir, 'cli-%s.exe' % bitness)
        dst = os.path.join(self.command_dir, self.name+'.exe')
        shutil.copy(src, dst)

    @property
    def _cmd_path(self):
        # Can only be used once commands_dir has been set
        p = os.path.join(self.command_dir, self.name)
        if os.name == 'nt':
            p += '-script.py'
        return p

    def __enter__(self):
        if os.path.isfile(self._cmd_path):
            raise EnvironmentError("Command %r already exists at %s" %
                                            (self.name, self._cmd_path))

        if self.content is None:
            self.content = _record_run.format(python=sys.executable,
                                             recording_file=self.recording_file)

        with open(self._cmd_path, 'w') as f:
            f.write(self.content)

        if os.name == 'nt':
            self._copy_exe()
        else:
            os.chmod(self._cmd_path, 0o755) # Set executable bit

        prepend_to_path(self.command_dir)

        return self

    def __exit__(self, etype, evalue, tb):
        remove_from_path(self.command_dir)
        shutil.rmtree(self.command_dir)

    def get_calls(self):
        """Get a list of calls made to this mocked command.

        This relies on the default script content, so it will return an
        empty list if you specified a different content parameter.

        For each time the command was run, the list will contain a dictionary
        with keys argv, env and cwd.
        """
        if recording_dir is None:
            return []
        if not os.path.isfile(self.recording_file):
            return []

        with open(self.recording_file, 'r') as f:
            # 1E is ASCII record separator, last chunk is empty
            chunks = f.read().split('\x1e')[:-1]

        return [json.loads(c) for c in chunks]

@contextlib.contextmanager
def assert_calls(cmd, args=None):
    """Assert that a block of code runs the given command.

    If args is passed, also check that it was called at least once with the
    given arguments (not including the command name).

    Use as a context manager, e.g.::

        with assert_calls('git'):
            some_function_wrapping_git()

        with assert_calls('git', ['add', myfile]):
            some_other_function()
    """
    with MockCommand(cmd) as mc:
        yield

    calls = mc.get_calls()
    assert calls != [], "Command %r was not called" % cmd

    if args is not None:
        if not any(args == c['argv'][1:] for c in calls):
            msg = ["Command %r was not called with specified args (%r)" %
                            (cmd, args),
                   "It was called with these arguments: "]
            for c in calls:
                msg.append('  %r' % c['argv'][1:])
            raise AssertionError('\n'.join(msg))
<|endoftext|>


<commit_before>import unittest

from mock import Mock

from hecuba.iter import Block

class MockStorageObj:
   pass

class BlockTest(unittest.TestCase):
    def static_creation_test(self):
        class res: pass

        results = res()
        results.blockid = "aaaablockid"
        results.entry_point = 'localhsot'
        results.dict_name = ['pk1']
        results.tab = "tab1"
        results.ksp = 'ksp1'
        results.tkns = [1l, 2l, 3l, 3l]
        results.storageobj_classname = 'block_tests.MockStorageObj'

        MockStorageObj.__init__ = Mock(return_value=None)
        b = Block.build_remotely(results)
        self.assertIsInstance(b.storageobj, MockStorageObj)
        MockStorageObj.__init__.assert_called_once_with(ksp=results.ksp, table=results.tab)
        self.fail('to be implemented')

    def init_creation_test(self):
        blockid = "aaaablockid"
        peer = 'localhsot'
        keynames = ['pk1']
        tablename = "tab1"
        keyspace = 'ksp1'
        tokens = [1l, 2l, 3l, 3l]
        MockStorageObj.__init__ = Mock(return_value=None)
        b = Block(blockid, peer, keynames, tablename, keyspace, tokens, 'block_tests.MockStorageObj')
        self.assertIsInstance(b.storageobj, MockStorageObj)
        MockStorageObj.__init__.assert_called_once_with(ksp=keyspace, table=tablename)
    '''

    def itering_test(self):
        """
        Block should be iterable and return in BlockIter
        :return:
        """
        self.fail('to be implemented')

    def get_and_set_item_test(self):
        self.fail('to be implemented')
    '''

    def iter_and_get_sets_test(self):
        """
        The iterator should read the same elements I can get with a __getitem__
        :return:
        """
        blockid = "aaaablockid"
        peer = 'localhsot'
        keynames = ['pk1']
        tablename = "tab1"
        keyspace = 'ksp1'
        tokens = [1l, 2l, 3l, 3l]
        MockStorageObj.__init__ = Mock(return_value=None)
        b = Block(blockid, peer, keynames, tablename, keyspace, tokens, 'block_tests.MockStorageObj')
        self.assertIsInstance(b.storageobj, MockStorageObj)
        MockStorageObj.__init__.assert_called_once_with(ksp=keyspace, table=tablename)
        b['test1'] = 123124
        self.assertEqual(123124, b['test1'])

    def getID_test(self):
        """
        Check the id is the same
        :return:
        """
        from hecuba.iter import Block
        Block.__init__ = Mock(return_value=None)
        bl = Block()
        bl.blockid = 'myuuid'
        self.assertEquals('myuuid', bl.getID())
        self.assertNotEquals('myuuid2', bl.getID())
    '''

    def iteritems_test(self):
        self.fail('to be implemented')

    def itervalues(self):
        self.fail('to be implemented')

    def iterkeys(self):
        self.fail('to be implemented')
    '''
<commit_msg>something breaks, but debugging works.. :/<commit_after>import unittest

from mock import Mock
from app.words import Words
from hecuba.iter import Block

class MockStorageObj:
   pass

class BlockTest(unittest.TestCase):
    def static_creation_test(self):
        class res: pass

        results = res()
        results.blockid = "aaaablockid"
        results.entry_point = 'localhsot'
        results.dict_name = ['pk1']
        results.tab = "tab1"
        results.ksp = 'ksp1'
        results.tkns = [1l, 2l, 3l, 3l]
        results.storageobj_classname = 'block_tests.MockStorageObj'
        old = Words.__init__
        Words.__init__ = Mock(return_value=None)
        b = Block.build_remotely(results)
        self.assertIsInstance(b.storageobj, Words)
        Words.__init__.assert_called_once_with(ksp=keyspace, table=tablename)
        Words.__init__ = old

    def init_creation_test(self):
        blockid = "aaaablockid"
        peer = 'localhsot'
        keynames = ['pk1']
        tablename = "tab1"
        keyspace = 'ksp1'
        tokens = [1l, 2l, 3l, 3l]
        old = Words.__init__
        Words.__init__ = Mock(return_value=None)
        b = Block(blockid, peer, keynames, tablename, keyspace, tokens, 'app.words.Words')
        self.assertIsInstance(b.storageobj, Words)
        Words.__init__.assert_called_once_with(ksp=keyspace, table=tablename)
        Words.__init__ = old
    '''

    def itering_test(self):
        """
        Block should be iterable and return in BlockIter
        :return:
        """
        self.fail('to be implemented')

    def get_and_set_item_test(self):
        self.fail('to be implemented')
    '''

    def iter_and_get_sets_test(self):
        """
        The iterator should read the same elements I can get with a __getitem__
        :return:
        """
        blockid = "aaaablockid"
        peer = 'localhsot'
        keynames = ['pk1']
        tablename = "tab1"
        keyspace = 'ksp1'
        tokens = [1l, 2l, 3l, 3l]
        old = Words.__init__
        Words.__init__ = Mock(return_value=None)
        b = Block(blockid, peer, keynames, tablename, keyspace, tokens, 'app.words.Words')
        self.assertIsInstance(b.storageobj, Words)
        Words.__init__.assert_called_once_with(ksp=keyspace, table=tablename)
        Words.__init__ = old
        b['test1'] = 123124
        self.assertEqual(123124, b['test1'])

    def getID_test(self):
        """
        Check the id is the same
        :return:
        """
        from hecuba.iter import Block
        Block.__init__ = Mock(return_value=None)
        bl = Block()
        bl.blockid = 'myuuid'
        self.assertEquals('myuuid', bl.getID())
        self.assertNotEquals('myuuid2', bl.getID())
    '''

    def iteritems_test(self):
        self.fail('to be implemented')

    def itervalues(self):
        self.fail('to be implemented')

    def iterkeys(self):
        self.fail('to be implemented')
    '''
<|endoftext|>


<commit_before>import unittest
import decimal
from mock import MagicMock
from bs4 import BeautifulSoup

from eactivities import clubs
from . import xml

class TestClub(unittest.TestCase):
    def setUp(self):
        def invoke_sideeffect(*args):
            return self.boring_sideeffect(*args)

        self.eactivities = MagicMock()
        self.eactivities.load_and_start.side_effect = invoke_sideeffect

        self.response = {
            '/finance/transactions/211': xml.finance_transactions_211,
            '/admin/csp/details/211': xml.admin_csp_details_211,
        }

        self.club = clubs.Club(self.eactivities, 211)

    def boring_sideeffect(self, url):
        return (
            BeautifulSoup(
                self.response[url]
            ), None
        )

    def test_init(self):
        self.assertEquals(self.club.eactivities, self.eactivities)
        self.assertEquals(self.club.id, 211)
        self.assertEquals(self.club.name, "RCC FERRET FANCIERS")

    def test_getattr(self):
        self.eactivities.ajax_handler.return_value = BeautifulSoup(
            xml.admin_csp_details_211_tab395
        ), None
        with self.assertRaises(AttributeError):
            self.club.lol
        self.eactivities.ajax_handler.assert_called_with(
            {'navigate': '395', 'ajax': 'activatetabs'}
        )
        self.assertEquals(self.club.name, "RCC FERRET FANCIERS")
        self.assertTrue(self.club.active)
        self.assertEquals(self.club.website, "http://www.union.ic.ac.uk/rcc/ffanciers")
        self.assertEquals(self.club.email, "ffanciers@imperial.ac.uk")
        self.assertEquals(self.club.current_profile_entry, [
            u'A short description.',
            u'A long description.'
        ])
        self.assertEquals(self.club.members['full_members'], 342)
        self.assertEquals(self.club.members['full_members_quota'], 120)
        self.assertEquals(self.club.members['membership_cost'], decimal.Decimal('5.00'))
        self.assertEquals(self.club.members['associate_members'], 11)

    def test_getattr_noaccess(self):
        self.response['/admin/csp/details/211'] = xml.norecords
        with self.assertRaises(AttributeError):
            self.club.lol
        with self.assertRaises(AttributeError):
            self.club.website
        with self.assertRaises(AttributeError):
            self.club.email
        with self.assertRaises(AttributeError):
            self.club.active
        with self.assertRaises(AttributeError):
            self.club.current_profile_entry

        self.assertEquals(self.club.members['full_members'], 342)
        self.assertEquals(self.club.members['full_members_quota'], 120)
        self.assertEquals(self.club.members['membership_cost'], decimal.Decimal('5.00'))
        self.assertEquals(self.club.members['associate_members'], 11)<commit_msg>Add newline to end of file<commit_after>import unittest
import decimal

from mock import MagicMock
from bs4 import BeautifulSoup

from eactivities import clubs
from . import xml

class TestClub(unittest.TestCase):
    def setUp(self):
        def invoke_sideeffect(*args):
            return self.boring_sideeffect(*args)

        self.eactivities = MagicMock()
        self.eactivities.load_and_start.side_effect = invoke_sideeffect

        self.response = {
            '/finance/transactions/211': xml.finance_transactions_211,
            '/admin/csp/details/211': xml.admin_csp_details_211,
        }

        self.club = clubs.Club(self.eactivities, 211)

    def boring_sideeffect(self, url):
        return (
            BeautifulSoup(
                self.response[url]
            ), None
        )

    def test_init(self):
        self.assertEquals(self.club.eactivities, self.eactivities)
        self.assertEquals(self.club.id, 211)
        self.assertEquals(self.club.name, "RCC FERRET FANCIERS")

    def test_getattr(self):
        self.eactivities.ajax_handler.return_value = BeautifulSoup(
            xml.admin_csp_details_211_tab395
        ), None
        with self.assertRaises(AttributeError):
            self.club.lol
        self.eactivities.ajax_handler.assert_called_with(
            {'navigate': '395', 'ajax': 'activatetabs'}
        )
        self.assertEquals(self.club.name, "RCC FERRET FANCIERS")
        self.assertTrue(self.club.active)
        self.assertEquals(self.club.website, "http://www.union.ic.ac.uk/rcc/ffanciers")
        self.assertEquals(self.club.email, "ffanciers@imperial.ac.uk")
        self.assertEquals(self.club.current_profile_entry, [
            u'A short description.',
            u'A long description.'
        ])
        self.assertEquals(self.club.members['full_members'], 342)
        self.assertEquals(self.club.members['full_members_quota'], 120)
        self.assertEquals(self.club.members['membership_cost'], decimal.Decimal('5.00'))
        self.assertEquals(self.club.members['associate_members'], 11)

    def test_getattr_noaccess(self):
        self.response['/admin/csp/details/211'] = xml.norecords
        with self.assertRaises(AttributeError):
            self.club.lol
        with self.assertRaises(AttributeError):
            self.club.website
        with self.assertRaises(AttributeError):
            self.club.email
        with self.assertRaises(AttributeError):
            self.club.active
        with self.assertRaises(AttributeError):
            self.club.current_profile_entry

        self.assertEquals(self.club.members['full_members'], 342)
        self.assertEquals(self.club.members['full_members_quota'], 120)
        self.assertEquals(self.club.members['membership_cost'], decimal.Decimal('5.00'))
        self.assertEquals(self.club.members['associate_members'], 11)
<|endoftext|>


<commit_before>#! /usr/bin/python
# -*- coding: utf-8 -*-

# import funkcí z jiného adresáře
# import sys
import os.path

path_to_script = os.path.dirname(os.path.abspath(__file__))
# sys.path.append(os.path.join(path_to_script, "../py/computation/"))
# sys.path.append(os.path.join(path_to_script, "../"))
import unittest

from nose.plugins.attrib import attr
import numpy as np
import laplacianSmoothing as ls
import step_remove_boxes_iner_faces as rmbox
import fileio
# import visualize
import startConversion as sc

class CommonTest(unittest.TestCase):
    def test_smooth_alberto(self):
        vertexes = np.array([
            [1, 3, 6],
            [2, 2, 5],
            [2, 2, 4],
            [2, 1, 6],
            [1, 3, 5]])
        faces = np.array([
            [0, 1, 2],
            [0, 1, 3],
            [1, 3, 4],
            [3, 4, 1]])
        expected_vertex = np.array(
            [1.25, 2.75, 5.5])
        nv = ls.makeSmoothing(vertexes, faces)
        self.assertAlmostEqual(0, np.sum(nv[0] - expected_vertex))

    def test_real_data_per_partes(self):
        vertexes, faces = fileio.readFile(
            os.path.join(path_to_script, "smallbb2.obj")
        )
        vertexes, inv_vertexes = rmbox.removeDoubleVertexes(vertexes)
        faces = rmbox.reindexVertexesInFaces(faces, inv_vertexes)
        faces = rmbox.removeDoubleFacesByAlberto(faces)

        # visualize.visualize(vertexes, faces)

        # rmbox.writeFile(
        #     os.path.join(path_to_script, 'test_smallbb2_cleaned.obj'),
        #     vertexes, faces)
        smooth_vertexes = ls.iterativeLaplacianSmoothing(vertexes, faces)
        expected_vertex = np.array(
            [1, 3, 5])
        self.assertAlmostEqual(
            0, np.sum(smooth_vertexes[32] - expected_vertex))
        # visualize.visualize(smooth_vertexes, faces)

    def test_real_data(self):
        V, F = fileio.readFile(
            os.path.join(path_to_script, "smallbb2.obj")
        )
        V, F = sc.makeCleaningAndSmoothing(V, F)
        # visualize.visualize(V, F)
        # expected_vertex = np.array(
        #     [1, 3, 5])
        # print V[32]
        # self.assertAlmostEqual(
        #     0, np.sum(V[32] - expected_vertex))

    def makeAll_test(self):
        from larcc import VIEW, EXPLODE, MKPOLS
        from startConversion import convert, makeCleaningAndSmoothing
        from py.computation.fileio import readFile
        # from visualize import visualize
        from py.computation.step_triangularmesh import triangulate_quads
        import shutil

        outputdir = 'tests/testpklz'
        if os.path.exists(outputdir):
            shutil.rmtree(outputdir)

        inputfile = 'tests/nrn4.pklz'
        bordersize = [4, 2, 3]
        outputdir = outputdir
        outputfile = 'test_nrn4'
        borderdir = outputdir + '/border'

        convert(inputfile, bordersize, outputdir, borderdir=borderdir)
        V, F = readFile(os.path.join(outputdir, 'stl/model-2.obj'))
        F3 = triangulate_quads(F)
        # visualize(V, F3)
        VIEW(EXPLODE(1.2, 1.2, 1.2)(MKPOLS((V, F3))))
        V, F = makeCleaningAndSmoothing(
            V, F,
            os.path.join(outputdir, outputfile))

        F3 = triangulate_quads(F)
        # visualize(V, F3)
        # VIEW(EXPLODE(1.2, 1.2, 1.2)(MKPOLS((V, F3))))

    def test_real_pklz_data(self):
        import startConversion
        import shutil
        from py.computation.step_triangularmesh import triangulate_quads
        from visualize import check_references
        # from larcc import VIEW, EXPLODE, MKPOLS
        outputdir = 'tests/tmptestpklz'
        if os.path.exists(outputdir):
            shutil.rmtree(outputdir)
        V, F = startConversion.makeAll(
            inputfile='tests/nrn4.pklz',
            bordersize=[4, 2, 3],
            outputdir=outputdir,
            outputfile='test_nrn4',
            visualization=False,
            borderdir=outputdir + '/border'
            # borderdir='tmp/border'
        )
        F3 = triangulate_quads(F)
        self.assertTrue(check_references(V, F))
        self.assertTrue(check_references(V, F3))

    @attr('actual')
    @attr('interactive')
    def test_real_pklz_data_visual(self):
        import startConversion
        import shutil
        from py.computation.step_triangularmesh import triangulate_quads
        from visualize import visualize, check_references
        # from larcc import VIEW, EXPLODE, MKPOLS
        outputdir = 'tests/tmptestpklz'
        if os.path.exists(outputdir):
            shutil.rmtree(outputdir)
        V, F = startConversion.makeAll(
            inputfile='tests/nrn4.pklz',
            bordersize=[4, 2, 3],
            outputdir=outputdir,
            outputfile='test_nrn4',
            visualization=False,
            borderdir=outputdir + '/border'
            # borderdir='tmp/border'
        )
        F3 = triangulate_quads(F)
        visualize(V, F3, explode=True)
        self.assertTrue(check_references(V, F))
        # VIEW(EXPLODE(1.2, 1.2, 1.2)(MKPOLS((V, F3))))

if __name__ == "__main__":
    unittest.main()
<commit_msg>remove visualization from non interactive tests<commit_after>#! /usr/bin/python
# -*- coding: utf-8 -*-

# import funkcí z jiného adresáře
# import sys
import os.path

path_to_script = os.path.dirname(os.path.abspath(__file__))
# sys.path.append(os.path.join(path_to_script, "../py/computation/"))
# sys.path.append(os.path.join(path_to_script, "../"))
import unittest

from nose.plugins.attrib import attr
import numpy as np
import laplacianSmoothing as ls
import step_remove_boxes_iner_faces as rmbox
import fileio
# import visualize
import startConversion as sc

class CommonTest(unittest.TestCase):
    def test_smooth_alberto(self):
        vertexes = np.array([
            [1, 3, 6],
            [2, 2, 5],
            [2, 2, 4],
            [2, 1, 6],
            [1, 3, 5]])
        faces = np.array([
            [0, 1, 2],
            [0, 1, 3],
            [1, 3, 4],
            [3, 4, 1]])
        expected_vertex = np.array(
            [1.25, 2.75, 5.5])
        nv = ls.makeSmoothing(vertexes, faces)
        self.assertAlmostEqual(0, np.sum(nv[0] - expected_vertex))

    def test_real_data_per_partes(self):
        vertexes, faces = fileio.readFile(
            os.path.join(path_to_script, "smallbb2.obj")
        )
        vertexes, inv_vertexes = rmbox.removeDoubleVertexes(vertexes)
        faces = rmbox.reindexVertexesInFaces(faces, inv_vertexes)
        faces = rmbox.removeDoubleFacesByAlberto(faces)

        # visualize.visualize(vertexes, faces)

        # rmbox.writeFile(
        #     os.path.join(path_to_script, 'test_smallbb2_cleaned.obj'),
        #     vertexes, faces)
        smooth_vertexes = ls.iterativeLaplacianSmoothing(vertexes, faces)
        expected_vertex = np.array(
            [1, 3, 5])
        self.assertAlmostEqual(
            0, np.sum(smooth_vertexes[32] - expected_vertex))
        # visualize.visualize(smooth_vertexes, faces)

    def test_real_data(self):
        V, F = fileio.readFile(
            os.path.join(path_to_script, "smallbb2.obj")
        )
        V, F = sc.makeCleaningAndSmoothing(V, F)
        # visualize.visualize(V, F)
        # expected_vertex = np.array(
        #     [1, 3, 5])
        # print V[32]
        # self.assertAlmostEqual(
        #     0, np.sum(V[32] - expected_vertex))

    def makeAll_test(self):
        # from larcc import VIEW, EXPLODE, MKPOLS
        from startConversion import convert, makeCleaningAndSmoothing
        from py.computation.fileio import readFile
        # from visualize import visualize
        from visualize import check_references

        from py.computation.step_triangularmesh import triangulate_quads
        import shutil

        outputdir = 'tests/tmptestmakeall'
        if os.path.exists(outputdir):
            shutil.rmtree(outputdir)

        inputfile = 'tests/nrn4.pklz'
        bordersize = [4, 2, 3]
        outputdir = outputdir
        outputfile = 'test_nrn4'
        borderdir = outputdir + '/border'

        convert(inputfile, bordersize, outputdir, borderdir=borderdir)
        V, F = readFile(os.path.join(outputdir, 'stl/model-2.obj'))
        F3 = triangulate_quads(F)
        # visualize(V, F3)
        # VIEW(EXPLODE(1.2, 1.2, 1.2)(MKPOLS((V, F3))))
        V, F = makeCleaningAndSmoothing(
            V, F,
            os.path.join(outputdir, outputfile))

        F3 = triangulate_quads(F)
        self.assertTrue(check_references(V, F3))
        # visualize(V, F3, explode=True)
        # VIEW(EXPLODE(1.2, 1.2, 1.2)(MKPOLS((V, F3))))

    def test_real_pklz_data(self):
        import startConversion
        import shutil
        from py.computation.step_triangularmesh import triangulate_quads
        from visualize import check_references
        # from larcc import VIEW, EXPLODE, MKPOLS
        outputdir = 'tests/tmptestpklz'
        if os.path.exists(outputdir):
            shutil.rmtree(outputdir)
        V, F = startConversion.makeAll(
            inputfile='tests/nrn4.pklz',
            bordersize=[4, 2, 3],
            outputdir=outputdir,
            outputfile='test_nrn4',
            visualization=False,
            borderdir=outputdir + '/border'
            # borderdir='tmp/border'
        )
        F3 = triangulate_quads(F)
        self.assertTrue(check_references(V, F))
        self.assertTrue(check_references(V, F3))

    @attr('actual')
    @attr('interactive')
    def test_real_pklz_data_visual(self):
        import startConversion
        import shutil
        from py.computation.step_triangularmesh import triangulate_quads
        from visualize import visualize, check_references
        # from larcc import VIEW, EXPLODE, MKPOLS
        outputdir = 'tests/tmptestpklz'
        if os.path.exists(outputdir):
            shutil.rmtree(outputdir)
        V, F = startConversion.makeAll(
            inputfile='tests/nrn4.pklz',
            bordersize=[4, 2, 3],
            outputdir=outputdir,
            outputfile='test_nrn4',
            visualization=False,
            borderdir=outputdir + '/border'
            # borderdir='tmp/border'
        )
        F3 = triangulate_quads(F)
        visualize(V, F3, explode=True)
        self.assertTrue(check_references(V, F))
        # VIEW(EXPLODE(1.2, 1.2, 1.2)(MKPOLS((V, F3))))

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


<commit_before>from invoke.vendor.six.moves.queue import Queue

from invoke.exceptions import ExceptionWrapper
from invoke.util import ExceptionHandlingThread as EHThread

from spec import Spec, ok_, eq_

# TODO: rename
class ExceptionHandlingThread_(Spec):
    class via_target:
        def setup(self):
            def worker(q):
                q.put(7)
            self.worker = worker

        def base_case(self):
            queue = Queue()
            t = EHThread(target=self.worker, args=[queue])
            t.start()
            t.join()
            eq_(queue.get(block=False), 7)
            ok_(queue.empty())

        def catches_exceptions(self):
            # Induce exception by submitting a bad queue obj
            t = EHThread(target=self.worker, args=[None])
            t.start()
            t.join()
            wrapper = t.exception()
            ok_(isinstance(wrapper, ExceptionWrapper))
            eq_(wrapper.kwargs, {'args': [None], 'target': self.worker})
            eq_(wrapper.type, AttributeError)
            ok_(isinstance(wrapper.value, AttributeError))

        def exhibits_is_dead_flag(self):
            t = EHThread(target=self.worker, args=[None])
            t.start()
            t.join()
            ok_(t.is_dead)
            t = EHThread(target=self.worker, args=[Queue()])
            t.start()
            t.join()
            ok_(not t.is_dead)

    class via_subclassing:
        def setup(self):
            class MyThread(EHThread):
                def __init__(self, *args, **kwargs):
                    self.queue = kwargs.pop('queue')
                    super(MyThread, self).__init__(*args, **kwargs)

                def _run(self):
                    self.queue.put(7)
            self.klass = MyThread

        def base_case(self):
            queue = Queue()
            t = self.klass(queue=queue)
            t.start()
            t.join()
            eq_(queue.get(block=False), 7)
            ok_(queue.empty())

        def catches_exceptions(self):
            # Induce exception by submitting a bad queue obj
            t = self.klass(queue=None)
            t.start()
            t.join()
            wrapper = t.exception()
            ok_(isinstance(wrapper, ExceptionWrapper))
            eq_(wrapper.kwargs, {})
            eq_(wrapper.type, AttributeError)
            ok_(isinstance(wrapper.value, AttributeError))

        def exhibits_is_dead_flag(self):
            t = self.klass(queue=None)
            t.start()
            t.join()
            ok_(t.is_dead)
            t = self.klass(queue=Queue())
            t.start()
            t.join()
            ok_(not t.is_dead)
<commit_msg>flake8<commit_after>from invoke.vendor.six.moves.queue import Queue

from invoke.exceptions import ExceptionWrapper
from invoke.util import ExceptionHandlingThread as EHThread

from spec import Spec, ok_, eq_

# TODO: rename
class ExceptionHandlingThread_(Spec):
    class via_target:
        def setup(self):
            def worker(q):
                q.put(7)
            self.worker = worker

        def base_case(self):
            queue = Queue()
            t = EHThread(target=self.worker, args=[queue])
            t.start()
            t.join()
            eq_(queue.get(block=False), 7)
            ok_(queue.empty())

        def catches_exceptions(self):
            # Induce exception by submitting a bad queue obj
            t = EHThread(target=self.worker, args=[None])
            t.start()
            t.join()
            wrapper = t.exception()
            ok_(isinstance(wrapper, ExceptionWrapper))
            eq_(wrapper.kwargs, {'args': [None], 'target': self.worker})
            eq_(wrapper.type, AttributeError)
            ok_(isinstance(wrapper.value, AttributeError))

        def exhibits_is_dead_flag(self):
            t = EHThread(target=self.worker, args=[None])
            t.start()
            t.join()
            ok_(t.is_dead)
            t = EHThread(target=self.worker, args=[Queue()])
            t.start()
            t.join()
            ok_(not t.is_dead)

    class via_subclassing:
        def setup(self):
            class MyThread(EHThread):
                def __init__(self, *args, **kwargs):
                    self.queue = kwargs.pop('queue')
                    super(MyThread, self).__init__(*args, **kwargs)

                def _run(self):
                    self.queue.put(7)
            self.klass = MyThread

        def base_case(self):
            queue = Queue()
            t = self.klass(queue=queue)
            t.start()
            t.join()
            eq_(queue.get(block=False), 7)
            ok_(queue.empty())

        def catches_exceptions(self):
            # Induce exception by submitting a bad queue obj
            t = self.klass(queue=None)
            t.start()
            t.join()
            wrapper = t.exception()
            ok_(isinstance(wrapper, ExceptionWrapper))
            eq_(wrapper.kwargs, {})
            eq_(wrapper.type, AttributeError)
            ok_(isinstance(wrapper.value, AttributeError))

        def exhibits_is_dead_flag(self):
            t = self.klass(queue=None)
            t.start()
            t.join()
            ok_(t.is_dead)
            t = self.klass(queue=Queue())
            t.start()
            t.join()
            ok_(not t.is_dead)
<|endoftext|>