<commit_before>"""Test functions for deliver_cute project."""
from __future__ import unicode_literals, absolute_import

import random
from string import ascii_letters, digits
from itertools import product, chain
from django.test import TestCase
from django.core import mail
from django.core.urlresolvers import reverse
from nose_parameterized import parameterized

from on_schedule import fix_image_links
from constants import SUBREDDIT_NAMES, LIMIT, EMAIL, UNICODE
from tests.classes import (
    FakePost,
    SubscriberFactory,
    SubRedditFactory,
    BATCH_SIZE,
    BATCH_PARAMS,
    ATTR_PARAMS,
    # SUBR_BATCH_SIZE,
    # SUBR_PARAMS,
    SUBR_NAME_PARAMS,
)

# TODO
# test unicode status of incoming PRAW post objects
# test escaped HTML of outgoing html
#   test fix_urls
#       make some bad urls
#   test sort_urls
#   test subscribers_for_now

# edge cases:
#   unsorted
#   already sorted
#   no subscribers
#   no subreddits
#   no posts
#   bad links
#   limit 0
#   very high limit

CUTE_POSTS = []
FIXED_LINKS = list(fix_image_links(CUTE_POSTS))
SUBJECT = 'DEBUG'
TEXT = 'Plain text message.'
BODY = '''

Test Header

can't not apostrophe

'''

PROTO = ('http://', 'https://')
DOMAIN = ('i.imgur.com/', )
HASH = ''.join(random.sample(ascii_letters + digits, 8))
EXT = ('.jpg', '.gifv', '.gif', '.png', )

BAD_DOMAIN = ('www.imgur.com/', 'reddit.com/', 'gfycat.com/')
BAD_EXT = ('', )

GOOD_URLS = product(PROTO, DOMAIN, HASH, EXT)
BAD_URLS = product(PROTO, BAD_DOMAIN, HASH, BAD_EXT)

class EmailCase(TestCase):
    """Testing sending of email."""

    def setUp(self):
        """Send an email."""
        mail.send_mail(
            SUBJECT, TEXT, EMAIL, [EMAIL],
            html_message=BODY,
            fail_silently=False,
        )

    def test_outbox(self):
        """Test sending an email."""
        self.assertEqual(len(mail.outbox), 1)

    def test_subject(self):
        """Test sending an email."""
        email = mail.outbox[0]
        self.assertEqual(SUBJECT, email.subject)

class RedditAPICase(TestCase):
    """Test retrieval of posts from reddit API."""

    def setUp(self):
        """Get post data to test."""
        from on_schedule import create_post_map
        # test with different limits
        self.no_posts = create_post_map([], LIMIT)
        self.all_posts = create_post_map(SUBREDDIT_NAMES, LIMIT)

    def test_no_subreddits(self):
        """Confirm that zero subreddits returns an empty dictionary."""
        self.assertEqual(self.no_posts, {})

    def test_dictionary(self):
        """Confirm that given subreddits returns a dictionary."""
        self.assertIsInstance(self.all_posts, dict)

    # @parameterized.expand(SUBR_NAME_PARAMS)
    # def test_cute_posts(self, name):
    #     """Test that gathered posts have links."""
    #     for post in self.all_posts[name]:
    #         self.assertTrue(post.url.startswith('http'))

    # @parameterized.expand(SUBR_NAME_PARAMS)
    # def test_cute_posts_count(self, name):
    #     """Test that number of links is at or under the limit per subreddit."""
    #     self.assertLessEqual(len(self.all_posts[name]), LIMIT)

class FakePostsCase(TestCase):
    """Using fake posts to test unicode and html escaping."""

    def __init__(self, *args, **kwargs):
        """Initialize data groups."""
        from on_schedule import htmlize_posts
        super(FakePostsCase, self).__init__(*args, **kwargs)
        self.fake_posts = FakePost.create_batch(BATCH_SIZE)
        self.fake_post_attrs = list(chain(
            *((p.title, p.url, p.permalink, p.subreddit.display_name)
              for p in self.fake_posts)))
        self.htmlized_posts = list(htmlize_posts(self.fake_posts))
        self.duplicates = FakePost.create_batch_with_dupes(BATCH_SIZE)

    def setUp(self):
        """Set up fake_posts."""
        from on_schedule import get_email_body
        self.subscriber = SubscriberFactory.create(email=EMAIL)
        self.email_body = get_email_body(self.subscriber, self.htmlized_posts)

    @parameterized.expand(ATTR_PARAMS)
    def test_unicode_attrs(self, idx):
        """Ensure that all FakePost attributes are unicode."""
        attr = self.fake_post_attrs[idx]
        self.assertIsInstance(attr, UNICODE)

    @parameterized.expand(BATCH_PARAMS)
    def test_htmlize_unicode(self, idx):
        """Test that htmlize runs without breaking."""
        htmlized_post = self.htmlized_posts[idx]
        self.assertIsInstance(htmlized_post, UNICODE)

    @parameterized.expand(BATCH_PARAMS)
    def test_html_post_contains_title(self, idx):
        """Ensure that all FakePost attributes in htmlized version."""
        post = self.fake_posts[idx]
        htmlized_post = self.htmlized_posts[idx]
        self.assertIn(post.title, htmlized_post)

    @parameterized.expand(BATCH_PARAMS)
    def test_html_post_contains_url(self, idx):
        """Ensure that all FakePost attributes in htmlized version."""
        post = self.fake_posts[idx]
        htmlized_post = self.htmlized_posts[idx]
        self.assertIn(post.url, htmlized_post)

    @parameterized.expand(BATCH_PARAMS)
    def test_html_post_contains_permalink(self, idx):
        """Ensure that all FakePost attributes in htmlized version."""
        post = self.fake_posts[idx]
        htmlized_post = self.htmlized_posts[idx]
        self.assertIn(post.permalink, htmlized_post)

    @parameterized.expand(BATCH_PARAMS)
    def test_html_post_contains_subreddit(self, idx):
        """Ensure that all FakePost attributes in htmlized version."""
        post = self.fake_posts[idx]
        htmlized_post = self.htmlized_posts[idx]
        self.assertIn(post.subreddit.display_name, htmlized_post)

    @parameterized.expand(BATCH_PARAMS)
    def test_email_body_contains(self, idx):
        """Ensure that htmlized posts are contained by email body."""
        htmlized_post = self.htmlized_posts[idx]
        self.assertIn(htmlized_post, self.email_body)

    def test_email_body_unsub_link(self):
        """Ensure that all FakePost attributes are unicode."""
        hash_ = self.subscriber.unsubscribe_hash
        unsub_url = reverse('unsubscribe', args=(hash_, ))
        self.assertIn(unsub_url, self.email_body)

    def test_email_body_unicode(self):
        """Ensure that all FakePost attributes are unicode."""
        self.assertIsInstance(self.email_body, UNICODE)

    def test_dedupe_posts(self):
        """Test that urls of deduped posts is equal to set of those urls."""
        from on_schedule import dedupe_posts
        found = set()
        urls = [post.url for post in dedupe_posts(self.duplicates, found)]
        self.assertEqual(
            list(sorted(urls)),
            list(sorted(set(urls)))
        )

    # test html escaping by checking for &quot, \u2018 etc.

class CheckURLCase(TestCase):
    """Test URL matching regexes."""

    def setUp(self):
        """Get regex pattern."""
        from on_schedule import SRC_PAT
        self.regex = SRC_PAT

    @parameterized.expand((url, ) for url in GOOD_URLS)
    def test_src_pat_good(self, url):
        """Confirm that link regex works as expected for good urls."""
        self.assertIsNotNone(self.regex.match(''.join(url)))

    @parameterized.expand((url, ) for url in BAD_URLS)
    def test_src_pat_bad(self, url):
        """Confirm that link regex works as expected for bad urls."""
        self.assertIsNone(self.regex.match(''.join(url)))

    # def test_cute_links_source(fixed_link):
    #     """Confirm that links fixed by source fixer match the expected pattern."""
    #     assert self.regex.match(fixed_link.url) is not None

# @pytest.fixture(params=FIXED_LINKS)
# def fixed_link(request):
#     """Generate link fixed by having correct source url."""
#     return request.param

#

# def test_moonmoon():
#     """Test html escaping problems."""
#     import praw
#     from on_schedule import (
#         send_email,
#         htmlize_posts,
#         USER_AGENT,
#     )
#     reddit = praw.Reddit(user_agent=USER_AGENT)
#     moonmoon_post = reddit.get_submission(submission_id='4spncq')
#     body = '' + next(htmlize_posts((moonmoon_post, ))) + ''
#     send_email(WILL_EMAIL, WILL_EMAIL, [WILL_EMAIL], 'ESCAPE TEST', body)

class DebugCase(TestCase):
    """Run full on_schedule script in debug mode."""

    def setUp(self):
        """Add debug user with project email to test database."""
        from on_schedule import main
        self.subreddits = SubRedditFactory.create_random_batch()
        self.subscriber = SubscriberFactory.create(email=EMAIL)
        self.subscriber.subreddits.add(*self.subreddits)
        self.result = main(True)

    def test_main(self):
        """Test the main() function of on_schedule.py in debug mode."""
        self.result = self.assertEqual(self.result, 1)

    def test_outbox(self):
        """Test sending an email."""
        self.assertEqual(len(mail.outbox), 1)

    def test_recipient(self):
        """Test sending an email."""
        email = mail.outbox[0]
        self.assertEqual(self.subscriber.email, email.to[0])

    def test_unsubscribe_link(self):
        """Check that unsubscribe link is in outgoing email."""
        email = mail.outbox[0]
        unsub_url = reverse(
            'unsubscribe',
            args=(self.subscriber.unsubscribe_hash, )
        )
        self.assertIn(unsub_url, email.alternatives[0][0])
<commit_msg>Updated DebugCase to use __init__()<commit_after>"""Test functions for deliver_cute project."""
from __future__ import unicode_literals, absolute_import

import random
from string import ascii_letters, digits
from itertools import product, chain
from django.test import TestCase
from django.core import mail
from django.core.urlresolvers import reverse
from nose_parameterized import parameterized

from on_schedule import fix_image_links
from constants import SUBREDDIT_NAMES, LIMIT, EMAIL, UNICODE
from tests.classes import (
    FakePost,
    SubscriberFactory,
    SubRedditFactory,
    BATCH_SIZE,
    BATCH_PARAMS,
    ATTR_PARAMS,
    # SUBR_BATCH_SIZE,
    # SUBR_PARAMS,
    SUBR_NAME_PARAMS,
)

# TODO
# test unicode status of incoming PRAW post objects
# test escaped HTML of outgoing html
#   test fix_urls
#       make some bad urls
#   test sort_urls
#   test subscribers_for_now

# edge cases:
#   unsorted
#   already sorted
#   no subscribers
#   no subreddits
#   no posts
#   bad links
#   limit 0
#   very high limit

CUTE_POSTS = []
FIXED_LINKS = list(fix_image_links(CUTE_POSTS))
SUBJECT = 'DEBUG'
TEXT = 'Plain text message.'
BODY = '''

Test Header

can't not apostrophe

'''

