<commit_before>import psv
import unittest

csv = """Name,Price,Available,Company
Product 1,10,1,Yahoo
Product 2,15,0,Microsoft
Product 3,1,1,Google
Product 4,20,0,Yahoo
Product 5,25,1,Yahoo
Product 6,30,1,Google
Product 7,10,0,Yahoo
"""

class psv_selections_test(unittest.TestCase):

    def construct(self):
        self.csvdoc = psv.loads(csv)

    def test_delete_rows(self):
        self.construct()
        try:
            del self.csvdoc.rows[0]
        except Exception as err:
            self.fail(err)

    def test_delete_rows_getitem(self):
        self.construct()
        try:
            del self.csvdoc[0]
        except Exception as err:
            self.fail(err)

    def test_select_accepts_func(self):
        self.construct()
        try:
            self.csvdoc.select(lambda x: True)
        except Exception as err:
            self.fail(str(err))

    def test_select_function_generation(self):
        self.construct()
        try:
            self.csvdoc.select("name")
            self.csvdoc.select(name="Product 1")
            self.csvdoc.select("name", price=10)
            self.csvdoc.select("name", price=lambda p: p > 10)
            self.csvdoc.select("name", price=10, company="Yahoo", available=1)
        except Exception as err:
            self.fail(str(err))

    def test_select_function_generation_results(self):
        self.construct()
        self.assertEqual(len(self.csvdoc.select("name")), 7)
        self.assertEqual(len(self.csvdoc.select(lambda x: x.name)), 7)
        self.assertEqual(len(self.csvdoc.select(name="Product 1")), 1)
        self.assertEqual(len(self.csvdoc.select("name", price=10)), 2)
        self.assertEqual(len(self.csvdoc.select(lambda x: x.name, price=10)), 2)
        self.assertEqual(len(self.csvdoc.select("name", price=lambda p: p > 10)), 4)
        self.assertEqual(len(self.csvdoc.select(lambda x: x.name, price=lambda p: p > 10)), 4)
        self.assertEqual(len(self.csvdoc.select("name", price=10, company="Yahoo", available=1)), 1)

    def test_safe_select_accepts_func(self):
        self.construct()
        try:
            self.csvdoc.safe_select(lambda x: True)
        except Exception as err:
            self.fail(str(err))

    def test_safe_select_function_generation(self):
        self.construct()
        try:
            self.csvdoc.safe_select("name")
            self.csvdoc.safe_select(name="Product 1")
            self.csvdoc.safe_select("name", price=10)
            self.csvdoc.safe_select("name", price=lambda p: p > 10)
            self.csvdoc.safe_select("name", price=10, company="Yahoo", available=1)
        except Exception as err:
            self.fail(str(err))

    def test_safe_select_function_generation_results(self):
        self.construct()
        self.assertEqual(len(self.csvdoc.safe_select("name")), 7)
        self.assertEqual(len(self.csvdoc.safe_select(lambda x: x.name)), 7)
        self.assertEqual(len(self.csvdoc.safe_select(name="Product 1")), 1)
        self.assertEqual(len(self.csvdoc.safe_select("name", price=10)), 2)
        self.assertEqual(len(self.csvdoc.safe_select(lambda x: x.name, price=10)), 2)
        self.assertEqual(len(self.csvdoc.safe_select("name", price=lambda p: p > 10)), 4)
        self.assertEqual(len(self.csvdoc.safe_select(lambda x: x.name, price=lambda p: p > 10)), 4)
        self.assertEqual(len(self.csvdoc.safe_select("name", price=10, company="Yahoo", available=1)), 1)

    def test_no_output(self):
        self.construct()
        self.csvdoc.no_output()
        self.assertEqual(self.csvdoc.lenoutput(), 0)

    def test_all_output(self):
        self.construct()
        self.csvdoc.no_output()
        self.csvdoc.all_output()
        self.assertEqual(self.csvdoc.lenoutput(), 7)

    def test_flip_output(self):
        self.construct()
        self.csvdoc[:3].no_output()
        self.csvdoc.flip_output()
        self.assertEqual(self.csvdoc.lenoutput(), 3)

    def test_enable(self):
        self.construct()
        self.csvdoc.no_output()
        self.csvdoc.enable(name="Product 1")
        self.assertEqual(self.csvdoc.lenoutput(), 1)

    def test_disable(self):
        self.construct()
        self.csvdoc.disable(name="Product 1")
        self.assertEqual(self.csvdoc.lenoutput(), 6)

    def test_flip(self):
        self.construct()
        self.csvdoc.flip(name="Product 1")
        self.assertEqual(self.csvdoc.lenoutput(), 6)

    def test_grab(self):
        self.construct()
        self.assertEqual(tuple(self.csvdoc["name"]), self.csvdoc.grab("name"))
        self.assertEqual(tuple(self.csvdoc["name", "price"]), self.csvdoc.grab("name", "price"))

    def test_unique(self):
        self.construct()
        self.assertEqual(set(self.csvdoc["name"]), self.csvdoc.unique("name"))
        self.assertEqual(set(self.csvdoc["name", "price"]), self.csvdoc.unique("name", "price"))

    def test_indexing(self):
        self.construct()
        self.assertTrue(isinstance(self.csvdoc.grab("name", "ROW_OBJ")[0][1], psv.core.objects.rowobjects.BaseRow))
        try:
            self.csvdoc.grab("ROW_OBJ")
            self.csvdoc.fail("PSV did not catch incorrect ROW_OBJ use")
        except:
            pass

        self.assertTrue(isinstance(self.csvdoc[0],  psv.core.objects.rowobjects.BaseRow))

    def test_tabulating(self):
        self.construct()
        try:
            self.csvdoc.tabulate()
            self.csvdoc.tabulate(format="html", limit=10, only_ascii=False, text_limit=1000, remove_newline=False)
        except Exception as err:
            self.fail(str(err))

    def test_find(self):
        self.construct()
        self.assertTrue(bool(self.csvdoc.find(name="Product 1")))
        self.assertFalse(bool(self.csvdoc.find(name="INVALID NAME")))

    def test_findall(self):
        self.construct()
        self.assertEqual(len(self.csvdoc.find_all(company="Yahoo")), 4)
        self.assertFalse(bool(self.csvdoc.find_all(company="INVALID COMPANY")))

    def test_single_find(self):
        self.construct()
        self.assertTrue(bool(self.csvdoc.single_find(name="Product 1")))
        self.assertFalse(bool(self.csvdoc.single_find(name="INVALID NAME")))
        try:
            self.csvdoc.find(company="Yahoo")
            self.fail("Single Find did not raise exception for duplicates")
        except Exception:
            pass

    def test_merge(self):
        self.construct()
        try:
            self.csvdoc.merge(self.csvdoc[:int(len(self.csvdoc)/2)])
        except Exception as err:
            self.fail(err)

    def test_safe_merge(self):
        self.construct()
        try:
            self.csvdoc.safe_merge(self.csvdoc[:int(len(self.csvdoc)/2)])
        except Exception as err:
            self.fail(err)

    def test_non_hash_merge(self):
        self.construct()
        try:
            self.csvdoc.non_hash_merge(self.csvdoc[:int(len(self.csvdoc)/2)])
        except Exception as err:
            self.fail(err)

    def test_columns(self):
        self.construct()
        self.csvdoc.columns
        self.csvdoc.columns = ["Hello 5"]

    def test_addrow(self):
        self.construct()
        row = self.csvdoc.addrow()
        self.assertEqual(row, self.csvdoc[-1])

    def test_addrow_kw(self):
        import random
        self.construct()
        row = self.csvdoc.addrow(**({x:random.randint(1,100) for x in self.csvdoc.columns} ))
        self.assertEqual(row, self.csvdoc[-1])

<commit_msg>Added tests for any() select method<commit_after>import psv
import unittest

csv = """Name,Price,Available,Company
Product 1,10,1,Yahoo
Product 2,15,0,Microsoft
Product 3,1,1,Google
Product 4,20,0,Yahoo
Product 5,25,1,Yahoo
Product 6,30,1,Google
Product 7,10,0,Yahoo
"""

