<commit_before>#!/usr/bin/env python3
from serverpanel import create_app

from flask.ext.testing import TestCase

import platform
import unittest
import json
import tempfile

class MyTest(TestCase):

    def create_app(self):
        app = create_app('config')
        app.config['DEBUG'] = False
        return app

    def test_main(self):
        # check if route returns code 200
        response = self.client.get('/')
        self.assert_template_used('main.html')
        self.assert200(response)

    def test_api_details(self):
        # check if route returns code 200
        response = self.client.get('/api/version')
        self.assert200(response)
        data = json.loads(response.data.decode('utf-8'))
        self.assertTrue('name' in data.keys())
        self.assertTrue('version' in data.keys())

    def test_route_hostname(self):
        # check if route returns code 200
        response = self.client.get('/api/server/hostname')
        self.assert200(response)

        # check if object returned contains the desired data
        data = json.loads(response.data.decode('utf-8'))
        self.assertTrue('hostname' in data.keys())

    def test_route_os(self):
        # check if route returns code 200
        response = self.client.get('/api/server/os')
        self.assert200(response)

        # check if object returned contains the desired data
        data = json.loads(response.data.decode('utf-8'))
        self.assertTrue('os_name' in data.keys())

    def test_route_uptime(self):
        # check if route returns code 200
        response = self.client.get('/api/server/uptime')
        self.assert200(response)

        # check if object returned contains the desired data
        data = json.loads(response.data.decode('utf-8'))
        self.assertTrue('uptime' in data.keys())

    def test_route_cpu_cores(self):
        # check if route returns code 200
        response = self.client.get('/api/system/cpu/cores')
        self.assert200(response)

        # check if object returned contains the desired data
        data = json.loads(response.data.decode('utf-8'))
        self.assertTrue('logical_cores' in data.keys())
        self.assertTrue('physical_cores' in data.keys())

    def test_route_cpu_load(self):
        # check if route returns code 200
        response = self.client.get('/api/system/cpu/load')
        self.assert200(response)

        # check if object returned contains the desired data
        data = json.loads(response.data.decode('utf-8'))
        self.assertTrue(len(data) > 0)

    def test_route_memory(self):
        # check if route returns code 200
        response = self.client.get('/api/system/memory')
        self.assert200(response)

        # check if object returned contains the desired data
        data = json.loads(response.data.decode('utf-8'))
        self.assertTrue('available' in data.keys())
        self.assertTrue('free' in data.keys())
        self.assertTrue('percent' in data.keys())
        self.assertTrue('total' in data.keys())
        self.assertTrue('used' in data.keys())

    def test_route_swap(self):
        # check if route returns code 200
        response = self.client.get('/api/system/swap')
        self.assert200(response)

        # check if object returned contains the desired data
        data = json.loads(response.data.decode('utf-8'))
        self.assertTrue('sin' in data.keys())
        self.assertTrue('sout' in data.keys())
        self.assertTrue('free' in data.keys())
        self.assertTrue('percent' in data.keys())
        self.assertTrue('total' in data.keys())
        self.assertTrue('used' in data.keys())

    def test_route_disk_space(self):
        # check if route returns code 200
        response = self.client.get('/api/system/disk/space')
        self.assert200(response)

        # check if object returned contains the desired data
        data = json.loads(response.data.decode('utf-8'))
        for disk in data:
            self.assertTrue('device' in disk.keys())
            self.assertTrue('fstype' in disk.keys())
            self.assertTrue('mountpoint' in disk.keys())
            self.assertTrue('opts' in disk.keys())
            self.assertTrue('usage' in disk.keys())
            self.assertTrue('free' in disk['usage'].keys())
            self.assertTrue('percent' in disk['usage'].keys())
            self.assertTrue('total' in disk['usage'].keys())
            self.assertTrue('used' in disk['usage'].keys())

    def test_route_disk_io(self):
        # check if route returns code 200
        response = self.client.get('/api/system/disk/io')
        self.assert200(response)

        # check if object returned contains the desired data
        data = json.loads(response.data.decode('utf-8'))
        for disk in data:
            self.assertTrue('device' in disk.keys())
            self.assertTrue('io' in disk.keys())
            self.assertTrue('read_bytes' in disk['io'].keys())
            self.assertTrue('read_count' in disk['io'].keys())
            self.assertTrue('read_time' in disk['io'].keys())
            self.assertTrue('write_bytes' in disk['io'].keys())
            self.assertTrue('write_count' in disk['io'].keys())
            self.assertTrue('write_time' in disk['io'].keys())

    def test_route_network_io(self):
        # check if route returns code 200
        response = self.client.get('/api/system/network/io')
        self.assert200(response)

        # check if object returned contains the desired data
        data = json.loads(response.data.decode('utf-8'))
        for network in data:
            self.assertTrue('device' in network.keys())
            self.assertTrue('address' in network.keys())
            self.assertTrue('io' in network.keys())
            self.assertTrue('bytes_recv' in network['io'].keys())
            self.assertTrue('bytes_sent' in network['io'].keys())
            self.assertTrue('dropin' in network['io'].keys())
            self.assertTrue('dropout' in network['io'].keys())
            self.assertTrue('errin' in network['io'].keys())
            self.assertTrue('errout' in network['io'].keys())
            self.assertTrue('packets_recv' in network['io'].keys())
            self.assertTrue('packets_sent' in network['io'].keys())

    def test_route_processes(self):
        # check if route returns code 200
        response = self.client.get('/api/system/processes')
        self.assert200(response)

        # check if object returned contains the desired data
        data = json.loads(response.data.decode('utf-8'))
        for proc in data:
            self.assertTrue('pid' in proc.keys())
            self.assertTrue('name' in proc.keys())
            self.assertTrue('cpu_percentage' in proc.keys())

    def test_pihole_disabled(self):
        self.app.extensions['flask-serverinfo'].pihole_enabled = False
        response = self.client.get('/api/pihole/stats')
        self.assert200(response)

        data = json.loads(response.data.decode('utf-8'))
        self.assertTrue('enabled' in data.keys())

    @unittest.skipIf(platform.system() != 'Linux', "PiHole only available on linux")
    def test_pihole_enabled(self):
        self.app.extensions['flask-serverinfo'].pihole_enabled = True
        self.app.extensions['flask-serverinfo'].pihole_blocked_domains = tempfile.mkstemp(text="1")
        self.app.extensions['flask-serverinfo'].pihole_log = tempfile.mkstemp(text="1")

        response = self.client.get('/api/pihole/stats')
        self.assert200(response)

        data = json.loads(response.data.decode('utf-8'))
        self.assertTrue('enabled' in data.keys())
        self.assertTrue('blocked_domains' in data.keys())
        self.assertTrue('dns_queries_today' in data.keys())
        self.assertTrue('ads_blocked_today' in data.keys())
        self.assertTrue('ads_percentage_today' in data.keys())

if __name__ == '__main__':
    unittest.main()
<commit_msg>messing around with unit tests and code coverage<commit_after>#!/usr/bin/env python3
from serverpanel import create_app

from flask.ext.testing import TestCase

import platform
import unittest
import json
import tempfile

class MyTest(TestCase):

    def create_app(self):
        app = create_app('config')
        app.config['DEBUG'] = False
        return app

    def test_main(self):
        # check if route returns code 200
        response = self.client.get('/')
        self.assert_template_used('main.html')
        self.assert200(response)

    def test_api_details(self):
        # check if route returns code 200
        response = self.client.get('/api/version')
        self.assert200(response)
        data = json.loads(response.data.decode('utf-8'))
        self.assertTrue('name' in data.keys())
        self.assertTrue('version' in data.keys())

    def test_route_hostname(self):
        # check if route returns code 200
        response = self.client.get('/api/server/hostname')
        self.assert200(response)

        # check if object returned contains the desired data
        data = json.loads(response.data.decode('utf-8'))
        self.assertTrue('hostname' in data.keys())

    def test_route_os(self):
        # check if route returns code 200
        response = self.client.get('/api/server/os')
        self.assert200(response)

        # check if object returned contains the desired data
        data = json.loads(response.data.decode('utf-8'))
        self.assertTrue('os_name' in data.keys())

    def test_route_uptime(self):
        # check if route returns code 200
        response = self.client.get('/api/server/uptime')
        self.assert200(response)

        # check if object returned contains the desired data
        data = json.loads(response.data.decode('utf-8'))
        self.assertTrue('uptime' in data.keys())

    def test_route_cpu_cores(self):
        # check if route returns code 200
        response = self.client.get('/api/system/cpu/cores')
        self.assert200(response)

        # check if object returned contains the desired data
        data = json.loads(response.data.decode('utf-8'))
        self.assertTrue('logical_cores' in data.keys())
        self.assertTrue('physical_cores' in data.keys())

    def test_route_cpu_load(self):
        # check if route returns code 200
        response = self.client.get('/api/system/cpu/load')
        self.assert200(response)

        # check if object returned contains the desired data
        data = json.loads(response.data.decode('utf-8'))
        self.assertTrue(len(data) > 0)

    def test_route_memory(self):
        # check if route returns code 200
        response = self.client.get('/api/system/memory')
        self.assert200(response)

        # check if object returned contains the desired data
        data = json.loads(response.data.decode('utf-8'))
        self.assertTrue('available' in data.keys())
        self.assertTrue('free' in data.keys())
        self.assertTrue('percent' in data.keys())
        self.assertTrue('total' in data.keys())
        self.assertTrue('used' in data.keys())

    def test_route_swap(self):
        # check if route returns code 200
        response = self.client.get('/api/system/swap')
        self.assert200(response)

        # check if object returned contains the desired data
        data = json.loads(response.data.decode('utf-8'))
        self.assertTrue('sin' in data.keys())
        self.assertTrue('sout' in data.keys())
        self.assertTrue('free' in data.keys())
        self.assertTrue('percent' in data.keys())
        self.assertTrue('total' in data.keys())
        self.assertTrue('used' in data.keys())

    def test_route_disk_space(self):
        # check if route returns code 200
        response = self.client.get('/api/system/disk/space')
        self.assert200(response)

        # check if object returned contains the desired data
        data = json.loads(response.data.decode('utf-8'))
        for disk in data:
            self.assertTrue('device' in disk.keys())
            self.assertTrue('fstype' in disk.keys())
            self.assertTrue('mountpoint' in disk.keys())
            self.assertTrue('opts' in disk.keys())
            self.assertTrue('usage' in disk.keys())
            self.assertTrue('free' in disk['usage'].keys())
            self.assertTrue('percent' in disk['usage'].keys())
            self.assertTrue('total' in disk['usage'].keys())
            self.assertTrue('used' in disk['usage'].keys())

    def test_route_disk_io(self):
        # check if route returns code 200
        response = self.client.get('/api/system/disk/io')
        self.assert200(response)

        # check if object returned contains the desired data
        data = json.loads(response.data.decode('utf-8'))
        for disk in data:
            self.assertTrue('device' in disk.keys())
            self.assertTrue('io' in disk.keys())
            self.assertTrue('read_bytes' in disk['io'].keys())
            self.assertTrue('read_count' in disk['io'].keys())
            self.assertTrue('read_time' in disk['io'].keys())
            self.assertTrue('write_bytes' in disk['io'].keys())
            self.assertTrue('write_count' in disk['io'].keys())
            self.assertTrue('write_time' in disk['io'].keys())

    def test_route_network_io(self):
        # check if route returns code 200
        response = self.client.get('/api/system/network/io')
        self.assert200(response)

        # check if object returned contains the desired data
        data = json.loads(response.data.decode('utf-8'))
        for network in data:
            self.assertTrue('device' in network.keys())
            self.assertTrue('address' in network.keys())
            self.assertTrue('io' in network.keys())
            self.assertTrue('bytes_recv' in network['io'].keys())
            self.assertTrue('bytes_sent' in network['io'].keys())
            self.assertTrue('dropin' in network['io'].keys())
            self.assertTrue('dropout' in network['io'].keys())
            self.assertTrue('errin' in network['io'].keys())
            self.assertTrue('errout' in network['io'].keys())
            self.assertTrue('packets_recv' in network['io'].keys())
            self.assertTrue('packets_sent' in network['io'].keys())

    def test_route_processes(self):
        # check if route returns code 200
        response = self.client.get('/api/system/processes')
        self.assert200(response)

        # check if object returned contains the desired data
        data = json.loads(response.data.decode('utf-8'))
        for proc in data:
            self.assertTrue('pid' in proc.keys())
            self.assertTrue('name' in proc.keys())
            self.assertTrue('cpu_percentage' in proc.keys())

    def test_pihole_disabled(self):
        self.app.extensions['flask-serverinfo'].pihole_enabled = False
        response = self.client.get('/api/pihole/stats')
        self.assert200(response)

        data = json.loads(response.data.decode('utf-8'))
        self.assertTrue('enabled' in data.keys())

    @unittest.skipIf(platform.system() != 'Linux', "PiHole only available on linux")
    def test_pihole_enabled(self):
        self.app.extensions['flask-serverinfo'].pihole_enabled = True
        h, self.app.extensions['flask-serverinfo'].pihole_blocked_domains = tempfile.mkstemp(text="1")
        h, self.app.extensions['flask-serverinfo'].pihole_log = tempfile.mkstemp(text="1")

        response = self.client.get('/api/pihole/stats')
        self.assert200(response)

        data = json.loads(response.data.decode('utf-8'))
        self.assertTrue('enabled' in data.keys())
        self.assertTrue('blocked_domains' in data.keys())
        self.assertTrue('dns_queries_today' in data.keys())
        self.assertTrue('ads_blocked_today' in data.keys())
        self.assertTrue('ads_percentage_today' in data.keys())

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