PROTO = ('http://', 'https://')
DOMAIN = ('i.imgur.com/', )
HASH = ''.join(random.sample(ascii_letters + digits, 8))
EXT = ('.jpg', '.gifv', '.gif', '.png', )

BAD_DOMAIN = ('www.imgur.com/', 'reddit.com/', 'gfycat.com/')
BAD_EXT = ('', )

GOOD_URLS = product(PROTO, DOMAIN, HASH, EXT)
BAD_URLS = product(PROTO, BAD_DOMAIN, HASH, BAD_EXT)

class EmailCase(TestCase):
    """Testing sending of email."""

    def setUp(self):
        """Send an email."""
        mail.send_mail(
            SUBJECT, TEXT, EMAIL, [EMAIL],
            html_message=BODY,
            fail_silently=False,
        )

    def test_outbox(self):
        """Test sending an email."""
        self.assertEqual(len(mail.outbox), 1)

    def test_subject(self):
        """Test sending an email."""
        email = mail.outbox[0]
        self.assertEqual(SUBJECT, email.subject)

class RedditAPICase(TestCase):
    """Test retrieval of posts from reddit API."""

    def setUp(self):
        """Get post data to test."""
        from on_schedule import create_post_map
        # test with different limits
        self.no_posts = create_post_map([], LIMIT)
        self.all_posts = create_post_map(SUBREDDIT_NAMES, LIMIT)

    def test_no_subreddits(self):
        """Confirm that zero subreddits returns an empty dictionary."""
        self.assertEqual(self.no_posts, {})

    def test_dictionary(self):
        """Confirm that given subreddits returns a dictionary."""
        self.assertIsInstance(self.all_posts, dict)

    # @parameterized.expand(SUBR_NAME_PARAMS)
    # def test_cute_posts(self, name):
    #     """Test that gathered posts have links."""
    #     for post in self.all_posts[name]:
    #         self.assertTrue(post.url.startswith('http'))

    # @parameterized.expand(SUBR_NAME_PARAMS)
    # def test_cute_posts_count(self, name):
    #     """Test that number of links is at or under the limit per subreddit."""
    #     self.assertLessEqual(len(self.all_posts[name]), LIMIT)

class FakePostsCase(TestCase):
    """Using fake posts to test unicode and html escaping."""

    def __init__(self, *args, **kwargs):
        """Initialize data groups."""
        from on_schedule import htmlize_posts
        super(FakePostsCase, self).__init__(*args, **kwargs)
        self.fake_posts = FakePost.create_batch(BATCH_SIZE)
        self.fake_post_attrs = list(chain(
            *((p.title, p.url, p.permalink, p.subreddit.display_name)
              for p in self.fake_posts)))
        self.htmlized_posts = list(htmlize_posts(self.fake_posts))
        self.duplicates = FakePost.create_batch_with_dupes(BATCH_SIZE)

    def setUp(self):
        """Set up fake_posts."""
        from on_schedule import get_email_body
        self.subscriber = SubscriberFactory.create(email=EMAIL)
        self.email_body = get_email_body(self.subscriber, self.htmlized_posts)

    @parameterized.expand(ATTR_PARAMS)
    def test_unicode_attrs(self, idx):
        """Ensure that all FakePost attributes are unicode."""
        attr = self.fake_post_attrs[idx]
        self.assertIsInstance(attr, UNICODE)

    @parameterized.expand(BATCH_PARAMS)
    def test_htmlize_unicode(self, idx):
        """Test that htmlize runs without breaking."""
        htmlized_post = self.htmlized_posts[idx]
        self.assertIsInstance(htmlized_post, UNICODE)

    @parameterized.expand(BATCH_PARAMS)
    def test_html_post_contains_title(self, idx):
        """Ensure that all FakePost attributes in htmlized version."""
        post = self.fake_posts[idx]
        htmlized_post = self.htmlized_posts[idx]
        self.assertIn(post.title, htmlized_post)

    @parameterized.expand(BATCH_PARAMS)
    def test_html_post_contains_url(self, idx):
        """Ensure that all FakePost attributes in htmlized version."""
        post = self.fake_posts[idx]
        htmlized_post = self.htmlized_posts[idx]
        self.assertIn(post.url, htmlized_post)

    @parameterized.expand(BATCH_PARAMS)
    def test_html_post_contains_permalink(self, idx):
        """Ensure that all FakePost attributes in htmlized version."""
        post = self.fake_posts[idx]
        htmlized_post = self.htmlized_posts[idx]
        self.assertIn(post.permalink, htmlized_post)

    @parameterized.expand(BATCH_PARAMS)
    def test_html_post_contains_subreddit(self, idx):
        """Ensure that all FakePost attributes in htmlized version."""
        post = self.fake_posts[idx]
        htmlized_post = self.htmlized_posts[idx]
        self.assertIn(post.subreddit.display_name, htmlized_post)

    @parameterized.expand(BATCH_PARAMS)
    def test_email_body_contains(self, idx):
        """Ensure that htmlized posts are contained by email body."""
        htmlized_post = self.htmlized_posts[idx]
        self.assertIn(htmlized_post, self.email_body)

    def test_email_body_unsub_link(self):
        """Ensure that all FakePost attributes are unicode."""
        hash_ = self.subscriber.unsubscribe_hash
        unsub_url = reverse('unsubscribe', args=(hash_, ))
        self.assertIn(unsub_url, self.email_body)

    def test_email_body_unicode(self):
        """Ensure that all FakePost attributes are unicode."""
        self.assertIsInstance(self.email_body, UNICODE)

    def test_dedupe_posts(self):
        """Test that urls of deduped posts is equal to set of those urls."""
        from on_schedule import dedupe_posts
        found = set()
        urls = [post.url for post in dedupe_posts(self.duplicates, found)]
        self.assertEqual(
            list(sorted(urls)),
            list(sorted(set(urls)))
        )

    # test html escaping by checking for &quot, \u2018 etc.

class CheckURLCase(TestCase):
    """Test URL matching regexes."""

    def setUp(self):
        """Get regex pattern."""
        from on_schedule import SRC_PAT
        self.regex = SRC_PAT

    @parameterized.expand((url, ) for url in GOOD_URLS)
    def test_src_pat_good(self, url):
        """Confirm that link regex works as expected for good urls."""
        self.assertIsNotNone(self.regex.match(''.join(url)))

    @parameterized.expand((url, ) for url in BAD_URLS)
    def test_src_pat_bad(self, url):
        """Confirm that link regex works as expected for bad urls."""
        self.assertIsNone(self.regex.match(''.join(url)))

    # def test_cute_links_source(fixed_link):
    #     """Confirm that links fixed by source fixer match the expected pattern."""
    #     assert self.regex.match(fixed_link.url) is not None

# @pytest.fixture(params=FIXED_LINKS)
# def fixed_link(request):
#     """Generate link fixed by having correct source url."""
#     return request.param

#

# def test_moonmoon():
#     """Test html escaping problems."""
#     import praw
#     from on_schedule import (
#         send_email,
#         htmlize_posts,
#         USER_AGENT,
#     )
#     reddit = praw.Reddit(user_agent=USER_AGENT)
#     moonmoon_post = reddit.get_submission(submission_id='4spncq')
#     body = '' + next(htmlize_posts((moonmoon_post, ))) + ''
#     send_email(WILL_EMAIL, WILL_EMAIL, [WILL_EMAIL], 'ESCAPE TEST', body)

class DebugCase(TestCase):
    """Run full on_schedule script in debug mode."""

    def __init__(self):
        from on_schedule import htmlize_posts
        super(DebugCase, self).__init__(*args, **kwargs)
        from on_schedule import main
        self.subreddits = SubRedditFactory.create_random_batch()
        self.subscriber = SubscriberFactory.create(email=EMAIL)
        self.subscriber.subreddits.add(*self.subreddits)
        self.result = main(True)

    def test_main(self):
        """Test the main() function of on_schedule.py in debug mode."""
        self.result = self.assertEqual(self.result, 1)

    def test_outbox(self):
        """Test sending an email."""
        self.assertEqual(len(mail.outbox), 1)

    def test_recipient(self):
        """Test sending an email."""
        email = mail.outbox[0]
        self.assertEqual(self.subscriber.email, email.to[0])

    def test_unsubscribe_link(self):
        """Check that unsubscribe link is in outgoing email."""
        email = mail.outbox[0]
        unsub_url = reverse(
            'unsubscribe',
            args=(self.subscriber.unsubscribe_hash, )
        )
        self.assertIn(unsub_url, email.alternatives[0][0])
<|endoftext|>


<commit_before>from mock import patch
from lxc4u.service import LXCService

def test_service_list_names():
    """Test list container names times"""
    tests = [
        ('lxc1\nlxc2\nlxc3\n', ['lxc1', 'lxc2', 'lxc3']),
        ('lxc4\nlxc5\n', ['lxc4', 'lxc5']),
        ('', []),
    ]
    for ls_str, expected in tests:
        yield do_service_list_names, ls_str, expected

@patch('subwrap.run')
def do_service_list_names(ls_str, expected, mock_run):
    # Setup Mocks
    mock_resp = mock_run.return_value
    mock_resp.std_out = ls_str
    mock_resp.has_attr(std_out=ls_str)

    # Run Test
    lxc_list = LXCService.list_names()

    # Assertions
    mock_run.assert_called_with(['lxc-ls'])
    assert lxc_list == expected

@patch('subwrap.run')
def test_service_create(mock_run):
    LXCService.create('something')
    mock_run.assert_any_calls()

@patch('subwrap.run')
def test_service_start(mock_run):
    LXCService.start('something')
    mock_run.assert_any_calls()

@patch('subwrap.run')
def test_service_stop(mock_run):
    LXCService.stop('something')
    mock_run.assert_any_calls()

@patch('subwrap.run')
def test_service_destroy(mock_run):
    LXCService.destroy('something')
    mock_run.assert_any_calls()

def test_service_info():
    tests = [
        ("state:   RUNNING\npid:    12345", {"state": "RUNNING", "pid": "12345"}),
        ("state:   STOPPED\npid:    -1", {"state": "STOPPED", "pid": "-1"}),
    ]
    for info_str, expected in tests:
        yield do_service_info, info_str, expected

@patch('subwrap.run')
def do_service_info(info_str, expected, mock_run):
    # Setup Mocks
    mock_resp = mock_run.return_value
    mock_resp.std_out = info_str

    # Run Test
    info = LXCService.info("something")

    # Assertions
    assert info == expected

@patch('subwrap.run')
def test_service_lxc_path(mock_run):
    mock_resp = mock_run.returnG_value
    mock_resp.std_out = '/var/lib/lxc\n'

    assert LXCService.lxc_path() == '/var/lib/lxc'
    assert LXCService.lxc_path('hello') == '/var/lib/lxc/hello'
<commit_msg>Typo Fix<commit_after>from mock import patch
from lxc4u.service import LXCService