class psv_selections_test(unittest.TestCase):

    def construct(self):
        self.csvdoc = psv.loads(csv)

    def test_delete_rows(self):
        self.construct()
        try:
            del self.csvdoc.rows[0]
        except Exception as err:
            self.fail(err)

    def test_delete_rows_getitem(self):
        self.construct()
        try:
            del self.csvdoc[0]
        except Exception as err:
            self.fail(err)

    def test_select_accepts_func(self):
        self.construct()
        try:
            self.csvdoc.select(lambda x: True)
        except Exception as err:
            self.fail(str(err))

    def test_select_function_generation(self):
        self.construct()
        try:
            self.csvdoc.select("name")
            self.csvdoc.select(name="Product 1")
            self.csvdoc.select("name", price=10)
            self.csvdoc.select("name", price=lambda p: p > 10)
            self.csvdoc.select("name", price=10, company="Yahoo", available=1)
        except Exception as err:
            self.fail(str(err))

    def test_any_select_function_generation(self):
        self.construct()
        try:
            self.csvdoc.any("name")
            self.csvdoc.any(name="Product 1")
            self.csvdoc.any("name", price=10)
            self.csvdoc.any("name", price=lambda p: p > 10)
            self.csvdoc.any("name", price=10, company="Yahoo", available=1)
        except Exception as err:
            self.fail(str(err))

    def test_select_function_generation_results(self):
        self.construct()
        self.assertEqual(len(self.csvdoc.select("name")), 7)
        self.assertEqual(len(self.csvdoc.select(lambda x: x.name)), 7)
        self.assertEqual(len(self.csvdoc.select(name="Product 1")), 1)
        self.assertEqual(len(self.csvdoc.select("name", price=10)), 2)
        self.assertEqual(len(self.csvdoc.select(lambda x: x.name, price=10)), 2)
        self.assertEqual(len(self.csvdoc.select("name", price=lambda p: p > 10)), 4)
        self.assertEqual(len(self.csvdoc.select(lambda x: x.name, price=lambda p: p > 10)), 4)
        self.assertEqual(len(self.csvdoc.select("name", price=10, company="Yahoo", available=1)), 1)

    def test_any_select_function_generation_results(self):
        self.construct()
        self.assertEqual(len(self.csvdoc.any("name")), 7)
        self.assertEqual(len(self.csvdoc.any(lambda x: x.name)), 7)
        self.assertEqual(len(self.csvdoc.any(name="Product 1")), 1)
        self.assertEqual(len(self.csvdoc.any("name", price=10)), 7)
        self.assertEqual(len(self.csvdoc.any(lambda x: x.name, price=10)), 7)
        self.assertEqual(len(self.csvdoc.any("name", price=lambda p: p > 10)), 7)
        self.assertEqual(len(self.csvdoc.any(lambda x: x.name, price=lambda p: p > 10)), 7)
        self.assertEqual(len(self.csvdoc.any("name", price=10, company="Yahoo", available=1)), 7)

    def test_safe_select_accepts_func(self):
        self.construct()
        try:
            self.csvdoc.safe_select(lambda x: True)
        except Exception as err:
            self.fail(str(err))

    def test_safe_select_function_generation(self):
        self.construct()
        try:
            self.csvdoc.safe_select("name")
            self.csvdoc.safe_select(name="Product 1")
            self.csvdoc.safe_select("name", price=10)
            self.csvdoc.safe_select("name", price=lambda p: p > 10)
            self.csvdoc.safe_select("name", price=10, company="Yahoo", available=1)
        except Exception as err:
            self.fail(str(err))

    def test_any_safe_select_function_generation(self):
        self.construct()
        try:
            self.csvdoc.safe_any("name")
            self.csvdoc.safe_any(name="Product 1")
            self.csvdoc.safe_any("name", price=10)
            self.csvdoc.safe_any("name", price=lambda p: p > 10)
            self.csvdoc.safe_any("name", price=10, company="Yahoo", available=1)
        except Exception as err:
            self.fail(str(err))

    def test_safe_select_function_generation_results(self):
        self.construct()
        self.assertEqual(len(self.csvdoc.safe_select("name")), 7)
        self.assertEqual(len(self.csvdoc.safe_select(lambda x: x.name)), 7)
        self.assertEqual(len(self.csvdoc.safe_select(name="Product 1")), 1)
        self.assertEqual(len(self.csvdoc.safe_select("name", price=10)), 2)
        self.assertEqual(len(self.csvdoc.safe_select(lambda x: x.name, price=10)), 2)
        self.assertEqual(len(self.csvdoc.safe_select("name", price=lambda p: p > 10)), 4)
        self.assertEqual(len(self.csvdoc.safe_select(lambda x: x.name, price=lambda p: p > 10)), 4)
        self.assertEqual(len(self.csvdoc.safe_select("name", price=10, company="Yahoo", available=1)), 1)

    def test_any_safe_select_function_generation_results(self):
        self.construct()
        self.assertEqual(len(self.csvdoc.safe_any("name")), 7)
        self.assertEqual(len(self.csvdoc.safe_any(lambda x: x.name)), 7)
        self.assertEqual(len(self.csvdoc.safe_any(name="Product 1")), 1)
        self.assertEqual(len(self.csvdoc.safe_any("name", price=10)), 7)
        self.assertEqual(len(self.csvdoc.safe_any(lambda x: x.name, price=10)), 7)
        self.assertEqual(len(self.csvdoc.safe_any("name", price=lambda p: p > 10)), 7)
        self.assertEqual(len(self.csvdoc.safe_any(lambda x: x.name, price=lambda p: p > 10)), 7)
        self.assertEqual(len(self.csvdoc.safe_any("name", price=10, company="Yahoo", available=1)), 7)

    def test_no_output(self):
        self.construct()
        self.csvdoc.no_output()
        self.assertEqual(self.csvdoc.lenoutput(), 0)

    def test_all_output(self):
        self.construct()
        self.csvdoc.no_output()
        self.csvdoc.all_output()
        self.assertEqual(self.csvdoc.lenoutput(), 7)

    def test_flip_output(self):
        self.construct()
        self.csvdoc[:3].no_output()
        self.csvdoc.flip_output()
        self.assertEqual(self.csvdoc.lenoutput(), 3)

    def test_enable(self):
        self.construct()
        self.csvdoc.no_output()
        self.csvdoc.enable(name="Product 1")
        self.assertEqual(self.csvdoc.lenoutput(), 1)

    def test_disable(self):
        self.construct()
        self.csvdoc.disable(name="Product 1")
        self.assertEqual(self.csvdoc.lenoutput(), 6)

    def test_flip(self):
        self.construct()
        self.csvdoc.flip(name="Product 1")
        self.assertEqual(self.csvdoc.lenoutput(), 6)

    def test_grab(self):
        self.construct()
        self.assertEqual(tuple(self.csvdoc["name"]), self.csvdoc.grab("name"))
        self.assertEqual(tuple(self.csvdoc["name", "price"]), self.csvdoc.grab("name", "price"))

    def test_unique(self):
        self.construct()
        self.assertEqual(set(self.csvdoc["name"]), self.csvdoc.unique("name"))
        self.assertEqual(set(self.csvdoc["name", "price"]), self.csvdoc.unique("name", "price"))

    def test_indexing(self):
        self.construct()
        self.assertTrue(isinstance(self.csvdoc.grab("name", "ROW_OBJ")[0][1], psv.core.objects.rowobjects.BaseRow))
        try:
            self.csvdoc.grab("ROW_OBJ")
            self.csvdoc.fail("PSV did not catch incorrect ROW_OBJ use")
        except:
            pass

        self.assertTrue(isinstance(self.csvdoc[0],  psv.core.objects.rowobjects.BaseRow))

    def test_tabulating(self):
        self.construct()
        try:
            self.csvdoc.tabulate()
            self.csvdoc.tabulate(format="html", limit=10, only_ascii=False, text_limit=1000, remove_newline=False)
        except Exception as err:
            self.fail(str(err))

    def test_find(self):
        self.construct()
        self.assertTrue(bool(self.csvdoc.find(name="Product 1")))
        self.assertFalse(bool(self.csvdoc.find(name="INVALID NAME")))

    def test_findall(self):
        self.construct()
        self.assertEqual(len(self.csvdoc.find_all(company="Yahoo")), 4)
        self.assertFalse(bool(self.csvdoc.find_all(company="INVALID COMPANY")))

    def test_single_find(self):
        self.construct()
        self.assertTrue(bool(self.csvdoc.single_find(name="Product 1")))
        self.assertFalse(bool(self.csvdoc.single_find(name="INVALID NAME")))
        try:
            self.csvdoc.find(company="Yahoo")
            self.fail("Single Find did not raise exception for duplicates")
        except Exception:
            pass

    def test_merge(self):
        self.construct()
        try:
            self.csvdoc.merge(self.csvdoc[:int(len(self.csvdoc)/2)])
        except Exception as err:
            self.fail(err)

    def test_safe_merge(self):
        self.construct()
        try:
            self.csvdoc.safe_merge(self.csvdoc[:int(len(self.csvdoc)/2)])
        except Exception as err:
            self.fail(err)

    def test_non_hash_merge(self):
        self.construct()
        try:
            self.csvdoc.non_hash_merge(self.csvdoc[:int(len(self.csvdoc)/2)])
        except Exception as err:
            self.fail(err)

    def test_columns(self):
        self.construct()
        self.csvdoc.columns
        self.csvdoc.columns = ["Hello 5"]

    def test_addrow(self):
        self.construct()
        row = self.csvdoc.addrow()
        self.assertEqual(row, self.csvdoc[-1])

    def test_addrow_kw(self):
        import random
        self.construct()
        row = self.csvdoc.addrow(**({x:random.randint(1,100) for x in self.csvdoc.columns} ))
        self.assertEqual(row, self.csvdoc[-1])

<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
#
# Copyright (C) 2007-2011 Edgewall Software, 2013-2019 the Babel team
# All rights reserved.
#
# This software is licensed as described in the file LICENSE, which
# you should have received as part of this distribution. The terms
# are also available at http://babel.edgewall.org/wiki/License.
#
# This software consists of voluntary contributions made by many
# individuals. For the exact contribution history, see the revision
# history and logs, available at http://babel.edgewall.org/log/.

import unittest

import pytest

from babel import util
from babel._compat import BytesIO
from babel.util import parse_future_flags

def test_distinct():
    assert list(util.distinct([1, 2, 1, 3, 4, 4])) == [1, 2, 3, 4]
    assert list(util.distinct('foobar')) == ['f', 'o', 'b', 'a', 'r']

def test_pathmatch():
    assert util.pathmatch('**.py', 'bar.py')
    assert util.pathmatch('**.py', 'foo/bar/baz.py')
    assert not util.pathmatch('**.py', 'templates/index.html')
    assert util.pathmatch('**/templates/*.html', 'templates/index.html')
    assert not util.pathmatch('**/templates/*.html', 'templates/foo/bar.html')
    assert util.pathmatch('^foo/**.py', 'foo/bar/baz/blah.py')
    assert not util.pathmatch('^foo/**.py', 'blah/foo/bar/baz.py')
    assert util.pathmatch('./foo/**.py', 'foo/bar/baz/blah.py')
    assert util.pathmatch('./blah.py', 'blah.py')
    assert not util.pathmatch('./foo/**.py', 'blah/foo/bar/baz.py')

class FixedOffsetTimezoneTestCase(unittest.TestCase):

    def test_zone_negative_offset(self):
        self.assertEqual('Etc/GMT-60', util.FixedOffsetTimezone(-60).zone)

    def test_zone_zero_offset(self):
        self.assertEqual('Etc/GMT+0', util.FixedOffsetTimezone(0).zone)

    def test_zone_positive_offset(self):
        self.assertEqual('Etc/GMT+330', util.FixedOffsetTimezone(330).zone)

parse_encoding = lambda s: util.parse_encoding(BytesIO(s.encode('utf-8')))

def test_parse_encoding_defined():
    assert parse_encoding(u'# coding: utf-8') == 'utf-8'

def test_parse_encoding_undefined():
    assert parse_encoding(u'') is None

def test_parse_encoding_non_ascii():
    assert parse_encoding(u'K\xf6ln') is None

@pytest.mark.parametrize('source, result', [
    ('''
from __future__ import print_function,
    division, with_statement,
    unicode_literals
''', 0x10000 | 0x2000 | 0x8000 | 0x20000),
    ('''
from __future__ import print_function, division
print('hello')
''', 0x10000 | 0x2000),
    ('''
from __future__ import print_function, division, unknown,,,,,
print 'hello'
''', 0x10000 | 0x2000),
    ('''
from __future__ import (
    print_function,
    division)
''', 0x10000 | 0x2000),
    ('''
from __future__ import \\
    print_function, \\
    division
''', 0x10000 | 0x2000),
])
def test_parse_future(source, result):
    fp = BytesIO(source.encode('latin-1'))
    flags = parse_future_flags(fp)
    assert flags == result
<commit_msg>fix tests when using Python 3.9a6<commit_after># -*- coding: utf-8 -*-
#
# Copyright (C) 2007-2011 Edgewall Software, 2013-2019 the Babel team
# All rights reserved.
#
# This software is licensed as described in the file LICENSE, which
# you should have received as part of this distribution. The terms
# are also available at http://babel.edgewall.org/wiki/License.
#
# This software consists of voluntary contributions made by many
# individuals. For the exact contribution history, see the revision
# history and logs, available at http://babel.edgewall.org/log/.

import __future__
import unittest

import pytest

from babel import util
from babel._compat import BytesIO
from babel.util import parse_future_flags

