<commit_before>import sys
import time
import periphery
from .asserts import AssertRaises

if sys.version_info[0] == 3:
    raw_input = input

serial_device = None

def test_arguments():
    print("Starting arguments test...")

    # Invalid data bits
    with AssertRaises(ValueError):
        periphery.Serial(serial_device, 115200, databits=4)
    with AssertRaises(ValueError):
        periphery.Serial(serial_device, 115200, databits=9)
    # Invalid parity
    with AssertRaises(ValueError):
        periphery.Serial(serial_device, 115200, parity="blah")
    # Invalid stopb bits
    with AssertRaises(ValueError):
        periphery.Serial(serial_device, 115200, stopbits=0)
    with AssertRaises(ValueError):
        periphery.Serial(serial_device, 115200, stopbits=3)

    # Everything else is fair game, although termios might not like it.

    print("Arguments test passed.")

def test_open_close():
    print("Starting open/close test...")

    serial = periphery.Serial(serial_device, 115200)

    # Confirm default settings
    assert serial.fd > 0
    assert serial.baudrate == 115200
    assert serial.databits == 8
    assert serial.parity == "none"
    assert serial.stopbits == 1
    assert serial.xonxoff == False
    assert serial.rtscts == False

    # Change some stuff and check that it changed
    serial.baudrate = 4800
    assert serial.baudrate == 4800
    serial.baudrate = 9600
    assert serial.baudrate == 9600
    serial.databits = 7
    assert serial.databits == 7
    serial.parity = "odd"
    assert serial.parity == "odd"
    serial.stopbits = 2
    assert serial.stopbits == 2
    serial.xonxoff = True
    assert serial.xonxoff == True
    # Test serial port may not support rtscts

    serial.close()

    print("Open/close test passed.")

def test_loopback():
    print("Starting loopback test...")

    lorem_ipsum = b"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."

    serial = periphery.Serial(serial_device, 115200)

    # Test write/flush/read with bytes write
    print("Write, flush, read lorem ipsum with bytes type")
    assert serial.write(lorem_ipsum) == len(lorem_ipsum)
    serial.flush()
    buf = serial.read(len(lorem_ipsum), timeout=3)
    assert buf == lorem_ipsum

    # Test write/flush/read with bytearray write
    print("Write, flush, read lorem ipsum with bytearray type")
    assert serial.write(bytearray(lorem_ipsum)) == len(lorem_ipsum)
    serial.flush()
    buf = serial.read(len(lorem_ipsum), timeout=3)
    assert buf == lorem_ipsum

    # Test write/flush/read with list write
    print("Write, flush, read lorem ipsum with list type")
    assert serial.write(list(bytearray(lorem_ipsum))) == len(lorem_ipsum)
    serial.flush()
    buf = serial.read(len(lorem_ipsum), timeout=3)
    assert buf == lorem_ipsum

    # Test poll/write/flush/poll/input waiting/read
    print("Write, flush, poll, input waiting, read lorem ipsum")
    assert serial.poll(0.5) == False
    assert serial.write(lorem_ipsum) == len(lorem_ipsum)
    serial.flush()
    assert serial.poll(0.5) == True
    periphery.sleep_ms(500)
    assert serial.input_waiting() == len(lorem_ipsum)
    buf = serial.read(len(lorem_ipsum))
    assert buf == lorem_ipsum

    # Test non-blocking poll
    print("Check non-blocking poll")
    assert serial.poll(0) == False

    # Test a very large read-write (likely to exceed internal buffer size (~4096))
    print("Write, flush, read large buffer")
    lorem_hugesum = b"\xaa" * (4096 * 3)
    assert serial.write(lorem_hugesum) == len(lorem_hugesum)
    serial.flush()
    buf = serial.read(len(lorem_hugesum), timeout=3)
    assert buf == lorem_hugesum

    # Test read timeout
    print("Check read timeout")
    tic = time.time()
    assert serial.read(4096 * 3, timeout=2) == b""
    toc = time.time()
    assert (toc - tic) > 1

    # Test non-blocking read
    print("Check non-blocking read")
    tic = time.time()
    assert serial.read(4096 * 3, timeout=0) == b""
    toc = time.time()
    # Assuming we weren't context switched out for a second
    assert int(toc - tic) == 0

    serial.close()

    print("Loopback test passed.")

def test_interactive():
    print("Starting interactive test...")

    buf = b"Hello World!"

    serial = periphery.Serial(serial_device, 4800)

    print("Starting interactive test. Get out your logic analyzer, buddy!")
    raw_input("Press enter to continue...")

    serial.baudrate = 4800
    raw_input("Press enter to start transfer...")
    assert serial.write(buf) == len(buf)
    assert raw_input("Serial transfer baudrate 4800, 8n1 occurred? y/n ") == "y"

    serial.baudrate = 9600
    raw_input("Press enter to start transfer...")
    assert serial.write(buf) == len(buf)
    assert raw_input("Serial transfer baudrate 9600, 8n1 occurred? y/n ") == "y"

    serial.baudrate = 115200
    raw_input("Press enter to start transfer...")
    assert serial.write(buf) == len(buf)
    assert raw_input("Serial transfer baudrate 115200, 8n1 occurred? y/n ") == "y"

    serial.close()

    print("Interactive test passed.")

if __name__ == "__main__":
    if len(sys.argv) < 2:
        print("Usage: python -m tests.test_serial <serial port device>")
        print("")
        print("[1/4] Arguments test: No requirements.")
        print("[2/4] Open/close test: Serial port device should be real.")
        print("[3/4] Loopback test: Serial TX and RX should be connected with a wire.")
        print("[4/4] Interactive test: Serial TX should be observed with an oscilloscope or logic analyzer.")
        print("")
        print("Hint: for Raspberry Pi 3, enable UART0 with:")
        print("   $ echo \"dtoverlay=pi3-disable-bt\" | sudo tee -a /boot/config.txt")
        print("   $ sudo systemctl disable hciuart")
        print("   $ sudo reboot")
        print("   (Note that this will disable Bluetooth)")
        print("Use pins UART0 TXD (header pin 8) and UART0 RXD (header pin 10),")
        print("connect a loopback between TXD and RXD, and run this test with:")
        print("    python -m tests.test_serial /dev/AMA0")
        print("")
        sys.exit(1)

    serial_device = sys.argv[1]

    print("Starting Serial tests...")

    test_arguments()
    test_open_close()
    test_loopback()
    test_interactive()

    print("All Serial tests passed.")
<commit_msg>tests/serial: run arguments test in ci environment<commit_after>import os
import sys
import time
import periphery
from .asserts import AssertRaises

if sys.version_info[0] == 3:
    raw_input = input

serial_device = None

def test_arguments():
    print("Starting arguments test...")

    # Invalid data bits
    with AssertRaises(ValueError):
        periphery.Serial("/dev/ttyS0", 115200, databits=4)
    with AssertRaises(ValueError):
        periphery.Serial("/dev/ttyS0", 115200, databits=9)
    # Invalid parity
    with AssertRaises(ValueError):
        periphery.Serial("/dev/ttyS0", 115200, parity="blah")
    # Invalid stop bits
    with AssertRaises(ValueError):
        periphery.Serial("/dev/ttyS0", 115200, stopbits=0)
    with AssertRaises(ValueError):
        periphery.Serial("/dev/ttyS0", 115200, stopbits=3)

    # Everything else is fair game, although termios might not like it.

    print("Arguments test passed.")

def test_open_close():
    print("Starting open/close test...")

    serial = periphery.Serial(serial_device, 115200)

    # Confirm default settings
    assert serial.fd > 0
    assert serial.baudrate == 115200
    assert serial.databits == 8
    assert serial.parity == "none"
    assert serial.stopbits == 1
    assert serial.xonxoff == False
    assert serial.rtscts == False

    # Change some stuff and check that it changed
    serial.baudrate = 4800
    assert serial.baudrate == 4800
    serial.baudrate = 9600
    assert serial.baudrate == 9600
    serial.databits = 7
    assert serial.databits == 7
    serial.parity = "odd"
    assert serial.parity == "odd"
    serial.stopbits = 2
    assert serial.stopbits == 2
    serial.xonxoff = True
    assert serial.xonxoff == True
    # Test serial port may not support rtscts

    serial.close()

    print("Open/close test passed.")

def test_loopback():
    print("Starting loopback test...")

    lorem_ipsum = b"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."

    serial = periphery.Serial(serial_device, 115200)

    # Test write/flush/read with bytes write
    print("Write, flush, read lorem ipsum with bytes type")
    assert serial.write(lorem_ipsum) == len(lorem_ipsum)
    serial.flush()
    buf = serial.read(len(lorem_ipsum), timeout=3)
    assert buf == lorem_ipsum

    # Test write/flush/read with bytearray write
    print("Write, flush, read lorem ipsum with bytearray type")
    assert serial.write(bytearray(lorem_ipsum)) == len(lorem_ipsum)
    serial.flush()
    buf = serial.read(len(lorem_ipsum), timeout=3)
    assert buf == lorem_ipsum

    # Test write/flush/read with list write
    print("Write, flush, read lorem ipsum with list type")
    assert serial.write(list(bytearray(lorem_ipsum))) == len(lorem_ipsum)
    serial.flush()
    buf = serial.read(len(lorem_ipsum), timeout=3)
    assert buf == lorem_ipsum

    # Test poll/write/flush/poll/input waiting/read
    print("Write, flush, poll, input waiting, read lorem ipsum")
    assert serial.poll(0.5) == False
    assert serial.write(lorem_ipsum) == len(lorem_ipsum)
    serial.flush()
    assert serial.poll(0.5) == True
    periphery.sleep_ms(500)
    assert serial.input_waiting() == len(lorem_ipsum)
    buf = serial.read(len(lorem_ipsum))
    assert buf == lorem_ipsum

    # Test non-blocking poll
    print("Check non-blocking poll")
    assert serial.poll(0) == False

    # Test a very large read-write (likely to exceed internal buffer size (~4096))
    print("Write, flush, read large buffer")
    lorem_hugesum = b"\xaa" * (4096 * 3)
    assert serial.write(lorem_hugesum) == len(lorem_hugesum)
    serial.flush()
    buf = serial.read(len(lorem_hugesum), timeout=3)
    assert buf == lorem_hugesum

    # Test read timeout
    print("Check read timeout")
    tic = time.time()
    assert serial.read(4096 * 3, timeout=2) == b""
    toc = time.time()
    assert (toc - tic) > 1

    # Test non-blocking read
    print("Check non-blocking read")
    tic = time.time()
    assert serial.read(4096 * 3, timeout=0) == b""
    toc = time.time()
    # Assuming we weren't context switched out for a second
    assert int(toc - tic) == 0

    serial.close()

    print("Loopback test passed.")

def test_interactive():
    print("Starting interactive test...")

    buf = b"Hello World!"

    serial = periphery.Serial(serial_device, 4800)

    print("Starting interactive test. Get out your logic analyzer, buddy!")
    raw_input("Press enter to continue...")

    serial.baudrate = 4800
    raw_input("Press enter to start transfer...")
    assert serial.write(buf) == len(buf)
    assert raw_input("Serial transfer baudrate 4800, 8n1 occurred? y/n ") == "y"

    serial.baudrate = 9600
    raw_input("Press enter to start transfer...")
    assert serial.write(buf) == len(buf)
    assert raw_input("Serial transfer baudrate 9600, 8n1 occurred? y/n ") == "y"

    serial.baudrate = 115200
    raw_input("Press enter to start transfer...")
    assert serial.write(buf) == len(buf)
    assert raw_input("Serial transfer baudrate 115200, 8n1 occurred? y/n ") == "y"

    serial.close()

    print("Interactive test passed.")