def test_service_list_names():
    """Test list container names times"""
    tests = [
        ('lxc1\nlxc2\nlxc3\n', ['lxc1', 'lxc2', 'lxc3']),
        ('lxc4\nlxc5\n', ['lxc4', 'lxc5']),
        ('', []),
    ]
    for ls_str, expected in tests:
        yield do_service_list_names, ls_str, expected

@patch('subwrap.run')
def do_service_list_names(ls_str, expected, mock_run):
    # Setup Mocks
    mock_resp = mock_run.return_value
    mock_resp.std_out = ls_str
    mock_resp.has_attr(std_out=ls_str)

    # Run Test
    lxc_list = LXCService.list_names()

    # Assertions
    mock_run.assert_called_with(['lxc-ls'])
    assert lxc_list == expected

@patch('subwrap.run')
def test_service_create(mock_run):
    LXCService.create('something')
    mock_run.assert_any_calls()

@patch('subwrap.run')
def test_service_start(mock_run):
    LXCService.start('something')
    mock_run.assert_any_calls()

@patch('subwrap.run')
def test_service_stop(mock_run):
    LXCService.stop('something')
    mock_run.assert_any_calls()

@patch('subwrap.run')
def test_service_destroy(mock_run):
    LXCService.destroy('something')
    mock_run.assert_any_calls()

def test_service_info():
    tests = [
        ("state:   RUNNING\npid:    12345", {"state": "RUNNING", "pid": "12345"}),
        ("state:   STOPPED\npid:    -1", {"state": "STOPPED", "pid": "-1"}),
    ]
    for info_str, expected in tests:
        yield do_service_info, info_str, expected

@patch('subwrap.run')
def do_service_info(info_str, expected, mock_run):
    # Setup Mocks
    mock_resp = mock_run.return_value
    mock_resp.std_out = info_str

    # Run Test
    info = LXCService.info("something")

    # Assertions
    assert info == expected

@patch('subwrap.run')
def test_service_lxc_path(mock_run):
    mock_resp = mock_run.return_value
    mock_resp.std_out = '/var/lib/lxc\n'

    assert LXCService.lxc_path() == '/var/lib/lxc'
    assert LXCService.lxc_path('hello') == '/var/lib/lxc/hello'
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
"""
    tests.serving
    ~~~~~~~~~~~~~

    Added serving tests.

    :copyright: (c) 2014 by Armin Ronacher.
    :license: BSD, see LICENSE for more details.
"""
import os
import ssl
import textwrap

try:
    import httplib
except ImportError:
    from http import client as httplib
try:
    from urllib2 import urlopen, HTTPError
except ImportError:  # pragma: no cover
    from urllib.request import urlopen
    from urllib.error import HTTPError

try:
    import OpenSSL
except ImportError:
    OpenSSL = None

import pytest

from werkzeug import __version__ as version, serving

def test_serving(dev_server):
    server = dev_server('from werkzeug.testapp import test_app as app')
    rv = urlopen('http://%s/?foo=bar&baz=blah' % server.addr).read()
    assert b'WSGI Information' in rv
    assert b'foo=bar&baz=blah' in rv
    assert b'Werkzeug/' + version.encode('ascii') in rv

def test_broken_app(dev_server):
    server = dev_server('''
    def app(environ, start_response):
        1 // 0
    ''')

    with pytest.raises(HTTPError) as excinfo:
        urlopen(server.url + '/?foo=bar&baz=blah').read()

    rv = excinfo.value.read()
    assert b'Internal Server Error' in rv

def test_absolute_requests(dev_server):
    server = dev_server('''
    def app(environ, start_response):
        assert environ['HTTP_HOST'] == 'surelynotexisting.example.com:1337'
        assert environ['PATH_INFO'] == '/index.htm'
        addr = environ['HTTP_X_WERKZEUG_ADDR']
        assert environ['SERVER_PORT'] == addr.split(':')[1]
        start_response('200 OK', [('Content-Type', 'text/html')])
        return [b'YES']
    ''')

    conn = httplib.HTTPConnection(server.addr)
    conn.request('GET', 'http://surelynotexisting.example.com:1337/index.htm',
                 headers={'X-Werkzeug-Addr': server.addr})
    res = conn.getresponse()
    assert res.read() == b'YES'

@pytest.mark.skipif(not hasattr(ssl, 'SSLContext'),
                    reason='Missing PEP 466 (Python 2.7.9+) or Python 3.')
@pytest.mark.skipif(OpenSSL is None,
                    reason='OpenSSL is required for cert generation.')
def test_stdlib_ssl_contexts(dev_server, tmpdir):
    certificate, private_key = \
        serving.make_ssl_devcert(str(tmpdir.mkdir('certs')))

    server = dev_server('''
    def app(environ, start_response):
        start_response('200 OK', [('Content-Type', 'text/html')])
        return [b'hello']

    import ssl
    ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
    ctx.load_cert_chain("%s", "%s")
    kwargs['ssl_context'] = ctx
    ''' % (certificate, private_key))

    assert server.addr is not None
    connection = httplib.HTTPSConnection(server.addr)
    connection.request('GET', '/')
    response = connection.getresponse()
    assert response.read() == b'hello'

@pytest.mark.skipif(OpenSSL is None, reason='OpenSSL is not installed.')
def test_ssl_context_adhoc(dev_server):
    server = dev_server('''
    def app(environ, start_response):
        start_response('200 OK', [('Content-Type', 'text/html')])
        return [b'hello']

    kwargs['ssl_context'] = 'adhoc'
    ''')
    connection = httplib.HTTPSConnection(server.addr)
    connection.request('GET', '/')
    response = connection.getresponse()
    assert response.read() == b'hello'

@pytest.mark.skipif(OpenSSL is None, reason='OpenSSL is not installed.')
def test_make_ssl_devcert(tmpdir):
    certificate, private_key = \
        serving.make_ssl_devcert(str(tmpdir))
    assert os.path.isfile(certificate)
    assert os.path.isfile(private_key)

def test_reloader_broken_imports(tmpdir, dev_server):
    server = dev_server('''
    def app(environ, start_response):
        import real_app
        return real_app.real_app(environ, start_response)

    kwargs['use_reloader'] = True
    ''')

    assert any('app.py' in str(x) for x in tmpdir.listdir())
    tmpdir.join('real_app.py').write("lol syntax error")
    connection = httplib.HTTPConnection(server.addr)
    connection.request('GET', '/')
    response = connection.getresponse()
    assert response.status == 500

    tmpdir.join('real_app.py').write(textwrap.dedent('''
    def real_app(environ, start_response):
        start_response('200 OK', [('Content-Type', 'text/html')])
        return [b'hello']
    '''))
    connection.request('GET', '/')
    response = connection.getresponse()
    assert response.status == 200
    assert response.read() == b'hello'
<commit_msg>Add testcase for #203<commit_after># -*- coding: utf-8 -*-
"""
    tests.serving
    ~~~~~~~~~~~~~

    Added serving tests.

    :copyright: (c) 2014 by Armin Ronacher.
    :license: BSD, see LICENSE for more details.
"""
import os
import ssl
import textwrap

try:
    import httplib
except ImportError:
    from http import client as httplib
try:
    from urllib2 import urlopen, HTTPError
except ImportError:  # pragma: no cover
    from urllib.request import urlopen
    from urllib.error import HTTPError

try:
    import OpenSSL
except ImportError:
    OpenSSL = None

import pytest

from werkzeug import __version__ as version, serving

def test_serving(dev_server):
    server = dev_server('from werkzeug.testapp import test_app as app')
    rv = urlopen('http://%s/?foo=bar&baz=blah' % server.addr).read()
    assert b'WSGI Information' in rv
    assert b'foo=bar&baz=blah' in rv
    assert b'Werkzeug/' + version.encode('ascii') in rv

def test_broken_app(dev_server):
    server = dev_server('''
    def app(environ, start_response):
        1 // 0
    ''')

    with pytest.raises(HTTPError) as excinfo:
        urlopen(server.url + '/?foo=bar&baz=blah').read()

    rv = excinfo.value.read()
    assert b'Internal Server Error' in rv

def test_absolute_requests(dev_server):
    server = dev_server('''
    def app(environ, start_response):
        assert environ['HTTP_HOST'] == 'surelynotexisting.example.com:1337'
        assert environ['PATH_INFO'] == '/index.htm'
        addr = environ['HTTP_X_WERKZEUG_ADDR']
        assert environ['SERVER_PORT'] == addr.split(':')[1]
        start_response('200 OK', [('Content-Type', 'text/html')])
        return [b'YES']
    ''')

    conn = httplib.HTTPConnection(server.addr)
    conn.request('GET', 'http://surelynotexisting.example.com:1337/index.htm#ignorethis',
                 headers={'X-Werkzeug-Addr': server.addr})
    res = conn.getresponse()
    assert res.read() == b'YES'

@pytest.mark.skipif(not hasattr(ssl, 'SSLContext'),
                    reason='Missing PEP 466 (Python 2.7.9+) or Python 3.')
@pytest.mark.skipif(OpenSSL is None,
                    reason='OpenSSL is required for cert generation.')
def test_stdlib_ssl_contexts(dev_server, tmpdir):
    certificate, private_key = \
        serving.make_ssl_devcert(str(tmpdir.mkdir('certs')))

    server = dev_server('''
    def app(environ, start_response):
        start_response('200 OK', [('Content-Type', 'text/html')])
        return [b'hello']

    import ssl
    ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
    ctx.load_cert_chain("%s", "%s")
    kwargs['ssl_context'] = ctx
    ''' % (certificate, private_key))

    assert server.addr is not None
    connection = httplib.HTTPSConnection(server.addr)
    connection.request('GET', '/')
    response = connection.getresponse()
    assert response.read() == b'hello'

@pytest.mark.skipif(OpenSSL is None, reason='OpenSSL is not installed.')
def test_ssl_context_adhoc(dev_server):
    server = dev_server('''
    def app(environ, start_response):
        start_response('200 OK', [('Content-Type', 'text/html')])
        return [b'hello']

    kwargs['ssl_context'] = 'adhoc'
    ''')
    connection = httplib.HTTPSConnection(server.addr)
    connection.request('GET', '/')
    response = connection.getresponse()
    assert response.read() == b'hello'

@pytest.mark.skipif(OpenSSL is None, reason='OpenSSL is not installed.')
def test_make_ssl_devcert(tmpdir):
    certificate, private_key = \
        serving.make_ssl_devcert(str(tmpdir))
    assert os.path.isfile(certificate)
    assert os.path.isfile(private_key)

def test_reloader_broken_imports(tmpdir, dev_server):
    server = dev_server('''
    def app(environ, start_response):
        import real_app
        return real_app.real_app(environ, start_response)

    kwargs['use_reloader'] = True
    ''')

    assert any('app.py' in str(x) for x in tmpdir.listdir())
    tmpdir.join('real_app.py').write("lol syntax error")
    connection = httplib.HTTPConnection(server.addr)
    connection.request('GET', '/')
    response = connection.getresponse()
    assert response.status == 500

    tmpdir.join('real_app.py').write(textwrap.dedent('''
    def real_app(environ, start_response):
        start_response('200 OK', [('Content-Type', 'text/html')])
        return [b'hello']
    '''))
    connection.request('GET', '/')
    response = connection.getresponse()
    assert response.status == 200
    assert response.read() == b'hello'
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
"""
test run for debugging the small dt/tolerance bug

Created on Thu Feb 27 14:44:03 2020

@author: reint fischer
"""