class _FF:
    division         = __future__.division.compiler_flag
    print_function   = __future__.print_function.compiler_flag
    with_statement   = __future__.with_statement.compiler_flag
    unicode_literals = __future__.unicode_literals.compiler_flag

def test_distinct():
    assert list(util.distinct([1, 2, 1, 3, 4, 4])) == [1, 2, 3, 4]
    assert list(util.distinct('foobar')) == ['f', 'o', 'b', 'a', 'r']

def test_pathmatch():
    assert util.pathmatch('**.py', 'bar.py')
    assert util.pathmatch('**.py', 'foo/bar/baz.py')
    assert not util.pathmatch('**.py', 'templates/index.html')
    assert util.pathmatch('**/templates/*.html', 'templates/index.html')
    assert not util.pathmatch('**/templates/*.html', 'templates/foo/bar.html')
    assert util.pathmatch('^foo/**.py', 'foo/bar/baz/blah.py')
    assert not util.pathmatch('^foo/**.py', 'blah/foo/bar/baz.py')
    assert util.pathmatch('./foo/**.py', 'foo/bar/baz/blah.py')
    assert util.pathmatch('./blah.py', 'blah.py')
    assert not util.pathmatch('./foo/**.py', 'blah/foo/bar/baz.py')

class FixedOffsetTimezoneTestCase(unittest.TestCase):

    def test_zone_negative_offset(self):
        self.assertEqual('Etc/GMT-60', util.FixedOffsetTimezone(-60).zone)

    def test_zone_zero_offset(self):
        self.assertEqual('Etc/GMT+0', util.FixedOffsetTimezone(0).zone)

    def test_zone_positive_offset(self):
        self.assertEqual('Etc/GMT+330', util.FixedOffsetTimezone(330).zone)

parse_encoding = lambda s: util.parse_encoding(BytesIO(s.encode('utf-8')))

def test_parse_encoding_defined():
    assert parse_encoding(u'# coding: utf-8') == 'utf-8'

def test_parse_encoding_undefined():
    assert parse_encoding(u'') is None

def test_parse_encoding_non_ascii():
    assert parse_encoding(u'K\xf6ln') is None

@pytest.mark.parametrize('source, result', [
    ('''
from __future__ import print_function,
    division, with_statement,
    unicode_literals
''', _FF.print_function | _FF.division | _FF.with_statement | _FF.unicode_literals),
    ('''
from __future__ import print_function, division
print('hello')
''', _FF.print_function | _FF.division),
    ('''
from __future__ import print_function, division, unknown,,,,,
print 'hello'
''', _FF.print_function | _FF.division),
    ('''
from __future__ import (
    print_function,
    division)
''', _FF.print_function | _FF.division),
    ('''
from __future__ import \\
    print_function, \\
    division
''', _FF.print_function | _FF.division),
])
def test_parse_future(source, result):
    fp = BytesIO(source.encode('latin-1'))
    flags = parse_future_flags(fp)
    assert flags == result
<|endoftext|>


<commit_before># Calculator project for collaboration
<commit_msg>division function is added<commit_after># Calculator project for collaboration

x = 0
y = 0

def division(x, y):
	if(y!=0):
		return(x/y)
	else:
		return("Division by Zero not defined")
<|endoftext|>


<commit_before>import pytest
import random

from pycoin.tx.TxOut import TxOut
from pycoin.tx.Spendable import Spendable

from nowallet import subclasses

@pytest.fixture
def server():
    return subclasses.MyServerInfo("onion",
                                   hostname="fdkhv2bb7hqel2e7.onion",
                                   ports=12345)

def test_myserverinfo_class(server):
    assert isinstance(server, subclasses.MyServerInfo)
    assert server.get_port("t") == ("fdkhv2bb7hqel2e7.onion", 12345, False)

@pytest.fixture
def lextxout_small_coin_small_script():
    return subclasses.LexTxOut(0, b"\x00")
@pytest.fixture
def lextxout_large_coin_small_script():
    return subclasses.LexTxOut(10, b"\x00")
@pytest.fixture
def lextxout_small_coin_large_script():
    return subclasses.LexTxOut(0, b"\xFF")
@pytest.fixture
def lextxout_large_coin_large_script():
    return subclasses.LexTxOut(10, b"\xFF")

def test_lextxout_ordering(lextxout_small_coin_small_script,
                           lextxout_large_coin_small_script,
                           lextxout_small_coin_large_script,
                           lextxout_large_coin_large_script):
    assert lextxout_large_coin_large_script == subclasses.LexTxOut(10, b"\xFF")
    lextxout_list = [lextxout_small_coin_small_script,
                     lextxout_large_coin_small_script,
                     lextxout_small_coin_large_script,
                     lextxout_large_coin_large_script]
    random.shuffle(lextxout_list)
    lextxout_list.sort()
    assert lextxout_list[0] == lextxout_small_coin_small_script
    assert lextxout_list[1] == lextxout_small_coin_large_script
    assert lextxout_list[2] == lextxout_large_coin_small_script
    assert lextxout_list[3] == lextxout_large_coin_large_script

def test_lextxout_demote(lextxout_small_coin_small_script):
    txout = subclasses.LexTxOut.demote(lextxout_small_coin_small_script)
    assert isinstance(txout, TxOut)
    assert txout.coin_value == 0
    assert txout.script == b"\x00"

@pytest.fixture
def lexspendable_small_hex_small_vout(lextxout_small_coin_small_script):
    spend = Spendable.from_tx_out(lextxout_small_coin_small_script, b"\x00", 0)
    return subclasses.LexSpendable.promote(spend)
@pytest.fixture
def lexspendable_large_hex_small_vout(lextxout_large_coin_small_script):
    spend = Spendable.from_tx_out(lextxout_large_coin_small_script, b"\xFF", 0)
    return subclasses.LexSpendable.promote(spend)
@pytest.fixture
def lexspendable_small_hex_large_vout(lextxout_small_coin_large_script):
    spend = Spendable.from_tx_out(lextxout_small_coin_large_script, b"\x00", 10)
    return subclasses.LexSpendable.promote(spend)
@pytest.fixture
def lexspendable_large_hex_large_vout(lextxout_large_coin_large_script):
    spend = Spendable.from_tx_out(lextxout_large_coin_large_script, b"\xFF", 10)
    return subclasses.LexSpendable.promote(spend)

def test_lexspendable_ordering(lextxout_large_coin_large_script,
                               lexspendable_small_hex_small_vout,
                               lexspendable_large_hex_small_vout,
                               lexspendable_small_hex_large_vout,
                               lexspendable_large_hex_large_vout):
    spend = Spendable.from_tx_out(lextxout_large_coin_large_script, b"\xFF", 10)
    assert lexspendable_large_hex_large_vout == \
        subclasses.LexSpendable.promote(spend)
    lexspendable_list = [lexspendable_small_hex_small_vout,
                         lexspendable_large_hex_small_vout,
                         lexspendable_small_hex_large_vout,
                         lexspendable_large_hex_large_vout]
    random.shuffle(lexspendable_list)
    lexspendable_list.sort()
    assert lexspendable_list[0] == lexspendable_small_hex_small_vout
    assert lexspendable_list[1] == lexspendable_small_hex_large_vout
    assert lexspendable_list[2] == lexspendable_large_hex_small_vout
    assert lexspendable_list[3] == lexspendable_large_hex_large_vout

def test_lexspendable_promote(lexspendable_small_hex_small_vout):
    spendable = Spendable.from_tx_out(TxOut(0, b"\x00"), b"\x00", 0)
    lexspendable = subclasses.LexSpendable.promote(spendable)
    assert isinstance(lexspendable, subclasses.LexSpendable)
    assert lexspendable.tx_hash == b"\x00"
    assert lexspendable.tx_out_index == 0

@pytest.fixture
def segwitbip32node_from_chbs():
    secret = "CORRECT HORSE BATTERY STAPLE".encode("utf-8")
    return subclasses.SegwitBIP32Node.from_master_secret(secret)

def test_segwitkey_script(segwitbip32node_from_chbs):
    script = segwitbip32node_from_chbs.p2sh_p2wpkh_script()
    assert isinstance(script, bytes)
    assert script == (b"\x00\x14\xe5\xba\xc1f\xbd[\x9fb\x04" + \
                      b"\xb1\xb4?\xb3\xc6!\x99qd\xc7\xfe")

def test_segwitkey_script_hash(segwitbip32node_from_chbs):
    script_hash = segwitbip32node_from_chbs.p2sh_p2wpkh_script_hash()
    assert isinstance(script_hash, bytes)
    assert script_hash == (b"H\x12\xe21\x90\x00:\xc2\xd2\xd7" + \
                           b"\xe3\x15\x99<\x96\x08\xaea\xac%")

def test_segwitkey_address(segwitbip32node_from_chbs):
    address = segwitbip32node_from_chbs.p2sh_p2wpkh_address()
    assert isinstance(address, str)
    assert address == "38G7CQfoej3fZQbHHey7Z1XPUGpVpJv4em"

<commit_msg>Update tests after renaming segwitkey script methods.<commit_after>import pytest
import random

from pycoin.tx.TxOut import TxOut
from pycoin.tx.Spendable import Spendable

from nowallet import subclasses

@pytest.fixture
def server():
    return subclasses.MyServerInfo("onion",
                                   hostname="fdkhv2bb7hqel2e7.onion",
                                   ports=12345)

def test_myserverinfo_class(server):
    assert isinstance(server, subclasses.MyServerInfo)
    assert server.get_port("t") == ("fdkhv2bb7hqel2e7.onion", 12345, False)

@pytest.fixture
def lextxout_small_coin_small_script():
    return subclasses.LexTxOut(0, b"\x00")
@pytest.fixture
def lextxout_large_coin_small_script():
    return subclasses.LexTxOut(10, b"\x00")
@pytest.fixture
def lextxout_small_coin_large_script():
    return subclasses.LexTxOut(0, b"\xFF")
@pytest.fixture
def lextxout_large_coin_large_script():
    return subclasses.LexTxOut(10, b"\xFF")

def test_lextxout_ordering(lextxout_small_coin_small_script,
                           lextxout_large_coin_small_script,
                           lextxout_small_coin_large_script,
                           lextxout_large_coin_large_script):
    assert lextxout_large_coin_large_script == subclasses.LexTxOut(10, b"\xFF")
    lextxout_list = [lextxout_small_coin_small_script,
                     lextxout_large_coin_small_script,
                     lextxout_small_coin_large_script,
                     lextxout_large_coin_large_script]
    random.shuffle(lextxout_list)
    lextxout_list.sort()
    assert lextxout_list[0] == lextxout_small_coin_small_script
    assert lextxout_list[1] == lextxout_small_coin_large_script
    assert lextxout_list[2] == lextxout_large_coin_small_script
    assert lextxout_list[3] == lextxout_large_coin_large_script