if __name__ == "__main__":
    if os.environ.get("CI") == "true":
        test_arguments()
        sys.exit(0)

    if len(sys.argv) < 2:
        print("Usage: python -m tests.test_serial <serial port device>")
        print("")
        print("[1/4] Arguments test: No requirements.")
        print("[2/4] Open/close test: Serial port device should be real.")
        print("[3/4] Loopback test: Serial TX and RX should be connected with a wire.")
        print("[4/4] Interactive test: Serial TX should be observed with an oscilloscope or logic analyzer.")
        print("")
        print("Hint: for Raspberry Pi 3, enable UART0 with:")
        print("   $ echo \"dtoverlay=pi3-disable-bt\" | sudo tee -a /boot/config.txt")
        print("   $ sudo systemctl disable hciuart")
        print("   $ sudo reboot")
        print("   (Note that this will disable Bluetooth)")
        print("Use pins UART0 TXD (header pin 8) and UART0 RXD (header pin 10),")
        print("connect a loopback between TXD and RXD, and run this test with:")
        print("    python -m tests.test_serial /dev/AMA0")
        print("")
        sys.exit(1)

    serial_device = sys.argv[1]

    print("Starting Serial tests...")

    test_arguments()
    test_open_close()
    test_loopback()
    test_interactive()

    print("All Serial tests passed.")
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
"""
serverモジュールのテスト
"""

import json
import socket
import threading
from Queue import Queue, Empty

from nose.tools import ok_, eq_

from apns_proxy_server.server import (
    APNSProxyServer)
from apns_proxy_server import validator

dummy_setting = {
    'BIND_PORT_FOR_ENTRY': 1000,
    'BIND_PORT_FOR_PULL': 200,
    'THREAD_NUMS_PER_APPLICATION': 1,
    'APPLICATIONS': []
}

def test_instance():
    server = APNSProxyServer(dummy_setting)
    ok_(server)
    ok_(server.start)

def test_create_worker():
    server = APNSProxyServer(dummy_setting)
    server.create_workers([{
        "application_id": "myApp1",
        "name": "My App1",
        "sandbox": False,
        "cert_file": "sample.cert",
        "key_file": "sample.key"
    }, {
        "application_id": "myApp2",
        "name": "My App2",
        "sandbox": False,
        "cert_file": "sample.cert",
        "key_file": "sample.key"
    }], 1)
    eq_(len(server.task_queues), 2)
    for k in server.task_queues.keys():
        ok_(isinstance(server.task_queues[k], Queue))

def test_dispatch_known_app():
    server = APNSProxyServer(dummy_setting)
    server.create_workers([{
        "application_id": "myApp1",
        "name": "My App1",
        "sandbox": False,
        "cert_file": "sample.cert",
        "key_file": "sample.key"
    }, {
        "application_id": "myApp2",
        "name": "My App2",
        "sandbox": False,
        "cert_file": "sample.cert",
        "key_file": "sample.key"
    }], 1)

    token = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
    eq_(server.dispatch_queue(json.dumps({
        "token": token,
        "appid": "myApp1",
        "test": True,
        "aps": {
            "alert": "This is test",
            "badge": 1,
            "sound": "default"
        },
        "expiry": None
        })), True, "Dispatch should be success")

    eq_(server.dispatch_queue(json.dumps({
        "token": token,
        "appid": "myApp2",
        "test": True,
        "aps": {
            "alert": "This is test",
            "badge": 1,
            "sound": "default",
        },
        "expiry": None
        })), True, "Dispatch should be success")

def test_dispatch_unknown_app():
    server = APNSProxyServer(dummy_setting)
    server.create_workers([{
        "application_id": "myApp2",
        "name": "My App2",
        "sandbox": False,
        "cert_file": "sample.cert",
        "key_file": "sample.key"
    }], 1)

    token = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
    eq_(server.dispatch_queue(json.dumps({
        "token": token,
        "appid": "unknownApp",
        "test": True,
        "aps": {
            "alert": "This is test",
            "badge": 1,
            "sound": "default"
        },
        "expiry": None
        })), False, "Dispatch should be failed of unknown appid")

def test_dispatch_messages():
    server = APNSProxyServer(dummy_setting)
    server.create_workers([{
        "application_id": "myApp2",
        "name": "My App2",
        "sandbox": False,
        "cert_file": "sample.cert",
        "key_file": "sample.key"
    }], 1)

    token = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
    eq_(server.dispatch_queue(json.dumps({
        "token": token,
        "appid": "myApp2",
        "aps": {
            "content_available": True
        },
        "test": True
        })), True)
    eq_(server.dispatch_queue(json.dumps({
        "token": token,
        "appid": "myApp2",
        "aps": {
            "sound": None,
            "badge": 99
        },
        "priority": 5,
        "test": True
        })), True)

def test_thread_count():
    """
    スレッド生成数のテスト
    """
    before_num = threading.active_count()

    server = APNSProxyServer(dummy_setting)
    server.create_workers([{
        "application_id": "myApp1",
        "name": "My App1",
        "sandbox": False,
        "cert_file": "sample.cert",
        "key_file": "sample.key"
    }, {
        "application_id": "myApp2",
        "name": "My App2",
        "sandbox": False,
        "cert_file": "sample.cert",
        "key_file": "sample.key"
    }], 3)

    after_num = threading.active_count()

    eq_(before_num + 6, after_num)

def test_start():
    """
    サーバーが起動できる事のテスト
    """
    def server(error_queue):
        try:
            import tests.data.valid_settings
            s = validator.validate_settings(tests.data.valid_settings)
            server = APNSProxyServer(s)
            server.start()
        except Exception, e:
            error_queue.put(e)

    q = Queue()
    thread = threading.Thread(target=server, args=(q,))
    thread.setDaemon(True)
    thread.start()

    try:
        error = q.get(True, 1)
        raise error
    except Empty:
        ok_(True)

def test_connect():
    """
    待ちうけポートに接続できる事のテスト
    """
    def server():
        server = APNSProxyServer({
            'BIND_PORT_FOR_ENTRY': 15555,
            'BIND_PORT_FOR_PULL': 15556,
            'THREAD_NUMS_PER_APPLICATION': 5,
            'APPLICATIONS': []
        })
        server.start()

    thread = threading.Thread(target=server)
    thread.setDaemon(True)
    thread.start()

    socket1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    socket1.connect(('localhost', 15555))
    socket2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    socket2.connect(('localhost', 15556))

    ok_(True)
<commit_msg>Add sleep to connection test<commit_after># -*- coding: utf-8 -*-
"""
serverモジュールのテスト
"""

import json
import socket
import threading
import time
from Queue import Queue, Empty

from nose.tools import ok_, eq_

from apns_proxy_server.server import (
    APNSProxyServer)
from apns_proxy_server import validator

dummy_setting = {
    'BIND_PORT_FOR_ENTRY': 1000,
    'BIND_PORT_FOR_PULL': 200,
    'THREAD_NUMS_PER_APPLICATION': 1,
    'APPLICATIONS': []
}

def test_instance():
    server = APNSProxyServer(dummy_setting)
    ok_(server)
    ok_(server.start)

def test_create_worker():
    server = APNSProxyServer(dummy_setting)
    server.create_workers([{
        "application_id": "myApp1",
        "name": "My App1",
        "sandbox": False,
        "cert_file": "sample.cert",
        "key_file": "sample.key"
    }, {
        "application_id": "myApp2",
        "name": "My App2",
        "sandbox": False,
        "cert_file": "sample.cert",
        "key_file": "sample.key"
    }], 1)
    eq_(len(server.task_queues), 2)
    for k in server.task_queues.keys():
        ok_(isinstance(server.task_queues[k], Queue))

def test_dispatch_known_app():
    server = APNSProxyServer(dummy_setting)
    server.create_workers([{
        "application_id": "myApp1",
        "name": "My App1",
        "sandbox": False,
        "cert_file": "sample.cert",
        "key_file": "sample.key"
    }, {
        "application_id": "myApp2",
        "name": "My App2",
        "sandbox": False,
        "cert_file": "sample.cert",
        "key_file": "sample.key"
    }], 1)

    token = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
    eq_(server.dispatch_queue(json.dumps({
        "token": token,
        "appid": "myApp1",
        "test": True,
        "aps": {
            "alert": "This is test",
            "badge": 1,
            "sound": "default"
        },
        "expiry": None
        })), True, "Dispatch should be success")

    eq_(server.dispatch_queue(json.dumps({
        "token": token,
        "appid": "myApp2",
        "test": True,
        "aps": {
            "alert": "This is test",
            "badge": 1,
            "sound": "default",
        },
        "expiry": None
        })), True, "Dispatch should be success")

def test_dispatch_unknown_app():
    server = APNSProxyServer(dummy_setting)
    server.create_workers([{
        "application_id": "myApp2",
        "name": "My App2",
        "sandbox": False,
        "cert_file": "sample.cert",
        "key_file": "sample.key"
    }], 1)

    token = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
    eq_(server.dispatch_queue(json.dumps({
        "token": token,
        "appid": "unknownApp",
        "test": True,
        "aps": {
            "alert": "This is test",
            "badge": 1,
            "sound": "default"
        },
        "expiry": None
        })), False, "Dispatch should be failed of unknown appid")

def test_dispatch_messages():
    server = APNSProxyServer(dummy_setting)
    server.create_workers([{
        "application_id": "myApp2",
        "name": "My App2",
        "sandbox": False,
        "cert_file": "sample.cert",
        "key_file": "sample.key"
    }], 1)

    token = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
    eq_(server.dispatch_queue(json.dumps({
        "token": token,
        "appid": "myApp2",
        "aps": {
            "content_available": True
        },
        "test": True
        })), True)
    eq_(server.dispatch_queue(json.dumps({
        "token": token,
        "appid": "myApp2",
        "aps": {
            "sound": None,
            "badge": 99
        },
        "priority": 5,
        "test": True
        })), True)

def test_thread_count():
    """
    スレッド生成数のテスト
    """
    before_num = threading.active_count()

    server = APNSProxyServer(dummy_setting)
    server.create_workers([{
        "application_id": "myApp1",
        "name": "My App1",
        "sandbox": False,
        "cert_file": "sample.cert",
        "key_file": "sample.key"
    }, {
        "application_id": "myApp2",
        "name": "My App2",
        "sandbox": False,
        "cert_file": "sample.cert",
        "key_file": "sample.key"
    }], 3)

    after_num = threading.active_count()

    eq_(before_num + 6, after_num)

def test_start():
    """
    サーバーが起動できる事のテスト
    """
    def server(error_queue):
        try:
            import tests.data.valid_settings
            s = validator.validate_settings(tests.data.valid_settings)
            server = APNSProxyServer(s)
            server.start()
        except Exception, e:
            error_queue.put(e)

    q = Queue()
    thread = threading.Thread(target=server, args=(q,))
    thread.setDaemon(True)
    thread.start()

    try:
        error = q.get(True, 1)
        raise error
    except Empty:
        ok_(True)

def test_connect():
    """
    待ちうけポートに接続できる事のテスト
    """
    def server():
        server = APNSProxyServer({
            'BIND_PORT_FOR_ENTRY': 15555,
            'BIND_PORT_FOR_PULL': 15556,
            'THREAD_NUMS_PER_APPLICATION': 5,
            'APPLICATIONS': []
        })
        server.start()

    thread = threading.Thread(target=server)
    thread.setDaemon(True)
    thread.start()

    time.sleep(1)

    socket1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    socket1.connect(('localhost', 15555))
    socket2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    socket2.connect(('localhost', 15556))

    ok_(True)
<|endoftext|>


<commit_before>from __future__ import absolute_import

import unittest

import servy.server

def fn():
    pass

class Simple(object):
    @classmethod
    def fn():
        pass

class Complex(servy.server.Container):
    simple = Simple
    fn = fn

class ServerInitiation(unittest.TestCase):
    def test_explicit(self):
        server = servy.server.Server(
            fn=fn,
        )
        self.assertEqual(server.procedures, {
            'fn': fn,
        })

    def test_explicit_with_junk(self):
        server = servy.server.Server(
            junk=type,
        )
        self.assertEqual(server.procedures, {})

    def test_decorator_simple_container(self):
        Server = servy.server.Server(Simple)
        self.assertEqual(Server.procedures, {
            'fn': Simple.fn,
        })

    def test_decorator_simple_non_container(self):
        @servy.server.Server
        class Server(object):
            simple = Simple

        self.assertEqual(Server.procedures, {})

    def test_decorator_complex(self):
        @servy.server.Server
        class Server(object):
            c = Complex

        self.assertEqual(Server.procedures, {
            'c.fn': Complex.fn,
        })