# Local Parcels path for Reint
# import sys
#
# sys.path.insert(0, "\\Users\\Gebruiker\\Documents\\GitHub\\parcels\\")  # Set path to find the newest parcels code

from parcels import FieldSet, ParticleSet, JITParticle, AdvectionRK4, ErrorCode
import numpy as np
from datetime import timedelta
from os import path
import pytest

### Functions ###

@pytest.mark.parametrize('mode', ['scipy', 'jit'])
@pytest.mark.parametrize('dt', [0.002, -0.002, 0.004,  -0.004, 0.01, -0.01, 1.0, -1.0])
def test_consistent_time_accumulation(mode, dt):
    def deleteparticle(particle, fieldset, time):
        """ This function deletes particles as they exit the domain and prints a message about their attributes at that moment
        """
        print('Particle '+str(particle.id)+' has died at t = '+str(time)+' at lon, lat, depth = '+str(particle.lon)+', '+str(particle.lat)+', '+str(particle.depth))
        particle.delete()

    outputdt = timedelta(seconds=0.1)  # make this a parameter if the test result differs depending on this parameter value
    runtime = timedelta(seconds=1.5)   # make this a parameter if the test result differs depending on this parameter value
    datafile = path.join(path.dirname(__file__), 'test_data', 'dt_field')

    fieldset = FieldSet.from_parcels(datafile, allow_time_extrapolation=True)
    lon = fieldset.U.lon
    lat = fieldset.U.lat

    lons, lats = np.meshgrid(lon, lat)  # meshgrid at all gridpoints in the flow data
    lons = lons.flatten()
    lats = lats.flatten()
    inittime = np.asarray([0] * len(lons))

    pset = ParticleSet(fieldset=fieldset, pclass=JITParticle, lon=lons, lat=lats, time=inittime)
    output_file = pset.ParticleFile(name='TEST1', outputdt=outputdt)

    pset.execute(AdvectionRK4,
                     runtime=runtime,
                     dt=timedelta(seconds=dt),
                     recovery={ErrorCode.ErrorOutOfBounds: deleteparticle},
                     output_file=output_file)

    output_file.close()<commit_msg>#762 - disabled testing for now for test_smalldt until reint commits error checks<commit_after># -*- coding: utf-8 -*-
"""
test run for debugging the small dt/tolerance bug

Created on Thu Feb 27 14:44:03 2020

@author: reint fischer
"""

# Local Parcels path for Reint
# import sys
#
# sys.path.insert(0, "\\Users\\Gebruiker\\Documents\\GitHub\\parcels\\")  # Set path to find the newest parcels code

from parcels import FieldSet, ParticleSet, JITParticle, AdvectionRK4, ErrorCode
import numpy as np
from datetime import timedelta
from os import path
import pytest

### Functions ###

@pytest.mark.parametrize('mode', ['scipy', 'jit'])
@pytest.mark.parametrize('dt', [0.002, -0.002, 0.004,  -0.004, 0.01, -0.01, 1.0, -1.0])
def test_consistent_time_accumulation(mode, dt):
    def deleteparticle(particle, fieldset, time):
        """ This function deletes particles as they exit the domain and prints a message about their attributes at that moment
        """
        print('Particle '+str(particle.id)+' has died at t = '+str(time)+' at lon, lat, depth = '+str(particle.lon)+', '+str(particle.lat)+', '+str(particle.depth))
        particle.delete()

    outputdt = timedelta(seconds=0.1)  # make this a parameter if the test result differs depending on this parameter value
    runtime = timedelta(seconds=1.5)   # make this a parameter if the test result differs depending on this parameter value
    datafile = path.join(path.dirname(__file__), 'test_data', 'dt_field')

    fieldset = FieldSet.from_parcels(datafile, allow_time_extrapolation=True)
    lon = fieldset.U.lon
    lat = fieldset.U.lat

    lons, lats = np.meshgrid(lon, lat)  # meshgrid at all gridpoints in the flow data
    lons = lons.flatten()
    lats = lats.flatten()
    inittime = np.asarray([0] * len(lons))

    #pset = ParticleSet(fieldset=fieldset, pclass=JITParticle, lon=lons, lat=lats, time=inittime)
    #output_file = pset.ParticleFile(name='TEST1', outputdt=outputdt)
    #pset.execute(AdvectionRK4, runtime=runtime, dt=timedelta(seconds=dt), recovery={ErrorCode.ErrorOutOfBounds: deleteparticle}, output_file=output_file)
    #output_file.close()<|endoftext|>


<commit_before>version = '1.3.0'
<commit_msg>Bump version.<commit_after>version = '1.3.1'
<|endoftext|>


<commit_before>from django.utils.version import get_version

VERSION = (2, 0, 2, 'final', 0)

__version__ = get_version(VERSION)
<commit_msg>Bump to 2.0.3<commit_after>from django.utils.version import get_version

VERSION = (2, 0, 3, 'final', 0)

__version__ = get_version(VERSION)
<|endoftext|>


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

from oled.device import ssd1306
from oled.render import canvas

import mock
import baseline_data

port = 1
bus = mock.smbus(port)
addr = 0x3C

def teardown_function(function):
    bus.reset()

def test_init():
    ssd1306(bus)
    assert len(bus.recordings) == 35
    # Bursts 0/1 are initialization commands
    cmds = [174, 213, 128, 168, 63, 211, 0, 64, 141, 20, 32, 0,
            160, 200, 218, 18, 129, 207, 217, 241, 219, 64, 164,
            166, 33, 0, 127, 34, 0, 7]
    assert bus.recordings[0].mode == 0
    assert bus.recordings[1].mode == 0
    assert bus.recordings[0].data + bus.recordings[1].data == cmds

    # Next 32 bursts are all data: zero's to clear the RAM
    # (32 * 32 = 1024 = 128 * 64 / 8)
    for i in range(32):
        assert bus.recordings[i + 2] == mock.recording(60, 64, [0] * 32)

    # Last burst is a command to show the screen
    assert bus.recordings[34] == mock.recording(60, 0, [175])

def test_hide():
    device = ssd1306(bus)
    bus.reset()
    device.hide()
    assert len(bus.recordings) == 1
    assert bus.recordings[0] == mock.recording(60, 0, [174])

def test_show():
    device = ssd1306(bus)
    bus.reset()
    device.show()
    assert len(bus.recordings) == 1
    assert bus.recordings[0] == mock.recording(60, 0, [175])

def test_diplay():
    device = ssd1306(bus)
    bus.reset()

    # Use the same drawing primitives as the demo
    with canvas(device) as draw:
        baseline_data.primitives(device, draw)

    assert len(bus.recordings) == 33

    # Initial command to reset the display
    assert bus.recordings[0] == mock.recording(60, 0, [33, 0, 127, 34, 0, 7])

    # Next 32 recordings are data representing the drawn image
    for i in range(32):
        assert bus.recordings[i + 1] == baseline_data.demo_ssd1306[i]
<commit_msg>Fix spelling<commit_after>#!/usr/bin/env python

from oled.device import ssd1306
from oled.render import canvas

import mock
import baseline_data

port = 1
bus = mock.smbus(port)
addr = 0x3C

def teardown_function(function):
    bus.reset()

def test_init():
    ssd1306(bus)
    assert len(bus.recordings) == 35
    # Bursts 0/1 are initialization commands
    cmds = [174, 213, 128, 168, 63, 211, 0, 64, 141, 20, 32, 0,
            160, 200, 218, 18, 129, 207, 217, 241, 219, 64, 164,
            166, 33, 0, 127, 34, 0, 7]
    assert bus.recordings[0].mode == 0
    assert bus.recordings[1].mode == 0
    assert bus.recordings[0].data + bus.recordings[1].data == cmds

    # Next 32 bursts are all data: zero's to clear the RAM
    # (32 * 32 = 1024 = 128 * 64 / 8)
    for i in range(32):
        assert bus.recordings[i + 2] == mock.recording(60, 64, [0] * 32)

    # Last burst is a command to show the screen
    assert bus.recordings[34] == mock.recording(60, 0, [175])

def test_hide():
    device = ssd1306(bus)
    bus.reset()
    device.hide()
    assert len(bus.recordings) == 1
    assert bus.recordings[0] == mock.recording(60, 0, [174])

def test_show():
    device = ssd1306(bus)
    bus.reset()
    device.show()
    assert len(bus.recordings) == 1
    assert bus.recordings[0] == mock.recording(60, 0, [175])

def test_display():
    device = ssd1306(bus)
    bus.reset()

    # Use the same drawing primitives as the demo
    with canvas(device) as draw:
        baseline_data.primitives(device, draw)

    assert len(bus.recordings) == 33

    # Initial command to reset the display
    assert bus.recordings[0] == mock.recording(60, 0, [33, 0, 127, 34, 0, 7])

    # Next 32 recordings are data representing the drawn image
    for i in range(32):
        assert bus.recordings[i + 1] == baseline_data.demo_ssd1306[i]
<|endoftext|>


<commit_before>"""
    Copyright (C) 2016-2022 Kerygma Digital Co.

    This Source Code Form is subject to the terms of the Mozilla Public
    License, v. 2.0. If a copy of the MPL was not distributed with this file,
    You can obtain one at https://mozilla.org/MPL/2.0/.
"""

import os
import requests
import disnake
from logger import VyLogger
from http.client import HTTPConnection
import logging

from Paginator import CreatePaginator

logger = VyLogger("default")
logging.getLogger("urllib3").setLevel(logging.CRITICAL)
logging.getLogger("requests").setLevel(logging.CRITICAL)