<commit_before>import unittest

import replace

class ReplaceTestCase(unittest.TestCase):

    def test_alpha_numeric(self):
        text = 'abc123'
        output_text = replace.alpha_num(text)
        self.assertEqual(text, output_text)

        text = 'abc 123 **'
        output_text = replace.alpha_num(text)
        self.assertNotEqual(text, output_text)<commit_msg>Increasing test coverage<commit_after>import unittest

import replace

class ReplaceTestCase(unittest.TestCase):

    def test_alpha_numeric(self):
        text = 'abc123'
        expected_text = 'abc123'
        output_text = replace.alpha_num(text)
        self.assertEqual(expected_text, output_text)

        text = 'abc 123 ***'
        expected_text = 'abc123'
        output_text = replace.alpha_num(text)
        self.assertEqual(expected_text, output_text)

        text = '***'
        expected_text = ''
        output_text = replace.alpha_num(text)
        self.assertEqual(expected_text, output_text)

    def test_slugify(self):
        text = 'foo-bar-buzz'
        expected_text = 'foo-bar-buzz'
        output_text = replace.slugify(text)
        self.assertEqual(expected_text, output_text)

        text = 'foo bar buzz !*('
        expected_text = 'foo-bar-buzz'
        output_text = replace.slugify(text)
        self.assertEqual(expected_text, output_text)

        text = ' '
        expected_text = ''
        output_text = replace.slugify(text)
        self.assertEqual(expected_text, output_text)

    def test_wrap(self):
        text = 'foo'
        expected_text = 'foo'
        output_text = replace.wrap(text, '', '')
        self.assertEqual(expected_text, output_text)

    def test_classify(self):
        text = 'foo bar'
        expected_text = 'FooBar'
        output_text = replace.classify(text)
        self.assertEqual(expected_text, output_text)

    def test_title(self):
        text = 'i love biscuits'
        expected_text = 'I Love Biscuits'
        output_text = replace.title(text)
        self.assertEqual(expected_text, output_text)

<|endoftext|>


<commit_before>from django.test import TestCase
from auth.backends import CrowdBackend

class TestCrowdBackend(TestCase):
    pass

<commit_msg>lots o' tests<commit_after>import json
import logging
import requests
from django.contrib.auth.models import User
from django.test import TestCase
from mock import patch
from auth.backends import CrowdBackend
from testfixtures import LogCapture

class TestCrowdBackend(TestCase):
    """
    Testing operation for normal case.
    """

    def setUp(self):
        self.config = CrowdBackend.config

        # a sample 'good' response from Crowd
        # though it is missing a 'last-name' field
        self.good = {'active': True,
                     'attributes': {'attributes': [],
                     'link': {'href': 'snipple', 'rel': 'self'}},
                     'display-name': 'Kraken McKraken',
                     'email': 'kraken.mckraken@example.com',
                     'expand': 'attributes',
                     'first-name': 'Kraken',
                     'link': {'href': 'nozzle', 'rel': 'self'},
                     'name': 'kraken.mckraken',
                     'password': {'link': {'href': 'gobble', 'rel': 't'}}}

    def test_config(self):

        self.assertEqual('foo', self.config.AppName)
        self.assertEqual('bar', self.config.AppPassword)
        self.assertEqual('baz', self.config.URL)

        with self.assertRaises(AttributeError):
            self.config.FOO

    def test_authenticate(self):
        with patch.object(requests, 'post') as mock_method:
            mock_method.return_value.content = json.dumps(self.good)
            mock_method.return_value.status_code = 200
            with LogCapture(level=logging.INFO) as log_test:
                user = CrowdBackend().authenticate('kraken.mckraken', 'quux')
                self.assertIn('<kraken.mckraken> authenticated via Crowd', str(
                    log_test))

            self.assertEqual('kraken.mckraken', user.username)
            self.assertIsInstance(user, User)
            self.assertEqual('kraken.mckraken@example.com', user.email)

class TestCrowdErrors(TestCase):
    """
    Check error conditions: settings is misconfigured, authentication fails,
    an unparseable response is received from Crowd.  Also check that logs
    are generated.
    """

    def setUp(self):
        # sample error response
        self.bad = {'message': 'zizzle'}
        # non-parseable response (not JSON)
        self.really_bad = 'fibnozzle'

    def test_crowd_user(self):
        """
        Misconfigured settings.
        """

        with patch.dict('settings.CROWD_AUTH', {'AppName': 'fubar'},
                        clear=True):
            with LogCapture(level=logging.ERROR) as log_test:
                return_value = CrowdBackend().crowd_user()
                self.assertIn(
                    '\'AppPassword\' not found in settings.CROWD_AUTH',
                    str(log_test))
            self.assertIsNone(return_value)

    def test_bad_crowd_response(self):
        """
        Authentication fails.
        """
        with patch.object(requests, 'post') as mock_method:
            mock_method.return_value.content = json.dumps(self.bad)
            mock_method.return_value.status_code = 400
            with LogCapture(level=logging.INFO) as log_test:
                user = CrowdBackend().authenticate('kraken.mckraken', 'quux')
                self.assertIn(
                    'Crowd authentication for <kraken.mckraken> failed',
                    str(log_test))

            self.assertIsNone(user)

    def test_unparseable_response(self):
        """
        Non-JSON received from Crowd.
        """
        with patch.object(requests, 'post') as mock_method:
            mock_method.return_value.content = self.really_bad
            mock_method.return_value.status_code = 400
            with LogCapture(level=logging.INFO) as log_test:
                user = CrowdBackend().authenticate('kraken.mckraken', 'quux')
                self.assertIn('Error parsing server response', str(log_test))

            self.assertIsNone(user)

    def test_dumb_thing_just_to_get_100_percent_coverage(self):
        """
        'get_user' is boilerplate Django authentication backend code, but I
        wanted 100% coverage.  ;-)
        """
        self.assertIsNone(CrowdBackend().get_user(42))
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
import unittest
from hanspell import spell_checker
from hanspell.constants import CheckResult

class SpellCheckerTests(unittest.TestCase):
    def setUp(self):
        pass

    def test_basic_check(self):
        result = spell_checker.check(u'안녕 하세요. 저는 한국인 입니다. 이문장은 한글로 작성됬습니다.')

        assert result.errors == 4
        assert result.checked == u'안녕하세요. 저는 한국인입니다. 이 문장은 한글로 작성됐습니다.'

    def test_words(self):
        result = spell_checker.check(u'한아이가 장난깜을 갖고놀고있다. 그만하게 할가?')
        assert result.errors == 4

        items = result.words
        assert items[u'한'] == CheckResult.WRONG_SPACING
        assert items[u'아이가'] == CheckResult.WRONG_SPACING
        assert items[u'장난감을'] == CheckResult.AMBIGUOUS
        assert items[u'갖고'] == CheckResult.WRONG_SPACING
        assert items[u'놀고'] == CheckResult.WRONG_SPACING
        assert items[u'있다.'] == CheckResult.WRONG_SPACING
        assert items[u'그만하게'] == CheckResult.PASSED
        assert items[u'할까?'] == CheckResult.WRONG_SPELLING

    def test_list(self):
        results = spell_checker.check([u'안녕 하세요.', u'저는 한국인 입니다.'])
        assert results[0].checked == u'안녕하세요.'
        assert results[1].checked == u'저는 한국인입니다.'

if __name__ == '__main__':
    unittest.main()
<commit_msg>Add test code for long paragraph<commit_after># -*- coding: utf-8 -*-
import unittest
from hanspell import spell_checker
from hanspell.constants import CheckResult
from textwrap import dedent as trim

class SpellCheckerTests(unittest.TestCase):
    def setUp(self):
        pass

    def test_basic_check(self):
        result = spell_checker.check(u'안녕 하세요. 저는 한국인 입니다. 이문장은 한글로 작성됬습니다.')

        assert result.errors == 4
        assert result.checked == u'안녕하세요. 저는 한국인입니다. 이 문장은 한글로 작성됐습니다.'

    def test_words(self):
        result = spell_checker.check(u'한아이가 장난깜을 갖고놀고있다. 그만하게 할가?')
        assert result.errors == 4

        items = result.words
        assert items[u'한'] == CheckResult.WRONG_SPACING
        assert items[u'아이가'] == CheckResult.WRONG_SPACING
        assert items[u'장난감을'] == CheckResult.AMBIGUOUS
        assert items[u'갖고'] == CheckResult.WRONG_SPACING
        assert items[u'놀고'] == CheckResult.WRONG_SPACING
        assert items[u'있다.'] == CheckResult.WRONG_SPACING
        assert items[u'그만하게'] == CheckResult.PASSED
        assert items[u'할까?'] == CheckResult.WRONG_SPELLING

    def test_list(self):
        results = spell_checker.check([u'안녕 하세요.', u'저는 한국인 입니다.'])
        assert results[0].checked == u'안녕하세요.'
        assert results[1].checked == u'저는 한국인입니다.'

    def test_long_paragraph(self):
        paragraph = trim("""
        ubit.info(유빗인포)는 코나미 리듬게임, 유비트의 플레이 데이터 관리 및 열람 서비스입니다. 등록 후에 자신과 친구의 기록을 p.eagate.573.jp에 접속할 필요 없이 본 웹 사이트에서 바로 확인할 수 있습니다.
        등록 후에는 "https://ubit.info/별칭"으로 자신의 개인 페이지가 생성되며 이 주소(별칭)를 아는 사람만 접속할 수 있습니다. 다른 친구에게 기록을 보여주고 싶다면 본인의 인포 주소를 알려주면 됩니다.
        이 사이트는 최신 브라우저 환경만을 제대로 지원합니다. 만약 크롬, 파이어폭스 등의 최신 브라우저 안정버전(stable)을 사용하고 있는데도 페이지 레이아웃이 깨지는 경우 사이트 관리자에게 문의해주세요.
        등록 과정은 간단합니다. 상단 메뉴에서 등록을 클릭한 후 양식에 맞게 입력하시면 자동으로 공개설정이 완료됨과 동시에 유빗인포 계정이 생성됩니다.
        """)

        result = spell_checker.check(paragraph)

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


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