<commit_msg>add procedure call tests<commit_after>from __future__ import absolute_import

import unittest

import webob
import webob.exc

import servy.server
import servy.proto as proto

def fn():
    pass

class Simple(object):
    @classmethod
    def fn():
        pass

class Complex(servy.server.Container):
    simple = Simple
    fn = fn

class ServerInitiation(unittest.TestCase):
    def test_explicit(self):
        server = servy.server.Server(
            fn=fn,
        )
        self.assertEqual(server.procedures, {
            'fn': fn,
        })

    def test_explicit_with_junk(self):
        server = servy.server.Server(
            junk=type,
        )
        self.assertEqual(server.procedures, {})

    def test_decorator_simple_container(self):
        Server = servy.server.Server(Simple)
        self.assertEqual(Server.procedures, {
            'fn': Simple.fn,
        })

    def test_decorator_simple_non_container(self):
        @servy.server.Server
        class Server(object):
            simple = Simple

        self.assertEqual(Server.procedures, {})

    def test_decorator_complex(self):
        @servy.server.Server
        class Server(object):
            c = Complex

        self.assertEqual(Server.procedures, {
            'c.fn': Complex.fn,
        })

@servy.server.Server
class RPC(object):
    NAME = 'rpc'

    @classmethod
    def proc(cls):
        return 'rpc'

    @classmethod
    def proc_ext(cls, prefix, suffix=None):
        suffix = suffix or ''
        return '{}_{}'.format(prefix, suffix)

class ProcedureCall(unittest.TestCase):
    def test_docs(self):
        request = webob.Request.blank('/')
        request.method = 'GET'

        response = RPC(request)
        self.assertEqual(response, 'proc\n    None\n\nproc_ext\n    None\n\n')

    def test_method_not_allowed(self):
        request = webob.Request.blank('/proc')
        request.method = 'PUT'

        with self.assertRaises(webob.exc.HTTPMethodNotAllowed):
            RPC(request)

    def test_proc_not_found(self):
        request = webob.Request.blank('/not_found')
        request.method = 'POST'

        with self.assertRaises(webob.exc.HTTPNotFound):
            RPC(request)

    def test_no_body(self):
        request = webob.Request.blank('/proc')
        request.method = 'POST'

        with self.assertRaises(webob.exc.HTTPBadRequest):
            RPC(request)

    def test_call_without_args(self):
        request = webob.Request.blank('/proc')
        request.method = 'POST'
        request.body = proto.Request.encode((), {})

        response = proto.Response.decode(RPC(request))
        self.assertEqual(response, 'rpc')

    def test_call_with_args(self):
        request = webob.Request.blank('/proc_ext')
        request.method = 'POST'
        request.body = proto.Request.encode(('O'), {'suffix': 'O'})

        response = proto.Response.decode(RPC(request))
        self.assertEqual(response, 'O_O')
<|endoftext|>


<commit_before>"""
Tests for var/shapes.py

"""

from __future__ import division, print_function

__author__ = "Ralf Farkas"

import numpy as np
import vip_hci as vip

from helpers import aarc

pretty_odd = np.array([
    [1, 1, 1, 1, 1],
    [1, 2, 2, 2, 1],
    [1, 2, 3, 2, 1],
    [1, 2, 2, 2, 1],
    [1, 1, 1, 1, 1]
])

pretty_even = np.array([
    [1, 1, 1, 1, 1, 1],
    [1, 2, 2, 2, 2, 1],
    [1, 2, 3, 3, 2, 1],
    [1, 2, 3, 3, 2, 1],
    [1, 2, 2, 2, 2, 1],
    [1, 1, 1, 1, 1, 1]
])

def test_frame_center():
    frames = 39
    nlambda = 2

    res44 = (1.5, 1.5)
    res55 = (2.0, 2.0)

    # 2D
    assert vip.var.frame_center(np.zeros((4, 4))) == res44
    assert vip.var.frame_center(np.zeros((5, 5))) == res55

    # 3D
    assert vip.var.frame_center(np.zeros((frames, 4, 4))) == res44
    assert vip.var.frame_center(np.zeros((frames, 5, 5))) == res55

    # 4D
    assert vip.var.frame_center(np.zeros((nlambda, frames, 4, 4))) == res44
    assert vip.var.frame_center(np.zeros((nlambda, frames, 5, 5))) == res55

def test_mask_circle():

    size = 5
    radius = 2

    ones = np.ones((size, size))

    # "in" and "out" should be complementary
    res_in = vip.var.mask_circle(ones, radius=radius, mode="in")
    res_out = vip.var.mask_circle(ones, radius=radius, mode="out")
    aarc(res_in+res_out, ones)

    # radius=2 -> central region should be 3x3 pixels = 9 pixels
    aarc(res_out.sum(), 9)

def test_get_square():
    aarc(vip.var.get_square(pretty_odd, size=3, x=2, y=2),
         np.array([[2, 2, 2],
                   [2, 3, 2],
                   [2, 2, 2]]))

    aarc(vip.var.get_square(pretty_odd, size=2, x=2, y=2),
         np.array([[2, 2, 2],
                   [2, 3, 2],
                   [2, 2, 2]]))
    # -> prints warning

    aarc(vip.var.get_square(pretty_odd, size=2, x=2, y=2, force=True),
         np.array([[2, 2],
                   [2, 3]]))

    aarc(vip.var.get_square(pretty_even, size=2, x=3, y=3),
         np.array([[3, 3],
                  [3, 3]]))

    aarc(vip.var.get_square(pretty_even, size=3, x=3, y=3),
         np.array([[2, 2, 2, 2],
                   [2, 3, 3, 2],
                   [2, 3, 3, 2],
                   [2, 2, 2, 2]]))
    # -> prints warning

    aarc(vip.var.get_square(pretty_even, size=2, x=4, y=2, force=True),
         np.array([[2, 2],
                   [3, 2]]))

def test_get_circle():

    ar = np.ones((10, 10), dtype=int)
    aarc(vip.var.get_circle(ar, radius=4, output_values=False),
         np.array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                   [0, 0, 0, 1, 1, 1, 1, 0, 0, 0],
                   [0, 0, 1, 1, 1, 1, 1, 1, 0, 0],
                   [0, 1, 1, 1, 1, 1, 1, 1, 1, 0],
                   [0, 1, 1, 1, 1, 1, 1, 1, 1, 0],
                   [0, 1, 1, 1, 1, 1, 1, 1, 1, 0],
                   [0, 1, 1, 1, 1, 1, 1, 1, 1, 0],
                   [0, 0, 1, 1, 1, 1, 1, 1, 0, 0],
                   [0, 0, 0, 1, 1, 1, 1, 0, 0, 0],
                   [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]))

    aarc(vip.var.get_circle(pretty_odd, radius=4, output_values=True),
         np.array([1, 1, 1, 1, 1, 1, 2, 2, 2, 1, 1, 2, 3, 2, 1, 1, 2, 2,
                   2, 1, 1, 1, 1, 1, 1]))

    aarc(vip.var.get_circle(pretty_even, radius=4, output_values=True),
         np.array([1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 1, 1, 2, 3, 3, 2, 1,
                   1, 2, 3, 3, 2, 1, 1, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1]))

def test_get_annulus_segments():
    arr = np.ones((10, 10))

    # single segment, like the old get_annulus. Note the ``[0]``.

    res = vip.var.get_annulus_segments(arr, 2, 3)[0]

    truth = (np.array([0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3,
                       3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6,
                       6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9,
                       9, 9]),
             np.array([3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8, 0, 1,
                       2, 3, 6, 7, 8, 9, 0, 1, 2, 7, 8, 9, 0, 1, 2, 7, 8, 9, 0, 1, 2, 3,
                       6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8, 3, 4,
                       5, 6]))

    aarc(res, truth)

    res = vip.var.get_annulus_segments(arr, 2, 3, mode="val")[0]
    truth = np.array([1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.,
                      1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.,
                      1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.,
                      1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.])

    aarc(res, truth)

    # multiple segments:

    res = vip.var.get_annulus_segments(pretty_even, 2, 3, nsegm=2)
    truth = [(np.array([0, 0, 0, 1, 1, 2, 3, 4, 4, 5, 5, 5]),
              np.array([3, 4, 5, 4, 5, 5, 5, 4, 5, 3, 4, 5])),
             (np.array([0, 0, 0, 1, 1, 2, 3, 4, 4, 5, 5, 5]),
              np.array([0, 1, 2, 0, 1, 0, 0, 0, 1, 0, 1, 2]))]

    aarc(res, truth)

    res = vip.var.get_annulus_segments(pretty_even, 2, 3, nsegm=3)
    truth = [(np.array([2, 3, 4, 4, 5, 5, 5]),
              np.array([5, 5, 4, 5, 3, 4, 5])),
             (np.array([0, 0, 0, 0, 0, 0, 1, 1, 1, 1]),
              np.array([0, 1, 2, 3, 4, 5, 0, 1, 4, 5])),
             (np.array([2, 3, 4, 4, 5, 5, 5]),
              np.array([0, 0, 0, 1, 0, 1, 2]))]

    assert repr(res) == repr(truth)
    # TODO: cannot compare using `allclose`, as elements have variable length!

    # tuple as input:

    res = vip.var.get_annulus_segments((6, 6), 2, 3, nsegm=3)
    assert repr(res) == repr(truth)

    # masked arr:

    res = vip.var.get_annulus_segments(arr, 2, 3, mode="mask")[0]
    truth = np.array([[0., 0., 0., 1., 1., 1., 1., 0., 0., 0.],
                      [0., 1., 1., 1., 1., 1., 1., 1., 1., 0.],
                      [0., 1., 1., 1., 1., 1., 1., 1., 1., 0.],
                      [1., 1., 1., 1., 0., 0., 1., 1., 1., 1.],
                      [1., 1., 1., 0., 0., 0., 0., 1., 1., 1.],
                      [1., 1., 1., 0., 0., 0., 0., 1., 1., 1.],
                      [1., 1., 1., 1., 0., 0., 1., 1., 1., 1.],
                      [0., 1., 1., 1., 1., 1., 1., 1., 1., 0.],
                      [0., 1., 1., 1., 1., 1., 1., 1., 1., 0.],
                      [0., 0., 0., 1., 1., 1., 1., 0., 0., 0.]])
    aarc(res, truth)

    # tuple as input:

    res = vip.var.get_annulus_segments((10, 10), 2, 3, mode="mask")[0]
    # masking a zeros array -> only zeros left!
    assert res.sum() == 0

def test_dist():
    assert vip.var.dist(0, 0, 1, 1) == np.sqrt(2)
    assert vip.var.dist(1, 2, 3, 4) == 2 * np.sqrt(2)

def test_get_ellipse():
    f = np.ones((6, 10))

    # masked array:
    fem = vip.var.get_ellipse(f, 4, 2, 90, mode="mask")
    assert fem.sum() == 28  # outer region masked, 28 pixels kept

    # values:
    fev = vip.var.get_ellipse(f, 4, 2, 90, mode="val")
    assert fev.sum() == 28

    # indices:
    fei = vip.var.get_ellipse(f, 4, 2, 90, mode="ind")
    assert fei[0].shape == fei[1].shape == (28,)
<commit_msg>TST: test for get_ell_annulus<commit_after>"""
Tests for var/shapes.py

"""

from __future__ import division, print_function

__author__ = "Ralf Farkas"

import numpy as np
import vip_hci as vip

from helpers import aarc

pretty_odd = np.array([
    [1, 1, 1, 1, 1],
    [1, 2, 2, 2, 1],
    [1, 2, 3, 2, 1],
    [1, 2, 2, 2, 1],
    [1, 1, 1, 1, 1]
])

pretty_even = np.array([
    [1, 1, 1, 1, 1, 1],
    [1, 2, 2, 2, 2, 1],
    [1, 2, 3, 3, 2, 1],
    [1, 2, 3, 3, 2, 1],
    [1, 2, 2, 2, 2, 1],
    [1, 1, 1, 1, 1, 1]
])