async def submit_command(
    rch: disnake.abc.Messageable, user: disnake.abc.User, body: str
):
    ch = await rch._get_channel()

    isDM = ch.type == disnake.ChannelType.private
    guildId = ch.id if isDM else user.id

    reqbody = {
        "UserId": str(user.id),
        "GuildId": str(guildId),
        "IsDM": isDM,
        "Body": body,
        "Token": os.environ.get("ENDPOINT_TOKEN"),
    }

    endpoint = os.environ.get("ENDPOINT")
    resp = requests.post(f"{endpoint}/commands/process", json=reqbody)

    if resp.json()["type"] == "cmd":
        if resp.json()["ok"]:
            logger.info(f"<{user.id}#{ch.id}@{guildId}> " + resp.json()["logStatement"])
        else:
            logger.error(
                f"<{user.id}#{ch.id}@{guildId}> " + resp.json()["logStatement"]
            )

        if len(resp.json()["pages"]) == 1:
            # todo: webhook stuff should not be dailyverse-specific
            if resp.json()["removeWebhook"] and not isDM:
                try:
                    webhooks = await ch.guild.webhooks()

                    for webhook in webhooks:
                        if webhook.user.id == ch.guild.me.id:
                            await webhook.delete(
                                reason=f"User ID {user.id} performed a command that removes BibleBot-related webhooks."
                            )
                except disnake.errors.Forbidden:
                    await ch.send(
                        embed=create_error_embed(
                            "/dailyverseset",
                            "I was unable to remove our existing webhooks for this server. I need the **`Manage Webhooks`** permission to manage automatic daily verses.",
                        )
                    )

            if resp.json()["createWebhook"] and not isDM:
                try:
                    # Unlike other libraries, we have to convert an
                    # image into bytes to pass as the webhook avatar.
                    with open("./data/avatar.png", "rb") as image:
                        webhook = await ch.create_webhook(
                            name="BibleBot Automatic Daily Verses",
                            avatar=bytearray(image.read()),
                            reason="For automatic daily verses from BibleBot.",
                        )

                    # Send a request to the webhook controller, which will update the DB.
                    reqbody["Body"] = f"{webhook.id}/{webhook.token}||{ch.id}"
                    requests.post(f"{endpoint}/webhooks/process", json=reqbody)

                    return convert_embed(resp.json()["pages"][0])
                except disnake.errors.Forbidden:
                    await ch.send(
                        embed=create_error_embed(
                            "/dailyverseset",
                            "I was unable to create a webhook for this channel. I need the **`Manage Webhooks`** permission to enable automatic daily verses.",
                        )
                    )

            return convert_embed(resp.json()["pages"][0])
        else:
            return create_pagination_embeds_from_pages(resp.json()["pages"])
    elif resp.json()["type"] == "verse":
        if "does not support the" in resp.json()["logStatement"]:
            return create_error_embed("Verse Error", resp.json()["logStatement"])

        display_style = resp.json()["displayStyle"]
        if display_style == "embed":
            for verse in resp.json()["verses"]:
                return create_embed_from_verse(verse)
        elif display_style == "blockquote":
            for verse in resp.json()["verses"]:
                reference_title = (
                    verse["reference"]["asString"]
                    + " - "
                    + verse["reference"]["version"]["name"]
                )
                verse_title = (
                    ("**" + verse["title"] + "**\n> \n> ")
                    if len(verse["title"]) > 0
                    else ""
                )
                verse_text = verse["text"]

                return f"**{reference_title}**\n\n> {verse_title}{verse_text}"
        elif display_style == "code":
            for verse in resp.json()["verses"]:
                reference_title = (
                    verse["reference"]["asString"]
                    + " - "
                    + verse["reference"]["version"]["name"]
                )
                verse_title = (
                    (verse["title"] + "\n\n") if len(verse["title"]) > 0 else ""
                )
                verse_text = verse["text"].replace("*", "")

                return (
                    f"**{reference_title}**\n\n```json\n{verse_title} {verse_text}```"
                )

async def submit_command_raw(
    rch: disnake.abc.Messageable, user: disnake.abc.User, body: str
):
    ch = await rch._get_channel()

    isDM = ch.type == disnake.ChannelType.private
    guildId = ch.id if isDM else user.id

    reqbody = {
        "UserId": str(user.id),
        "GuildId": str(guildId),
        "IsDM": isDM,
        "Body": body,
        "Token": os.environ.get("ENDPOINT_TOKEN"),
    }

    endpoint = os.environ.get("ENDPOINT")
    resp = requests.post(f"{endpoint}/commands/process", json=reqbody)

    return resp.json()

async def submit_verse(rch: disnake.abc.Messageable, user: disnake.abc.User, body: str):
    ch = await rch._get_channel()

    isDM = ch.type == disnake.ChannelType.private
    guildId = ch.id if isDM else user.id

    reqbody = {
        "UserId": str(user.id),
        "GuildId": str(guildId),
        "IsDM": isDM,
        "Body": body,
        "Token": os.environ.get("ENDPOINT_TOKEN"),
    }

    endpoint = os.environ.get("ENDPOINT")
    resp = requests.post(f"{endpoint}/verses/process", json=reqbody)

    if resp.json()["logStatement"]:
        logger.info(f"<{user.id}#{ch.id}@{guildId}> " + resp.json()["logStatement"])

    if "does not support the" in resp.json()["logStatement"]:
        await ch.send(
            embed=create_error_embed("Verse Error", resp.json()["logStatement"])
        )
        return

    display_style = resp.json()["displayStyle"]
    if display_style == "embed":
        if resp.json()["paginate"] and len(resp.json()["verses"]) > 1:
            embeds = create_pagination_embeds_from_verses(resp.json()["verses"])
            paginator = CreatePaginator(embeds, user.id, 180)

            await ch.send(embed=embeds[0], view=paginator)
        else:
            for verse in resp.json()["verses"]:
                await ch.send(embed=create_embed_from_verse(verse))
    elif display_style == "blockquote":
        for verse in resp.json()["verses"]:
            reference_title = (
                verse["reference"]["asString"]
                + " - "
                + verse["reference"]["version"]["name"]
            )
            verse_title = (
                ("**" + verse["title"] + "**\n> \n> ")
                if len(verse["title"]) > 0
                else ""
            )
            verse_text = verse["text"]

            await ch.send(f"**{reference_title}**\n\n> {verse_title}{verse_text}")
    elif display_style == "code":
        for verse in resp.json()["verses"]:
            reference_title = (
                verse["reference"]["asString"]
                + " - "
                + verse["reference"]["version"]["name"]
            )
            verse_title = (verse["title"] + "\n\n") if len(verse["title"]) > 0 else ""
            verse_text = verse["text"].replace("*", "")

            await ch.send(
                f"**{reference_title}**\n\n```json\n{verse_title} {verse_text}```"
            )

def convert_embed(internal_embed):
    embed = disnake.Embed()

    embed.title = internal_embed["title"]
    embed.description = internal_embed["description"]
    embed.url = internal_embed["url"]
    embed.color = internal_embed["color"]

    if internal_embed["fields"] is not None:
        for field in internal_embed["fields"]:
            embed.add_field(
                name=field["name"], value=field["value"], inline=field["inline"]
            )

    embed.set_footer(
        text=internal_embed["footer"]["text"],
        icon_url=internal_embed["footer"]["icon_url"],
    )

    return embed

def create_embed_from_verse(verse):
    embed = disnake.Embed()

    reference_title = (
        verse["reference"]["asString"] + " - " + verse["reference"]["version"]["name"]
    )

    embed.set_author(name=reference_title)
    embed.title = verse["title"]
    embed.description = verse["text"]
    embed.color = 6709986

    embed.set_footer(
        text="BibleBot v9.2-beta by Kerygma Digital",
        icon_url="https://i.imgur.com/hr4RXpy.png",
    )

    return embed

def create_error_embed(title, description):
    embed = disnake.Embed()

    embed.title = title
    embed.description = description
    embed.color = 16723502

    embed.set_footer(
        text="BibleBot v9.2-beta by Kerygma Digital",
        icon_url="https://i.imgur.com/hr4RXpy.png",
    )

    return embed

def create_pagination_embeds_from_pages(pages):
    embeds = []
    starting_page = None

    # For whatever reason, the paginator library has the buttons
    # performing the opposite effect, "next" goes to the previous
    # page and vice versa. This reverses the array and makes sure
    # the first page is properly the first embed, which is still a
    # requirement despite the paginator working backwards.
    #
    # I could fix this myself by forking the library
    # (it's a two-line fix), but I'm too lazy for that.
    for page in pages[::-1]:
        page_embed = convert_embed(page)

        if f"Page 1 of" in page_embed.title:
            starting_page = page_embed
        else:
            embeds.append(page_embed)

    if starting_page == None:
        starting_page = embeds.pop()

    embeds.insert(0, starting_page)

    return embeds

def create_pagination_embeds_from_verses(verses):
    embeds = []
    starting_verse = None

    # For whatever reason, the paginator library has the buttons
    # performing the opposite effect, "next" goes to the previous
    # page and vice versa. This reverses the array and makes sure
    # the first page is properly the first embed, which is still a
    # requirement despite the paginator working backwards.
    #
    # I could fix this myself by forking the library
    # (it's a two-line fix), but I'm too lazy for that.
    for verse in verses[::-1]:
        verse_embed = create_embed_from_verse(verse)

        if verse == verses[-1]:
            starting_verse = verse_embed
        else:
            embeds.append(verse_embed)

    embeds.insert(0, starting_verse)

    return embeds
<commit_msg>Fix more quirks.<commit_after>"""
    Copyright (C) 2016-2022 Kerygma Digital Co.

    This Source Code Form is subject to the terms of the Mozilla Public
    License, v. 2.0. If a copy of the MPL was not distributed with this file,
    You can obtain one at https://mozilla.org/MPL/2.0/.
"""

import os
import requests
import disnake
from logger import VyLogger
from http.client import HTTPConnection
import logging

from Paginator import CreatePaginator

logger = VyLogger("default")
logging.getLogger("urllib3").setLevel(logging.CRITICAL)
logging.getLogger("requests").setLevel(logging.CRITICAL)
HTTPConnection.debuglevel = 0

async def submit_command(
    rch: disnake.abc.Messageable, user: disnake.abc.User, body: str
):
    ch = await rch._get_channel()

    isDM = ch.type == disnake.ChannelType.private
    guildId = ch.id if isDM else user.id

    reqbody = {
        "UserId": str(user.id),
        "GuildId": str(guildId),
        "IsDM": isDM,
        "Body": body,
        "Token": os.environ.get("ENDPOINT_TOKEN"),
    }

    endpoint = os.environ.get("ENDPOINT")
    resp = requests.post(f"{endpoint}/commands/process", json=reqbody)

    if resp.json()["type"] == "cmd":
        if resp.json()["ok"]:
            logger.info(f"<{user.id}#{ch.id}@{guildId}> " + resp.json()["logStatement"])
        else:
            logger.error(
                f"<{user.id}#{ch.id}@{guildId}> " + resp.json()["logStatement"]
            )

        if len(resp.json()["pages"]) == 1:
            # todo: webhook stuff should not be dailyverse-specific
            if resp.json()["removeWebhook"] and not isDM:
                try:
                    webhooks = await ch.guild.webhooks()

                    for webhook in webhooks:
                        if webhook.user.id == ch.guild.me.id:
                            await webhook.delete(
                                reason=f"User ID {user.id} performed a command that removes BibleBot-related webhooks."
                            )
                except disnake.errors.Forbidden:
                    await ch.send(
                        embed=create_error_embed(
                            "/dailyverseset",
                            "I was unable to remove our existing webhooks for this server. I need the **`Manage Webhooks`** permission to manage automatic daily verses.",
                        )
                    )

            if resp.json()["createWebhook"] and not isDM:
                try:
                    # Unlike other libraries, we have to convert an
                    # image into bytes to pass as the webhook avatar.
                    with open("./data/avatar.png", "rb") as image:
                        webhook = await ch.create_webhook(
                            name="BibleBot Automatic Daily Verses",
                            avatar=bytearray(image.read()),
                            reason="For automatic daily verses from BibleBot.",
                        )

                    # Send a request to the webhook controller, which will update the DB.
                    reqbody["Body"] = f"{webhook.id}/{webhook.token}||{ch.id}"
                    requests.post(f"{endpoint}/webhooks/process", json=reqbody)

                    return convert_embed(resp.json()["pages"][0])
                except disnake.errors.Forbidden:
                    await ch.send(
                        embed=create_error_embed(
                            "/dailyverseset",
                            "I was unable to create a webhook for this channel. I need the **`Manage Webhooks`** permission to enable automatic daily verses.",
                        )
                    )

            return convert_embed(resp.json()["pages"][0])
        else:
            return create_pagination_embeds_from_pages(resp.json()["pages"])
    elif resp.json()["type"] == "verse":
        if "does not support the" in resp.json()["logStatement"]:
            return create_error_embed("Verse Error", resp.json()["logStatement"])

        display_style = resp.json()["displayStyle"]
        if display_style == "embed":
            for verse in resp.json()["verses"]:
                return create_embed_from_verse(verse)
        elif display_style == "blockquote":
            for verse in resp.json()["verses"]:
                reference_title = (
                    verse["reference"]["asString"]
                    + " - "
                    + verse["reference"]["version"]["name"]
                )
                verse_title = (
                    ("**" + verse["title"] + "**\n> \n> ")
                    if len(verse["title"]) > 0
                    else ""
                )
                verse_text = verse["text"]

                return f"**{reference_title}**\n\n> {verse_title}{verse_text}"
        elif display_style == "code":
            for verse in resp.json()["verses"]:
                reference_title = (
                    verse["reference"]["asString"]
                    + " - "
                    + verse["reference"]["version"]["name"]
                )
                verse_title = (
                    (verse["title"] + "\n\n") if len(verse["title"]) > 0 else ""
                )
                verse_text = verse["text"].replace("*", "")

                return (
                    f"**{reference_title}**\n\n```json\n{verse_title} {verse_text}```"
                )