import locale
import os
import shutil
import sys
import tempfile

try:
    import unittest2 as unittest
except ImportError:
    import unittest

import bootstrapper

DIRNAME = os.path.abspath(os.path.dirname(__file__))

class TestBootstrapper(unittest.TestCase):

    requirements = 'test-requirements.txt'
    venv = 'test-env'

    def tearDown(self):
        if hasattr(self, 'old_stdout'):
            sys.stdout = self.old_stdout

        if hasattr(self, 'old_stderr'):
            sys.stderr = self.old_stderr

        self.delete(self.requirements, self.venv)

    def delete(self, *files):
        for item in files:
            if os.path.isfile(item):
                os.unlink(item)
            elif os.path.isdir(item):
                shutil.rmtree(item)

    def init_requirements(self, *lines):
        with open(self.requirements, 'w+') as handler:
            handler.write('\n'.join(lines))
        self.assertTrue(os.path.isfile(self.requirements))

    def message(self, out, err, echo=False):
        output = '\n'.join(('[STDOUT]', out, '', '[STDERR]', err))
        if echo:
            print(output)
        else:
            return output

    def run_cmd(self, cmd):
        encoding = locale.getdefaultlocale()[1]
        tout, terr = tempfile.TemporaryFile(), tempfile.TemporaryFile()

        self.old_stdout, self.old_stderr = sys.stdout, sys.stderr
        sys.stdout, sys.stderr = tout, terr

        if cmd == 'bootstrap':
            bootstrapper.main('-e', self.venv, '-r', self.requirements)
        elif cmd.startswith('pip '):
            bootstrapper.pip_cmd(self.venv, cmd[4:], echo=True)
        else:
            assert False, 'Command {0!r} is not supported!'.format(cmd)

        tout.seek(0)
        out = tout.read().decode(encoding)

        terr.seek(0)
        err = terr.read().decode(encoding)

        return (out, err)

    def test_application_bootstrap(self):
        self.assertFalse(os.path.isdir(self.venv))
        out, err = self.run_cmd('bootstrap')
        self.assertTrue(os.path.isdir(self.venv))

        out, _ = self.run_cmd('pip freeze')
        self.assertIn('playpauseandstop/bootstrapper.git@', out)
        self.assertIn('#egg=bootstrapper-', out)

    def test_project_bootstrap(self):
        self.assertFalse(os.path.isdir(self.venv))
        self.init_requirements('ordereddict==1.1')
        out, err = self.run_cmd('bootstrap')
        self.assertTrue(os.path.isdir(self.venv), self.message(out, err))

        out, _ = self.run_cmd('pip freeze')
        self.assertIn('ordereddict==1.1', out)

if __name__ == '__main__':
    unittest.main()
<commit_msg>One more attempt to fix tests on Python 3.<commit_after>#!/usr/bin/env python

import os
import shutil
import sys
import tempfile

try:
    import unittest2 as unittest
except ImportError:
    import unittest

import bootstrapper

DIRNAME = os.path.abspath(os.path.dirname(__file__))

class TestBootstrapper(unittest.TestCase):

    requirements = 'test-requirements.txt'
    venv = 'test-env'

    def tearDown(self):
        if hasattr(self, 'old_stdout'):
            sys.stdout = self.old_stdout

        if hasattr(self, 'old_stderr'):
            sys.stderr = self.old_stderr

        self.delete(self.requirements, self.venv)

    def delete(self, *files):
        for item in files:
            if os.path.isfile(item):
                os.unlink(item)
            elif os.path.isdir(item):
                shutil.rmtree(item)

    def init_requirements(self, *lines):
        with open(self.requirements, 'w+') as handler:
            handler.write('\n'.join(lines))
        self.assertTrue(os.path.isfile(self.requirements))

    def message(self, out, err, echo=False):
        output = '\n'.join(('[STDOUT]', out, '', '[STDERR]', err))
        if echo:
            print(output)
        else:
            return output

    def run_cmd(self, cmd):
        kwargs = {'encoding': 'utf-8'} if bootstrapper.IS_PY3 else {}
        tout = tempfile.TemporaryFile(**kwargs)
        terr = tempfile.TemporaryFile(**kwargs)

        self.old_stdout, self.old_stderr = sys.stdout, sys.stderr
        sys.stdout, sys.stderr = tout, terr

        if cmd == 'bootstrap':
            bootstrapper.main('-e', self.venv, '-r', self.requirements)
        elif cmd.startswith('pip '):
            bootstrapper.pip_cmd(self.venv, cmd[4:], echo=True)
        else:
            assert False, 'Command {0!r} is not supported!'.format(cmd)

        tout.seek(0)
        terr.seek(0)

        return (tout.read(), terr.read())

    def test_application_bootstrap(self):
        self.assertFalse(os.path.isdir(self.venv))
        out, err = self.run_cmd('bootstrap')
        self.assertTrue(os.path.isdir(self.venv))

        out, _ = self.run_cmd('pip freeze')
        self.assertIn('playpauseandstop/bootstrapper.git@', out)
        self.assertIn('#egg=bootstrapper-', out)

    def test_project_bootstrap(self):
        self.assertFalse(os.path.isdir(self.venv))
        self.init_requirements('ordereddict==1.1')
        out, err = self.run_cmd('bootstrap')
        self.assertTrue(os.path.isdir(self.venv), self.message(out, err))

        out, _ = self.run_cmd('pip freeze')
        self.assertIn('ordereddict==1.1', out)

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


<commit_before>import muffin
import pytest

@pytest.fixture(scope='session')
def app(loop):
    return muffin.Application(
        'elasticsearch_app', loop=loop,
        PLUGINS=('muffin_elasticsearch',)
    )

def test_plugin_register(app):
    assert 'elasticsearch' in app.ps
    assert app.ps.elasticsearch.conn

@pytest.mark.async
def test_elasticsearch_create_get(app):
    body = {'str': 'foo', 'int': 1}
    result = yield from app.ps.elasticsearch.create(
        index='test',
        doc_type='test',
        id=42,
        body=body
    )

    assert result['ok'] is True

    result = yield from app.ps.elastisearch.get(
        index='test',
        doc_type='test',
        id=42
    )
    assert result['_source'] == body
<commit_msg>improve asserts in tests<commit_after>import muffin
import pytest

@pytest.fixture(scope='session')
def app(loop):
    return muffin.Application(
        'elasticsearch_app', loop=loop,
        PLUGINS=('muffin_elasticsearch',)
    )

def test_plugin_register(app):
    assert 'elasticsearch' in app.ps
    assert app.ps.elasticsearch.conn

@pytest.mark.async
def test_elasticsearch_create_get(app):
    body = {'str': 'foo', 'int': 1}
    result = yield from app.ps.elasticsearch.create(
        index='test',
        doc_type='test',
        id=42,
        body=body
    )

    assert 'created' in result, result.keys()
    assert result['created'] is True, result['created']

    result = yield from app.ps.elasticsearch.get(
        index='test',
        doc_type='test',
        id=42
    )
    assert '_source' in result, result.keys()
    assert result['_source'] == body, result
<|endoftext|>


<commit_before>from json import loads
from os.path import basename
from tempfile import NamedTemporaryFile
from threading import Thread

from nose.tools import eq_, raises
from six import u
from six.moves import BaseHTTPServer

from pyhectane import Connection

class SimpleHttpHandler(BaseHTTPServer.BaseHTTPRequestHandler):
    """
    Simple handler that responds to all GET and POST requests with an empty
    JSON response. Logging is also disabled.
    """

    def _respond(self):
        self.send_response(200)
        self.send_header('Content-length', '2')
        self.send_header('Content-type', 'text/html')
        self.end_headers()
        self.wfile.write(b'{}')

    def do_GET(self):
        self._respond()

    def do_POST(self):
        self._respond()
        self.data = self.rfile.read()

    def log_message(self, format, *args):
        pass

class SimpleHttpServer(BaseHTTPServer.HTTPServer):
    """
    Extremely simple HTTP server that captures requests and stores them for
    later retrieval and examination.
    """

    def process_request(self, request, client_address):
        """
        Store the request before processing it.
        """
        self.request = self.RequestHandlerClass(request, client_address, self)

class Request:
    """
    Allows a single request to be processed by using Python's "with" statement.
    A server is run in a separate thread for processing requests. The server
    captures the request information and makes its attributes available.
    """

    def __init__(self):
        self._server = SimpleHttpServer(('127.0.0.1', 0), SimpleHttpHandler)
        self._server.timeout = 2
        self._thread = Thread(target=self._server.serve_forever, args=[0.1])
        self.port = self._server.server_address[1]

    def __getattr__(self, name):
        return getattr(self._server.request, name)

    def __enter__(self):
        self._server.request = None
        self._thread.start()

    def __exit__(self, type, value, traceback):
        self._server.shutdown()
        self._thread.join()

class TestConnection:
    """
    Run simple tests against Connection's methods.
    """

    _FROM = 'from@example.com'
    _TO = 'to@example.com'
    _SUBJECT = 'Test'
    _DATA = u('0123456789')

    def setUp(self):
        self._r = Request()
        self._c = Connection(port=self._r.port)

    def test_raw(self):
        with self._r:
            self._c.raw(self._FROM, [self._TO], self._DATA)
        eq_(self._r.command, 'POST')
        eq_(self._r.path, '/v1/raw')

    @raises(TypeError)
    def test_raw_bad_to(self):
        with self._r:
            self._c.raw(self._FROM, self._TO, self._DATA)

    def test_send(self):
        with self._r:
            self._c.send(self._FROM, [self._TO], self._SUBJECT, self._DATA)
        eq_(self._r.command, 'POST')
        eq_(self._r.path, '/v1/send')

    @raises(TypeError)
    def test_send_bad_to(self):
        with self._r:
            self._c.send(self._FROM, self._TO, self._SUBJECT, self._DATA)

    @raises(ValueError)
    def test_send_empty_content(self):
        with self._r:
            self._c.send(self._FROM, [self._TO], self._SUBJECT)

    def test_send_attachment_filename(self):
        with NamedTemporaryFile() as f:
            f.write(self._DATA.encode())
            with self._r:
                self._c.send(self._FROM, [self._TO], self._SUBJECT, self._DATA,
                             attachments=[f.name])
            data = loads(self._r.data.decode())
            eq_(len(data['attachments']), 1)
            eq_(data['attachments'][0]['filename'], basename(f.name))
            eq_(data['attachments'][0]['encoded'], True)

    def test_status(self):
        with self._r:
            self._c.status()
        eq_(self._r.command, 'GET')
        eq_(self._r.path, '/v1/status')

    def test_version(self):
        with self._r:
            self._c.version()
        eq_(self._r.command, 'GET')
        eq_(self._r.path, '/v1/version')
<commit_msg>Made a specific distinction between binary and text sample data.<commit_after>from json import loads
from os.path import basename
from tempfile import NamedTemporaryFile
from threading import Thread

from nose.tools import eq_, raises
from six import b, u
from six.moves import BaseHTTPServer

from pyhectane import Connection

class SimpleHttpHandler(BaseHTTPServer.BaseHTTPRequestHandler):
    """
    Simple handler that responds to all GET and POST requests with an empty
    JSON response. Logging is also disabled.
    """

    def _respond(self):
        self.send_response(200)
        self.send_header('Content-length', '2')
        self.send_header('Content-type', 'text/html')
        self.end_headers()
        self.wfile.write(b'{}')

    def do_GET(self):
        self._respond()

    def do_POST(self):
        self._respond()
        self.data = self.rfile.read()

    def log_message(self, format, *args):
        pass

class SimpleHttpServer(BaseHTTPServer.HTTPServer):
    """
    Extremely simple HTTP server that captures requests and stores them for
    later retrieval and examination.
    """

    def process_request(self, request, client_address):
        """
        Store the request before processing it.
        """
        self.request = self.RequestHandlerClass(request, client_address, self)