def test_frame_center():
    frames = 39
    nlambda = 2

    res44 = (1.5, 1.5)
    res55 = (2.0, 2.0)

    # 2D
    assert vip.var.frame_center(np.zeros((4, 4))) == res44
    assert vip.var.frame_center(np.zeros((5, 5))) == res55

    # 3D
    assert vip.var.frame_center(np.zeros((frames, 4, 4))) == res44
    assert vip.var.frame_center(np.zeros((frames, 5, 5))) == res55

    # 4D
    assert vip.var.frame_center(np.zeros((nlambda, frames, 4, 4))) == res44
    assert vip.var.frame_center(np.zeros((nlambda, frames, 5, 5))) == res55

def test_mask_circle():

    size = 5
    radius = 2

    ones = np.ones((size, size))

    # "in" and "out" should be complementary
    res_in = vip.var.mask_circle(ones, radius=radius, mode="in")
    res_out = vip.var.mask_circle(ones, radius=radius, mode="out")
    aarc(res_in+res_out, ones)

    # radius=2 -> central region should be 3x3 pixels = 9 pixels
    aarc(res_out.sum(), 9)

def test_get_square():
    aarc(vip.var.get_square(pretty_odd, size=3, x=2, y=2),
         np.array([[2, 2, 2],
                   [2, 3, 2],
                   [2, 2, 2]]))

    aarc(vip.var.get_square(pretty_odd, size=2, x=2, y=2),
         np.array([[2, 2, 2],
                   [2, 3, 2],
                   [2, 2, 2]]))
    # -> prints warning

    aarc(vip.var.get_square(pretty_odd, size=2, x=2, y=2, force=True),
         np.array([[2, 2],
                   [2, 3]]))

    aarc(vip.var.get_square(pretty_even, size=2, x=3, y=3),
         np.array([[3, 3],
                  [3, 3]]))

    aarc(vip.var.get_square(pretty_even, size=3, x=3, y=3),
         np.array([[2, 2, 2, 2],
                   [2, 3, 3, 2],
                   [2, 3, 3, 2],
                   [2, 2, 2, 2]]))
    # -> prints warning

    aarc(vip.var.get_square(pretty_even, size=2, x=4, y=2, force=True),
         np.array([[2, 2],
                   [3, 2]]))

def test_get_circle():

    ar = np.ones((10, 10), dtype=int)
    aarc(vip.var.get_circle(ar, radius=4, output_values=False),
         np.array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                   [0, 0, 0, 1, 1, 1, 1, 0, 0, 0],
                   [0, 0, 1, 1, 1, 1, 1, 1, 0, 0],
                   [0, 1, 1, 1, 1, 1, 1, 1, 1, 0],
                   [0, 1, 1, 1, 1, 1, 1, 1, 1, 0],
                   [0, 1, 1, 1, 1, 1, 1, 1, 1, 0],
                   [0, 1, 1, 1, 1, 1, 1, 1, 1, 0],
                   [0, 0, 1, 1, 1, 1, 1, 1, 0, 0],
                   [0, 0, 0, 1, 1, 1, 1, 0, 0, 0],
                   [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]))

    aarc(vip.var.get_circle(pretty_odd, radius=4, output_values=True),
         np.array([1, 1, 1, 1, 1, 1, 2, 2, 2, 1, 1, 2, 3, 2, 1, 1, 2, 2,
                   2, 1, 1, 1, 1, 1, 1]))

    aarc(vip.var.get_circle(pretty_even, radius=4, output_values=True),
         np.array([1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 1, 1, 2, 3, 3, 2, 1,
                   1, 2, 3, 3, 2, 1, 1, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1]))

def test_get_annulus_segments():
    arr = np.ones((10, 10))

    # single segment, like the old get_annulus. Note the ``[0]``.

    res = vip.var.get_annulus_segments(arr, 2, 3)[0]

    truth = (np.array([0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3,
                       3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6,
                       6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9,
                       9, 9]),
             np.array([3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8, 0, 1,
                       2, 3, 6, 7, 8, 9, 0, 1, 2, 7, 8, 9, 0, 1, 2, 7, 8, 9, 0, 1, 2, 3,
                       6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8, 3, 4,
                       5, 6]))

    aarc(res, truth)

    res = vip.var.get_annulus_segments(arr, 2, 3, mode="val")[0]
    truth = np.array([1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.,
                      1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.,
                      1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.,
                      1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.])

    aarc(res, truth)

    # multiple segments:

    res = vip.var.get_annulus_segments(pretty_even, 2, 3, nsegm=2)
    truth = [(np.array([0, 0, 0, 1, 1, 2, 3, 4, 4, 5, 5, 5]),
              np.array([3, 4, 5, 4, 5, 5, 5, 4, 5, 3, 4, 5])),
             (np.array([0, 0, 0, 1, 1, 2, 3, 4, 4, 5, 5, 5]),
              np.array([0, 1, 2, 0, 1, 0, 0, 0, 1, 0, 1, 2]))]

    aarc(res, truth)

    res = vip.var.get_annulus_segments(pretty_even, 2, 3, nsegm=3)
    truth = [(np.array([2, 3, 4, 4, 5, 5, 5]),
              np.array([5, 5, 4, 5, 3, 4, 5])),
             (np.array([0, 0, 0, 0, 0, 0, 1, 1, 1, 1]),
              np.array([0, 1, 2, 3, 4, 5, 0, 1, 4, 5])),
             (np.array([2, 3, 4, 4, 5, 5, 5]),
              np.array([0, 0, 0, 1, 0, 1, 2]))]

    assert repr(res) == repr(truth)
    # TODO: cannot compare using `allclose`, as elements have variable length!

    # tuple as input:

    res = vip.var.get_annulus_segments((6, 6), 2, 3, nsegm=3)
    assert repr(res) == repr(truth)

    # masked arr:

    res = vip.var.get_annulus_segments(arr, 2, 3, mode="mask")[0]
    truth = np.array([[0., 0., 0., 1., 1., 1., 1., 0., 0., 0.],
                      [0., 1., 1., 1., 1., 1., 1., 1., 1., 0.],
                      [0., 1., 1., 1., 1., 1., 1., 1., 1., 0.],
                      [1., 1., 1., 1., 0., 0., 1., 1., 1., 1.],
                      [1., 1., 1., 0., 0., 0., 0., 1., 1., 1.],
                      [1., 1., 1., 0., 0., 0., 0., 1., 1., 1.],
                      [1., 1., 1., 1., 0., 0., 1., 1., 1., 1.],
                      [0., 1., 1., 1., 1., 1., 1., 1., 1., 0.],
                      [0., 1., 1., 1., 1., 1., 1., 1., 1., 0.],
                      [0., 0., 0., 1., 1., 1., 1., 0., 0., 0.]])
    aarc(res, truth)

    # tuple as input:

    res = vip.var.get_annulus_segments((10, 10), 2, 3, mode="mask")[0]
    # masking a zeros array -> only zeros left!
    assert res.sum() == 0

def test_dist():
    assert vip.var.dist(0, 0, 1, 1) == np.sqrt(2)
    assert vip.var.dist(1, 2, 3, 4) == 2 * np.sqrt(2)

def test_get_ellipse():
    f = np.ones((6, 10))

    # masked array:
    fem = vip.var.get_ellipse(f, 4, 2, 90, mode="mask")
    assert fem.sum() == 28  # outer region masked, 28 pixels kept

    # values:
    fev = vip.var.get_ellipse(f, 4, 2, 90, mode="val")
    assert fev.sum() == 28

    # indices:
    fei = vip.var.get_ellipse(f, 4, 2, 90, mode="ind")
    assert fei[0].shape == fei[1].shape == (28,)

def test_get_ell_annulus():

    f = np.ones((15, 30))

    fa = vip.var.get_ell_annulus(f, 8, 3, 90, 6, mode="mask")
    assert fa.sum() == 124
<|endoftext|>


<commit_before>import pytest
import time
import boto3
import uuid
import numpy as np
import time
import pywren
import subprocess
import logging
import unittest
import numpy as np
from flaky import flaky

class SimpleAsync(unittest.TestCase):

    def setUp(self):
        self.wrenexec = pywren.default_executor()

    def test_simple(self):

        def sum_list(x):
            return np.sum(x)

        x = np.arange(10)
        fut = self.wrenexec.call_async(sum_list, x)

        res = fut.result()
        self.assertEqual(res, np.sum(x))

    def test_exception(self):
        def throwexcept(x):
            raise Exception("Throw me out!")

        wrenexec = pywren.default_executor()
        fut = self.wrenexec.call_async(throwexcept, None)

        with pytest.raises(Exception) as execinfo:
            res = fut.result()
        assert 'Throw me out!' in str(execinfo.value)

    def test_subprocess(self):
        def uname(x):
            return subprocess.check_output("uname -a", shell=True)

        fut = self.wrenexec.call_async(uname, None)

        res = fut.result()

class SimpleMap(unittest.TestCase):

    def setUp(self):
        self.wrenexec = pywren.default_executor()

    def test_map(self):

        def plus_one(x):
            return x + 1
        N = 10

        x = np.arange(N)
        futures = self.wrenexec.map(plus_one, x)

        result_count = 0
        while result_count < N:

            fs_dones, fs_notdones = pywren.wait(futures)
            result_count = len(fs_dones)

        res = np.array([f.result() for f in futures])
        np.testing.assert_array_equal(res, x + 1)

class RuntimeCaching(unittest.TestCase):

    def setUp(self):
        self.wrenexec = pywren.default_executor()

    @flaky(max_runs=3)
    def test_cached_runtime(self):
        """
        Test the runtime caching by manually running with it off
        and then running with it on and comparing invocation times.
        Note that due to aws lambda internals this might not
        do the right thing so we mark it as flaky
        """

        def test_add(x):
            return x + 7

        t1 = time.time()
        fut = self.wrenexec.map(test_add, [10], use_cached_runtime=False)[0]
        res = fut.result()
        t2 = time.time()
        non_cached_latency = t2-t1

        assert fut._run_status['runtime_cached'] == False
        assert res == 17

        t1 = time.time()
        fut = self.wrenexec.map(test_add, [10], use_cached_runtime=True)[0]
        res = fut.result()
        t2 = time.time()
        cached_latency = t2-t1

        assert res == 17
        assert fut._run_status['runtime_cached'] == True

        assert cached_latency < non_cached_latency
<commit_msg>fix tests<commit_after>import pytest
import time
import boto3
import uuid
import numpy as np
import time
import pywren
import subprocess
import logging
import unittest
import numpy as np
from flaky import flaky

class SimpleAsync(unittest.TestCase):

    def setUp(self):
        self.wrenexec = pywren.default_executor()

    def test_simple(self):

        def sum_list(x):
            return np.sum(x)

        x = np.arange(10)
        fut = self.wrenexec.call_async(sum_list, x)

        res = fut.result()
        self.assertEqual(res, np.sum(x))

    def test_exception(self):
        def throwexcept(x):
            raise Exception("Throw me out!")

        wrenexec = pywren.default_executor()
        fut = self.wrenexec.call_async(throwexcept, None)

        with pytest.raises(Exception) as execinfo:
            res = fut.result()
        assert 'Throw me out!' in str(execinfo.value)

    def test_subprocess(self):
        def uname(x):
            return subprocess.check_output("uname -a", shell=True)

        fut = self.wrenexec.call_async(uname, None)

        res = fut.result()

class SimpleMap(unittest.TestCase):

    def setUp(self):
        self.wrenexec = pywren.default_executor()

    def test_map(self):

        def plus_one(x):
            return x + 1
        N = 10

        x = np.arange(N)
        futures = self.wrenexec.map(plus_one, x)

        result_count = 0
        while result_count < N:

            fs_dones, fs_notdones = pywren.wait(futures)
            result_count = len(fs_dones)

        res = np.array([f.result() for f in futures])
        np.testing.assert_array_equal(res, x + 1)