def test_lextxout_demote(lextxout_small_coin_small_script):
    txout = subclasses.LexTxOut.demote(lextxout_small_coin_small_script)
    assert isinstance(txout, TxOut)
    assert txout.coin_value == 0
    assert txout.script == b"\x00"

@pytest.fixture
def lexspendable_small_hex_small_vout(lextxout_small_coin_small_script):
    spend = Spendable.from_tx_out(lextxout_small_coin_small_script, b"\x00", 0)
    return subclasses.LexSpendable.promote(spend)
@pytest.fixture
def lexspendable_large_hex_small_vout(lextxout_large_coin_small_script):
    spend = Spendable.from_tx_out(lextxout_large_coin_small_script, b"\xFF", 0)
    return subclasses.LexSpendable.promote(spend)
@pytest.fixture
def lexspendable_small_hex_large_vout(lextxout_small_coin_large_script):
    spend = Spendable.from_tx_out(lextxout_small_coin_large_script, b"\x00", 10)
    return subclasses.LexSpendable.promote(spend)
@pytest.fixture
def lexspendable_large_hex_large_vout(lextxout_large_coin_large_script):
    spend = Spendable.from_tx_out(lextxout_large_coin_large_script, b"\xFF", 10)
    return subclasses.LexSpendable.promote(spend)

def test_lexspendable_ordering(lextxout_large_coin_large_script,
                               lexspendable_small_hex_small_vout,
                               lexspendable_large_hex_small_vout,
                               lexspendable_small_hex_large_vout,
                               lexspendable_large_hex_large_vout):
    spend = Spendable.from_tx_out(lextxout_large_coin_large_script, b"\xFF", 10)
    assert lexspendable_large_hex_large_vout == \
        subclasses.LexSpendable.promote(spend)
    lexspendable_list = [lexspendable_small_hex_small_vout,
                         lexspendable_large_hex_small_vout,
                         lexspendable_small_hex_large_vout,
                         lexspendable_large_hex_large_vout]
    random.shuffle(lexspendable_list)
    lexspendable_list.sort()
    assert lexspendable_list[0] == lexspendable_small_hex_small_vout
    assert lexspendable_list[1] == lexspendable_small_hex_large_vout
    assert lexspendable_list[2] == lexspendable_large_hex_small_vout
    assert lexspendable_list[3] == lexspendable_large_hex_large_vout

def test_lexspendable_promote(lexspendable_small_hex_small_vout):
    spendable = Spendable.from_tx_out(TxOut(0, b"\x00"), b"\x00", 0)
    lexspendable = subclasses.LexSpendable.promote(spendable)
    assert isinstance(lexspendable, subclasses.LexSpendable)
    assert lexspendable.tx_hash == b"\x00"
    assert lexspendable.tx_out_index == 0

@pytest.fixture
def segwitbip32node_from_chbs():
    secret = "CORRECT HORSE BATTERY STAPLE".encode("utf-8")
    return subclasses.SegwitBIP32Node.from_master_secret(secret)

def test_segwitkey_script(segwitbip32node_from_chbs):
    script = segwitbip32node_from_chbs.p2wpkh_script()
    assert isinstance(script, bytes)
    assert script == (b"\x00\x14\xe5\xba\xc1f\xbd[\x9fb\x04" + \
                      b"\xb1\xb4?\xb3\xc6!\x99qd\xc7\xfe")

def test_segwitkey_script_hash(segwitbip32node_from_chbs):
    script_hash = segwitbip32node_from_chbs.p2wpkh_script_hash()
    assert isinstance(script_hash, bytes)
    assert script_hash == (b"H\x12\xe21\x90\x00:\xc2\xd2\xd7" + \
                           b"\xe3\x15\x99<\x96\x08\xaea\xac%")

def test_segwitkey_address(segwitbip32node_from_chbs):
    address = segwitbip32node_from_chbs.p2sh_p2wpkh_address()
    assert isinstance(address, str)
    assert address == "38G7CQfoej3fZQbHHey7Z1XPUGpVpJv4em"

#def test_bech32_segwitkey_address(segwitbip32node_from_chbs):
#    address = segwitbip32node_from_chbs.p2sh_p2wpkh_address()
#    assert isinstance(address, str)
#    assert address == "38G7CQfoej3fZQbHHey7Z1XPUGpVpJv4em"

<|endoftext|>


<commit_before># coding: utf8
from __future__ import unicode_literals, print_function

import pytest
from wasabi.util import color, wrap, locale_escape, supports_ansi, format_repr

def test_color():
    assert color("test", fg="green") == "\x1b[38;5;2mtest\x1b[0m"
    assert color("test", fg=4) == "\x1b[38;5;4mtest\x1b[0m"
    assert color("test", bold=True) == "\x1b[1mtest\x1b[0m"
    assert color("test", fg="red", underline=True) == "\x1b[4;38;5;1mtest\x1b[0m"
    assert (
        color("test", fg=7, bg="red", bold=True) == "\x1b[1;38;5;7;48;5;1mtest\x1b[0m"
    )

def test_wrap():
    text = "Hello world, this is a test."
    assert wrap(text, indent=0) == text
    assert wrap(text, indent=4) == "    Hello world, this is a test."
    assert wrap(text, wrap_max=10, indent=0) == "Hello\nworld,\nthis is a\ntest."
    assert (
        wrap(text, wrap_max=5, indent=2)
        == "  Hello\n  world,\n  this\n  is\n  a\n  test."
    )

def test_format_repr():
    obj = {"hello": "world", "test": 123}
    formatted = format_repr(obj)
    assert formatted.replace("u'", "'") in [
        "{'hello': 'world', 'test': 123}",
        "{'test': 123, 'hello': 'world'}",
    ]
    formatted = format_repr(obj, max_len=10)
    assert formatted.replace("u'", "'") in [
        "{'hel ...  123}",
        "{'tes ... rld'}",
        "{'te ... rld'}",
    ]
    formatted = format_repr(obj, max_len=10, ellipsis="[...]")
    assert formatted.replace("u'", "'") in [
        "{'hel [...]  123}",
        "{'tes ... rld'}",
        "{'te [...] rld'}",
    ]

@pytest.mark.parametrize(
    "text,non_ansi", [("abc", "abc"), ("\u2714 abc", " abc"), ("👻", "")]
)
def test_locale_escape(text, non_ansi):
    result = locale_escape(text)
    if supports_ansi():
        assert result
    else:
        assert result == non_ansi
<commit_msg>Fix test<commit_after># coding: utf8
from __future__ import unicode_literals, print_function

import pytest
from wasabi.util import color, wrap, locale_escape, supports_ansi, format_repr

def test_color():
    assert color("test", fg="green") == "\x1b[38;5;2mtest\x1b[0m"
    assert color("test", fg=4) == "\x1b[38;5;4mtest\x1b[0m"
    assert color("test", bold=True) == "\x1b[1mtest\x1b[0m"
    assert color("test", fg="red", underline=True) == "\x1b[4;38;5;1mtest\x1b[0m"
    assert (
        color("test", fg=7, bg="red", bold=True) == "\x1b[1;38;5;7;48;5;1mtest\x1b[0m"
    )

def test_wrap():
    text = "Hello world, this is a test."
    assert wrap(text, indent=0) == text
    assert wrap(text, indent=4) == "    Hello world, this is a test."
    assert wrap(text, wrap_max=10, indent=0) == "Hello\nworld,\nthis is a\ntest."
    assert (
        wrap(text, wrap_max=5, indent=2)
        == "  Hello\n  world,\n  this\n  is\n  a\n  test."
    )

def test_format_repr():
    obj = {"hello": "world", "test": 123}
    formatted = format_repr(obj)
    assert formatted.replace("u'", "'") in [
        "{'hello': 'world', 'test': 123}",
        "{'test': 123, 'hello': 'world'}",
    ]
    formatted = format_repr(obj, max_len=10)
    assert formatted.replace("u'", "'") in [
        "{'hel ...  123}",
        "{'tes ... rld'}",
        "{'te ... rld'}",
    ]
    formatted = format_repr(obj, max_len=10, ellipsis="[...]")
    assert formatted.replace("u'", "'") in [
        "{'hel [...]  123}",
        "{'tes [...] rld'}",
        "{'te [...] rld'}",
    ]

@pytest.mark.parametrize(
    "text,non_ansi", [("abc", "abc"), ("\u2714 abc", " abc"), ("👻", "")]
)
def test_locale_escape(text, non_ansi):
    result = locale_escape(text)
    if supports_ansi():
        assert result
    else:
        assert result == non_ansi
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-

from nose.tools import raises

import pylons
from formencode import validators, Schema
from simplejson import loads

from tg.controllers import TGController
from tg.decorators import expose, validate
from tests.base import (TestWSGIController, data_dir,
    make_app, setup_session_dir, teardown_session_dir)

from tw.forms import TableForm, TextField
from tw.api import WidgetsList

def setup():
    setup_session_dir()

def teardown():
    teardown_session_dir()

class MyForm(TableForm):

    class fields(WidgetsList):
        """This WidgetsList is just a container."""
        title=TextField(validator = validators.NotEmpty())
        year = TextField(size=4, validator=validators.Int())

# then, we create an instance of this form
myform = MyForm("my_form", action='create')

class Pwd(Schema):
    pwd1 = validators.String(not_empty=True)
    pwd2 = validators.String(not_empty=True)
    chained_validators = [validators.FieldsMatch('pwd1', 'pwd2')]

class controller_based_validate(validate):

    def __init__(self, error_handler=None, *args, **kw):
        self.error_handler = error_handler
        self.needs_controller = True

        class Validators(object):
            def validate(self, controller, params, state):
                return params

        self.validators = Validators()

class ColonValidator(validators.FancyValidator):
    def validate_python(self, value, state):
        raise validators.Invalid('ERROR: Description', value, state)