class Request:
    """
    Allows a single request to be processed by using Python's "with" statement.
    A server is run in a separate thread for processing requests. The server
    captures the request information and makes its attributes available.
    """

    def __init__(self):
        self._server = SimpleHttpServer(('127.0.0.1', 0), SimpleHttpHandler)
        self._server.timeout = 2
        self._thread = Thread(target=self._server.serve_forever, args=[0.1])
        self.port = self._server.server_address[1]

    def __getattr__(self, name):
        return getattr(self._server.request, name)

    def __enter__(self):
        self._server.request = None
        self._thread.start()

    def __exit__(self, type, value, traceback):
        self._server.shutdown()
        self._thread.join()

class TestConnection:
    """
    Run simple tests against Connection's methods.
    """

    _FROM = 'from@example.com'
    _TO = 'to@example.com'
    _SUBJECT = 'Test'
    _BDATA = b('\x00\x01\x02')
    _SDATA = u('0123456789')

    def setUp(self):
        self._r = Request()
        self._c = Connection(port=self._r.port)

    def test_raw(self):
        with self._r:
            self._c.raw(self._FROM, [self._TO], self._SDATA)
        data = loads(self._r.data.decode())
        eq_(self._r.command, 'POST')
        eq_(self._r.path, '/v1/raw')
        eq_(data['body'], self._SDATA)

    @raises(TypeError)
    def test_raw_bad_to(self):
        with self._r:
            self._c.raw(self._FROM, self._TO, self._SDATA)

    def test_send(self):
        with self._r:
            self._c.send(self._FROM, [self._TO], self._SUBJECT, self._SDATA)
        eq_(self._r.command, 'POST')
        eq_(self._r.path, '/v1/send')

    @raises(TypeError)
    def test_send_bad_to(self):
        with self._r:
            self._c.send(self._FROM, self._TO, self._SUBJECT, self._SDATA)

    @raises(ValueError)
    def test_send_empty_content(self):
        with self._r:
            self._c.send(self._FROM, [self._TO], self._SUBJECT)

    def test_send_attachment_filename(self):
        with NamedTemporaryFile() as f:
            f.write(self._DATA.encode())
            with self._r:
                self._c.send(self._FROM, [self._TO], self._SUBJECT, self._DATA,
                             attachments=[f.name])
            data = loads(self._r.data.decode())
            eq_(len(data['attachments']), 1)
            eq_(data['attachments'][0]['filename'], basename(f.name))
            eq_(data['attachments'][0]['encoded'], True)

    def test_status(self):
        with self._r:
            self._c.status()
        eq_(self._r.command, 'GET')
        eq_(self._r.path, '/v1/status')

    def test_version(self):
        with self._r:
            self._c.version()
        eq_(self._r.command, 'GET')
        eq_(self._r.path, '/v1/version')
<|endoftext|>


<commit_before>import re
import sys
import unittest

from pysqlite2 import dbapi2 as sqlite3
from vtfunc import TableFunction

class Series(TableFunction):
    columns = ['value']
    params = ['start', 'stop', 'step']
    name = 'series'

    def initialize(self, start=0, stop=None, step=1):
        self.start = start
        self.stop = stop or float('inf')
        self.step = step
        self.curr = self.start

    def iterate(self, idx):
        if self.curr > self.stop:
            raise StopIteration

        ret = self.curr
        self.curr += self.step
        return (ret,)

class RegexSearch(TableFunction):
    columns = ['match']
    params = ['regex', 'search_string']
    name = 'regex_search'

    def initialize(self, regex=None, search_string=None):
        if regex and search_string:
            self._iter = re.finditer(regex, search_string)
        else:
            self._iter = None

    def iterate(self, idx):
        # We do not need `idx`, so just ignore it.
        if self._iter is None:
            raise StopIteration
        else:
            return (next(self._iter).group(0),)

class Split(TableFunction):
    params = ['data']
    columns = ['part']
    name = 'str_split'

    def initialize(self, data=None):
        self._parts = data.split()
        self._idx = 0

    def iterate(self, idx):
        if self._idx < len(self._parts):
            result = (self._parts[self._idx],)
            self._idx += 1
            return result
        raise StopIteration

class TestTableFunction(unittest.TestCase):
    def setUp(self):
        self.conn = sqlite3.connect(':memory:')

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

    def test_split(self):
        Split.register(self.conn)
        curs = self.conn.execute('select part from str_split(?) order by part '
                                 'limit 3', ('well hello huey and zaizee',))
        self.assertEqual([row for row, in curs.fetchall()],
                         ['and', 'hello', 'huey'])

    def test_split_tbl(self):
        Split.register(self.conn)
        self.conn.execute('create table post (content TEXT);')
        self.conn.execute('insert into post (content) values (?), (?), (?)',
                          ('huey secret post',
                           'mickey message',
                           'zaizee diary'))
        curs = self.conn.execute('SELECT * FROM post, str_split(post.content)')
        results = curs.fetchall()
        self.assertEqual(results, [
            ('huey secret post', 'huey'),
            ('huey secret post', 'secret'),
            ('huey secret post', 'post'),
            ('mickey message', 'mickey'),
            ('mickey message', 'message'),
            ('zaizee diary', 'zaizee'),
            ('zaizee diary', 'diary'),
        ])

    def test_series(self):
        Series.register(self.conn)

        def assertSeries(params, values, extra_sql=''):
            param_sql = ', '.join('?' * len(params))
            sql = 'SELECT * FROM series(%s)' % param_sql
            if extra_sql:
                sql = ' '.join((sql, extra_sql))
            curs = self.conn.execute(sql, params)
            self.assertEqual([row for row, in curs.fetchall()], values)

        assertSeries((0, 10, 2), [0, 2, 4, 6, 8, 10])
        assertSeries((5, None, 20), [5, 25, 45, 65, 85], 'LIMIT 5')
        assertSeries((4, 0, -1), [4, 3, 2], 'LIMIT 3')
        assertSeries((3, 5, 3), [3])
        assertSeries((3, 3, 1), [3])

    def test_series_tbl(self):
        Series.register(self.conn)
        self.conn.execute('CREATE TABLE nums (id INTEGER PRIMARY KEY)')
        self.conn.execute('INSERT INTO nums DEFAULT VALUES;')
        self.conn.execute('INSERT INTO nums DEFAULT VALUES;')
        curs = self.conn.execute(
            'SELECT * FROM nums, series(nums.id, nums.id + 2)')
        results = curs.fetchall()
        self.assertEqual(results, [
            (1, 1), (1, 2), (1, 3),
            (2, 2), (2, 3), (2, 4)])

        curs = self.conn.execute(
            'SELECT * FROM nums, series(nums.id) LIMIT 3')
        results = curs.fetchall()
        self.assertEqual(results, [(1, 1), (1, 2), (1, 3)])

    def test_regex(self):
        RegexSearch.register(self.conn)

        def assertResults(regex, search_string, values):
            sql = 'SELECT * FROM regex_search(?, ?)'
            curs = self.conn.execute(sql, (regex, search_string))
            self.assertEqual([row for row, in curs.fetchall()], values)

        assertResults(
            '[0-9]+',
            'foo 123 45 bar 678 nuggie 9.0',
            ['123', '45', '678', '9', '0'])
        assertResults(
            '[\w]+@[\w]+\.[\w]{2,3}',
            ('Dear charlie@example.com, this is nug@baz.com. I am writing on '
             'behalf of zaizee@foo.io. He dislikes your blog.'),
            ['charlie@example.com', 'nug@baz.com', 'zaizee@foo.io'])
        assertResults(
            '[a-z]+',
            '123.pDDFeewXee',
            ['p', 'eew', 'ee'])
        assertResults(
            '[0-9]+',
            'hello',
            [])

    def test_regex_tbl(self):
        messages = (
            'hello foo@example.fap, this is nuggie@example.fap. How are you?',
            'baz@example.com wishes to let charlie@crappyblog.com know that '
            'huey@example.com hates his blog',
            'testing no emails.',
            '')
        RegexSearch.register(self.conn)

        self.conn.execute('create table posts (id integer primary key, msg)')
        self.conn.execute('insert into posts (msg) values (?), (?), (?), (?)',
                          messages)
        cur = self.conn.execute('select posts.id, regex_search.rowid, regex_search.match '
                                'FROM posts, regex_search(?, posts.msg)',
                                ('[\w]+@[\w]+\.\w{2,3}',))
        results = cur.fetchall()
        self.assertEqual(results, [
            (1, 1, 'foo@example.fap'),
            (1, 2, 'nuggie@example.fap'),
            (2, 3, 'baz@example.com'),
            (2, 4, 'charlie@crappyblog.com'),
            (2, 5, 'huey@example.com'),
        ])

if __name__ == '__main__':
    unittest.main(argv=sys.argv)
<commit_msg>Don't use pysqlite<commit_after>import re
import sys
import unittest

import sqlite3
from vtfunc import TableFunction

class Series(TableFunction):
    columns = ['value']
    params = ['start', 'stop', 'step']
    name = 'series'

    def initialize(self, start=0, stop=None, step=1):
        self.start = start
        self.stop = stop or float('inf')
        self.step = step
        self.curr = self.start

    def iterate(self, idx):
        if self.curr > self.stop:
            raise StopIteration

        ret = self.curr
        self.curr += self.step
        return (ret,)

class RegexSearch(TableFunction):
    columns = ['match']
    params = ['regex', 'search_string']
    name = 'regex_search'

    def initialize(self, regex=None, search_string=None):
        if regex and search_string:
            self._iter = re.finditer(regex, search_string)
        else:
            self._iter = None

    def iterate(self, idx):
        # We do not need `idx`, so just ignore it.
        if self._iter is None:
            raise StopIteration
        else:
            return (next(self._iter).group(0),)

class Split(TableFunction):
    params = ['data']
    columns = ['part']
    name = 'str_split'

    def initialize(self, data=None):
        self._parts = data.split()
        self._idx = 0

    def iterate(self, idx):
        if self._idx < len(self._parts):
            result = (self._parts[self._idx],)
            self._idx += 1
            return result
        raise StopIteration