async def submit_command_raw(
    rch: disnake.abc.Messageable, user: disnake.abc.User, body: str
):
    ch = await rch._get_channel()

    isDM = ch.type == disnake.ChannelType.private
    guildId = ch.id if isDM else user.id

    reqbody = {
        "UserId": str(user.id),
        "GuildId": str(guildId),
        "IsDM": isDM,
        "Body": body,
        "Token": os.environ.get("ENDPOINT_TOKEN"),
    }

    endpoint = os.environ.get("ENDPOINT")
    resp = requests.post(f"{endpoint}/commands/process", json=reqbody)

    return resp.json()

async def submit_verse(rch: disnake.abc.Messageable, user: disnake.abc.User, body: str):
    ch = await rch._get_channel()

    isDM = ch.type == disnake.ChannelType.private
    guildId = ch.id if isDM else user.id

    reqbody = {
        "UserId": str(user.id),
        "GuildId": str(guildId),
        "IsDM": isDM,
        "Body": body,
        "Token": os.environ.get("ENDPOINT_TOKEN"),
    }

    endpoint = os.environ.get("ENDPOINT")
    resp = requests.post(f"{endpoint}/verses/process", json=reqbody)

    if resp.json()["logStatement"]:
        logger.info(f"<{user.id}#{ch.id}@{guildId}> " + resp.json()["logStatement"])

    if resp.json()["logStatement"]:
        if "does not support the" in resp.json()["logStatement"]:
            await ch.send(
                embed=create_error_embed("Verse Error", resp.json()["logStatement"])
            )
            return

    display_style = resp.json()["displayStyle"]
    if display_style == "embed":
        if resp.json()["paginate"] and len(resp.json()["verses"]) > 1:
            embeds = create_pagination_embeds_from_verses(resp.json()["verses"])
            paginator = CreatePaginator(embeds, user.id, 180)

            await ch.send(embed=embeds[0], view=paginator)
        else:
            for verse in resp.json()["verses"]:
                await ch.send(embed=create_embed_from_verse(verse))
    elif display_style == "blockquote":
        for verse in resp.json()["verses"]:
            reference_title = (
                verse["reference"]["asString"]
                + " - "
                + verse["reference"]["version"]["name"]
            )
            verse_title = (
                ("**" + verse["title"] + "**\n> \n> ")
                if len(verse["title"]) > 0
                else ""
            )
            verse_text = verse["text"]

            await ch.send(f"**{reference_title}**\n\n> {verse_title}{verse_text}")
    elif display_style == "code":
        for verse in resp.json()["verses"]:
            reference_title = (
                verse["reference"]["asString"]
                + " - "
                + verse["reference"]["version"]["name"]
            )
            verse_title = (verse["title"] + "\n\n") if len(verse["title"]) > 0 else ""
            verse_text = verse["text"].replace("*", "")

            await ch.send(
                f"**{reference_title}**\n\n```json\n{verse_title} {verse_text}```"
            )

def convert_embed(internal_embed):
    embed = disnake.Embed()

    embed.title = internal_embed["title"]
    embed.description = internal_embed["description"]
    embed.url = internal_embed["url"]
    embed.color = internal_embed["color"]

    if internal_embed["fields"] is not None:
        for field in internal_embed["fields"]:
            embed.add_field(
                name=field["name"], value=field["value"], inline=field["inline"]
            )

    embed.set_footer(
        text=internal_embed["footer"]["text"],
        icon_url=internal_embed["footer"]["icon_url"],
    )

    return embed

def create_embed_from_verse(verse):
    embed = disnake.Embed()

    reference_title = (
        verse["reference"]["asString"] + " - " + verse["reference"]["version"]["name"]
    )

    embed.set_author(name=reference_title)
    embed.title = verse["title"]
    embed.description = verse["text"]
    embed.color = 6709986

    embed.set_footer(
        text="BibleBot v9.2-beta by Kerygma Digital",
        icon_url="https://i.imgur.com/hr4RXpy.png",
    )

    return embed

def create_error_embed(title, description):
    embed = disnake.Embed()

    embed.title = title
    embed.description = description
    embed.color = 16723502

    embed.set_footer(
        text="BibleBot v9.2-beta by Kerygma Digital",
        icon_url="https://i.imgur.com/hr4RXpy.png",
    )

    return embed

def create_pagination_embeds_from_pages(pages):
    embeds = []
    starting_page = None

    # For whatever reason, the paginator library has the buttons
    # performing the opposite effect, "next" goes to the previous
    # page and vice versa. This reverses the array and makes sure
    # the first page is properly the first embed, which is still a
    # requirement despite the paginator working backwards.
    #
    # I could fix this myself by forking the library
    # (it's a two-line fix), but I'm too lazy for that.
    for page in pages[::-1]:
        page_embed = convert_embed(page)

        if f"Page 1 of" in page_embed.title:
            starting_page = page_embed
        else:
            embeds.append(page_embed)

    if starting_page == None:
        starting_page = embeds.pop()

    embeds.insert(0, starting_page)

    return embeds

def create_pagination_embeds_from_verses(verses):
    embeds = []
    starting_verse = None

    # For whatever reason, the paginator library has the buttons
    # performing the opposite effect, "next" goes to the previous
    # page and vice versa. This reverses the array and makes sure
    # the first page is properly the first embed, which is still a
    # requirement despite the paginator working backwards.
    #
    # I could fix this myself by forking the library
    # (it's a two-line fix), but I'm too lazy for that.
    for verse in verses[::-1]:
        verse_embed = create_embed_from_verse(verse)

        if verse == verses[-1]:
            starting_verse = verse_embed
        else:
            embeds.append(verse_embed)

    embeds.insert(0, starting_verse)

    return embeds
<|endoftext|>


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

from unittest import TestCase

from project_generator.targets import Targets
from project_generator.settings import ProjectSettings

class TestProject(TestCase):

    """test things related to the Project class"""

    def setUp(self):
        settings = ProjectSettings()
        self.targets = Targets(settings.get_env_settings('definitions'))

    def test_target(self):
        target = self.targets.get_mcu_record('frdm-k64f')
        # it's not empty dictionary and has at least mcu and tool specific
        assert bool(target)
        assert bool(target['mcu'])
        assert bool(target['tool_specific'])

    def test_core(self):
        core = self.targets.get_mcu_core('frdm-k64f')
        assert core[0] == 'cortex-m4f'

    def test_tool_def_nonexist(self):
        tool_def = self.targets.get_tool_def('frdm-k64f', 'notexists')
        assert tool_def is None

    def test_tool_def(self):
        # test k64f for uvision, should not be empty
        tool_def = self.targets.get_tool_def('frdm-k64f', 'uvision')
        assert bool(tool_def)

<commit_msg>Tests - target test removal<commit_after><|endoftext|>


<commit_before>import time

from tornado import ioloop
from tornado import gen

import pytest

import consul.tornado

@pytest.fixture
def loop():
    loop = ioloop.IOLoop()
    loop.make_current()
    return loop

class TestConsul(object):
    def test_kv(self, loop, consul_port):
        @gen.coroutine
        def main():
            c = consul.tornado.Consul(port=consul_port)
            index, data = yield c.kv.get('foo')
            assert data is None
            response = yield c.kv.put('foo', 'bar')
            assert response is True
            index, data = yield c.kv.get('foo')
            assert data['Value'] == 'bar'
            loop.stop()
        loop.run_sync(main)

    def test_kv_subscribe(self, loop, consul_port):
        c = consul.tornado.Consul(port=consul_port)

        @gen.coroutine
        def get():
            index, data = yield c.kv.get('foo')
            assert data is None
            index, data = yield c.kv.get('foo', index=index)
            assert data['Value'] == 'bar'
            loop.stop()

        @gen.coroutine
        def put():
            response = yield c.kv.put('foo', 'bar')
            assert response is True

        loop.add_timeout(time.time()+(1.0/100), put)
        loop.run_sync(get)

    def test_agent_services(self, loop, consul_port):
        @gen.coroutine
        def main():
            c = consul.tornado.Consul(port=consul_port)
            services = yield c.agent.services()
            assert services == {}
            response = yield c.agent.service.register('foo')
            assert response is True
            services = yield c.agent.services()
            assert services == {
                'foo': {
                    'Port': 0, 'ID': 'foo', 'Service': 'foo', 'Tags': None}}
            response = yield c.agent.service.deregister('foo')
            assert response is True
            services = yield c.agent.services()
            assert services == {}
            loop.stop()
        loop.run_sync(main)

    def test_health_service(self, loop, consul_port):
        @gen.coroutine
        def main():
            c = consul.tornado.Consul(port=consul_port)

            # check there are no nodes for the service 'foo'
            index, nodes = yield c.health.service('foo')
            assert nodes == []

            # register two nodes, one with a long ttl, the other shorter
            yield c.agent.service.register(
                'foo', service_id='foo:1', ttl='10s')
            yield c.agent.service.register(
                'foo', service_id='foo:2', ttl='20ms')

            # check the nodes show for the /health/service endpoint
            index, nodes = yield c.health.service('foo')
            assert [node['Service']['ID'] for node in nodes] == \
                ['foo:1', 'foo:2']

            # but that they aren't passing their health check
            index, nodes = yield c.health.service('foo', passing=True)
            assert nodes == []

            # ping the two node's health check
            yield c.health.check.ttl_pass('service:foo:1')
            yield c.health.check.ttl_pass('service:foo:2')

            # both nodes are now available
            index, nodes = yield c.health.service('foo', passing=True)
            assert [node['Service']['ID'] for node in nodes] == \
                ['foo:1', 'foo:2']

            # wait until the short ttl node fails
            time.sleep(40/1000.0)

            # only one node available
            index, nodes = yield c.health.service('foo', passing=True)
            assert [node['Service']['ID'] for node in nodes] == ['foo:1']

            # ping the failed node's health check
            yield c.health.check.ttl_pass('service:foo:2')

            # check both nodes are available
            index, nodes = yield c.health.service('foo', passing=True)
            assert [node['Service']['ID'] for node in nodes] == \
                ['foo:1', 'foo:2']

            # deregister the nodes
            yield c.agent.service.deregister('foo:1')
            yield c.agent.service.deregister('foo:2')

            index, nodes = yield c.health.service('foo')
            assert nodes == []

        loop.run_sync(main)

    def test_health_service_subscribe(self, loop, consul_port):
        c = consul.tornado.Consul(port=consul_port)

        class Config(object):
            pass

        config = Config()

        @gen.coroutine
        def monitor():
            yield c.agent.service.register(
                'foo', service_id='foo:1', ttl='20ms')
            index = None
            while True:
                index, nodes = yield c.health.service(
                    'foo', index=index, passing=True)
                config.nodes = [node['Service']['ID'] for node in nodes]

        def sleep(s):
            result = gen.Future()
            loop.add_timeout(
                time.time()+s, lambda: result.set_result(None))
            return result

        @gen.coroutine
        def keepalive():
            # give the monitor a chance to register the service
            yield sleep(50/1000.0)
            assert config.nodes == []

            # ping the service's health check
            yield c.health.check.ttl_pass('service:foo:1')
            yield sleep(10/1000.0)
            assert config.nodes == ['foo:1']

            # the service should fail
            yield sleep(20/1000.0)
            assert config.nodes == []

            yield c.agent.service.deregister('foo:1')
            loop.stop()

        loop.add_callback(monitor)
        loop.run_sync(keepalive)