class BasicTGController(TGController):

    @expose('json')
    @validate(validators={"some_int": validators.Int()})
    def validated_int(self, some_int):
        assert isinstance(some_int, int)
        return dict(response=some_int)

    @expose('json')
    @validate(validators={"a": validators.Int()})
    def validated_and_unvalidated(self, a, b):
        assert isinstance(a, int)
        assert isinstance(b, unicode)
        return dict(int=a, str=b)

    @expose()
    @controller_based_validate()
    def validate_controller_based_validator(self, *args, **kw):
        return 'ok'

    @expose('json')
    @validate(validators={"a": validators.Int(), "someemail": validators.Email})
    def two_validators(self, a=None, someemail=None, *args):
        errors = pylons.tmpl_context.form_errors
        values =  pylons.tmpl_context.form_values
        return dict(a=a, someemail=someemail,
                errors=str(errors), values=str(values))

    @expose('json')
    @validate(validators={"a": validators.Int()})
    def with_default_shadow(self, a, b=None ):
        """A default value should not cause the validated value to disappear"""
        assert isinstance( a, int ), type(a)
        return {
            'int': a,
        }

    @expose('json')
    @validate(validators={"e": ColonValidator()})
    def error_with_colon(self, e):
        errors = pylons.tmpl_context.form_errors
        return dict(errors=str(errors))

    @expose('json')
    @validate(validators={
        "a": validators.Int(),"b":validators.Int(),"c":validators.Int(),"d":validators.Int()
    })
    def with_default_shadow_long(self, a, b=None,c=None,d=None ):
        """A default value should not cause the validated value to disappear"""
        assert isinstance( a, int ), type(a)
        assert isinstance( b, int ), type(b)
        assert isinstance( c, int ), type(c)
        assert isinstance( d, int ), type(d)
        return {
            'int': [a,b,c,d],
        }

    @expose()
    def display_form(self, **kwargs):
        return str(myform.render(values=kwargs))

    @expose('json')
    @validate(form=myform)
    def process_form(self, **kwargs):
        kwargs['errors'] = pylons.tmpl_context.form_errors
        return dict(kwargs)

    @expose('json')
    @validate(form=myform, error_handler=process_form)
    def send_to_error_handler(self, **kwargs):
        kwargs['errors'] = pylons.tmpl_context.form_errors
        return dict(kwargs)

    @expose()
    def set_lang(self, lang=None):
        pylons.session['tg_lang'] = lang
        pylons.session.save()
        return 'ok'

    @expose()
    @validate(validators=Pwd())
    def password(self, pwd1, pwd2):
        if pylons.tmpl_context.form_errors:
            return "There was an error"
        else:
            return "Password ok!"

class TestTGController(TestWSGIController):

    def setUp(self):
        TestWSGIController.setUp(self)
        pylons.config.update({
            'pylons.paths': {'root': data_dir},
            'pylons.package': 'tests'})
        self.app = make_app(BasicTGController)

    def test_basic_validation_and_jsonification(self):
        """Ensure you can pass in a dictionary of validators"""
        form_values = {"some_int": 22}
        resp = self.app.post('/validated_int', form_values)
        assert '{"response": 22}'in resp, resp

    def test_for_other_params_after_validation(self):
        """Ensure that both validated and unvalidated data make it through"""
        form_values = {'a': 1, 'b': "string"}
        resp = self.app.post('/validated_and_unvalidated', form_values)
        assert '"int": 1' in resp
        assert '"str": "string"' in resp, resp

    def test_validation_shadowed_by_defaults( self ):
        """Catch regression on positional argument validation with defaults"""
        resp = self.app.post('/with_default_shadow/1?b=string')
        assert '"int": 1' in resp, resp

    def test_optional_shadowed_by_defaults( self ):
        """Catch regression on optional arguments being reverted to un-validated"""
        resp = self.app.post('/with_default_shadow_long/1?b=2&c=3&d=4')
        assert '"int": [1, 2, 3, 4]' in resp, resp

    @raises(AssertionError)
    def test_validation_fails_with_no_error_handler(self):
        form_values = {'a':'asdf', 'b':"string"}
        resp = self.app.post('/validated_and_unvalidated', form_values)

    def test_two_validators_errors(self):
        """Ensure that multiple validators are applied correctly"""
        form_values = {'a': '1', 'someemail': "guido@google.com"}
        resp = self.app.post('/two_validators', form_values)
        content = loads(resp.body)
        assert content['a'] == 1

    def test_validation_errors(self):
        """Ensure that dict validation produces a full set of errors"""
        form_values = {'a': '1', 'someemail': "guido~google.com"}
        resp = self.app.post('/two_validators', form_values)
        content = loads(resp.body)
        errors = content.get('errors', None)
        assert errors, 'There should have been at least one error'
        assert 'someemail' in errors, \
            'The email was invalid and should have been reported in the errors'

    def test_form_validation(self):
        """Check @validate's handing of ToscaWidget forms instances"""
        form_values = {'title': 'Razer', 'year': "2007"}
        resp = self.app.post('/process_form', form_values)
        values = loads(resp.body)
        assert values['year'] == 2007

    def test_error_with_colon(self):
        resp = self.app.post('/error_with_colon', {'e':"fakeparam"})
        assert 'Description' in resp.body, resp.body

    def test_form_render(self):
        """Test that myform renders properly"""
        resp = self.app.post('/display_form')
        assert 'id="my_form_title.label"' in resp, resp
        assert 'class="fieldlabel required"' in resp, resp
        assert "Title" in resp, resp

    def test_form_validation_error(self):
        """Test form validation with error message"""
        form_values = {'title': 'Razer', 'year': "t007"}
        resp = self.app.post('/process_form', form_values)
        values = loads(resp.body)
        assert "Please enter an integer value" in values['errors']['year'], \
            'Error message not found: %r' % values['errors']

    def test_form_validation_redirect(self):
        """Test form validation error message with redirect"""
        form_values = {'title': 'Razer', 'year': "t007"}
        resp = self.app.post('/send_to_error_handler', form_values)
        values = loads(resp.body)
        assert "Please enter an integer value" in values['errors']['year'], \
            'Error message not found: %r' % values['errors']

    def test_form_validation_translation(self):
        """Test translation of form validation error messages"""
        form_values = {'title': 'Razer', 'year': "t007"}
        # check with language set in request header
        resp = self.app.post('/process_form', form_values,
            headers={'Accept-Language': 'de,ru,it'})
        values = loads(resp.body)
        assert u"Bitte eine ganze Zahl eingeben" in values['errors']['year'], \
            'No German error message: %r' % values['errors']
        resp = self.app.post('/process_form', form_values,
            headers={'Accept-Language': 'ru,de,it'})
        values = loads(resp.body)
        assert u"Введите числовое значение" in values['errors']['year'], \
            'No Russian error message: %r' % values['errors']
        # check with language set in session
        self.app.post('/set_lang/de')
        resp = self.app.post('/process_form', form_values,
            headers={'Accept-Language': 'ru,it'})
        values = loads(resp.body)
        assert u"Bitte eine ganze Zahl eingeben" in values['errors']['year'], \
            'No German error message: %r' % values['errors']

    def test_form_validation_error(self):
        """Test schema validation"""
        form_values = {'pwd1': 'me', 'pwd2': 'you'}
        resp = self.app.post('/password', form_values)
        assert "There was an error" in resp, resp
        form_values = {'pwd1': 'you', 'pwd2': 'you'}
        resp = self.app.post('/password', form_values)
        assert "Password ok!" in resp, resp

    def test_controller_based_validator(self):
        """Test controller based validation"""
        resp = self.app.post('/validate_controller_based_validator')
        assert 'ok' in resp, resp
<commit_msg>all tests passing<commit_after># -*- coding: utf-8 -*-

from nose.tools import raises

import tg
import tests
from formencode import validators, Schema
from simplejson import loads

from tg.controllers import TGController
from tg.decorators import expose, validate
from tests.base import (TestWSGIController, data_dir,
    make_app, setup_session_dir, teardown_session_dir)

from tw.forms import TableForm, TextField
from tw.api import WidgetsList

def setup():
    setup_session_dir()

def teardown():
    teardown_session_dir()

class MyForm(TableForm):

    class fields(WidgetsList):
        """This WidgetsList is just a container."""
        title=TextField(validator = validators.NotEmpty())
        year = TextField(size=4, validator=validators.Int())

# then, we create an instance of this form
myform = MyForm("my_form", action='create')

class Pwd(Schema):
    pwd1 = validators.String(not_empty=True)
    pwd2 = validators.String(not_empty=True)
    chained_validators = [validators.FieldsMatch('pwd1', 'pwd2')]

class controller_based_validate(validate):

    def __init__(self, error_handler=None, *args, **kw):
        self.error_handler = error_handler
        self.needs_controller = True

        class Validators(object):
            def validate(self, controller, params, state):
                return params

        self.validators = Validators()

class ColonValidator(validators.FancyValidator):
    def validate_python(self, value, state):
        raise validators.Invalid('ERROR: Description', value, state)

class BasicTGController(TGController):

    @expose('json')
    @validate(validators={"some_int": validators.Int()})
    def validated_int(self, some_int):
        assert isinstance(some_int, int)
        return dict(response=some_int)

    @expose('json')
    @validate(validators={"a": validators.Int()})
    def validated_and_unvalidated(self, a, b):
        assert isinstance(a, int)
        assert isinstance(b, unicode)
        return dict(int=a, str=b)

    @expose()
    @controller_based_validate()
    def validate_controller_based_validator(self, *args, **kw):
        return 'ok'

    @expose('json')
    @validate(validators={"a": validators.Int(), "someemail": validators.Email})
    def two_validators(self, a=None, someemail=None, *args):
        errors = tg.tmpl_context.form_errors
        values =  tg.tmpl_context.form_values
        return dict(a=a, someemail=someemail,
                errors=str(errors), values=str(values))

    @expose('json')
    @validate(validators={"a": validators.Int()})
    def with_default_shadow(self, a, b=None ):
        """A default value should not cause the validated value to disappear"""
        assert isinstance( a, int ), type(a)
        return {
            'int': a,
        }

    @expose('json')
    @validate(validators={"e": ColonValidator()})
    def error_with_colon(self, e):
        errors = tg.tmpl_context.form_errors
        return dict(errors=str(errors))

    @expose('json')
    @validate(validators={
        "a": validators.Int(),"b":validators.Int(),"c":validators.Int(),"d":validators.Int()
    })
    def with_default_shadow_long(self, a, b=None,c=None,d=None ):
        """A default value should not cause the validated value to disappear"""
        assert isinstance( a, int ), type(a)
        assert isinstance( b, int ), type(b)
        assert isinstance( c, int ), type(c)
        assert isinstance( d, int ), type(d)
        return {
            'int': [a,b,c,d],
        }

    @expose()
    def display_form(self, **kwargs):
        return str(myform.render(values=kwargs))

    @expose('json')
    @validate(form=myform)
    def process_form(self, **kwargs):
        kwargs['errors'] = tg.tmpl_context.form_errors
        return dict(kwargs)

    @expose('json')
    @validate(form=myform, error_handler=process_form)
    def send_to_error_handler(self, **kwargs):
        kwargs['errors'] = tg.tmpl_context.form_errors
        return dict(kwargs)

    @expose()
    def set_lang(self, lang=None):
        tg.session['tg_lang'] = lang
        tg.session.save()
        return 'ok'

    @expose()
    @validate(validators=Pwd())
    def password(self, pwd1, pwd2):
        if tg.tmpl_context.form_errors:
            return "There was an error"
        else:
            return "Password ok!"