class TestTableFunction(unittest.TestCase):
    def setUp(self):
        self.conn = sqlite3.connect(':memory:')

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

    def test_split(self):
        Split.register(self.conn)
        curs = self.conn.execute('select part from str_split(?) order by part '
                                 'limit 3', ('well hello huey and zaizee',))
        self.assertEqual([row for row, in curs.fetchall()],
                         ['and', 'hello', 'huey'])

    def test_split_tbl(self):
        Split.register(self.conn)
        self.conn.execute('create table post (content TEXT);')
        self.conn.execute('insert into post (content) values (?), (?), (?)',
                          ('huey secret post',
                           'mickey message',
                           'zaizee diary'))
        curs = self.conn.execute('SELECT * FROM post, str_split(post.content)')
        results = curs.fetchall()
        self.assertEqual(results, [
            ('huey secret post', 'huey'),
            ('huey secret post', 'secret'),
            ('huey secret post', 'post'),
            ('mickey message', 'mickey'),
            ('mickey message', 'message'),
            ('zaizee diary', 'zaizee'),
            ('zaizee diary', 'diary'),
        ])

    def test_series(self):
        Series.register(self.conn)

        def assertSeries(params, values, extra_sql=''):
            param_sql = ', '.join('?' * len(params))
            sql = 'SELECT * FROM series(%s)' % param_sql
            if extra_sql:
                sql = ' '.join((sql, extra_sql))
            curs = self.conn.execute(sql, params)
            self.assertEqual([row for row, in curs.fetchall()], values)

        assertSeries((0, 10, 2), [0, 2, 4, 6, 8, 10])
        assertSeries((5, None, 20), [5, 25, 45, 65, 85], 'LIMIT 5')
        assertSeries((4, 0, -1), [4, 3, 2], 'LIMIT 3')
        assertSeries((3, 5, 3), [3])
        assertSeries((3, 3, 1), [3])

    def test_series_tbl(self):
        Series.register(self.conn)
        self.conn.execute('CREATE TABLE nums (id INTEGER PRIMARY KEY)')
        self.conn.execute('INSERT INTO nums DEFAULT VALUES;')
        self.conn.execute('INSERT INTO nums DEFAULT VALUES;')
        curs = self.conn.execute(
            'SELECT * FROM nums, series(nums.id, nums.id + 2)')
        results = curs.fetchall()
        self.assertEqual(results, [
            (1, 1), (1, 2), (1, 3),
            (2, 2), (2, 3), (2, 4)])

        curs = self.conn.execute(
            'SELECT * FROM nums, series(nums.id) LIMIT 3')
        results = curs.fetchall()
        self.assertEqual(results, [(1, 1), (1, 2), (1, 3)])

    def test_regex(self):
        RegexSearch.register(self.conn)

        def assertResults(regex, search_string, values):
            sql = 'SELECT * FROM regex_search(?, ?)'
            curs = self.conn.execute(sql, (regex, search_string))
            self.assertEqual([row for row, in curs.fetchall()], values)

        assertResults(
            '[0-9]+',
            'foo 123 45 bar 678 nuggie 9.0',
            ['123', '45', '678', '9', '0'])
        assertResults(
            '[\w]+@[\w]+\.[\w]{2,3}',
            ('Dear charlie@example.com, this is nug@baz.com. I am writing on '
             'behalf of zaizee@foo.io. He dislikes your blog.'),
            ['charlie@example.com', 'nug@baz.com', 'zaizee@foo.io'])
        assertResults(
            '[a-z]+',
            '123.pDDFeewXee',
            ['p', 'eew', 'ee'])
        assertResults(
            '[0-9]+',
            'hello',
            [])

    def test_regex_tbl(self):
        messages = (
            'hello foo@example.fap, this is nuggie@example.fap. How are you?',
            'baz@example.com wishes to let charlie@crappyblog.com know that '
            'huey@example.com hates his blog',
            'testing no emails.',
            '')
        RegexSearch.register(self.conn)

        self.conn.execute('create table posts (id integer primary key, msg)')
        self.conn.execute('insert into posts (msg) values (?), (?), (?), (?)',
                          messages)
        cur = self.conn.execute('select posts.id, regex_search.rowid, regex_search.match '
                                'FROM posts, regex_search(?, posts.msg)',
                                ('[\w]+@[\w]+\.\w{2,3}',))
        results = cur.fetchall()
        self.assertEqual(results, [
            (1, 1, 'foo@example.fap'),
            (1, 2, 'nuggie@example.fap'),
            (2, 3, 'baz@example.com'),
            (2, 4, 'charlie@crappyblog.com'),
            (2, 5, 'huey@example.com'),
        ])

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


<commit_before>from __future__ import division
import math
import cmath
import sys
from decimal import Decimal
import arrow

import maths
import tests.wallis.wallistests as wtests

"""
print maths.wallis_equation(1)
print maths.oldeq(1)
print maths.wallis_equation(2)
print maths.oldeq(2)
print maths.wallis_equation(1000)
print maths.oldeq(1000)
print maths.wallis_equation(10000)
print maths.oldeq(10000)

g = maths.genmill(start=20, stop=25)
for i in g:
    print i
"""
pistr = '3.141592653589793115997963468544'
pi = 3.141592653589793115997963468544

print 'str:\n', pistr
print 'float:\n', pi
print 'decimal:\n',Decimal(math.pi)
print 'mathpi:\n%.48f' % math.pi

print '\n\n'

t1 = arrow.now()
print Decimal(maths.wallis(10000000))
t2 = arrow.now()
print t2 - t1
print 'gen:'
print Decimal(maths.wallisgen(10000000))
t3 = arrow.now()
print t3 - t2
t1 = arrow.now()
print Decimal(maths.wallis(10000000))
t2 = arrow.now()
print t2 - t1
print 'gen:'
print Decimal(maths.wallisgen(10000000))
t3 = arrow.now()
print t3 - t2

#print maths.wallis(1)

if __name__ == "__main__":
    print sys.argv
<commit_msg>Setup timed test.<commit_after>from __future__ import division
import math
import cmath
import sys
from decimal import Decimal
import arrow

import maths
import tests.wallis.wallistests as wtests

"""
print maths.wallis_equation(1)
print maths.oldeq(1)
print maths.wallis_equation(2)
print maths.oldeq(2)
print maths.wallis_equation(1000)
print maths.oldeq(1000)
print maths.wallis_equation(10000)
print maths.oldeq(10000)

g = maths.genmill(start=20, stop=25)
for i in g:
    print i
"""
"""
pistr = '3.141592653589793115997963468544'
pi = 3.141592653589793115997963468544

print 'str:\n', pistr
print 'float:\n', pi
print 'decimal:\n',Decimal(math.pi)
print 'mathpi:\n%.48f' % math.pi

print '\n\n'
"""
i = str(sys.argv[1])

t1 = arrow.now(i)
print 'std:'
print Decimal(maths.wallis(10000000))
t2 = arrow.now(i)
print t2 - t1
print 'gen:'
print Decimal(maths.wallisgen(10000000))
t3 = arrow.now(i)
print t3 - t2
t1 = arrow.now(i)
print 'gen:'
print Decimal(maths.wallisgen(10000000))
t2 = arrow.now(i)
print t2 - t1
print "std:"
print Decimal(maths.wallis(10000000))
t3 = arrow.now(i)
print t3 - t2

#print maths.wallis(1)

if __name__ == "__main__":
    print sys.argv
<|endoftext|>


<commit_before>from indent_io import IndentIO
from cStringIO import StringIO
from pyast import *
import pytest

ast_output_tests = [

(While(BinOp(Const(4), '==', Const(1)),
    [While(Const(False),
        [Const(True),
         Const(4)])]),
"""while (4 == 1):
    while False:
        True
        4

"""),

(For('x', Const(4), [Pass()]),
"""for x in 4:
    pass
"""),

]

@pytest.mark.parametrize('ast,output', ast_output_tests)
def test_output(ast, output):
    ast.check()
    outbuf = StringIO()
    outio = IndentIO(outbuf)
    ast.write_to(outio)
    outbuf.seek(0)
    assert outbuf.read() == output

def test_indent_io():
    outbuf = StringIO()
    io = IndentIO(outbuf)

    io.write('%d\n' % io.level)
    with io.indent():
        io.write('%d\n' % io.level)
        with io.indent():
            io.write('%d-' % io.level)
            io.write('%d\n' % io.level)
            with io.indent():
                io.write('%d\n' % io.level)
            io.write('%d\n' % io.level)
        io.write('%d\n' % io.level)
    io.write('%d\n' % io.level)

    outbuf.seek(0)
    assert outbuf.read() ==\
"""0
    1
        2-2
            3
        2
    1
0
"""
<commit_msg>Strip trailing whitespace in AST tests.<commit_after>from indent_io import IndentIO
from cStringIO import StringIO
from pyast import *
import pytest

ast_output_tests = [

(While(BinOp(Const(4), '==', Const(1)),
    [While(Const(False),
        [Const(True),
         Const(4)])]),
"""while (4 == 1):
    while False:
        True
        4"""),

(For('x', Const(4), [Pass()]),
"""for x in 4:
    pass"""),

]

@pytest.mark.parametrize('ast,output', ast_output_tests)
def test_output(ast, output):
    ast.check()
    outbuf = StringIO()
    outio = IndentIO(outbuf)
    ast.write_to(outio)
    outbuf.seek(0)
    # We strip whitespace off of the actual output here; Otherwise we will often
    # get trailing whitespace on an empty line, which is weird to look at here
    # given that it matters semantically for the tests, and it doesn't affect
    # the python semantics, so we don't care.
    assert outbuf.read().strip() == output

def test_indent_io():
    outbuf = StringIO()
    io = IndentIO(outbuf)

    io.write('%d\n' % io.level)
    with io.indent():
        io.write('%d\n' % io.level)
        with io.indent():
            io.write('%d-' % io.level)
            io.write('%d\n' % io.level)
            with io.indent():
                io.write('%d\n' % io.level)
            io.write('%d\n' % io.level)
        io.write('%d\n' % io.level)
    io.write('%d\n' % io.level)

    outbuf.seek(0)
    assert outbuf.read() ==\
"""0
    1
        2-2
            3
        2
    1
0
"""
<|endoftext|>


<commit_before>#!/usr/bin/env python3
"""
this module contains test cases (based on Python's unittest)
"""

import unittest

from pieces import (
    ChessPiece,
    King,
    Queen,
    Bishop,
    Rook,
    Knight,
)

class ChessPieceTest(unittest.TestCase):
    def test_set_pos(self):
        """
        test case for ChessPiece.set_pos and ChessPiece.get_pos methods
        """
        piece = ChessPiece(3, 4)
        self.assertEqual(piece.get_pos(), (3, 4))

        piece.set_pos(6, 5)
        self.assertEqual(piece.get_pos(), (6, 5))

    def test_pos_attacked_by_board(self):
        """
        test case for ChessPiece.pos_attacked_by_board class method
        test board:
        ---------------------
        | Q | . | . | . | K |
        ---------------------
        | . | . | . | . | . |
        ---------------------
        | . | . | . | . | R |
        ---------------------
        | B |   | . | . | . |
        ---------------------
        | . | . |   |   | N |
        ---------------------
        """
        row_count = 5
        col_count = 5
        board = {
            (0, 0): 'Q',
            (0, 4): 'K',
            (2, 4): 'R',
            (3, 0): 'B',
            (4, 4): 'N',
        }

        self.assertTrue(ChessPiece.pos_attacked_by_board(0, 1, board))
        self.assertTrue(ChessPiece.pos_attacked_by_board(0, 2, board))
        self.assertTrue(ChessPiece.pos_attacked_by_board(0, 3, board))
        self.assertTrue(ChessPiece.pos_attacked_by_board(1, 0, board))
        self.assertTrue(ChessPiece.pos_attacked_by_board(1, 1, board))
        self.assertTrue(ChessPiece.pos_attacked_by_board(1, 2, board))
        self.assertTrue(ChessPiece.pos_attacked_by_board(1, 3, board))
        self.assertTrue(ChessPiece.pos_attacked_by_board(1, 4, board))
        self.assertTrue(ChessPiece.pos_attacked_by_board(2, 0, board))
        self.assertTrue(ChessPiece.pos_attacked_by_board(2, 1, board))
        self.assertTrue(ChessPiece.pos_attacked_by_board(2, 2, board))
        self.assertTrue(ChessPiece.pos_attacked_by_board(2, 3, board))
        self.assertFalse(ChessPiece.pos_attacked_by_board(3, 1, board))
        self.assertTrue(ChessPiece.pos_attacked_by_board(3, 2, board))
        self.assertTrue(ChessPiece.pos_attacked_by_board(3, 3, board))
        self.assertTrue(ChessPiece.pos_attacked_by_board(3, 4, board))
        self.assertTrue(ChessPiece.pos_attacked_by_board(4, 0, board))
        self.assertTrue(ChessPiece.pos_attacked_by_board(4, 1, board))
        self.assertFalse(ChessPiece.pos_attacked_by_board(4, 2, board))
        self.assertFalse(ChessPiece.pos_attacked_by_board(4, 3, board))

class KingTest(unittest.TestCase):
    def test_attacks_1(self):
        """
        test case for King.attacks_pos method
        """
        king = King(5, 5)

        self.assertTrue(king.attacks_pos(4, 5))
        self.assertTrue(king.attacks_pos(5, 4))
        self.assertTrue(king.attacks_pos(4, 4))
        self.assertTrue(king.attacks_pos(6, 5))
        self.assertTrue(king.attacks_pos(5, 6))
        self.assertTrue(king.attacks_pos(6, 6))

        self.assertFalse(king.attacks_pos(0, 0))
        self.assertFalse(king.attacks_pos(1, 1))
        self.assertFalse(king.attacks_pos(2, 2))
        self.assertFalse(king.attacks_pos(3, 3))
        self.assertFalse(king.attacks_pos(3, 4))