<commit_msg>work on making tornado's test_health_service more robust<commit_after>import time

from tornado import ioloop
from tornado import gen

import pytest

import consul.tornado

@pytest.fixture
def loop():
    loop = ioloop.IOLoop()
    loop.make_current()
    return loop

class TestConsul(object):
    def test_kv(self, loop, consul_port):
        @gen.coroutine
        def main():
            c = consul.tornado.Consul(port=consul_port)
            index, data = yield c.kv.get('foo')
            assert data is None
            response = yield c.kv.put('foo', 'bar')
            assert response is True
            index, data = yield c.kv.get('foo')
            assert data['Value'] == 'bar'
            loop.stop()
        loop.run_sync(main)

    def test_kv_subscribe(self, loop, consul_port):
        c = consul.tornado.Consul(port=consul_port)

        @gen.coroutine
        def get():
            index, data = yield c.kv.get('foo')
            assert data is None
            index, data = yield c.kv.get('foo', index=index)
            assert data['Value'] == 'bar'
            loop.stop()

        @gen.coroutine
        def put():
            response = yield c.kv.put('foo', 'bar')
            assert response is True

        loop.add_timeout(time.time()+(1.0/100), put)
        loop.run_sync(get)

    def test_agent_services(self, loop, consul_port):
        @gen.coroutine
        def main():
            c = consul.tornado.Consul(port=consul_port)
            services = yield c.agent.services()
            assert services == {}
            response = yield c.agent.service.register('foo')
            assert response is True
            services = yield c.agent.services()
            assert services == {
                'foo': {
                    'Port': 0, 'ID': 'foo', 'Service': 'foo', 'Tags': None}}
            response = yield c.agent.service.deregister('foo')
            assert response is True
            services = yield c.agent.services()
            assert services == {}
            loop.stop()
        loop.run_sync(main)

    def test_health_service(self, loop, consul_port):
        @gen.coroutine
        def main():
            c = consul.tornado.Consul(port=consul_port)

            # check there are no nodes for the service 'foo'
            index, nodes = yield c.health.service('foo')
            assert nodes == []

            # register two nodes, one with a long ttl, the other shorter
            yield c.agent.service.register(
                'foo', service_id='foo:1', ttl='10s')
            yield c.agent.service.register(
                'foo', service_id='foo:2', ttl='100ms')

            time.sleep(10/1000.0)

            # check the nodes show for the /health/service endpoint
            index, nodes = yield c.health.service('foo')
            assert [node['Service']['ID'] for node in nodes] == \
                ['foo:1', 'foo:2']

            # but that they aren't passing their health check
            index, nodes = yield c.health.service('foo', passing=True)
            assert nodes == []

            # ping the two node's health check
            yield c.health.check.ttl_pass('service:foo:1')
            yield c.health.check.ttl_pass('service:foo:2')

            time.sleep(10/1000.0)

            # both nodes are now available
            index, nodes = yield c.health.service('foo', passing=True)
            assert [node['Service']['ID'] for node in nodes] == \
                ['foo:1', 'foo:2']

            # wait until the short ttl node fails
            time.sleep(110/1000.0)

            # only one node available
            index, nodes = yield c.health.service('foo', passing=True)
            assert [node['Service']['ID'] for node in nodes] == ['foo:1']

            # ping the failed node's health check
            yield c.health.check.ttl_pass('service:foo:2')

            time.sleep(10/1000.0)

            # check both nodes are available
            index, nodes = yield c.health.service('foo', passing=True)
            assert [node['Service']['ID'] for node in nodes] == \
                ['foo:1', 'foo:2']

            # deregister the nodes
            yield c.agent.service.deregister('foo:1')
            yield c.agent.service.deregister('foo:2')

            time.sleep(10/1000.0)

            index, nodes = yield c.health.service('foo')
            assert nodes == []

        loop.run_sync(main)

    def test_health_service_subscribe(self, loop, consul_port):
        c = consul.tornado.Consul(port=consul_port)

        class Config(object):
            pass

        config = Config()

        @gen.coroutine
        def monitor():
            yield c.agent.service.register(
                'foo', service_id='foo:1', ttl='20ms')
            index = None
            while True:
                index, nodes = yield c.health.service(
                    'foo', index=index, passing=True)
                config.nodes = [node['Service']['ID'] for node in nodes]

        def sleep(s):
            result = gen.Future()
            loop.add_timeout(
                time.time()+s, lambda: result.set_result(None))
            return result

        @gen.coroutine
        def keepalive():
            # give the monitor a chance to register the service
            yield sleep(50/1000.0)
            assert config.nodes == []

            # ping the service's health check
            yield c.health.check.ttl_pass('service:foo:1')
            yield sleep(10/1000.0)
            assert config.nodes == ['foo:1']

            # the service should fail
            yield sleep(20/1000.0)
            assert config.nodes == []

            yield c.agent.service.deregister('foo:1')
            loop.stop()

        loop.add_callback(monitor)
        loop.run_sync(keepalive)
<|endoftext|>


<commit_before>import pytest
import numpy as np

@pytest.mark.parametrize('kind', ['puf', 'cps'])
def test_weights(kind, puf_weights, cps_weights, growfactors, puf, cps):
    # test range of years in weights file
    first_growfactors_year = growfactors.index.min()
    last_growfactors_year = growfactors.index.max()
    if kind == 'puf':
        weights = puf_weights
        first_weights_year = 2011  # change value when using newer PUF data
        last_weights_year = last_growfactors_year
        data = puf
    elif kind == 'cps':
        weights = cps_weights
        first_weights_year = 2014  # change value when using newer CPS data
        last_weights_year = last_growfactors_year
        data = cps
    else:
       raise ValueError('illegal kind = {}'.format(kind))
    sorted_weights_columns = sorted([col for col in weights])
    first_weights_column = sorted_weights_columns[0]
    last_weights_column = sorted_weights_columns[-1]
    assert first_weights_column == 'WT{}'.format(first_weights_year)
    assert last_weights_column == 'WT{}'.format(last_weights_year)
    # test number of rows in weights file
    assert weights.shape[0] == data.shape[0]
    # test range of weight values for each year
    min_weight = 0  # weight must be non-negative,
    max_weight = 1800000  # but can be quite large
    for col in weights:
       if weights[col].min() < min_weight:
           msg = '{} weights[{}].min()={} < {}'
           raise ValueError(msg.format(kind, col,
                                       weights[col].min(), min_weight))
       if weights[col].max() > max_weight:
           msg = '{} weights[{}].max()={} > {}'
           raise ValueError(msg.format(kind, col,
                                       weights[col].max(), max_weight))
<commit_msg>Revise test_weights.py code<commit_after>import pytest
import numpy as np

@pytest.mark.parametrize('kind', ['puf', 'cps'])
def test_weights(kind, puf_weights, cps_weights, growfactors):
    # test range of years in weights file
    first_growfactors_year = growfactors.index.min()
    last_growfactors_year = growfactors.index.max()
    if kind == 'puf':
        weights = puf_weights
        first_weights_year = 2011  # change value when using newer PUF data
        expected_num_records = 239002  # change value when using newer PUF data
        last_weights_year = last_growfactors_year
    elif kind == 'cps':
        weights = cps_weights
        first_weights_year = 2014  # change value when using newer CPS data
        expected_num_records = 456465  # change value when using newer CPS data
        last_weights_year = last_growfactors_year
    else:
       raise ValueError('illegal kind = {}'.format(kind))
    sorted_weights_columns = sorted([col for col in weights])
    first_weights_column = sorted_weights_columns[0]
    last_weights_column = sorted_weights_columns[-1]
    assert first_weights_column == 'WT{}'.format(first_weights_year)
    assert last_weights_column == 'WT{}'.format(last_weights_year)
    # test number of rows in weights file
    assert weights.shape[0] == expected_num_records
    # test range of weight values for each year
    min_weight = 0  # weight must be non-negative,
    max_weight = 1800000  # but can be quite large
    for col in weights:
       if weights[col].min() < min_weight:
           msg = '{} weights[{}].min()={} < {}'
           raise ValueError(msg.format(kind, col,
                                       weights[col].min(), min_weight))
       if weights[col].max() > max_weight:
           msg = '{} weights[{}].max()={} > {}'
           raise ValueError(msg.format(kind, col,
                                       weights[col].max(), max_weight))
<|endoftext|>


<commit_before>from todoman.widgets import ExtendedEdit

# We ignore `size` when testing keypresses, because it's not used anywhere.
# Just pass any number when writing tests, unless we start using the value.

BASE_STRING = 'The lazy fox bla bla\n@ät'