class RuntimeCaching(unittest.TestCase):

    def setUp(self):
        self.wrenexec = pywren.default_executor()

    @flaky(max_runs=3)
    def test_cached_runtime(self):
        """
        Test the runtime caching by manually running with it off
        and then running with it on and comparing invocation times.
        Note that due to aws lambda internals this might not
        do the right thing so we mark it as flaky
        """

        def test_add(x):
            return x + 7

        t1 = time.time()
        fut = self.wrenexec.map(test_add, [10], use_cached_runtime=False)[0]
        res = fut.result()
        t2 = time.time()
        non_cached_latency = t2-t1

        assert fut.run_status['runtime_cached'] == False
        assert res == 17

        t1 = time.time()
        fut = self.wrenexec.map(test_add, [10], use_cached_runtime=True)[0]
        res = fut.result()
        t2 = time.time()
        cached_latency = t2-t1

        assert res == 17
        assert fut.run_status['runtime_cached'] == True

        assert cached_latency < non_cached_latency
<|endoftext|>


<commit_before>import string
import random

import h5py
import atpy
import pytest
import numpy as np

from hyperion.sources import Source

def random_id(length=32):
    return string.join(random.sample(string.letters + string.digits, length), '')

def virtual_file():
    return h5py.File(random_id(), driver='core', backing_store=False)

def test_spectrum_atpy():
    t = atpy.Table()
    t.add_column('nu', [1, 2, 3])
    t.add_column('fnu', [1, 2, 3])
    s = Source()
    s.luminosity = 0.
    s.spectrum = t

def test_spectrum_atpy_invalid():
    t = atpy.Table()  # table is empty, so invalid
    s = Source()
    s.luminosity = 0.
    with pytest.raises(TypeError):
        s.spectrum = t

def test_spectrum_tuple():
    nu = np.array([1, 2, 3])
    fnu = np.array([1, 2, 3])
    s = Source()
    s.luminosity = 0.
    s.spectrum = (nu, fnu)

def test_spectrum_tuple_invalid1():
    nu = [1, 2, 3]  # should be a numpy array
    fnu = np.array([1, 2, 3])
    s = Source()
    s.luminosity = 0.
    with pytest.raises(TypeError):
        s.spectrum = (nu, fnu)

def test_spectrum_tuple_invalid2():
    nu = np.array([1, 2, 3])
    fnu = [1, 2, 3]  # should be a numpy array
    s = Source()
    s.luminosity = 0.
    with pytest.raises(TypeError):
        s.spectrum = (nu, fnu)

def test_spectrum_tuple_invalid3():
    nu = np.array([1, 2, 3])
    fnu = np.array([1, 2, 3, 4])  # sizes don't agree
    s = Source()
    s.luminosity = 0.
    with pytest.raises(TypeError):
        s.spectrum = (nu, fnu)

def test_spectrum_tuple_invalid4():
    nu = np.array([[1, 2, 3], [4, 5, 6]])
    fnu = np.array([[1, 2, 3], [4, 5, 6]])  # arrays should be 1D
    s = Source()
    s.luminosity = 0.
    with pytest.raises(TypeError):
        s.spectrum = (nu, fnu)
<commit_msg>Added another spectrum setting test<commit_after>import string
import random

import h5py
import atpy
import pytest
import numpy as np

from hyperion.sources import Source

def random_id(length=32):
    return string.join(random.sample(string.letters + string.digits, length), '')

def virtual_file():
    return h5py.File(random_id(), driver='core', backing_store=False)

def test_spectrum_atpy():
    t = atpy.Table()
    t.add_column('nu', [1, 2, 3])
    t.add_column('fnu', [1, 2, 3])
    s = Source()
    s.luminosity = 0.
    s.spectrum = t

def test_spectrum_atpy_invalid():
    t = atpy.Table()  # table is empty, so invalid
    s = Source()
    s.luminosity = 0.
    with pytest.raises(TypeError):
        s.spectrum = t

def test_spectrum_tuple():
    nu = np.array([1, 2, 3])
    fnu = np.array([1, 2, 3])
    s = Source()
    s.luminosity = 0.
    s.spectrum = (nu, fnu)

def test_spectrum_tuple_invalid1():
    nu = [1, 2, 3]  # should be a numpy array
    fnu = np.array([1, 2, 3])
    s = Source()
    s.luminosity = 0.
    with pytest.raises(TypeError):
        s.spectrum = (nu, fnu)

def test_spectrum_tuple_invalid2():
    nu = np.array([1, 2, 3])
    fnu = [1, 2, 3]  # should be a numpy array
    s = Source()
    s.luminosity = 0.
    with pytest.raises(TypeError):
        s.spectrum = (nu, fnu)

def test_spectrum_tuple_invalid3():
    nu = np.array([1, 2, 3])
    fnu = np.array([1, 2, 3, 4])  # sizes don't agree
    s = Source()
    s.luminosity = 0.
    with pytest.raises(TypeError):
        s.spectrum = (nu, fnu)

def test_spectrum_tuple_invalid4():
    nu = np.array([[1, 2, 3], [4, 5, 6]])
    fnu = np.array([[1, 2, 3], [4, 5, 6]])  # arrays should be 1D
    s = Source()
    s.luminosity = 0.
    with pytest.raises(TypeError):
        s.spectrum = (nu, fnu)

def test_spectrum_tuple_invalid5():
    nu = np.array([1, 2, 3])
    fnu = np.array([1, 2, 3])
    s = Source()
    s.luminosity = 0.
    with pytest.raises(TypeError):
        s.spectrum = (nu, fnu, fnu)  # too many items
<|endoftext|>


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

import logging
import argparse
import time

from os import getcwd, chdir

from test_fixtures import KeyStore, with_aktualizr, with_uptane_backend, with_secondary, with_director, with_imagerepo,\
    with_sysroot, with_treehub, TestRunner

logger = logging.getLogger(__file__)

"""
 Test update of Primary and Secondary if their package manager differs, `ostree`
 and binary (`none` or `fake`) respectively

 Aktualizr/Primary's package manager is set to `ostree`
 Secondary's package manager is set to `fake` which means a file/binary update
 Primary goal is to verify whether aktualizr succeeds with a binary/fake update of Secondary
 while aktualizr/Primary is configured with ostree package manager
"""
@with_uptane_backend(start_generic_server=True)
@with_secondary(start=True)
@with_director()
@with_treehub()
@with_sysroot()
@with_aktualizr(start=False, run_mode='once', output_logs=True)
def test_primary_ostree_secondary_file_updates(uptane_repo, secondary, aktualizr, director, sysroot,
                                               treehub, uptane_server, **kwargs):
    target_rev = treehub.revision
    # add an ostree update for Primary
    uptane_repo.add_ostree_target(aktualizr.id, target_rev)
    # add a fake/binary update for Secondary
    secondary_update_hash = uptane_repo.add_image(secondary.id, "secondary-update.bin")

    with aktualizr:
        aktualizr.wait_for_completion()

    # check the Primary update, must be in pending state since it requires reboot
    pending_rev = aktualizr.get_primary_pending_version()
    if pending_rev != target_rev:
        logger.error("Pending version {} != the target version {}".format(pending_rev, target_rev))
        return False

    # check the Secondary update
    current_secondary_image_hash = aktualizr.get_current_image_info(secondary.id)
    if current_secondary_image_hash != secondary_update_hash:
        logger.error("Current Secondary image {} != expected image {}".format(current_secondary_image_hash,
                                                                              secondary_update_hash))
        return False

    # emulate reboot and run aktualizr once more
    sysroot.update_revision(pending_rev)
    aktualizr.emulate_reboot()

    with aktualizr:
        aktualizr.wait_for_completion()

    # check the Primary update after reboot
    result = director.get_install_result() and (target_rev == aktualizr.get_current_primary_image_info())
    return result

"""
 Test update of Secondary's ostree repo if an ostree target metadata are expired

 Metadata are valid at the moment of a new ostree revision installation,
 but are expired after that and before Secondary is rebooted,
 we still expect that the installed update is applied in this case
"""
@with_treehub()
@with_uptane_backend()
@with_director()
@with_sysroot()
@with_secondary(start=False)
@with_aktualizr(start=False, run_mode='once', output_logs=True)
def test_secodary_ostree_update_if_metadata_expires(uptane_repo, secondary, aktualizr, treehub, sysroot, director, **kwargs):
    target_rev = treehub.revision
    expires_within_sec = 10

    uptane_repo.add_ostree_target(secondary.id, target_rev, expires_within_sec=expires_within_sec)
    start_time = time.time()

    with secondary:
        with aktualizr:
            aktualizr.wait_for_completion()

    pending_rev = aktualizr.get_current_pending_image_info(secondary.id)

    if pending_rev != target_rev:
        logger.error("Pending version {} != the target one {}".format(pending_rev, target_rev))
        return False

    # wait until the target metadata are expired
    time.sleep(max(0, expires_within_sec - (time.time() - start_time)))

    sysroot.update_revision(pending_rev)
    secondary.emulate_reboot()

    with secondary:
        with aktualizr:
            aktualizr.wait_for_completion()

    if not director.get_install_result():
        logger.error("Installation result is not successful")
        return False

    installed_rev = aktualizr.get_current_image_info(secondary.id)

    if installed_rev != target_rev:
        logger.error("Installed version {} != the target one {}".format(installed_rev, target_rev))
        return False

    return True

"""
 Test update of Primary's ostree repo if an ostree target metadata are expired

 Metadata are valid at the moment of a new ostree revision installation,
 but are expired after that and before Primary is rebooted,
 we still expect that the installed update is applied in this case
"""
@with_uptane_backend(start_generic_server=True)
@with_director()
@with_treehub()
@with_sysroot()
@with_aktualizr(start=False, run_mode='once', output_logs=True)
def test_primary_ostree_update_if_metadata_expires(uptane_repo, aktualizr, director, sysroot, treehub, uptane_server, **kwargs):
    target_rev = treehub.revision
    expires_within_sec = 10

    # add an ostree update for Primary
    uptane_repo.add_ostree_target(aktualizr.id, target_rev, expires_within_sec=expires_within_sec)
    start_time = time.time()

    with aktualizr:
        aktualizr.wait_for_completion()

    # check the Primary update, must be in pending state since it requires reboot
    pending_rev = aktualizr.get_primary_pending_version()
    if pending_rev != target_rev:
        logger.error("Pending version {} != the target version {}".format(pending_rev, target_rev))
        return False

    # wait until the target metadata are expired
    time.sleep(max(0, expires_within_sec - (time.time() - start_time)))

    # emulate reboot and run aktualizr once more
    sysroot.update_revision(pending_rev)
    aktualizr.emulate_reboot()

    with aktualizr:
        aktualizr.wait_for_completion()

    # check the Primary update after reboot
    result = director.get_install_result() and (target_rev == aktualizr.get_current_primary_image_info())
    return result

if __name__ == "__main__":
    logging.basicConfig(level=logging.INFO)

    parser = argparse.ArgumentParser(description='Test backend failure')
    parser.add_argument('-b', '--build-dir', help='build directory', default='build')
    parser.add_argument('-s', '--src-dir', help='source directory', default='.')

    input_params = parser.parse_args()

    KeyStore.base_dir = input_params.src_dir
    initial_cwd = getcwd()
    chdir(input_params.build_dir)

    test_suite = [
        test_primary_ostree_secondary_file_updates,
        test_secodary_ostree_update_if_metadata_expires,
        test_primary_ostree_update_if_metadata_expires
    ]

    test_suite_run_result = TestRunner(test_suite).run()

    chdir(initial_cwd)
    exit(0 if test_suite_run_result else 1)
<commit_msg>Fix flaky test by waiting for Secondary to start up.<commit_after>#!/usr/bin/env python3

import logging
import argparse
import time

from os import getcwd, chdir

from test_fixtures import KeyStore, with_aktualizr, with_uptane_backend, with_secondary, with_director, with_imagerepo,\
    with_sysroot, with_treehub, TestRunner

logger = logging.getLogger(__file__)