class QueenTest(unittest.TestCase):
    def test_attacks_1(self):
        """
        test case for Queen.attacks_pos method
        """
        queen = Queen(5, 5)

        self.assertTrue(queen.attacks_pos(0, 5))
        self.assertTrue(queen.attacks_pos(5, 0))

        self.assertTrue(queen.attacks_pos(4, 5))
        self.assertTrue(queen.attacks_pos(5, 6))

        self.assertTrue(queen.attacks_pos(3, 3))
        self.assertTrue(queen.attacks_pos(8, 2))

        self.assertFalse(queen.attacks_pos(0, 1))
        self.assertFalse(queen.attacks_pos(0, 2))
        self.assertFalse(queen.attacks_pos(1, 2))
        self.assertFalse(queen.attacks_pos(1, 3))
        self.assertFalse(queen.attacks_pos(1, 4))
        self.assertFalse(queen.attacks_pos(3, 2))
        self.assertFalse(queen.attacks_pos(3, 4))

class BishopTest(unittest.TestCase):
    def test_attacks_1(self):
        """
        test case for Bishop.attacks_pos method
        """
        bishop = Bishop(5, 5)

        self.assertTrue(bishop.attacks_pos(1, 1))
        self.assertTrue(bishop.attacks_pos(2, 8))
        self.assertTrue(bishop.attacks_pos(7, 3))

        self.assertFalse(bishop.attacks_pos(0, 5))
        self.assertFalse(bishop.attacks_pos(5, 0))
        self.assertFalse(bishop.attacks_pos(5, 4))
        self.assertFalse(bishop.attacks_pos(5, 6))

class RookTest(unittest.TestCase):
    def test_attacks_1(self):
        """
        test case for Rook.attacks_pos method
        """
        rook = Rook(5, 5)

        self.assertTrue(rook.attacks_pos(1, 5))
        self.assertTrue(rook.attacks_pos(5, 3))
        self.assertTrue(rook.attacks_pos(5, 4))

        self.assertFalse(rook.attacks_pos(4, 4))
        self.assertFalse(rook.attacks_pos(3, 4))
        self.assertFalse(rook.attacks_pos(6, 6))

class KnightTest(unittest.TestCase):
    def test_attacks_1(self):
        """
        test case for Knight.attacks_pos method
        """
        knight = Knight(5, 5)

        self.assertTrue(knight.attacks_pos(6, 7))
        self.assertTrue(knight.attacks_pos(4, 3))
        self.assertTrue(knight.attacks_pos(3, 6))

        self.assertFalse(knight.attacks_pos(5, 4))
        self.assertFalse(knight.attacks_pos(0, 5))
        self.assertFalse(knight.attacks_pos(4, 4))

if __name__ == '__main__':
    unittest.main()
<commit_msg>tests.py: fix docstrings<commit_after>#!/usr/bin/env python3
"""
this module contains test cases (based on Python's unittest)
"""

import unittest

from pieces import (
    ChessPiece,
    King,
    Queen,
    Bishop,
    Rook,
    Knight,
)

class ChessPieceTest(unittest.TestCase):
    def test_set_pos(self):
        """
        test method for ChessPiece.set_pos and ChessPiece.get_pos methods
        """
        piece = ChessPiece(3, 4)
        self.assertEqual(piece.get_pos(), (3, 4))

        piece.set_pos(6, 5)
        self.assertEqual(piece.get_pos(), (6, 5))

    def test_pos_attacked_by_board(self):
        """
        test method for ChessPiece.pos_attacked_by_board class method
        test board:
        ---------------------
        | Q | . | . | . | K |
        ---------------------
        | . | . | . | . | . |
        ---------------------
        | . | . | . | . | R |
        ---------------------
        | B |   | . | . | . |
        ---------------------
        | . | . |   |   | N |
        ---------------------
        """
        row_count = 5
        col_count = 5
        board = {
            (0, 0): 'Q',
            (0, 4): 'K',
            (2, 4): 'R',
            (3, 0): 'B',
            (4, 4): 'N',
        }

        self.assertTrue(ChessPiece.pos_attacked_by_board(0, 1, board))
        self.assertTrue(ChessPiece.pos_attacked_by_board(0, 2, board))
        self.assertTrue(ChessPiece.pos_attacked_by_board(0, 3, board))
        self.assertTrue(ChessPiece.pos_attacked_by_board(1, 0, board))
        self.assertTrue(ChessPiece.pos_attacked_by_board(1, 1, board))
        self.assertTrue(ChessPiece.pos_attacked_by_board(1, 2, board))
        self.assertTrue(ChessPiece.pos_attacked_by_board(1, 3, board))
        self.assertTrue(ChessPiece.pos_attacked_by_board(1, 4, board))
        self.assertTrue(ChessPiece.pos_attacked_by_board(2, 0, board))
        self.assertTrue(ChessPiece.pos_attacked_by_board(2, 1, board))
        self.assertTrue(ChessPiece.pos_attacked_by_board(2, 2, board))
        self.assertTrue(ChessPiece.pos_attacked_by_board(2, 3, board))
        self.assertFalse(ChessPiece.pos_attacked_by_board(3, 1, board))
        self.assertTrue(ChessPiece.pos_attacked_by_board(3, 2, board))
        self.assertTrue(ChessPiece.pos_attacked_by_board(3, 3, board))
        self.assertTrue(ChessPiece.pos_attacked_by_board(3, 4, board))
        self.assertTrue(ChessPiece.pos_attacked_by_board(4, 0, board))
        self.assertTrue(ChessPiece.pos_attacked_by_board(4, 1, board))
        self.assertFalse(ChessPiece.pos_attacked_by_board(4, 2, board))
        self.assertFalse(ChessPiece.pos_attacked_by_board(4, 3, board))

class KingTest(unittest.TestCase):
    def test_attacks_1(self):
        """
        test method for King.attacks_pos method
        """
        king = King(5, 5)

        self.assertTrue(king.attacks_pos(4, 5))
        self.assertTrue(king.attacks_pos(5, 4))
        self.assertTrue(king.attacks_pos(4, 4))
        self.assertTrue(king.attacks_pos(6, 5))
        self.assertTrue(king.attacks_pos(5, 6))
        self.assertTrue(king.attacks_pos(6, 6))

        self.assertFalse(king.attacks_pos(0, 0))
        self.assertFalse(king.attacks_pos(1, 1))
        self.assertFalse(king.attacks_pos(2, 2))
        self.assertFalse(king.attacks_pos(3, 3))
        self.assertFalse(king.attacks_pos(3, 4))

class QueenTest(unittest.TestCase):
    def test_attacks_1(self):
        """
        test method for Queen.attacks_pos method
        """
        queen = Queen(5, 5)

        self.assertTrue(queen.attacks_pos(0, 5))
        self.assertTrue(queen.attacks_pos(5, 0))

        self.assertTrue(queen.attacks_pos(4, 5))
        self.assertTrue(queen.attacks_pos(5, 6))

        self.assertTrue(queen.attacks_pos(3, 3))
        self.assertTrue(queen.attacks_pos(8, 2))

        self.assertFalse(queen.attacks_pos(0, 1))
        self.assertFalse(queen.attacks_pos(0, 2))
        self.assertFalse(queen.attacks_pos(1, 2))
        self.assertFalse(queen.attacks_pos(1, 3))
        self.assertFalse(queen.attacks_pos(1, 4))
        self.assertFalse(queen.attacks_pos(3, 2))
        self.assertFalse(queen.attacks_pos(3, 4))

class BishopTest(unittest.TestCase):
    def test_attacks_1(self):
        """
        test method for Bishop.attacks_pos method
        """
        bishop = Bishop(5, 5)

        self.assertTrue(bishop.attacks_pos(1, 1))
        self.assertTrue(bishop.attacks_pos(2, 8))
        self.assertTrue(bishop.attacks_pos(7, 3))

        self.assertFalse(bishop.attacks_pos(0, 5))
        self.assertFalse(bishop.attacks_pos(5, 0))
        self.assertFalse(bishop.attacks_pos(5, 4))
        self.assertFalse(bishop.attacks_pos(5, 6))

class RookTest(unittest.TestCase):
    def test_attacks_1(self):
        """
        test method for Rook.attacks_pos method
        """
        rook = Rook(5, 5)

        self.assertTrue(rook.attacks_pos(1, 5))
        self.assertTrue(rook.attacks_pos(5, 3))
        self.assertTrue(rook.attacks_pos(5, 4))

        self.assertFalse(rook.attacks_pos(4, 4))
        self.assertFalse(rook.attacks_pos(3, 4))
        self.assertFalse(rook.attacks_pos(6, 6))

class KnightTest(unittest.TestCase):
    def test_attacks_1(self):
        """
        test method for Knight.attacks_pos method
        """
        knight = Knight(5, 5)

        self.assertTrue(knight.attacks_pos(6, 7))
        self.assertTrue(knight.attacks_pos(4, 3))
        self.assertTrue(knight.attacks_pos(3, 6))

        self.assertFalse(knight.attacks_pos(5, 4))
        self.assertFalse(knight.attacks_pos(0, 5))
        self.assertFalse(knight.attacks_pos(4, 4))

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


<commit_before>"""
    Routes API Tests
    ~~~~~~~~~~~~~~~~

    Tests for the Routes API
"""

import os
import json
import unittest

from app import app, db
from app.models import Route

BASE_DIR = app.config['BASE_DIR']

def clean_db(func):
    def inner(*args, **kwargs):
        db.drop_all()
        db.create_all()
        return func(*args, **kwargs)
    return inner

class RouteModelTestCase(unittest.TestCase):
    def setUp(self):
        self.route = Route(origin_point="A", destination_point="B",
                           distance=10)

    def test_route_representation(self):
        route = self.route
        expected = '<Route A-B-10>'

        self.assertEqual(expected, repr(route))