class TestTGController(TestWSGIController):

    def setUp(self):
        TestWSGIController.setUp(self)
        tg.config.update({
            'paths': {'root': data_dir},
            'package': tests})
        self.app = make_app(BasicTGController)

    def test_basic_validation_and_jsonification(self):
        """Ensure you can pass in a dictionary of validators"""
        form_values = {"some_int": 22}
        resp = self.app.post('/validated_int', form_values)
        assert '{"response": 22}'in resp, resp

    def test_for_other_params_after_validation(self):
        """Ensure that both validated and unvalidated data make it through"""
        form_values = {'a': 1, 'b': "string"}
        resp = self.app.post('/validated_and_unvalidated', form_values)
        assert '"int": 1' in resp
        assert '"str": "string"' in resp, resp

    def test_validation_shadowed_by_defaults( self ):
        """Catch regression on positional argument validation with defaults"""
        resp = self.app.post('/with_default_shadow/1?b=string')
        assert '"int": 1' in resp, resp

    def test_optional_shadowed_by_defaults( self ):
        """Catch regression on optional arguments being reverted to un-validated"""
        resp = self.app.post('/with_default_shadow_long/1?b=2&c=3&d=4')
        assert '"int": [1, 2, 3, 4]' in resp, resp

    @raises(AssertionError)
    def test_validation_fails_with_no_error_handler(self):
        form_values = {'a':'asdf', 'b':"string"}
        resp = self.app.post('/validated_and_unvalidated', form_values)

    def test_two_validators_errors(self):
        """Ensure that multiple validators are applied correctly"""
        form_values = {'a': '1', 'someemail': "guido@google.com"}
        resp = self.app.post('/two_validators', form_values)
        content = loads(resp.body)
        assert content['a'] == 1

    def test_validation_errors(self):
        """Ensure that dict validation produces a full set of errors"""
        form_values = {'a': '1', 'someemail': "guido~google.com"}
        resp = self.app.post('/two_validators', form_values)
        content = loads(resp.body)
        errors = content.get('errors', None)
        assert errors, 'There should have been at least one error'
        assert 'someemail' in errors, \
            'The email was invalid and should have been reported in the errors'

    def test_form_validation(self):
        """Check @validate's handing of ToscaWidget forms instances"""
        form_values = {'title': 'Razer', 'year': "2007"}
        resp = self.app.post('/process_form', form_values)
        values = loads(resp.body)
        assert values['year'] == 2007

    def test_error_with_colon(self):
        resp = self.app.post('/error_with_colon', {'e':"fakeparam"})
        assert 'Description' in resp.body, resp.body

    def test_form_render(self):
        """Test that myform renders properly"""
        resp = self.app.post('/display_form')
        assert 'id="my_form_title.label"' in resp, resp
        assert 'class="fieldlabel required"' in resp, resp
        assert "Title" in resp, resp

    def test_form_validation_error(self):
        """Test form validation with error message"""
        form_values = {'title': 'Razer', 'year': "t007"}
        resp = self.app.post('/process_form', form_values)
        values = loads(resp.body)
        assert "Please enter an integer value" in values['errors']['year'], \
            'Error message not found: %r' % values['errors']

    def test_form_validation_redirect(self):
        """Test form validation error message with redirect"""
        form_values = {'title': 'Razer', 'year': "t007"}
        resp = self.app.post('/send_to_error_handler', form_values)
        values = loads(resp.body)
        assert "Please enter an integer value" in values['errors']['year'], \
            'Error message not found: %r' % values['errors']

    def test_form_validation_translation(self):
        """Test translation of form validation error messages"""
        form_values = {'title': 'Razer', 'year': "t007"}
        # check with language set in request header
        resp = self.app.post('/process_form', form_values,
            headers={'Accept-Language': 'de,ru,it'})
        values = loads(resp.body)
        assert u"Bitte eine ganze Zahl eingeben" in values['errors']['year'], \
            'No German error message: %r' % values['errors']
        resp = self.app.post('/process_form', form_values,
            headers={'Accept-Language': 'ru,de,it'})
        values = loads(resp.body)
        assert u"Введите числовое значение" in values['errors']['year'], \
            'No Russian error message: %r' % values['errors']
        # check with language set in session
        self.app.post('/set_lang/de')
        resp = self.app.post('/process_form', form_values,
            headers={'Accept-Language': 'ru,it'})
        values = loads(resp.body)
        assert u"Bitte eine ganze Zahl eingeben" in values['errors']['year'], \
            'No German error message: %r' % values['errors']

    def test_form_validation_error(self):
        """Test schema validation"""
        form_values = {'pwd1': 'me', 'pwd2': 'you'}
        resp = self.app.post('/password', form_values)
        assert "There was an error" in resp, resp
        form_values = {'pwd1': 'you', 'pwd2': 'you'}
        resp = self.app.post('/password', form_values)
        assert "Password ok!" in resp, resp

    def test_controller_based_validator(self):
        """Test controller based validation"""
        resp = self.app.post('/validate_controller_based_validator')
        assert 'ok' in resp, resp
<|endoftext|>


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

import os, imp, sys, unittest, ConfigParser, types

# setup system library path
pathname = os.path.realpath('../')
sys.path.insert(0, pathname)

from osg_configure.modules import exceptions
from osg_configure.modules import validation
from osg_configure.modules.utilities import get_test_config

pathname = os.path.join('../scripts', 'osg-configure')
if not os.path.exists(pathname):
  pathname = os.path.join('/', 'usr', 'sbin', 'osg-configure')
  if not os.path.exists(pathname):
    raise Exception("Can't find osg-configure script")

try:
    has_configure_osg = False
    fp = open(pathname, 'r')
    configure_osg = imp.load_module('test_module', fp, pathname, ('', '', 1))
    has_configure_osg = True
except:
    raise Exception("Can't import osg-configure script")

class TestValidation(unittest.TestCase):

    def test_valid_domain(self):
      """
      Check the valid_domain functionality
      """
      test_domain = "testing"
      self.failIf(validation.valid_domain(test_domain),
                  "testing marked as a valid domain address")

      test_domain = "34c93F.39f@~#"
      self.failIf(validation.valid_domain(test_domain),
                  "testing marked as a valid domain address")

      test_domain = "t-ea.34.org"
      self.failUnless(validation.valid_domain(test_domain),
                      "t-ea.34.org marked as an invalid domain address")

      test_domain = "uchicago.edu"
      self.failUnless(validation.valid_domain(test_domain, resolve = True),
                      "uchicago.edu marked as an invalid domain address")

      test_domain = "invalid.invalid"
      self.failIf(validation.valid_domain(test_domain, resolve = True),
                  "invalid.invalid marked as an valid domain address")

    def test_valid_email(self):
      """
      Check the valid email functionality
      """
      failed = False
      test_email = "fake@email@testing"
      self.failIf(validation.valid_email(test_email),
                  "fake@email@testing marked as a valid email address")

      test_email = "a.3a-3bc@t-ea.34.org"
      self.failUnless(validation.valid_email(test_email),
                      "a.3a-3bc@t-ea.34.org marked as an invalid email " \
                      "address")

    def test_valid_location(self):
      """
      Check the valid_location functionality
      """

      test_location = get_test_config("cemon/ignore_bdii.ini")
      self.failUnless(validation.valid_location(test_location),
                      "%s not marked as a valid location" % test_location)

      test_location = "configs/invalid_foo.config"
      self.failIf(validation.valid_location(test_location),
                  "%s marked as a valid location" % test_location)

    def test_valid_file_location(self):
      """
      Check the valid_file functionality
      """
      test_file = get_test_config("utilities/valid_boolean.ini")
      message = "%s not marked as a valid file location" % test_file
      self.failUnless(validation.valid_location(test_file), message)

      test_file = "configs/invalid_foo.config"
      message = "%s marked as a valid file location" % test_file
      self.failIf(validation.valid_location(test_file),
                  message)

    def test_valid_user(self):
      """
      Check the valid_user functionality
      """

      self.failUnless(validation.valid_user('root'),
                      "root not marked as a valid user")

      self.failIf(validation.valid_user('hacked'),
                  "'hacked' is considered a valid user")

    def test_valid_user_vo_file(self):
      """
      Test functionality of valid_user_vo_file function
      """

      test_file = get_test_config("./test_files/valid-user-vo-map.txt")
      self.failUnless(validation.valid_user_vo_file(test_file, False),
                      "Valid file flagged as invalid")

      test_file = get_test_config("./test_files/invalid-user-vo-map.txt")
      self.failIf(validation.valid_user_vo_file(test_file, False),
                  "Invalid file flagged as valid")
      bad_lines = validation.valid_user_vo_file(test_file, True)[1]
      standard_lines =  ['fdjkf394f023', 'sam= 34f3']
      self.failUnlessEqual(bad_lines, standard_lines,
                           "Wrong lines from the vo map obtained, " +
                           "got\n%s" % (bad_lines) +
                           "\nexpected\n%s" % (standard_lines))

    def test_valid_bookean(self):
      """
      Test functionality of valid_boolean function
      """
      config_file = get_test_config('utilities/valid_boolean.ini')
      config = ConfigParser.SafeConfigParser()
      config.read(config_file)
      self.failIf(validation.valid_boolean(config, 'Test', 'invalid_bool'),
                  'invalid_bool flagged as valid')
      self.failIf(validation.valid_boolean(config, 'Test', 'invalid_bool2'),
                  'invalid_bool2 flagged as valid')
      self.failIf(validation.valid_boolean(config, 'Test', 'missing'),
                  'invalid_bool2 flagged as valid')
      self.failUnless(validation.valid_boolean(config, 'Test', 'valid_bool'),
                      'valid_bool flagged as invalid')
      self.failUnless(validation.valid_boolean(config, 'Test', 'valid_bool2'),
                      'valid_bool2 flagged as invalid')

    def test_valid_executable(self):
      """
      Test functionality of valid_executable function
      """

      binary = "/bin/ls"
      text = get_test_config("test_files/subscriptions.xml")
      missing = "./test_files/foo"

      self.failIf(validation.valid_executable(missing),
                  "Non-existent file is not a valid executable")
      self.failIf(validation.valid_executable(text),
                  "Text file is not a valid executable")
      self.failUnless(validation.valid_executable(binary),
                      "/bin/ls should be a valid binary")

    def test_valid_file2(self):
      """
      Test functionality of valid_file function
      """

      filename = get_test_config('utilities/newline.ini')
      self.failIf(validation.valid_ini_file(filename),
                  "Didn't detect newline in %s"  % filename)

      filename = get_test_config('utilities/valid_boolean.ini')
      self.failUnless(validation.valid_ini_file(filename),
                      "Got error on valid file %s" % filename)

    def test_valid_references(self):
      """
      Test functionality of invalid_references_exist and make sure
      it catches invalid references correctly and lets valid references
      go
      """

      filename = get_test_config('utilities/invalid_ref1.ini')
      self.failIf(validation.valid_ini_file(filename),
                  "Didn't detect invalid reference in %s" % filename)

      filename = get_test_config('utilities/invalid_ref2.ini')
      self.failIf(validation.valid_ini_file(filename),
                  "Didn't detect invalid reference in %s" % filename)

      filename = get_test_config('utilities/valid_ref1.ini')
      self.failUnless(validation.valid_ini_file(filename),
                      "Got error on valid file %s" % filename)