"""
 Test update of Primary and Secondary if their package manager differs, `ostree`
 and binary (`none` or `fake`) respectively

 Aktualizr/Primary's package manager is set to `ostree`
 Secondary's package manager is set to `fake` which means a file/binary update
 Primary goal is to verify whether aktualizr succeeds with a binary/fake update of Secondary
 while aktualizr/Primary is configured with ostree package manager
"""
@with_uptane_backend(start_generic_server=True)
@with_secondary(start=True)
@with_director()
@with_treehub()
@with_sysroot()
@with_aktualizr(start=False, run_mode='once', output_logs=True)
def test_primary_ostree_secondary_file_updates(uptane_repo, secondary, aktualizr, director, sysroot,
                                               treehub, **kwargs):
    target_rev = treehub.revision
    # add an ostree update for Primary
    uptane_repo.add_ostree_target(aktualizr.id, target_rev)
    # add a fake/binary update for Secondary
    secondary_update_hash = uptane_repo.add_image(secondary.id, "secondary-update.bin")

    with aktualizr:
        aktualizr.wait_for_completion()

    # check the Primary update, must be in pending state since it requires reboot
    pending_rev = aktualizr.get_primary_pending_version()
    if pending_rev != target_rev:
        logger.error("Pending version {} != the target version {}".format(pending_rev, target_rev))
        return False

    # check the Secondary update
    current_secondary_image_hash = aktualizr.get_current_image_info(secondary.id)
    if current_secondary_image_hash != secondary_update_hash:
        logger.error("Current Secondary image {} != expected image {}".format(current_secondary_image_hash,
                                                                              secondary_update_hash))
        return False

    # emulate reboot and run aktualizr once more
    sysroot.update_revision(pending_rev)
    aktualizr.emulate_reboot()

    with aktualizr:
        aktualizr.wait_for_completion()

    # check the Primary update after reboot
    result = director.get_install_result() and (target_rev == aktualizr.get_current_primary_image_info())
    return result

"""
 Test update of Secondary's ostree repo if an ostree target metadata are expired

 Metadata are valid at the moment of a new ostree revision installation,
 but are expired after that and before Secondary is rebooted,
 we still expect that the installed update is applied in this case
"""
@with_uptane_backend()
@with_director()
@with_treehub()
@with_sysroot()
@with_secondary(start=False)
@with_aktualizr(start=False, run_mode='once', output_logs=True)
def test_secondary_ostree_update_if_metadata_expires(uptane_repo, secondary, aktualizr, director, sysroot, treehub, **kwargs):
    target_rev = treehub.revision
    expires_within_sec = 10

    # add an OSTree update for Secondary
    uptane_repo.add_ostree_target(secondary.id, target_rev, expires_within_sec=expires_within_sec)
    start_time = time.time()

    with secondary:
        with aktualizr:
            aktualizr.wait_for_completion()

    # check the Primary update, must be in pending state since it requires reboot
    pending_rev = aktualizr.get_current_pending_image_info(secondary.id)
    if pending_rev != target_rev:
        logger.error("Pending version {} != the target version {}".format(pending_rev, target_rev))
        return False

    # wait until the target metadata are expired
    time.sleep(max(0, expires_within_sec - (time.time() - start_time)))

    # emulate reboot and run aktualizr once more
    sysroot.update_revision(pending_rev)
    secondary.emulate_reboot()

    with secondary:
        # Wait for Secondary to initialize. wait_for_completion won't work; it
        # times out.
        time.sleep(5)
        with aktualizr:
            aktualizr.wait_for_completion()

    # check the Secondary update after reboot
    if not director.get_install_result():
        logger.error("Installation result is not successful")
        return False

    installed_rev = aktualizr.get_current_image_info(secondary.id)
    if installed_rev != target_rev:
        logger.error("Installed version {} != the target version {}".format(installed_rev, target_rev))
        return False

    return True

"""
 Test update of Primary's ostree repo if an ostree target metadata are expired

 Metadata are valid at the moment of a new ostree revision installation,
 but are expired after that and before Primary is rebooted,
 we still expect that the installed update is applied in this case
"""
@with_uptane_backend()
@with_director()
@with_treehub()
@with_sysroot()
@with_aktualizr(start=False, run_mode='once', output_logs=True)
def test_primary_ostree_update_if_metadata_expires(uptane_repo, aktualizr, director, sysroot, treehub, **kwargs):
    target_rev = treehub.revision
    expires_within_sec = 10

    # add an OSTree update for Primary
    uptane_repo.add_ostree_target(aktualizr.id, target_rev, expires_within_sec=expires_within_sec)
    start_time = time.time()

    with aktualizr:
        aktualizr.wait_for_completion()

    # check the Primary update, must be in pending state since it requires reboot
    pending_rev = aktualizr.get_primary_pending_version()
    if pending_rev != target_rev:
        logger.error("Pending version {} != the target version {}".format(pending_rev, target_rev))
        return False

    # wait until the target metadata are expired
    time.sleep(max(0, expires_within_sec - (time.time() - start_time)))

    # emulate reboot and run aktualizr once more
    sysroot.update_revision(pending_rev)
    aktualizr.emulate_reboot()

    with aktualizr:
        aktualizr.wait_for_completion()

    # check the Primary update after reboot
    if not director.get_install_result():
        logger.error("Installation result is not successful")
        return False

    installed_rev = aktualizr.get_current_primary_image_info()
    if installed_rev != target_rev:
        logger.error("Installed version {} != the target version {}".format(installed_rev, target_rev))
        return False

    return True

if __name__ == "__main__":
    logging.basicConfig(level=logging.INFO)

    parser = argparse.ArgumentParser(description='Test backend failure')
    parser.add_argument('-b', '--build-dir', help='build directory', default='build')
    parser.add_argument('-s', '--src-dir', help='source directory', default='.')

    input_params = parser.parse_args()

    KeyStore.base_dir = input_params.src_dir
    initial_cwd = getcwd()
    chdir(input_params.build_dir)

    test_suite = [
        test_primary_ostree_secondary_file_updates,
        test_secondary_ostree_update_if_metadata_expires,
        test_primary_ostree_update_if_metadata_expires
    ]

    test_suite_run_result = TestRunner(test_suite).run()

    chdir(initial_cwd)
    exit(0 if test_suite_run_result else 1)
<|endoftext|>


<commit_before>from __future__ import absolute_import

import nsq
import unittest

class WriterUnitTest(unittest.TestCase):

    def setUp(self):
        super(WriterUnitTest, self).setUp()

    def test_constructor(self):
        name = 'test'
        reconnect_interval = 10.0
        writer = nsq.Writer(nsqd_tcp_addresses=['127.0.0.1:4150'],
                            reconnect_interval=reconnect_interval,
                            name=name)
        self.assertEqual(writer.name, name)
        self.assertEqual(0, len(writer.conn_kwargs))
        self.assertEqual(writer.reconnect_interval, reconnect_interval)

    def test_bad_writer_arguments(self):
        bad_options = dict(foo=10)

        self.assertRaises(
            AssertionError,
            nsq.Writer,
            nsqd_tcp_addresses=['127.0.0.1:4150'],
            reconnect_interval=15.0,
            name='test', **bad_options)
<commit_msg>tests: Writer.mpub() with one message<commit_after>from __future__ import absolute_import

import time

import nsq
import unittest

from .test_reader import IntegrationBase

class WriterUnitTest(unittest.TestCase):

    def setUp(self):
        super(WriterUnitTest, self).setUp()

    def test_constructor(self):
        name = 'test'
        reconnect_interval = 10.0
        writer = nsq.Writer(nsqd_tcp_addresses=['127.0.0.1:4150'],
                            reconnect_interval=reconnect_interval,
                            name=name)
        self.assertEqual(writer.name, name)
        self.assertEqual(0, len(writer.conn_kwargs))
        self.assertEqual(writer.reconnect_interval, reconnect_interval)

    def test_bad_writer_arguments(self):
        bad_options = dict(foo=10)

        self.assertRaises(
            AssertionError,
            nsq.Writer,
            nsqd_tcp_addresses=['127.0.0.1:4150'],
            reconnect_interval=15.0,
            name='test', **bad_options)

class WriterIntegrationTest(IntegrationBase):
    identify_options = {
        'user_agent': 'sup',
        'heartbeat_interval': 10,
        'output_buffer_size': 4096,
        'output_buffer_timeout': 50
    }

    nsqd_command = ['nsqd', '--verbose']

    def test_writer_mpub_one(self):
        topic = 'test_writer_mpub_%s' % time.time()

        w = nsq.Writer(nsqd_tcp_addresses=['127.0.0.1:4150'], io_loop=self.io_loop,
                       **self.identify_options)

        def trypub():
            w.mpub(topic, b'{"one": 1}', callback=pubcb)

        def pubcb(conn, data):
            if isinstance(data, nsq.protocol.Error):
                if 'no open connections' in str(data):
                    self.io_loop.call_later(0.1, trypub)
                    return
            self.stop(data)

        self.io_loop.call_later(0.1, trypub)
        result = self.wait()
        print(str(result))
        assert not isinstance(result, Exception)
<|endoftext|>


<commit_before>import os
import shutil

from test.test_importer import TestImportSession
from test import _common

from beets import library
from beets import mediafile
from beets import config
from beets import plugins

class CopyArtifactsTestCase(_common.TestCase):
    """
    Provides common setup and teardown, a convenience method for exercising the
    plugin/importer, tools to setup a library, a directory containing files
    that are to be imported and an import session. The class also provides stubs
    for the autotagging library and assertions helpers.
    """
    def setUp(self):
        super(CopyArtifactsTestCase, self).setUp()

        self._setup_library()

        # Install the DummyIO to capture anything directed to stdout
        self.io.install()

    def _run_importer(self):
        """
        Create an instance of the plugin, run the importer, and
        remove/unregister the plugin instance so a new instance can
        be created when this method is run again.
        This is a convenience method that can be called to setup, exercise
        and teardown the system under test after setting any config options
        and before assertions are made regarding changes to the filesystem.
        """
        # Setup
        # Create an instance of the plugin
        plugins.find_plugins()

        # Exercise
        # Run the importer
        self.importer.run()

        # Teardown
        if plugins._instances:
            # Unregister listners
            del plugins._classes[0].listeners['import_task_files'][0]

            # Delete the plugin instance so a new one gets created for each test
            del plugins._instances[plugins._classes[0]]

    def _setup_library(self):
        self.lib_db = os.path.join(self.temp_dir, 'testlib.blb')
        self.lib_dir = os.path.join(self.temp_dir, 'testlib_dir')
        os.mkdir(self.lib_dir)

        self.lib = library.Library(self.lib_db)
        self.lib.directory =self.lib_dir
        self.lib.path_formats = [
            ('default', os.path.join('$artist', '$album', '$title')),
            ('singleton:true', os.path.join('singletons', '$title')),
            ('comp:true', os.path.join('compilations','$album', '$title')),
        ]

    def _create_flat_import_dir(self):
        """
        Creates a directory with media files and artifacts.
        Sets ``self.import_dir`` to the path of the directory. Also sets
        ``self.import_media`` to a list :class:`MediaFile` for all the media files in
        the directory.

        The directory has the following layout
          the_album/
            track_1.mp3
            artifact.file
            artifact.file2
        """
        self.import_dir = os.path.join(self.temp_dir, 'testsrcdir')
        if os.path.isdir(self.import_dir):
            shutil.rmtree(self.import_dir)

        album_path = os.path.join(self.import_dir, 'the_album')
        os.makedirs(album_path)

        resource_path = os.path.join(_common.RSRC, 'full.mp3')

        metadata = {
                     'artist': 'Tag Artist',
                     'album':  'Tag Album',
                     'albumartist':  None,
                     'mb_trackid': None,
                     'mb_albumid': None,
                     'comp': None
                   }

        # Copy media file
        medium_path = os.path.join(album_path, 'track_1.mp3')
        shutil.copy(resource_path, medium_path)
        medium = mediafile.MediaFile(medium_path)

        # Set metadata
        metadata['track'] = 1
        metadata['title'] = 'Tag Title 1'
        for attr in metadata: setattr(medium, attr, metadata[attr])
        medium.save()

        # Create artifact
        open(os.path.join(album_path, 'artifact.file'), 'a').close()
        open(os.path.join(album_path, 'artifact.file2'), 'a').close()

        self.import_media = [medium]

    def _create_nested_import_dir(self):
        """
        Creates a directory with media files and artifacts nested in subdirectories.
        Sets ``self.import_dir`` to the path of the directory. Also sets
        ``self.import_media`` to a list :class:`MediaFile` for all the media files in
        the directory.

        The directory has the following layout
          the_album/
            disc1/
              track_1.mp3
              artifact1.file
            disc2/
              track_1.mp3
              artifact2.file
        """
    def _setup_import_session(self, import_dir=None,
            delete=False, threaded=False, copy=True,
            singletons=False, move=False, autotag=True):
        config['import']['copy'] = copy
        config['import']['delete'] = delete
        config['import']['timid'] = True
        config['threaded'] = False
        config['import']['singletons'] = singletons
        config['import']['move'] = move
        config['import']['autotag'] = autotag
        config['import']['resume'] = False

        self.importer = TestImportSession(self.lib,
                                logfile=None,
                                paths=[import_dir or self.import_dir],
                                query=None)

    def assert_in_lib_dir(self, *segments):
        """
        Join the ``segments`` and assert that this path exists in the library
        directory
        """
        self.assertExists(os.path.join(self.lib_dir, *segments))

    def assert_not_in_lib_dir(self, *segments):
        """
        Join the ``segments`` and assert that this path does not exist in
        the library directory
        """
        self.assertNotExists(os.path.join(self.lib_dir, *segments))

    def assert_in_import_dir(self, *segments):
        """
        Join the ``segments`` and assert that this path exists in the import
        directory
        """
        self.assertExists(os.path.join(self.import_dir, *segments))

    def assert_not_in_import_dir(self, *segments):
        """
        Join the ``segments`` and assert that this path does not exist in
        the library directory
        """
        self.assertNotExists(os.path.join(self.import_dir, *segments))

    def assert_number_of_files_in_dir(self, count, *segments):
        """
        Assert that there are ``count`` files in path formed by joining ``segments``
        """
        self.assertEqual(len([name for name in os.listdir(os.path.join(*segments))]), count)