class RouteApiTestCase(unittest.TestCase):
    def setUp(self):
        app.config['TESTING'] = True
        app.config['SQL_ALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(BASE_DIR, 'test.db')
        self.app = app.test_client()
        db.create_all()

    def tearDown(self):
        db.session.remove()
        db.drop_all()

    def test_index_endpoint(self):
        response = self.app.get('/')
        expected = "Routes API Python Version :)"
        result = response.data.decode('utf-8')

        self.assertEqual(response.status_code, 200)
        self.assertIn(expected, result)

    def test_nonexistent_endpoint(self):
        response = self.app.get('/nonexistent')
        expected = "Not found"
        result = response.data.decode('utf-8')

        self.assertEqual(response.status_code, 404)
        self.assertIn(expected, result)

class RoutesApiTestCase(RouteApiTestCase):
    def test_empty_database(self):
        response = self.app.get('/routes')
        expected = '{\n"routes":[]\n}\n'
        result = response.data.decode('utf-8').replace(" ", "")

        self.assertEqual(response.status_code, 200)
        self.assertEqual(result, expected)

    @clean_db
    def test_show_all_routes(self):
        route = Route(origin_point="A", destination_point="B", distance=10)
        db.session.add(route)
        db.session.commit()
        expected = '{\n"routes":[\n{\n"destination_point":"B",\n"distance":10,\n"origin_point":"A",\n"uri":"/routes/1"\n}\n]\n}\n'

        response = self.app.get('/routes')
        result = response.data.decode('utf-8').replace(" ", "")

        self.assertEqual(response.status_code, 200)
        self.assertEqual(result, expected)

    @clean_db
    def test_create_route(self):
        route = {
            "origin_point": "A",
            "destination_point": "C",
            "distance": 20
        }
        data = json.dumps(route)
        expected = '{\n"route":{\n"destination_point":"C",\n"distance":20,\n"origin_point":"A",\n"uri":"/routes/1"\n}\n}\n'

        response = self.app.post('/routes', data=data,
                                 content_type="application/json")
        result = response.data.decode('utf-8').replace(" ", "")

        self.assertEqual(response.status_code, 201)
        self.assertEqual(result, expected)

    @clean_db
    def test_create_route_uniqueness(self):
        route = {
            "origin_point": "A",
            "destination_point": "C",
            "distance": 20
        }

        data = json.dumps(route)

        # first post
        response = self.app.post('/routes', data=data, content_type="application/json")
        expected = '{\n"route":{\n"destination_point":"C",\n"distance":20,\n"origin_point":"A",\n"uri":"/routes/1"\n}\n}\n'

        result = response.data.decode('utf-8').replace(" ", "")

        self.assertEqual(response.status_code, 201)
        self.assertEqual(result, expected)

        # second post
        response = self.app.post('/routes', data=data, content_type="application/json")
        expected = "Route already exists."
        result = response.data.decode('utf-8')

        self.assertEqual(response.status_code, 400)
        self.assertIn(expected, result)

    @clean_db
    def test_create_route_with_invalid_data(self):
        route = {
            "origin_point": "A",
            "destination_point": "B",
            "distance": "ABC"
        }

        data = json.dumps(route)

        response = self.app.post('/routes', data=data, content_type="application/json")
        expected = "Value 'ABC' for field 'distance' is not a valid integer."
        result = response.data.decode('utf-8')

        self.assertEqual(response.status_code, 400)
        self.assertIn(expected, result)

    @clean_db
    def test_update_route_destination_point(self):
        route = Route(origin_point="A", destination_point="C", distance=10)
        db.session.add(route)
        db.session.commit()

        fields_to_update = {
            "destination_point": "B"
        }

        data = json.dumps(fields_to_update)

        response = self.app.put('/routes/{}'.format(route.pk),
                                data=data, content_type="application/json")
        expected = u'{\n"route":{\n"destination_point":"B",\n"distance":10,\n"origin_point":"A",\n"uri":"/routes/1"\n}\n}\n'

        result = response.data.decode('utf-8').replace(" ", "")

        self.assertEqual(response.status_code, 200)
        self.assertEqual(result, expected)

    @clean_db
    def test_update_route_origin_point(self):
        route = Route(origin_point="A", destination_point="C", distance=10)
        db.session.add(route)
        db.session.commit()

        fields_to_update = {
            "origin_point": "B"
        }

        data = json.dumps(fields_to_update)

        response = self.app.put('/routes/{}'.format(route.pk),
                                data=data, content_type="application/json")
        expected = u'{\n"route":{\n"destination_point":"C",\n"distance":10,\n"origin_point":"B",\n"uri":"/routes/1"\n}\n}\n'

        result = response.data.decode('utf-8').replace(" ", "")

        self.assertEqual(response.status_code, 200)
        self.assertEqual(result, expected)

    @clean_db
    def test_update_route_distance(self):
        route = Route(origin_point="A", destination_point="C", distance=10)
        db.session.add(route)
        db.session.commit()

        fields_to_update = {
            "distance": 20
        }

        data = json.dumps(fields_to_update)

        response = self.app.put('/routes/{}'.format(route.pk),
                                data=data, content_type="application/json")
        expected = u'{\n"route":{\n"destination_point":"C",\n"distance":20,\n"origin_point":"A",\n"uri":"/routes/1"\n}\n}\n'

        result = response.data.decode('utf-8').replace(" ", "")

        self.assertEqual(response.status_code, 200)
        self.assertEqual(result, expected)

    def test_update_nonexistent_route(self):
        fields_to_update = {
            "destination_point": "B"
        }
        data = json.dumps(fields_to_update)
        response = self.app.put('/routes/123', data=data, content_type="application/json")
        expected = "Route not found"
        result = response.data.decode('utf-8')

        self.assertEqual(response.status_code, 404)
        self.assertIn(expected, result)

    @clean_db
    def test_get_route(self):
        route = Route(origin_point="A", destination_point="B", distance=10)
        db.session.add(route)
        db.session.commit()

        response = self.app.get('/routes/{}'.format(route.pk))
        expected = '{\n"route":{\n"destination_point":"B",\n"distance":10,\n"origin_point":"A",\n"uri":"/routes/1"\n}\n}\n'
        result = response.data.decode('utf-8').replace(" ", "")

        self.assertEqual(response.status_code, 200)
        self.assertEqual(result, expected)

    def test_get_nonexistent_route(self):
        response = self.app.get('/routes/123')
        expected = "Route not found"
        result = response.data.decode('utf-8')

        self.assertEqual(response.status_code, 404)
        self.assertIn(expected, result)

    @clean_db
    def test_delete_route(self):
        route = Route(origin_point="A", destination_point="B", distance=10)
        db.session.add(route)
        db.session.commit()

        response = self.app.delete('/routes/{}'.format(route.pk))
        expected = '{\n"result":true\n}\n'
        result = response.data.decode('utf-8').replace(" ", "")

        self.assertEqual(response.status_code, 200)
        self.assertEqual(result, expected)

    def test_delete_nonexistent_route(self):
        response = self.app.delete('/routes/1234')
        expected = "Route not found"
        result = response.data.decode('utf-8')

        self.assertEqual(response.status_code, 404)
        self.assertIn(expected, result)

class RouteCalculateCostApiTestCase(RouteApiTestCase):
    def setUp(self):
        app.config['TESTING'] = True
        app.config['SQL_ALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(BASE_DIR, 'test.d')
        self.app = app.test_client()
        db.create_all()

        # routes
        self._create_routes()

    def _create_routes(self):
        # routes
        routes = [
            Route(origin_point="A", destination_point="B", distance=10),
            Route(origin_point="A", destination_point="C", distance=20),
            Route(origin_point="B", destination_point="D", distance=15),
            Route(origin_point="C", destination_point="D", distance=30),
            Route(origin_point="B", destination_point="E", distance=50),
            Route(origin_point="D", destination_point="E", distance=30)
        ]

        for route in routes:
            db.session.add(route)

        db.session.commit()

    def test_calculate_cost(self):
        data = {
            "origin_point": "A",
            "destination_point": "D",
            "autonomy": 10,
            "fuel_price": 2.5
        }

        data = json.dumps(data)

        response = self.app.post('/routes/calculate-cost', data=data, content_type="application/json")

        expected = '{\n"cost":6.25,\n"path":"ABD"\n}\n'
        result = response.data.decode('utf-8').replace(" ", "")

        self.assertEqual(response.status_code, 200)
        self.assertEqual(result, expected)

    def test_calculate_cost_with_invalid_data(self):
        data = {
            "origin_point": "A",
            "destination_point": "D",
            "autonomy": "ABC",
            "fuel_price": 2.5
        }

        data = json.dumps(data)

        response = self.app.post('/routes/calculate-cost', data=data, content_type="application/json")
        expected = "Value 'ABC' for field 'autonomy' is not a valid integer."
        result = response.data.decode('utf-8')

        self.assertEqual(response.status_code, 400)
        self.assertIn(expected, result)

    def test_calculate_cost_with_invalid_fuel_price_data(self):
        data = {
            "origin_point": "A",
            "destination_point": "D",
            "autonomy": 10,
            "fuel_price": "XYZ"
        }

        data = json.dumps(data)

        response = self.app.post('/routes/calculate-cost', data=data, content_type="application/json")
        expected = "Value 'XYZ' for field 'fuel_price' is not a valid float."
        result = response.data.decode('utf-8')

        self.assertEqual(response.status_code, 400)
        self.assertIn(expected, result)

    def test_calculate_cost_with_missing_fields(self):
        data = {
            "origin_point": "A",
            "autonomy": 10,
            "fuel_price": 2.5
        }

        data = json.dumps(data)

        response = self.app.post('/routes/calculate-cost', data=data, content_type="application/json")
        expected = "Missing required parameter in the JSON body"
        result = response.data.decode('utf-8')

        self.assertEqual(response.status_code, 400)
        self.assertIn("destination_point", result)
        self.assertIn(expected, result)

    def test_calculate_cost_with_nonexistent_origin_point(self):
        data = {
            "origin_point": "Y",
            "destination_point": "A",
            "autonomy": 10,
            "fuel_price": 2.5
        }

        data = json.dumps(data)

        response = self.app.post('/routes/calculate-cost', data=data, content_type="application/json")
        expected = "Origin point \'Y\' not found"
        result = response.data.decode('utf-8')

        self.assertEqual(response.status_code, 400)
        self.assertIn(expected, result)

    def test_calculate_cost_with_nonexistent_destination_point(self):
        data = {
            "origin_point": "A",
            "destination_point": "X",
            "autonomy": 10,
            "fuel_price": 2.5
        }

        data = json.dumps(data)

        response = self.app.post('/routes/calculate-cost', data=data, content_type="application/json")
        expected = "Destination point \'X\' not found"
        result = response.data.decode('utf-8')

        self.assertEqual(response.status_code, 400)
        self.assertIn(expected, result)

if __name__ == '__main__':
    unittest.main()
<commit_msg>Update tests to use postgresql as the database<commit_after>"""
    Routes API Tests
    ~~~~~~~~~~~~~~~~

    Tests for the Routes API
"""

import os
import json
import unittest

from app import app, db
from app.models import Route

BASE_DIR = app.config['BASE_DIR']

def clean_db(func):
    def inner(*args, **kwargs):
        db.drop_all()
        db.create_all()
        return func(*args, **kwargs)
    return inner

class RouteModelTestCase(unittest.TestCase):
    def setUp(self):
        self.route = Route(origin_point="A", destination_point="B",
                           distance=10)

    def test_route_representation(self):
        route = self.route
        expected = '<Route A-B-10>'

        self.assertEqual(expected, repr(route))

class RouteApiTestCase(unittest.TestCase):
    def setUp(self):
        app.config['TESTING'] = True
        app.config['SQL_ALCHEMY_DATABASE_URI'] = 'postgresql://localhost/routes_api_python_test'
        self.app = app.test_client()
        db.create_all()

    def tearDown(self):
        db.session.remove()
        db.drop_all()

    def test_index_endpoint(self):
        response = self.app.get('/')
        expected = "Routes API Python Version :)"
        result = response.data.decode('utf-8')

        self.assertEqual(response.status_code, 200)
        self.assertIn(expected, result)

    def test_nonexistent_endpoint(self):
        response = self.app.get('/nonexistent')
        expected = "Not found"
        result = response.data.decode('utf-8')

        self.assertEqual(response.status_code, 404)
        self.assertIn(expected, result)

class RoutesApiTestCase(RouteApiTestCase):
    def test_empty_database(self):
        response = self.app.get('/routes')
        expected = '{\n"routes":[]\n}\n'
        result = response.data.decode('utf-8').replace(" ", "")

        self.assertEqual(response.status_code, 200)
        self.assertEqual(result, expected)

    @clean_db
    def test_show_all_routes(self):
        route = Route(origin_point="A", destination_point="B", distance=10)
        db.session.add(route)
        db.session.commit()
        expected = '{\n"routes":[\n{\n"destination_point":"B",\n"distance":10,\n"origin_point":"A",\n"uri":"/routes/1"\n}\n]\n}\n'

        response = self.app.get('/routes')
        result = response.data.decode('utf-8').replace(" ", "")

        self.assertEqual(response.status_code, 200)
        self.assertEqual(result, expected)

    @clean_db
    def test_create_route(self):
        route = {
            "origin_point": "A",
            "destination_point": "C",
            "distance": 20
        }
        data = json.dumps(route)
        expected = '{\n"route":{\n"destination_point":"C",\n"distance":20,\n"origin_point":"A",\n"uri":"/routes/1"\n}\n}\n'

        response = self.app.post('/routes', data=data,
                                 content_type="application/json")
        result = response.data.decode('utf-8').replace(" ", "")

        self.assertEqual(response.status_code, 201)
        self.assertEqual(result, expected)

    @clean_db
    def test_create_route_uniqueness(self):
        route = {
            "origin_point": "A",
            "destination_point": "C",
            "distance": 20
        }

        data = json.dumps(route)

        # first post
        response = self.app.post('/routes', data=data, content_type="application/json")
        expected = '{\n"route":{\n"destination_point":"C",\n"distance":20,\n"origin_point":"A",\n"uri":"/routes/1"\n}\n}\n'

        result = response.data.decode('utf-8').replace(" ", "")

        self.assertEqual(response.status_code, 201)
        self.assertEqual(result, expected)

        # second post
        response = self.app.post('/routes', data=data, content_type="application/json")
        expected = "Route already exists."
        result = response.data.decode('utf-8')

        self.assertEqual(response.status_code, 400)
        self.assertIn(expected, result)

    @clean_db
    def test_create_route_with_invalid_data(self):
        route = {
            "origin_point": "A",
            "destination_point": "B",
            "distance": "ABC"
        }

        data = json.dumps(route)

        response = self.app.post('/routes', data=data, content_type="application/json")
        expected = "Value 'ABC' for field 'distance' is not a valid integer."
        result = response.data.decode('utf-8')

        self.assertEqual(response.status_code, 400)
        self.assertIn(expected, result)

    @clean_db
    def test_update_route_destination_point(self):
        route = Route(origin_point="A", destination_point="C", distance=10)
        db.session.add(route)
        db.session.commit()

        fields_to_update = {
            "destination_point": "B"
        }

        data = json.dumps(fields_to_update)

        response = self.app.put('/routes/{}'.format(route.pk),
                                data=data, content_type="application/json")
        expected = u'{\n"route":{\n"destination_point":"B",\n"distance":10,\n"origin_point":"A",\n"uri":"/routes/1"\n}\n}\n'

        result = response.data.decode('utf-8').replace(" ", "")

        self.assertEqual(response.status_code, 200)
        self.assertEqual(result, expected)

    @clean_db
    def test_update_route_origin_point(self):
        route = Route(origin_point="A", destination_point="C", distance=10)
        db.session.add(route)
        db.session.commit()

        fields_to_update = {
            "origin_point": "B"
        }

        data = json.dumps(fields_to_update)

        response = self.app.put('/routes/{}'.format(route.pk),
                                data=data, content_type="application/json")
        expected = u'{\n"route":{\n"destination_point":"C",\n"distance":10,\n"origin_point":"B",\n"uri":"/routes/1"\n}\n}\n'

        result = response.data.decode('utf-8').replace(" ", "")

        self.assertEqual(response.status_code, 200)
        self.assertEqual(result, expected)

    @clean_db
    def test_update_route_distance(self):
        route = Route(origin_point="A", destination_point="C", distance=10)
        db.session.add(route)
        db.session.commit()

        fields_to_update = {
            "distance": 20
        }

        data = json.dumps(fields_to_update)

        response = self.app.put('/routes/{}'.format(route.pk),
                                data=data, content_type="application/json")
        expected = u'{\n"route":{\n"destination_point":"C",\n"distance":20,\n"origin_point":"A",\n"uri":"/routes/1"\n}\n}\n'

        result = response.data.decode('utf-8').replace(" ", "")

        self.assertEqual(response.status_code, 200)
        self.assertEqual(result, expected)

    def test_update_nonexistent_route(self):
        fields_to_update = {
            "destination_point": "B"
        }
        data = json.dumps(fields_to_update)
        response = self.app.put('/routes/123', data=data, content_type="application/json")
        expected = "Route not found"
        result = response.data.decode('utf-8')

        self.assertEqual(response.status_code, 404)
        self.assertIn(expected, result)

    @clean_db
    def test_get_route(self):
        route = Route(origin_point="A", destination_point="B", distance=10)
        db.session.add(route)
        db.session.commit()

        response = self.app.get('/routes/{}'.format(route.pk))
        expected = '{\n"route":{\n"destination_point":"B",\n"distance":10,\n"origin_point":"A",\n"uri":"/routes/1"\n}\n}\n'
        result = response.data.decode('utf-8').replace(" ", "")

        self.assertEqual(response.status_code, 200)
        self.assertEqual(result, expected)

    def test_get_nonexistent_route(self):
        response = self.app.get('/routes/123')
        expected = "Route not found"
        result = response.data.decode('utf-8')

        self.assertEqual(response.status_code, 404)
        self.assertIn(expected, result)

    @clean_db
    def test_delete_route(self):
        route = Route(origin_point="A", destination_point="B", distance=10)
        db.session.add(route)
        db.session.commit()

        response = self.app.delete('/routes/{}'.format(route.pk))
        expected = '{\n"result":true\n}\n'
        result = response.data.decode('utf-8').replace(" ", "")

        self.assertEqual(response.status_code, 200)
        self.assertEqual(result, expected)

    def test_delete_nonexistent_route(self):
        response = self.app.delete('/routes/1234')
        expected = "Route not found"
        result = response.data.decode('utf-8')

        self.assertEqual(response.status_code, 404)
        self.assertIn(expected, result)

class RouteCalculateCostApiTestCase(RouteApiTestCase):
    def setUp(self):
        app.config['TESTING'] = True
        app.config['SQL_ALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(BASE_DIR, 'test.d')
        self.app = app.test_client()
        db.create_all()

        # routes
        self._create_routes()

    def _create_routes(self):
        # routes
        routes = [
            Route(origin_point="A", destination_point="B", distance=10),
            Route(origin_point="A", destination_point="C", distance=20),
            Route(origin_point="B", destination_point="D", distance=15),
            Route(origin_point="C", destination_point="D", distance=30),
            Route(origin_point="B", destination_point="E", distance=50),
            Route(origin_point="D", destination_point="E", distance=30)
        ]

        for route in routes:
            db.session.add(route)

        db.session.commit()

    def test_calculate_cost(self):
        data = {
            "origin_point": "A",
            "destination_point": "D",
            "autonomy": 10,
            "fuel_price": 2.5
        }

        data = json.dumps(data)

        response = self.app.post('/routes/calculate-cost', data=data, content_type="application/json")

        expected = '{\n"cost":6.25,\n"path":"ABD"\n}\n'
        result = response.data.decode('utf-8').replace(" ", "")

        self.assertEqual(response.status_code, 200)
        self.assertEqual(result, expected)

    def test_calculate_cost_with_invalid_data(self):
        data = {
            "origin_point": "A",
            "destination_point": "D",
            "autonomy": "ABC",
            "fuel_price": 2.5
        }

        data = json.dumps(data)

        response = self.app.post('/routes/calculate-cost', data=data, content_type="application/json")
        expected = "Value 'ABC' for field 'autonomy' is not a valid integer."
        result = response.data.decode('utf-8')

        self.assertEqual(response.status_code, 400)
        self.assertIn(expected, result)

    def test_calculate_cost_with_invalid_fuel_price_data(self):
        data = {
            "origin_point": "A",
            "destination_point": "D",
            "autonomy": 10,
            "fuel_price": "XYZ"
        }

        data = json.dumps(data)

        response = self.app.post('/routes/calculate-cost', data=data, content_type="application/json")
        expected = "Value 'XYZ' for field 'fuel_price' is not a valid float."
        result = response.data.decode('utf-8')

        self.assertEqual(response.status_code, 400)
        self.assertIn(expected, result)

    def test_calculate_cost_with_missing_fields(self):
        data = {
            "origin_point": "A",
            "autonomy": 10,
            "fuel_price": 2.5
        }

        data = json.dumps(data)

        response = self.app.post('/routes/calculate-cost', data=data, content_type="application/json")
        expected = "Missing required parameter in the JSON body"
        result = response.data.decode('utf-8')

        self.assertEqual(response.status_code, 400)
        self.assertIn("destination_point", result)
        self.assertIn(expected, result)

    def test_calculate_cost_with_nonexistent_origin_point(self):
        data = {
            "origin_point": "Y",
            "destination_point": "A",
            "autonomy": 10,
            "fuel_price": 2.5
        }

        data = json.dumps(data)

        response = self.app.post('/routes/calculate-cost', data=data, content_type="application/json")
        expected = "Origin point \'Y\' not found"
        result = response.data.decode('utf-8')

        self.assertEqual(response.status_code, 400)
        self.assertIn(expected, result)

    def test_calculate_cost_with_nonexistent_destination_point(self):
        data = {
            "origin_point": "A",
            "destination_point": "X",
            "autonomy": 10,
            "fuel_price": 2.5
        }

        data = json.dumps(data)

        response = self.app.post('/routes/calculate-cost', data=data, content_type="application/json")
        expected = "Destination point \'X\' not found"
        result = response.data.decode('utf-8')

        self.assertEqual(response.status_code, 400)
        self.assertIn(expected, result)

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


<commit_before>import unittest
import os

import numpy as np
from matplotlib import pyplot as plt
import matplotlib

from roipoly import RoiPoly

if os.environ.get('DISPLAY', '') == '':
    print('No DISPLAY found. Using non-interactive "Agg" backend.')
    matplotlib.use('Agg')

class TestRoiPoly(unittest.TestCase):

    def setUp(self):
        roi1_properties = {
            'x': [1, 1, 3, 3],
            'y': [1, 3, 3, 1]
        }
        fig = plt.figure()
        roi1 = RoiPoly(color='r', fig=fig, show_fig=False)
        roi1.x = roi1_properties['x']
        roi1.y = roi1_properties['y']
        self.roi1 = roi1
        self.img1 = np.ones((5, 5)) * range(5)
        self.roi1_expected_mask = np.array(
            [[False, False, False, False, False],
             [False, False, False, False, False],
             [False, True, True, True, False],
             [False, True, True, True, False],
             [False, False, False, False, False]])

    def test_get_mask(self):
        result = self.roi1.get_mask(self.img1)
        np.testing.assert_array_equal(result, self.roi1_expected_mask)

    def test_get_mean_and_std(self):
        mean, std = self.roi1.get_mean_and_std(self.img1)
        masked_img = self.img1.copy()
        masked_img[~self.roi1_expected_mask] = np.nan
        expected_mean = np.nanmean(masked_img)
        expected_std = np.nanstd(masked_img)
        np.testing.assert_almost_equal(mean, expected_mean)
        np.testing.assert_almost_equal(std, expected_std)
<commit_msg>rearrange matplotlib import fix for travis<commit_after>import unittest
import os

import numpy as np
import matplotlib
if os.environ.get('DISPLAY', '') == '':
    print('No DISPLAY found. Using non-interactive "Agg"backend.')
    matplotlib.use('Agg')
from matplotlib import pyplot as plt

from roipoly import RoiPoly

class TestRoiPoly(unittest.TestCase):

    def setUp(self):
        roi1_properties = {
            'x': [1, 1, 3, 3],
            'y': [1, 3, 3, 1]
        }
        fig = plt.figure()
        roi1 = RoiPoly(color='r', fig=fig, show_fig=False)
        roi1.x = roi1_properties['x']
        roi1.y = roi1_properties['y']
        self.roi1 = roi1
        self.img1 = np.ones((5, 5)) * range(5)
        self.roi1_expected_mask = np.array(
            [[False, False, False, False, False],
             [False, False, False, False, False],
             [False, True, True, True, False],
             [False, True, True, True, False],
             [False, False, False, False, False]])

    def test_get_mask(self):
        result = self.roi1.get_mask(self.img1)
        np.testing.assert_array_equal(result, self.roi1_expected_mask)

    def test_get_mean_and_std(self):
        mean, std = self.roi1.get_mean_and_std(self.img1)
        masked_img = self.img1.copy()
        masked_img[~self.roi1_expected_mask] = np.nan
        expected_mean = np.nanmean(masked_img)
        expected_std = np.nanstd(masked_img)
        np.testing.assert_almost_equal(mean, expected_mean)
        np.testing.assert_almost_equal(std, expected_std)
<|endoftext|>