def test_extended_edit_delete_word():
    extended_edit = ExtendedEdit(None)

    extended_edit.set_edit_text(BASE_STRING)
    extended_edit.edit_pos = 9
    extended_edit.keypress(10, 'ctrl w')
    assert extended_edit.edit_pos == 4
    assert extended_edit.get_edit_text() == 'The fox bla bla\n@ät'

    extended_edit.set_edit_text('The-lazy-fox-bla-bla\n@ät')
    extended_edit.edit_pos = 8
    extended_edit.keypress(10, 'ctrl w')
    assert extended_edit.edit_pos == 4
    assert extended_edit.get_edit_text() == 'The--fox-bla-bla\n@ät'

    extended_edit.set_edit_text(BASE_STRING)
    extended_edit.edit_pos = 6
    extended_edit.keypress(10, 'ctrl w')
    assert extended_edit.edit_pos == 4
    assert extended_edit.get_edit_text() == 'The zy fox bla bla\n@ät'

    extended_edit.set_edit_text(BASE_STRING)
    extended_edit.edit_pos = 0
    extended_edit.keypress(10, 'ctrl w')
    assert extended_edit.edit_pos == 0
    assert extended_edit.get_edit_text() == BASE_STRING

def test_extended_edit_delete_sol():
    extended_edit = ExtendedEdit(None)

    extended_edit.set_edit_text(BASE_STRING)
    extended_edit.edit_pos = 9
    extended_edit.keypress(10, 'ctrl u')
    assert extended_edit.edit_pos == 0
    assert extended_edit.get_edit_text() == 'fox bla bla\n@ät'

    extended_edit.set_edit_text(BASE_STRING)
    extended_edit.edit_pos = 0
    extended_edit.keypress(10, 'ctrl u')
    assert extended_edit.edit_pos == 0
    assert extended_edit.get_edit_text() == BASE_STRING

def test_extended_edit_delete_eol():
    extended_edit = ExtendedEdit(None)

    extended_edit.set_edit_text(BASE_STRING)
    extended_edit.edit_pos = 9
    extended_edit.keypress(10, 'ctrl k')
    assert extended_edit.edit_pos == 9
    assert extended_edit.get_edit_text() == 'The lazy \n@ät'

    extended_edit.set_edit_text(BASE_STRING)
    extended_edit.edit_pos = 20
    extended_edit.keypress(10, 'ctrl k')
    assert extended_edit.edit_pos == 20
    assert extended_edit.get_edit_text() == BASE_STRING

    extended_edit.set_edit_text(BASE_STRING)
    extended_edit.edit_pos = 24
    extended_edit.keypress(10, 'ctrl k')
    assert extended_edit.edit_pos == 24
    assert extended_edit.get_edit_text() == BASE_STRING

def test_extended_edit_goto_sol():
    extended_edit = ExtendedEdit(None)

    extended_edit.set_edit_text(BASE_STRING)
    extended_edit.edit_pos = 9
    extended_edit.keypress(10, 'ctrl a')
    assert extended_edit.edit_pos == 0
    assert extended_edit.get_edit_text() == BASE_STRING

    extended_edit.set_edit_text(BASE_STRING)
    extended_edit.edit_pos = 23
    extended_edit.keypress(10, 'ctrl a')
    assert extended_edit.edit_pos == 21
    assert extended_edit.get_edit_text() == BASE_STRING

def test_extended_edit_goto_eol():
    extended_edit = ExtendedEdit(None)

    extended_edit.set_edit_text(BASE_STRING)
    extended_edit.edit_pos = 9
    extended_edit.keypress(10, 'ctrl e')
    assert extended_edit.edit_pos == 20
    assert extended_edit.get_edit_text() == BASE_STRING

    extended_edit.set_edit_text(BASE_STRING)
    extended_edit.edit_pos = 22
    extended_edit.keypress(10, 'ctrl e')
    assert extended_edit.edit_pos == 24
    assert extended_edit.get_edit_text() == BASE_STRING

def test_extended_edit_delete_next_char():
    extended_edit = ExtendedEdit(None)

    extended_edit.set_edit_text(BASE_STRING)
    extended_edit.edit_pos = 9
    extended_edit.keypress(10, 'ctrl d')
    assert extended_edit.edit_pos == 9
    assert extended_edit.get_edit_text() == 'The lazy ox bla bla\n@ät'

    extended_edit.set_edit_text(BASE_STRING)
    extended_edit.edit_pos = 0
    extended_edit.keypress(10, 'ctrl d')
    assert extended_edit.edit_pos == 0
    assert extended_edit.get_edit_text() == 'he lazy fox bla bla\n@ät'

    extended_edit.set_edit_text(BASE_STRING)
    extended_edit.edit_pos = 24
    extended_edit.keypress(10, 'ctrl d')
    assert extended_edit.edit_pos == 24
    assert extended_edit.get_edit_text() == 'The lazy fox bla bla\n@ät'

    extended_edit.set_edit_text(BASE_STRING)
    extended_edit.edit_pos = 24
    extended_edit.keypress(10, 'ctrl d')
    assert extended_edit.edit_pos == 24
    assert extended_edit.get_edit_text() == 'The lazy fox bla bla\n@ät'

# TODO: plain ol' keypresses
# TODO: can we test ctrl o (maybe with some unittest.mock?)
<commit_msg>Add more tests for ExtendedEdit<commit_after>from unittest import mock

from todoman.widgets import ExtendedEdit

# We ignore `size` when testing keypresses, because it's not used anywhere.
# Just pass any number when writing tests, unless we start using the value.

BASE_STRING = 'The lazy fox bla bla\n@ät'

def test_extended_edit_delete_word():
    extended_edit = ExtendedEdit(None)

    extended_edit.set_edit_text(BASE_STRING)
    extended_edit.edit_pos = 9
    extended_edit.keypress(10, 'ctrl w')
    assert extended_edit.edit_pos == 4
    assert extended_edit.get_edit_text() == 'The fox bla bla\n@ät'

    extended_edit.set_edit_text('The-lazy-fox-bla-bla\n@ät')
    extended_edit.edit_pos = 8
    extended_edit.keypress(10, 'ctrl w')
    assert extended_edit.edit_pos == 4
    assert extended_edit.get_edit_text() == 'The--fox-bla-bla\n@ät'

    extended_edit.set_edit_text(BASE_STRING)
    extended_edit.edit_pos = 6
    extended_edit.keypress(10, 'ctrl w')
    assert extended_edit.edit_pos == 4
    assert extended_edit.get_edit_text() == 'The zy fox bla bla\n@ät'

    extended_edit.set_edit_text(BASE_STRING)
    extended_edit.edit_pos = 0
    extended_edit.keypress(10, 'ctrl w')
    assert extended_edit.edit_pos == 0
    assert extended_edit.get_edit_text() == BASE_STRING

def test_extended_edit_delete_sol():
    extended_edit = ExtendedEdit(None)

    extended_edit.set_edit_text(BASE_STRING)
    extended_edit.edit_pos = 9
    extended_edit.keypress(10, 'ctrl u')
    assert extended_edit.edit_pos == 0
    assert extended_edit.get_edit_text() == 'fox bla bla\n@ät'

    extended_edit.set_edit_text(BASE_STRING)
    extended_edit.edit_pos = 0
    extended_edit.keypress(10, 'ctrl u')
    assert extended_edit.edit_pos == 0
    assert extended_edit.get_edit_text() == BASE_STRING

def test_extended_edit_delete_eol():
    extended_edit = ExtendedEdit(None)

    extended_edit.set_edit_text(BASE_STRING)
    extended_edit.edit_pos = 9
    extended_edit.keypress(10, 'ctrl k')
    assert extended_edit.edit_pos == 9
    assert extended_edit.get_edit_text() == 'The lazy \n@ät'

    extended_edit.set_edit_text(BASE_STRING)
    extended_edit.edit_pos = 20
    extended_edit.keypress(10, 'ctrl k')
    assert extended_edit.edit_pos == 20
    assert extended_edit.get_edit_text() == BASE_STRING

    extended_edit.set_edit_text(BASE_STRING)
    extended_edit.edit_pos = 24
    extended_edit.keypress(10, 'ctrl k')
    assert extended_edit.edit_pos == 24
    assert extended_edit.get_edit_text() == BASE_STRING

def test_extended_edit_goto_sol():
    extended_edit = ExtendedEdit(None)

    extended_edit.set_edit_text(BASE_STRING)
    extended_edit.edit_pos = 9
    extended_edit.keypress(10, 'ctrl a')
    assert extended_edit.edit_pos == 0
    assert extended_edit.get_edit_text() == BASE_STRING

    extended_edit.set_edit_text(BASE_STRING)
    extended_edit.edit_pos = 23
    extended_edit.keypress(10, 'ctrl a')
    assert extended_edit.edit_pos == 21
    assert extended_edit.get_edit_text() == BASE_STRING

def test_extended_edit_goto_eol():
    extended_edit = ExtendedEdit(None)

    extended_edit.set_edit_text(BASE_STRING)
    extended_edit.edit_pos = 9
    extended_edit.keypress(10, 'ctrl e')
    assert extended_edit.edit_pos == 20
    assert extended_edit.get_edit_text() == BASE_STRING

    extended_edit.set_edit_text(BASE_STRING)
    extended_edit.edit_pos = 22
    extended_edit.keypress(10, 'ctrl e')
    assert extended_edit.edit_pos == 24
    assert extended_edit.get_edit_text() == BASE_STRING

def test_extended_edit_delete_next_char():
    extended_edit = ExtendedEdit(None)

    extended_edit.set_edit_text(BASE_STRING)
    extended_edit.edit_pos = 9
    extended_edit.keypress(10, 'ctrl d')
    assert extended_edit.edit_pos == 9
    assert extended_edit.get_edit_text() == 'The lazy ox bla bla\n@ät'

    extended_edit.set_edit_text(BASE_STRING)
    extended_edit.edit_pos = 0
    extended_edit.keypress(10, 'ctrl d')
    assert extended_edit.edit_pos == 0
    assert extended_edit.get_edit_text() == 'he lazy fox bla bla\n@ät'

    extended_edit.set_edit_text(BASE_STRING)
    extended_edit.edit_pos = 24
    extended_edit.keypress(10, 'ctrl d')
    assert extended_edit.edit_pos == 24
    assert extended_edit.get_edit_text() == 'The lazy fox bla bla\n@ät'

    extended_edit.set_edit_text(BASE_STRING)
    extended_edit.edit_pos = 24
    extended_edit.keypress(10, 'ctrl d')
    assert extended_edit.edit_pos == 24
    assert extended_edit.get_edit_text() == 'The lazy fox bla bla\n@ät'

def test_extended_edit_input():
    """
    Very basic test to make sure we don't break basic editing

    We don't need to do more testing because that's done upstream. We basically
    want to test that we properly forward unhandled keypresses.
    """
    extended_edit = ExtendedEdit(mock.MagicMock())
    extended_edit.keypress((10,), 'h')
    extended_edit.keypress((10,), 'i')

    assert extended_edit.get_edit_text() == 'hi'

def test_extended_edit_editor():
    extended_edit = ExtendedEdit(mock.MagicMock())
    extended_edit.set_edit_text(BASE_STRING)

    with mock.patch('click.edit', return_value='Sheep!') as edit:
        extended_edit.keypress(10, 'ctrl o')

    assert edit.call_count == 1
    assert edit.call_args == mock.call(BASE_STRING)
    assert extended_edit.get_edit_text() == 'Sheep!'
<|endoftext|>