<commit_msg>convert plugin class set into a list before indexing into it<commit_after>import os
import shutil

from test.test_importer import TestImportSession
from test import _common

from beets import library
from beets import mediafile
from beets import config
from beets import plugins

class CopyArtifactsTestCase(_common.TestCase):
    """
    Provides common setup and teardown, a convenience method for exercising the
    plugin/importer, tools to setup a library, a directory containing files
    that are to be imported and an import session. The class also provides stubs
    for the autotagging library and assertions helpers.
    """
    def setUp(self):
        super(CopyArtifactsTestCase, self).setUp()

        self._setup_library()

        # Install the DummyIO to capture anything directed to stdout
        self.io.install()

    def _run_importer(self):
        """
        Create an instance of the plugin, run the importer, and
        remove/unregister the plugin instance so a new instance can
        be created when this method is run again.
        This is a convenience method that can be called to setup, exercise
        and teardown the system under test after setting any config options
        and before assertions are made regarding changes to the filesystem.
        """
        # Setup
        # Create an instance of the plugin
        plugins.find_plugins()

        # Exercise
        # Run the importer
        self.importer.run()

        # Teardown
        if plugins._instances:
            classes = list(plugins._classes)

            # Unregister listners
            del classes[0].listeners['import_task_files'][0]

            # Delete the plugin instance so a new one gets created for each test
            del plugins._instances[classes[0]]

    def _setup_library(self):
        self.lib_db = os.path.join(self.temp_dir, 'testlib.blb')
        self.lib_dir = os.path.join(self.temp_dir, 'testlib_dir')
        os.mkdir(self.lib_dir)

        self.lib = library.Library(self.lib_db)
        self.lib.directory =self.lib_dir
        self.lib.path_formats = [
            ('default', os.path.join('$artist', '$album', '$title')),
            ('singleton:true', os.path.join('singletons', '$title')),
            ('comp:true', os.path.join('compilations','$album', '$title')),
        ]

    def _create_flat_import_dir(self):
        """
        Creates a directory with media files and artifacts.
        Sets ``self.import_dir`` to the path of the directory. Also sets
        ``self.import_media`` to a list :class:`MediaFile` for all the media files in
        the directory.

        The directory has the following layout
          the_album/
            track_1.mp3
            artifact.file
            artifact.file2
        """
        self.import_dir = os.path.join(self.temp_dir, 'testsrcdir')
        if os.path.isdir(self.import_dir):
            shutil.rmtree(self.import_dir)

        album_path = os.path.join(self.import_dir, 'the_album')
        os.makedirs(album_path)

        resource_path = os.path.join(_common.RSRC, 'full.mp3')

        metadata = {
                     'artist': 'Tag Artist',
                     'album':  'Tag Album',
                     'albumartist':  None,
                     'mb_trackid': None,
                     'mb_albumid': None,
                     'comp': None
                   }

        # Copy media file
        medium_path = os.path.join(album_path, 'track_1.mp3')
        shutil.copy(resource_path, medium_path)
        medium = mediafile.MediaFile(medium_path)

        # Set metadata
        metadata['track'] = 1
        metadata['title'] = 'Tag Title 1'
        for attr in metadata: setattr(medium, attr, metadata[attr])
        medium.save()

        # Create artifact
        open(os.path.join(album_path, 'artifact.file'), 'a').close()
        open(os.path.join(album_path, 'artifact.file2'), 'a').close()

        self.import_media = [medium]

    def _create_nested_import_dir(self):
        """
        Creates a directory with media files and artifacts nested in subdirectories.
        Sets ``self.import_dir`` to the path of the directory. Also sets
        ``self.import_media`` to a list :class:`MediaFile` for all the media files in
        the directory.

        The directory has the following layout
          the_album/
            disc1/
              track_1.mp3
              artifact1.file
            disc2/
              track_1.mp3
              artifact2.file
        """
    def _setup_import_session(self, import_dir=None,
            delete=False, threaded=False, copy=True,
            singletons=False, move=False, autotag=True):
        config['import']['copy'] = copy
        config['import']['delete'] = delete
        config['import']['timid'] = True
        config['threaded'] = False
        config['import']['singletons'] = singletons
        config['import']['move'] = move
        config['import']['autotag'] = autotag
        config['import']['resume'] = False

        self.importer = TestImportSession(self.lib,
                                logfile=None,
                                paths=[import_dir or self.import_dir],
                                query=None)

    def assert_in_lib_dir(self, *segments):
        """
        Join the ``segments`` and assert that this path exists in the library
        directory
        """
        self.assertExists(os.path.join(self.lib_dir, *segments))

    def assert_not_in_lib_dir(self, *segments):
        """
        Join the ``segments`` and assert that this path does not exist in
        the library directory
        """
        self.assertNotExists(os.path.join(self.lib_dir, *segments))

    def assert_in_import_dir(self, *segments):
        """
        Join the ``segments`` and assert that this path exists in the import
        directory
        """
        self.assertExists(os.path.join(self.import_dir, *segments))

    def assert_not_in_import_dir(self, *segments):
        """
        Join the ``segments`` and assert that this path does not exist in
        the library directory
        """
        self.assertNotExists(os.path.join(self.import_dir, *segments))

    def assert_number_of_files_in_dir(self, count, *segments):
        """
        Assert that there are ``count`` files in path formed by joining ``segments``
        """
        self.assertEqual(len([name for name in os.listdir(os.path.join(*segments))]), count)
<|endoftext|>


<commit_before>"""
Test cases for the HTML/JavaScript scrubber and widgets.
"""
import re
from hashlib import sha256
from unittest import SkipTest
import numpy as np

try:
    from holoviews.ipython import IPTestCase
    from holoviews.ipython.widgets import ScrubberWidget, SelectionWidget
    # Standardize backend due to random inconsistencies
    from matplotlib import pyplot
    pyplot.switch_backend('agg')
except:
    raise SkipTest("Matplotlib required to test widgets")

from holoviews import Image, HoloMap
from holoviews.plotting import RasterPlot

def digest_data(data):
    hashfn = sha256()
    hashfn.update(data.encode('utf-16'))
    return hashfn.hexdigest()

prefixes =  ['anim', '_anim_slider', '_anim_img',
             '_anim_loop_select', 'textInput', '_anim_widget', 'valMap']
filters  = [re.compile('{p}[a-f0-9]+'.format(p=p)) for p in prefixes]
filters += [re.compile('new Animation\([a-z0-9_, "]+\)')]
filters += [re.compile('new NDSlider\([a-z0-9_, "]+')]

def normalize(data):
    for f in filters:
        data = re.sub(f, '[CLEARED]', data)
    # Hack around inconsistencies in jinja between Python 2 and 3
    return data.replace('0.0', '0').replace('1.0', '1')

class TestWidgets(IPTestCase):

    def setUp(self):
        super(TestWidgets, self).setUp()
        im1 = Image(np.array([[1,2],[3,4]]))
        im2 = Image(np.array([[1,2],[3,5]]))
        holomap = HoloMap(initial_items=[(0,im1), (1,im2)], key_dimensions=['test'])
        self.plot1 = RasterPlot(im1)
        self.plot2 = RasterPlot(holomap)

    def tearDown(self):
        super(TestWidgets, self).tearDown()

    def test_scrubber_widget_1(self):
        html = normalize(ScrubberWidget(self.plot1)())
        self.assertEqual(digest_data(html), 'b3b5a2c1b797e7382a6d56c507483ecc5415a3268c27d7eae072ac0167acb50f')

    def test_selection_widget_1(self):
        html = normalize(SelectionWidget(self.plot1)())
        self.assertEqual(digest_data(html), '36b0f181d797a4336a45b316e3d7653f4f948cfb4e6599dc6ba33c12461b2bb4')

    def test_scrubber_widget_2(self):
        html = normalize(ScrubberWidget(self.plot2)())
        self.assertEqual(digest_data(html), '623d3ab77b1ac49a429f1e8736064ff46219f17245c2caeea8bc3e9acba8efb3')

    def test_selection_widget_2(self):
        html = normalize(SelectionWidget(self.plot2)())
        self.assertEqual(digest_data(html), 'e9acde7559fd2c99165ebf43bf803a18dd6036ce7c7e9ec08f61480497e8d4c0')
<commit_msg>Updated widget unit test SHAs<commit_after>"""
Test cases for the HTML/JavaScript scrubber and widgets.
"""
import re
from hashlib import sha256
from unittest import SkipTest
import numpy as np

try:
    from holoviews.ipython import IPTestCase
    from holoviews.ipython.widgets import ScrubberWidget, SelectionWidget
    # Standardize backend due to random inconsistencies
    from matplotlib import pyplot
    pyplot.switch_backend('agg')
except:
    raise SkipTest("Matplotlib required to test widgets")

from holoviews import Image, HoloMap
from holoviews.plotting import RasterPlot

def digest_data(data):
    hashfn = sha256()
    hashfn.update(data.encode('utf-16'))
    return hashfn.hexdigest()

prefixes =  ['anim', '_anim_slider', '_anim_img',
             '_anim_loop_select', 'textInput', '_anim_widget', 'valMap']
filters  = [re.compile('{p}[a-f0-9]+'.format(p=p)) for p in prefixes]
filters += [re.compile('new Animation\([a-z0-9_, "]+\)')]
filters += [re.compile('new NDSlider\([a-z0-9_, "]+')]

def normalize(data):
    for f in filters:
        data = re.sub(f, '[CLEARED]', data)
    # Hack around inconsistencies in jinja between Python 2 and 3
    return data.replace('0.0', '0').replace('1.0', '1')

class TestWidgets(IPTestCase):

    def setUp(self):
        super(TestWidgets, self).setUp()
        im1 = Image(np.array([[1,2],[3,4]]))
        im2 = Image(np.array([[1,2],[3,5]]))
        holomap = HoloMap(initial_items=[(0,im1), (1,im2)], key_dimensions=['test'])
        self.plot1 = RasterPlot(im1)
        self.plot2 = RasterPlot(holomap)

    def tearDown(self):
        super(TestWidgets, self).tearDown()

    def test_scrubber_widget_1(self):
        html = normalize(ScrubberWidget(self.plot1)())
        self.assertEqual(digest_data(html), 'b3b5a2c1b797e7382a6d56c507483ecc5415a3268c27d7eae072ac0167acb50f')

    def test_selection_widget_1(self):
        html = normalize(SelectionWidget(self.plot1)())
        self.assertEqual(digest_data(html), '36775b2ff70764232269307281d91702a73b07c48d22e665dcadfa3eb00824c2')

    def test_scrubber_widget_2(self):
        html = normalize(ScrubberWidget(self.plot2)())
        self.assertEqual(digest_data(html), '623d3ab77b1ac49a429f1e8736064ff46219f17245c2caeea8bc3e9acba8efb3')

    def test_selection_widget_2(self):
        html = normalize(SelectionWidget(self.plot2)())
        self.assertEqual(digest_data(html), '93f285c4218b50231b5755756f14536733943ead9511c831a3b608a342cd2bbd')
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
from __future__ import unicode_literals