if __name__ == '__main__':
    unittest.main()

<commit_msg>Fix typo in function name<commit_after>#!/usr/bin/env python

import os, imp, sys, unittest, ConfigParser, types

# setup system library path
pathname = os.path.realpath('../')
sys.path.insert(0, pathname)

from osg_configure.modules import exceptions
from osg_configure.modules import validation
from osg_configure.modules.utilities import get_test_config

pathname = os.path.join('../scripts', 'osg-configure')
if not os.path.exists(pathname):
  pathname = os.path.join('/', 'usr', 'sbin', 'osg-configure')
  if not os.path.exists(pathname):
    raise Exception("Can't find osg-configure script")

try:
    has_configure_osg = False
    fp = open(pathname, 'r')
    configure_osg = imp.load_module('test_module', fp, pathname, ('', '', 1))
    has_configure_osg = True
except:
    raise Exception("Can't import osg-configure script")

class TestValidation(unittest.TestCase):

    def test_valid_domain(self):
      """
      Check the valid_domain functionality
      """
      test_domain = "testing"
      self.failIf(validation.valid_domain(test_domain),
                  "testing marked as a valid domain address")

      test_domain = "34c93F.39f@~#"
      self.failIf(validation.valid_domain(test_domain),
                  "testing marked as a valid domain address")

      test_domain = "t-ea.34.org"
      self.failUnless(validation.valid_domain(test_domain),
                      "t-ea.34.org marked as an invalid domain address")

      test_domain = "uchicago.edu"
      self.failUnless(validation.valid_domain(test_domain, resolve = True),
                      "uchicago.edu marked as an invalid domain address")

      test_domain = "invalid.invalid"
      self.failIf(validation.valid_domain(test_domain, resolve = True),
                  "invalid.invalid marked as an valid domain address")

    def test_valid_email(self):
      """
      Check the valid email functionality
      """
      failed = False
      test_email = "fake@email@testing"
      self.failIf(validation.valid_email(test_email),
                  "fake@email@testing marked as a valid email address")

      test_email = "a.3a-3bc@t-ea.34.org"
      self.failUnless(validation.valid_email(test_email),
                      "a.3a-3bc@t-ea.34.org marked as an invalid email " \
                      "address")

    def test_valid_location(self):
      """
      Check the valid_location functionality
      """

      test_location = get_test_config("cemon/ignore_bdii.ini")
      self.failUnless(validation.valid_location(test_location),
                      "%s not marked as a valid location" % test_location)

      test_location = "configs/invalid_foo.config"
      self.failIf(validation.valid_location(test_location),
                  "%s marked as a valid location" % test_location)

    def test_valid_file_location(self):
      """
      Check the valid_file functionality
      """
      test_file = get_test_config("utilities/valid_boolean.ini")
      message = "%s not marked as a valid file location" % test_file
      self.failUnless(validation.valid_location(test_file), message)

      test_file = "configs/invalid_foo.config"
      message = "%s marked as a valid file location" % test_file
      self.failIf(validation.valid_location(test_file),
                  message)

    def test_valid_user(self):
      """
      Check the valid_user functionality
      """

      self.failUnless(validation.valid_user('root'),
                      "root not marked as a valid user")

      self.failIf(validation.valid_user('hacked'),
                  "'hacked' is considered a valid user")

    def test_valid_user_vo_file(self):
      """
      Test functionality of valid_user_vo_file function
      """

      test_file = get_test_config("./test_files/valid-user-vo-map.txt")
      self.failUnless(validation.valid_user_vo_file(test_file, False),
                      "Valid file flagged as invalid")

      test_file = get_test_config("./test_files/invalid-user-vo-map.txt")
      self.failIf(validation.valid_user_vo_file(test_file, False),
                  "Invalid file flagged as valid")
      bad_lines = validation.valid_user_vo_file(test_file, True)[1]
      standard_lines =  ['fdjkf394f023', 'sam= 34f3']
      self.failUnlessEqual(bad_lines, standard_lines,
                           "Wrong lines from the vo map obtained, " +
                           "got\n%s" % (bad_lines) +
                           "\nexpected\n%s" % (standard_lines))

    def test_valid_boolean(self):
      """
      Test functionality of valid_boolean function
      """
      config_file = get_test_config('utilities/valid_boolean.ini')
      config = ConfigParser.SafeConfigParser()
      config.read(config_file)
      self.failIf(validation.valid_boolean(config, 'Test', 'invalid_bool'),
                  'invalid_bool flagged as valid')
      self.failIf(validation.valid_boolean(config, 'Test', 'invalid_bool2'),
                  'invalid_bool2 flagged as valid')
      self.failIf(validation.valid_boolean(config, 'Test', 'missing'),
                  'invalid_bool2 flagged as valid')
      self.failUnless(validation.valid_boolean(config, 'Test', 'valid_bool'),
                      'valid_bool flagged as invalid')
      self.failUnless(validation.valid_boolean(config, 'Test', 'valid_bool2'),
                      'valid_bool2 flagged as invalid')

    def test_valid_executable(self):
      """
      Test functionality of valid_executable function
      """

      binary = "/bin/ls"
      text = get_test_config("test_files/subscriptions.xml")
      missing = "./test_files/foo"

      self.failIf(validation.valid_executable(missing),
                  "Non-existent file is not a valid executable")
      self.failIf(validation.valid_executable(text),
                  "Text file is not a valid executable")
      self.failUnless(validation.valid_executable(binary),
                      "/bin/ls should be a valid binary")

    def test_valid_file2(self):
      """
      Test functionality of valid_file function
      """

      filename = get_test_config('utilities/newline.ini')
      self.failIf(validation.valid_ini_file(filename),
                  "Didn't detect newline in %s"  % filename)

      filename = get_test_config('utilities/valid_boolean.ini')
      self.failUnless(validation.valid_ini_file(filename),
                      "Got error on valid file %s" % filename)

    def test_valid_references(self):
      """
      Test functionality of invalid_references_exist and make sure
      it catches invalid references correctly and lets valid references
      go
      """

      filename = get_test_config('utilities/invalid_ref1.ini')
      self.failIf(validation.valid_ini_file(filename),
                  "Didn't detect invalid reference in %s" % filename)

      filename = get_test_config('utilities/invalid_ref2.ini')
      self.failIf(validation.valid_ini_file(filename),
                  "Didn't detect invalid reference in %s" % filename)

      filename = get_test_config('utilities/valid_ref1.ini')
      self.failUnless(validation.valid_ini_file(filename),
                      "Got error on valid file %s" % filename)

if __name__ == '__main__':
    unittest.main()

<|endoftext|>


<commit_before>from tests.utils import scratch_file
from tests.utils import service_ok

import pytest

SERVICE_URL = 'http://map1c.vis.earthdata.nasa.gov/wmts-geo/wmts.cgi'

@pytest.mark.online
@pytest.mark.skipif(not service_ok(SERVICE_URL),
                    reason="WMTS service is unreachable")
def test_wmts():
    # Find out what a WMTS has to offer. Service metadata:
    from owslib.wmts import WebMapTileService
    wmts = WebMapTileService(SERVICE_URL)
    assert wmts.identification.type == 'OGC WMTS'
    assert wmts.identification.version == '1.0.0'
    assert wmts.identification.title == 'NASA Global Imagery Browse Services for EOSDIS'
    bytearray(wmts.identification.abstract, 'utf-8')
    bytearray(b'Near real time imagery from multiple NASA instruments')
    assert wmts.identification.keywords == ['World', 'Global']
    # Service Provider:
    assert wmts.provider.name == 'National Aeronautics and Space Administration'
    assert wmts.provider.url == 'https://earthdata.nasa.gov/'
    # Available Layers:
    assert len(wmts.contents.keys()) > 0
    assert sorted(list(wmts.contents))[0] == 'AIRS_All_Sky_Outgoing_Longwave_Radiation_Daily_Day'
    # Fetch a tile (using some defaults):
    tile = wmts.gettile(layer='MODIS_Terra_CorrectedReflectance_TrueColor',
                        tilematrixset='EPSG4326_250m', tilematrix='0',
                        row=0, column=0, format="image/jpeg")
    out = open(scratch_file('nasa_modis_terra_truecolour.jpg'), 'wb')
    bytes_written = out.write(tile.read())
    out.close()
    # Test styles for several layers
    # TODO: fix dict order
    # assert wmts.contents['MLS_SO2_147hPa_Night'].styles == {'default': {'isDefault': True, 'title': 'default'}}
    assert wmts.contents['MLS_SO2_147hPa_Night'].styles['default']['isDefault'] is True
    # assert wmts.contents['MLS_SO2_147hPa_Night'].styles == {'default': {'isDefault': True, 'title': 'default'}}
    assert wmts.contents['MLS_SO2_147hPa_Night'].styles['default']['isDefault'] is True

SERVICE_URL_ARCGIS = 'http://data.geus.dk/arcgis/rest/services/OneGeologyGlobal/S071_G2500_OneGeology/MapServer/WMTS/1.0.0/WMTSCapabilities.xml'  # noqa

@pytest.mark.online
@pytest.mark.skipif(not service_ok(SERVICE_URL_ARCGIS),
                    reason="WMTS service is unreachable")
def test_wmts_without_serviceprovider_tag():
    # Test a WMTS without a ServiceProvider tag in Capababilities XML
    wmts = WebMapTileService(SERVICE_URL_ARCGIS)
<commit_msg>fixed wmts test<commit_after>from tests.utils import scratch_file
from tests.utils import service_ok

import pytest

SERVICE_URL = 'http://map1c.vis.earthdata.nasa.gov/wmts-geo/wmts.cgi'

@pytest.mark.online
@pytest.mark.skipif(not service_ok(SERVICE_URL),
                    reason="WMTS service is unreachable")
def test_wmts():
    # Find out what a WMTS has to offer. Service metadata:
    from owslib.wmts import WebMapTileService
    wmts = WebMapTileService(SERVICE_URL)
    assert wmts.identification.type == 'OGC WMTS'
    assert wmts.identification.version == '1.0.0'
    assert wmts.identification.title == 'NASA Global Imagery Browse Services for EOSDIS'
    bytearray(wmts.identification.abstract, 'utf-8')
    bytearray(b'Near real time imagery from multiple NASA instruments')
    assert wmts.identification.keywords == ['World', 'Global']
    # Service Provider:
    assert wmts.provider.name == 'National Aeronautics and Space Administration'
    assert wmts.provider.url == 'https://earthdata.nasa.gov/'
    # Available Layers:
    assert len(wmts.contents.keys()) > 0
    assert sorted(list(wmts.contents))[0] == 'AIRS_CO_Total_Column_Day'
    # Fetch a tile (using some defaults):
    tile = wmts.gettile(layer='MODIS_Terra_CorrectedReflectance_TrueColor',
                        tilematrixset='EPSG4326_250m', tilematrix='0',
                        row=0, column=0, format="image/jpeg")
    out = open(scratch_file('nasa_modis_terra_truecolour.jpg'), 'wb')
    bytes_written = out.write(tile.read())
    out.close()
    # Test styles for several layers
    # TODO: fix dict order
    # assert wmts.contents['MLS_SO2_147hPa_Night'].styles == {'default': {'isDefault': True, 'title': 'default'}}
    assert wmts.contents['MLS_SO2_147hPa_Night'].styles['default']['isDefault'] is True
    # assert wmts.contents['MLS_SO2_147hPa_Night'].styles == {'default': {'isDefault': True, 'title': 'default'}}
    assert wmts.contents['MLS_SO2_147hPa_Night'].styles['default']['isDefault'] is True

SERVICE_URL_ARCGIS = 'http://data.geus.dk/arcgis/rest/services/OneGeologyGlobal/S071_G2500_OneGeology/MapServer/WMTS/1.0.0/WMTSCapabilities.xml'  # noqa

@pytest.mark.online
@pytest.mark.skipif(not service_ok(SERVICE_URL_ARCGIS),
                    reason="WMTS service is unreachable")
def test_wmts_without_serviceprovider_tag():
    # Test a WMTS without a ServiceProvider tag in Capababilities XML
    wmts = WebMapTileService(SERVICE_URL_ARCGIS)
<|endoftext|>


<commit_before>import types

import pytest

try:
    import cytoolz as toolz
except ImportError:
    HAVE_CYTOOLZ = False
else:
    HAVE_CYTOOLZ = True

try:
    import toolz
except ImportError:
    pass

@pytest.mark.skipif(not HAVE_CYTOOLZ, reason='requires cytoolz')
def test_get_cytoolz():
    from zbox import toolz as tz
    assert tz is toolz
    assert tz.curried is toolz.curried

@pytest.mark.skipif(HAVE_CYTOOLZ, reason='testing no cytoolz')
def test_get_toolz():
    from zbox import toolz as tz
    assert tz is toolz
    assert tz.curried is toolz.curried

def test_gen():
    from zbox import gen
    c = toolz.concat([[1], [2], [3]])
    g = gen(c)
    assert not isinstance(c, types.GeneratorType)
    assert isinstance(g, types.GeneratorType)
    assert list(g) == list(toolz.concat([[1], [2], [3]]))
<commit_msg>move toolz import in test so it doesn't shadow cytoolz<commit_after>import types

import pytest

try:
    import toolz
except ImportError:
    pass

try:
    import cytoolz as toolz
except ImportError:
    HAVE_CYTOOLZ = False
else:
    HAVE_CYTOOLZ = True

@pytest.mark.skipif(not HAVE_CYTOOLZ, reason='requires cytoolz')
def test_get_cytoolz():
    from zbox import toolz as tz
    assert tz is toolz
    assert tz.curried is toolz.curried

@pytest.mark.skipif(HAVE_CYTOOLZ, reason='testing no cytoolz')
def test_get_toolz():
    from zbox import toolz as tz
    assert tz is toolz
    assert tz.curried is toolz.curried

def test_gen():
    from zbox import gen
    c = toolz.concat([[1], [2], [3]])
    g = gen(c)
    assert not isinstance(c, types.GeneratorType)
    assert isinstance(g, types.GeneratorType)
    assert list(g) == list(toolz.concat([[1], [2], [3]]))
<|endoftext|>


<commit_before>import numpy as np
from astropy import units as u
from astropy.coordinates import Angle
import blimpy as bl
from tests.data import voyager_h5, test_h5, test_fil

def test_waterfall_stream_1():

    print("\n===== test_waterfall_stream_1")

    source_name = "Not_Voyager_1"
    src_raj = Angle("17:10:03.984 hours")
    src_dej = Angle("12:10:58.8 degrees")
    tstart = 57650.78209490741
    tsamp = 18.253611008
    f_start = 8418.457032646984
    f_stop = 8421.386717353016
    n_fine_chans = 20
    n_tints = 8

    foff = (f_stop - f_start) / float(n_fine_chans)

    header = {"az_start": 0.0, "data_type": 1,
                   "fch1": f_start, "foff": foff,
                   "ibeam": 1, "machine_id": 42, "nbeams": 1, "nbits": 32,
                   "nchans": n_fine_chans, "nifs": 1, "rawdatafile": "nil",
                   "source_name": source_name, "src_raj": src_raj, "src_dej": src_dej,
                   "telescope_id": 42,
                   "tstart": tstart, "tsamp": tsamp, "zs_tart": 0.0}

    data_matrix = np.zeros((n_tints, 1, n_fine_chans), dtype=np.float32)

    wf = bl.Waterfall(header_dict=header, data_array=data_matrix)
    print("\nwf:", wf)
    wf.info()

def test_waterfall_stream_2():

    print("\n===== test_waterfall_stream_2")
    wf_voya1 = bl.Waterfall(voyager_h5)
    wf_voya2 = bl.Waterfall(header_dict=wf_voya1.header, data_array=wf_voya1.data)
    wf_voya2.info()
    wf_voya2.write_to_fil(test_h5)
    wf_voya2.write_to_fil(test_fil)

if __name__ == "__main__":
    test_waterfall_stream_1()
    test_waterfall_stream_2()
<commit_msg>Test fix to issue #270<commit_after>import numpy as np
from astropy import units as u
from astropy.coordinates import Angle
import blimpy as bl
from tests.data import voyager_h5, test_h5, test_fil

def test_waterfall_stream_1():

    print("\n===== test_waterfall_stream_1")

    source_name = "Not_Voyager_1"
    src_raj = Angle("17:10:03.984 hours")
    src_dej = Angle("12:10:58.8 degrees")
    tstart = 57650.78209490741
    tsamp = 18.253611008
    f_start = 8418.457032646984
    f_stop = 8421.386717353016
    n_fine_chans = 20
    n_tints = 8

    foff = (f_stop - f_start) / float(n_fine_chans)

    header = {"az_start": 0.0, "data_type": 1,
                   "fch1": f_start, "foff": foff,
                   "ibeam": 1, "machine_id": 42, "nbeams": 1, "nbits": 32,
                   "nchans": n_fine_chans, "nifs": 1, "rawdatafile": "nil",
                   "source_name": source_name, "src_raj": src_raj, "src_dej": src_dej,
                   "telescope_id": 42,
                   "tstart": tstart, "tsamp": tsamp, "zs_tart": 0.0}

    data_matrix = np.zeros((n_tints, 1, n_fine_chans), dtype=np.float32)

    wf = bl.Waterfall(header_dict=header, data_array=data_matrix)
    print("\nwf:", wf)
    wf.info()

def test_waterfall_stream_2():

    print("\n===== test_waterfall_stream_2")
    wf_voya1 = bl.Waterfall(voyager_h5)
    wf_voya2 = bl.Waterfall(header_dict=wf_voya1.header, data_array=wf_voya1.data)
    wf_voya2.info()
    wf_voya2.write_to_h5(test_h5)
    wf_voya2.write_to_fil(test_fil)

if __name__ == "__main__":
    test_waterfall_stream_1()
    test_waterfall_stream_2()
<|endoftext|>


<commit_before>#!/usr/bin/env python3
# encoding: utf-8

import ursgal
import unittest
import pprint
from ursgal import umapmaster as umama

TEST_DICT = {
    'enzyme' : {
        'default_value' : 'trypsin',
        'available_in_unode' : ['omssa', 'xtandem'],
        'description' : 'Enzyme used for digestions',
        'ukey_translation' : {
            'omssa_style_1' : '-ot',
            'xtandem_style_1' : 'enzyme'
        },
        'uvalue_translation' : {
            'omssa_style_1' : {
                'trypsin' : 1
            },
            'xtandem_style_1' : {
                'trypsin' : '[KR]|{P}'
            }
        }
    },
    'frag_mass_type' : {
        'default_value' : 'monoisotopic',
        'available_in_unode' : ['omssa'],
        'description' : 'use chemical average or monoisotopic mass for fragment ions.',
        'ukey_translation' : {
            'omssa_style_1' : '-tom',
        },
        'uvalue_translation' : {
            'omssa_style' : {
                'monoisotopic' : 0,
                'average' : 1
            }
        }
    },
}

class UMapMaster(unittest.TestCase):
    def setUp(self):
        self.umama_small = umama.UParamMapper( TEST_DICT )
        self.umama_default = umama.UParamMapper()

    def test_all_mappings_by_style(self):
        results = []
        for mDict in self.umama_small.mapping_dicts('omssa'):
            results.append( (mDict['ukey'], mDict['default_value']) )
        self.assertEqual(
            sorted(results),
            sorted([
                ('enzyme', 'trypsin'),
                ('frag_mass_type', 'monoisotopic' )
            ])
        )

if __name__ == '__main__':
    unittest.main()
<commit_msg>added tests to get_masked_params [ogawa]<commit_after>#!/usr/bin/env python3
# encoding: utf-8

import ursgal
import unittest
import pprint
from ursgal import umapmaster as umama

TEST_DICT = {
    'enzyme' : {
        'default_value' : 'trypsin',
        'available_in_unode' : ['omssa', 'xtandem'],
        'description' : 'Enzyme used for digestions',
        'ukey_translation' : {
            'omssa_style_1' : '-ot',
            'xtandem_style_1' : 'enzyme'
        },
        'uvalue_translation' : {
            'omssa_style_1' : {
                'trypsin' : 1
            },
            'xtandem_style_1' : {
                'trypsin' : '[KR]|{P}'
            }
        }
    },
    'frag_mass_type' : {
        'default_value' : 'monoisotopic',
        'available_in_unode' : ['omssa'],
        'description' : 'use chemical average or monoisotopic mass for fragment ions.',
        'ukey_translation' : {
            'omssa_style_1' : '-tom',
        },
        'uvalue_translation' : {
            'omssa_style' : {
                'monoisotopic' : 0,
                'average' : 1
            }
        }
    },
}

class UMapMaster(unittest.TestCase):
    def setUp(self):
        self.umama_small = umama.UParamMapper( TEST_DICT )
        self.umama_default = umama.UParamMapper()

    def test_all_mappings_by_style(self):
        results = []
        for mDict in self.umama_small.mapping_dicts('omssa'):
            results.append( (mDict['ukey'], mDict['default_value']) )
        self.assertEqual(
            sorted(results),
            sorted([
                ('enzyme', 'trypsin'),
                ('frag_mass_type', 'monoisotopic' )
            ])
        )

    def test_get_masked_params( self ):
        mask = ['default_value', 'description']
        masked_params = self.umama_small.get_masked_params(mask=mask)
        self.assertEqual(
            len(masked_params.keys()),
            len(TEST_DICT.keys())
        )
        self.assertEqual(
             len(masked_params['enzyme'].keys()), len(mask)
        )
        self.assertEqual(
            list(sorted(masked_params['enzyme'].keys())), sorted(mask)
        )

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