from decimal import Decimal as D

from django.test import TestCase
from django.utils.translation import activate

from shop.models import Cart, CartItem

from catalog.models import (
    Modifier, ModifierCondition, Product, Attribute, ProductAttributeValue)
from catalog import settings as scs

from tests.utils import warning

class ModifierTestCase(TestCase):
    def setUp(self):
        self.mod_1 = Modifier.objects.create(
            code='mod-1', percent=D(-30), kind=Modifier.KIND_STANDARD)
        self.mod_2 = Modifier.objects.create(
            code='mod-2', percent=D(30), kind=Modifier.KIND_DISCOUNT)
        self.mod_3 = Modifier.objects.create(
            code='mod-3', amount=D(-10), kind=Modifier.KIND_DISCOUNT)
        self.mod_4 = Modifier.objects.create(
            code='mod-4', amount=D(10), kind=Modifier.KIND_CART_MODIFIER)

        self.prod_1 = Product.objects.create(
            unit_price=D(100), is_discountable=True)
        self.prod_2 = Product.objects.create(
            unit_price=D(200), is_discountable=False)
        self.prod_3 = Product.objects.create(
            unit_price=D(300), is_discountable=True)
        self.prod_4 = Product.objects.create(
            unit_price=D(400), is_discountable=True)

    def test_calculate_add_price(self):
        self.assertEquals(self.mod_1.calculate_add_price(D(100), 1), D(-30))
        self.assertEquals(self.mod_2.calculate_add_price(D(100), 1), D(30))
        self.assertEquals(self.mod_3.calculate_add_price(D(10), 2), D(-10))
        self.assertEquals(self.mod_4.calculate_add_price(D(100), 4), D(40))

    def test_is_eligible_product(self):
        self.assertTrue(self.mod_1.is_eligible_product(self.prod_1))
        self.assertFalse(self.mod_2.is_eligible_product(self.prod_2))
        self.assertTrue(self.mod_3.is_eligible_product(self.prod_3))
        self.assertFalse(self.mod_4.is_eligible_product(self.prod_4))

class ModifierConditionTestCase(TestCase):
    def setUp(self):
        self.prod_1 = Product.objects.create(unit_price=D(300))
        self.prod_2 = Product.objects.create(unit_price=D(10))
        self.mod_1 = Modifier.objects.create(code='mod-1', percent=D(-30))
        self.cond_1 = ModifierCondition.objects.create(
            modifier=self.mod_1, path=scs.MODIFIER_CONDITIONS[0], arg=D(200))
        self.cond_2 = ModifierCondition.objects.create(
            modifier=self.mod_1, path=scs.MODIFIER_CONDITIONS[0], arg=D(50))

        self.cart_1 = Cart.objects.create()
        self.cart_1.current_total = D(100)
        self.item_1 = CartItem.objects.create(
            cart=self.cart_1, quantity=1, product=self.prod_1)
        self.item_2 = CartItem.objects.create(
            cart=self.cart_1, quantity=1, product=self.prod_2)

    def test_is_met(self):
        self.assertTrue(self.cond_1.is_met(cart_item=self.item_1))
        self.assertFalse(self.cond_1.is_met(cart_item=self.item_2))
        self.assertFalse(self.cond_1.is_met(cart=self.cart_1))
        self.assertTrue(self.cond_2.is_met(cart=self.cart_1))

class ProductTestCase(TestCase):
    def setUp(self):
        self.prod_1 = Product.objects.create(unit_price=D(300))
        self.prod_2 = Product.objects.create(
            unit_price=D(100), discount_percent=D(10))
        self.prod_1_var_1 = Product.objects.create(parent=self.prod_1)
        self.prod_2_var_1 = Product.objects.create(
            parent=self.prod_2, unit_price=D(200))

        self.attr_1 = Attribute.objects.create(
            code='attr_1', kind=Attribute.KIND_INTEGER)
        self.attr_1_val_1 = ProductAttributeValue.objects.create(
            attribute=self.attr_1, product=self.prod_1_var_1, value_integer=10)
        self.attr_2 = Attribute.objects.create(
            code='attr_2', kind=Attribute.KIND_BOOLEAN)
        self.attr_2_val_1 = ProductAttributeValue.objects.create(
            attribute=self.attr_2, product=self.prod_1_var_1,
            value_boolean=True)

    def test_get_price(self):
        self.assertEquals(self.prod_1.get_price(), D(300))
        self.assertEquals(self.prod_2.get_price(), D(90))
        self.assertEquals(self.prod_1_var_1.get_price(), D(300))
        self.assertEquals(self.prod_2_var_1.get_price(), D(180))

    def test_get_unit_price(self):
        self.assertEquals(self.prod_1_var_1.get_unit_price(), D(300))
        self.assertEquals(self.prod_2_var_1.get_unit_price(), D(200))

    def test_get_attrs(self):
        self.assertEquals(self.prod_1_var_1.get_attrs()[0]['value'], '10')
        self.assertTrue(self.prod_1_var_1.get_attrs()[1]['value'])

    def test_get_variations(self):
        self.assertEquals(len(self.prod_1.get_variations()), 2)

    def test_get_variant(self):
        self.assertTrue(self.prod_1.get_variant(attr_1=10, attr_2=True))
        self.assertFalse(self.prod_1.get_variant(attr_1=20, attr_2=True))
        self.assertFalse(self.prod_1.get_variant(attr_1=20, attr_2=False))

    def test_filter_variants(self):
        self.assertTrue(self.prod_1.filter_variants(attr_1=10, attr_2=True))
        self.assertFalse(self.prod_1.filter_variants(attr_1=10, attr_2=False))
        self.assertTrue(self.prod_1.filter_variants(attr_2=True))
        self.assertFalse(self.prod_1.filter_variants(attr_1=20, attr_2=False))
<commit_msg>test typo<commit_after># -*- coding: utf-8 -*-
from __future__ import unicode_literals

from decimal import Decimal as D

from django.test import TestCase
from django.utils.translation import activate

from shop.models import Cart, CartItem

from catalog.models import (
    Modifier, ModifierCondition, Product, Attribute, ProductAttributeValue)
from catalog import settings as scs

from tests.utils import warning

class ModifierTestCase(TestCase):
    def setUp(self):
        self.mod_1 = Modifier.objects.create(
            code='mod-1', percent=D(-30), kind=Modifier.KIND_STANDARD)
        self.mod_2 = Modifier.objects.create(
            code='mod-2', percent=D(30), kind=Modifier.KIND_DISCOUNT)
        self.mod_3 = Modifier.objects.create(
            code='mod-3', amount=D(-10), kind=Modifier.KIND_DISCOUNT)
        self.mod_4 = Modifier.objects.create(
            code='mod-4', amount=D(10), kind=Modifier.KIND_CART_MODIFIER)

        self.prod_1 = Product.objects.create(
            unit_price=D(100), is_discountable=True)
        self.prod_2 = Product.objects.create(
            unit_price=D(200), is_discountable=False)
        self.prod_3 = Product.objects.create(
            unit_price=D(300), is_discountable=True)
        self.prod_4 = Product.objects.create(
            unit_price=D(400), is_discountable=True)

    def test_calculate_add_price(self):
        self.assertEquals(self.mod_1.calculate_add_price(D(100), 1), D(-30))
        self.assertEquals(self.mod_2.calculate_add_price(D(100), 1), D(30))
        self.assertEquals(self.mod_3.calculate_add_price(D(10), 2), D(-20))
        self.assertEquals(self.mod_4.calculate_add_price(D(100), 4), D(40))

    def test_is_eligible_product(self):
        self.assertTrue(self.mod_1.is_eligible_product(self.prod_1))
        self.assertFalse(self.mod_2.is_eligible_product(self.prod_2))
        self.assertTrue(self.mod_3.is_eligible_product(self.prod_3))
        self.assertFalse(self.mod_4.is_eligible_product(self.prod_4))

class ModifierConditionTestCase(TestCase):
    def setUp(self):
        self.prod_1 = Product.objects.create(unit_price=D(300))
        self.prod_2 = Product.objects.create(unit_price=D(10))
        self.mod_1 = Modifier.objects.create(code='mod-1', percent=D(-30))
        self.cond_1 = ModifierCondition.objects.create(
            modifier=self.mod_1, path=scs.MODIFIER_CONDITIONS[0], arg=D(200))
        self.cond_2 = ModifierCondition.objects.create(
            modifier=self.mod_1, path=scs.MODIFIER_CONDITIONS[0], arg=D(50))

        self.cart_1 = Cart.objects.create()
        self.cart_1.current_total = D(100)
        self.item_1 = CartItem.objects.create(
            cart=self.cart_1, quantity=1, product=self.prod_1)
        self.item_2 = CartItem.objects.create(
            cart=self.cart_1, quantity=1, product=self.prod_2)

    def test_is_met(self):
        self.assertTrue(self.cond_1.is_met(cart_item=self.item_1))
        self.assertFalse(self.cond_1.is_met(cart_item=self.item_2))
        self.assertFalse(self.cond_1.is_met(cart=self.cart_1))
        self.assertTrue(self.cond_2.is_met(cart=self.cart_1))

class ProductTestCase(TestCase):
    def setUp(self):
        self.prod_1 = Product.objects.create(unit_price=D(300))
        self.prod_2 = Product.objects.create(
            unit_price=D(100), discount_percent=D(10))
        self.prod_1_var_1 = Product.objects.create(parent=self.prod_1)
        self.prod_2_var_1 = Product.objects.create(
            parent=self.prod_2, unit_price=D(200))

        self.attr_1 = Attribute.objects.create(
            code='attr_1', kind=Attribute.KIND_INTEGER)
        self.attr_1_val_1 = ProductAttributeValue.objects.create(
            attribute=self.attr_1, product=self.prod_1_var_1, value_integer=10)
        self.attr_2 = Attribute.objects.create(
            code='attr_2', kind=Attribute.KIND_BOOLEAN)
        self.attr_2_val_1 = ProductAttributeValue.objects.create(
            attribute=self.attr_2, product=self.prod_1_var_1,
            value_boolean=True)

    def test_get_price(self):
        self.assertEquals(self.prod_1.get_price(), D(300))
        self.assertEquals(self.prod_2.get_price(), D(90))
        self.assertEquals(self.prod_1_var_1.get_price(), D(300))
        self.assertEquals(self.prod_2_var_1.get_price(), D(180))

    def test_get_unit_price(self):
        self.assertEquals(self.prod_1_var_1.get_unit_price(), D(300))
        self.assertEquals(self.prod_2_var_1.get_unit_price(), D(200))

    def test_get_attrs(self):
        self.assertEquals(self.prod_1_var_1.get_attrs()[0]['value'], '10')
        self.assertTrue(self.prod_1_var_1.get_attrs()[1]['value'])

    def test_get_variations(self):
        self.assertEquals(len(self.prod_1.get_variations()), 2)

    def test_get_variant(self):
        self.assertTrue(self.prod_1.get_variant(attr_1=10, attr_2=True))
        self.assertFalse(self.prod_1.get_variant(attr_1=20, attr_2=True))
        self.assertFalse(self.prod_1.get_variant(attr_1=20, attr_2=False))

    def test_filter_variants(self):
        self.assertTrue(self.prod_1.filter_variants(attr_1=10, attr_2=True))
        self.assertFalse(self.prod_1.filter_variants(attr_1=10, attr_2=False))
        self.assertTrue(self.prod_1.filter_variants(attr_2=True))
        self.assertFalse(self.prod_1.filter_variants(attr_1=20, attr_2=False))
<|endoftext|>