<commit_before>import uuid

from test.helpers import ProviderTestBase
import test.helpers as helpers

class CloudNetworkServiceTestCase(ProviderTestBase):

    def __init__(self, methodName, provider):
        super(CloudNetworkServiceTestCase, self).__init__(
            methodName=methodName, provider=provider)

    def test_crud_network_service(self):
        name = 'cbtestnetworkservice-{0}'.format(uuid.uuid4())
        subnet_name = 'cbtestsubnetservice-{0}'.format(uuid.uuid4())
        net = self.provider.network.create(name=name)
        with helpers.cleanup_action(
            lambda:
                self.provider.network.delete(network_id=net.id)
        ):
            # test list method
            netl = self.provider.network.list()
            list_netl = [n for n in netl if n.name == name]
            self.assertTrue(
                len(list_netl) == 1,
                "List networks does not return the expected network %s" %
                name)

            # check get
            get_net = self.provider.network.get(network_id=net.id)
            self.assertTrue(
                get_net == net,
                "Get network did not return the expected network {0}."
                .format(name))

            # check subnet
            subnet = self.provider.network.create_subnet(
                network=net, cidr_block="10.0.0.1/24", name=subnet_name)
            with helpers.cleanup_action(
                lambda:
                    self.provider.network.delete_subnet(subnet=subnet)
            ):
                # test list method
                subnetl = self.provider.network.list_subnets()
                list_subnetl = [n for n in subnetl if n.name == subnet_name]
                self.assertTrue(
                    len(list_subnetl) == 1,
                    "List subnets does not return the expected subnet %s" %
                    subnet_name)

            subnetl = self.provider.network.list_subnets()
            found_subnet = [n for n in subnetl if n.name == subnet_name]
            self.assertTrue(
                len(found_subnet) == 0,
                "Subnet {0} should have been deleted but still exists."
                .format(subnet_name))

        netl = self.provider.network.list()
        found_net = [n for n in netl if n.name == name]
        self.assertTrue(
            len(found_net) == 0,
            "Network {0} should have been deleted but still exists."
            .format(name))

    def test_crud_network(self):
        name = 'cbtestnetwork-{0}'.format(uuid.uuid4())
        subnet_name = 'cbtestsubnet-{0}'.format(uuid.uuid4())
        net = self.provider.network.create(name=name)
        with helpers.cleanup_action(
            lambda: net.delete()
        ):
            net.wait_till_ready()

            self.assertTrue(
                net.id in repr(net),
                "repr(obj) should contain the object id so that the object"
                " can be reconstructed, but does not.")

            cidr = '10.0.1.0/24'
            sn = net.create_subnet(cidr_block=cidr, name=subnet_name)
            with helpers.cleanup_action(lambda: sn.delete()):
                self.assertTrue(
                    net.id in sn.network_id,
                    "Network ID %s should be specified in the subnet's network"
                    " id %s." % (net.id, sn.network_id))

                self.assertTrue(
                    cidr == sn.cidr_block,
                    "Subnet's CIDR %s should match the specified one %s." % (
                        sn.cidr_block, cidr))
<commit_msg>Increase Network test coverage<commit_after>import uuid

from test.helpers import ProviderTestBase
import test.helpers as helpers

class CloudNetworkServiceTestCase(ProviderTestBase):

    def __init__(self, methodName, provider):
        super(CloudNetworkServiceTestCase, self).__init__(
            methodName=methodName, provider=provider)

    def test_crud_network_service(self):
        name = 'cbtestnetworkservice-{0}'.format(uuid.uuid4())
        subnet_name = 'cbtestsubnetservice-{0}'.format(uuid.uuid4())
        net = self.provider.network.create(name=name)
        with helpers.cleanup_action(
            lambda:
                self.provider.network.delete(network_id=net.id)
        ):
            # test list method
            netl = self.provider.network.list()
            list_netl = [n for n in netl if n.name == name]
            self.assertTrue(
                len(list_netl) == 1,
                "List networks does not return the expected network %s" %
                name)

            # check get
            get_net = self.provider.network.get(network_id=net.id)
            self.assertTrue(
                get_net == net,
                "Get network did not return the expected network {0}."
                .format(name))

            # check subnet
            subnet = self.provider.network.create_subnet(
                network=net, cidr_block="10.0.0.1/24", name=subnet_name)
            with helpers.cleanup_action(
                lambda:
                    self.provider.network.delete_subnet(subnet=subnet)
            ):
                # test list method
                subnetl = self.provider.network.list_subnets()
                list_subnetl = [n for n in subnetl if n.name == subnet_name]
                self.assertTrue(
                    len(list_subnetl) == 1,
                    "List subnets does not return the expected subnet %s" %
                    subnet_name)

            subnetl = self.provider.network.list_subnets()
            found_subnet = [n for n in subnetl if n.name == subnet_name]
            self.assertTrue(
                len(found_subnet) == 0,
                "Subnet {0} should have been deleted but still exists."
                .format(subnet_name))

        netl = self.provider.network.list()
        found_net = [n for n in netl if n.name == name]
        self.assertEqual(
            len(found_net), 0,
            "Network {0} should have been deleted but still exists."
            .format(name))

    def test_crud_network(self):
        name = 'cbtestnetwork-{0}'.format(uuid.uuid4())
        subnet_name = 'cbtestsubnet-{0}'.format(uuid.uuid4())
        net = self.provider.network.create(name=name)
        with helpers.cleanup_action(
            lambda: net.delete()
        ):
            net.wait_till_ready()
            self.assertEqual(
                net.refresh(), 'available',
                "Network in state %s , yet should be 'available'" % net.state)

            self.assertIn(
                net.id, repr(net),
                "repr(obj) should contain the object id so that the object"
                " can be reconstructed, but does not.")

            self.assertIn(
                net.cidr_block, ['', '10.0.0.0/16'],
                "Network CIDR %s does not contain the expected value."
                % net.cidr_block)

            cidr = '10.0.1.0/24'
            sn = net.create_subnet(cidr_block=cidr, name=subnet_name)
            with helpers.cleanup_action(lambda: sn.delete()):
                self.assertIn(
                    sn.id, net.subnets(),
                    "Subnet ID %s should be listed in network subnets."
                    % sn.id)

                self.assertIn(
                    net.id, sn.network_id,
                    "Network ID %s should be specified in the subnet's network"
                    " id %s." % (net.id, sn.network_id))

                self.assertEqual(
                    cidr, sn.cidr_block,
                    "Subnet's CIDR %s should match the specified one %s." % (
                        sn.cidr_block, cidr))
<|endoftext|>


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

import sys

VERSION = (5, 2, 2)
__version__ = ".".join([str(s) for s in VERSION])

__title__ = "platformio"
__description__ = (
    "A professional collaborative platform for embedded development. "
    "Cross-platform IDE and Unified Debugger. "
    "Static Code Analyzer and Remote Unit Testing. "
    "Multi-platform and Multi-architecture Build System. "
    "Firmware File Explorer and Memory Inspection. "
    "IoT, Arduino, CMSIS, ESP-IDF, FreeRTOS, libOpenCM3, mbedOS, Pulp OS, SPL, "
    "STM32Cube, Zephyr RTOS, ARM, AVR, Espressif (ESP8266/ESP32), FPGA, "
    "MCS-51 (8051), MSP430, Nordic (nRF51/nRF52), NXP i.MX RT, PIC32, RISC-V, "
    "STMicroelectronics (STM8/STM32), Teensy"
)
__url__ = "https://platformio.org"

__author__ = "PlatformIO Labs"
__email__ = "contact@piolabs.com"

__license__ = "Apache Software License"
__copyright__ = "Copyright 2014-present PlatformIO Labs"

__accounts_api__ = "https://api.accounts.platformio.org"
__registry_api__ = [
    "https://api.registry.platformio.org",
    "https://api.registry.ns1.platformio.org",
]
__pioremote_endpoint__ = "ssl:host=remote.platformio.org:port=4413"

__default_requests_timeout__ = (10, None)  # (connect, read)

__core_packages__ = {
    "contrib-piohome": "~3.3.4",
    "contrib-pysite": "~2.%d%d.0" % (sys.version_info.major, sys.version_info.minor),
    "tool-unity": "~1.20500.0",
    "tool-scons": "~4.40200.0",
    "tool-cppcheck": "~1.260.0",
    "tool-clangtidy": "~1.120001.0",
    "tool-pvs-studio": "~7.14.0",
}

__check_internet_hosts__ = [
    "185.199.110.153",  # Github.com
    "88.198.170.159",  # platformio.org
    "github.com",
    "platformio.org",
]
<commit_msg>Bump version to 5.2.3a1<commit_after># Copyright (c) 2014-present PlatformIO <contact@platformio.org>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import sys

VERSION = (5, 2, "3a1")
__version__ = ".".join([str(s) for s in VERSION])

__title__ = "platformio"
__description__ = (
    "A professional collaborative platform for embedded development. "
    "Cross-platform IDE and Unified Debugger. "
    "Static Code Analyzer and Remote Unit Testing. "
    "Multi-platform and Multi-architecture Build System. "
    "Firmware File Explorer and Memory Inspection. "
    "IoT, Arduino, CMSIS, ESP-IDF, FreeRTOS, libOpenCM3, mbedOS, Pulp OS, SPL, "
    "STM32Cube, Zephyr RTOS, ARM, AVR, Espressif (ESP8266/ESP32), FPGA, "
    "MCS-51 (8051), MSP430, Nordic (nRF51/nRF52), NXP i.MX RT, PIC32, RISC-V, "
    "STMicroelectronics (STM8/STM32), Teensy"
)
__url__ = "https://platformio.org"

__author__ = "PlatformIO Labs"
__email__ = "contact@piolabs.com"

__license__ = "Apache Software License"
__copyright__ = "Copyright 2014-present PlatformIO Labs"

__accounts_api__ = "https://api.accounts.platformio.org"
__registry_api__ = [
    "https://api.registry.platformio.org",
    "https://api.registry.ns1.platformio.org",
]
__pioremote_endpoint__ = "ssl:host=remote.platformio.org:port=4413"

__default_requests_timeout__ = (10, None)  # (connect, read)

__core_packages__ = {
    "contrib-piohome": "~3.3.4",
    "contrib-pysite": "~2.%d%d.0" % (sys.version_info.major, sys.version_info.minor),
    "tool-unity": "~1.20500.0",
    "tool-scons": "~4.40200.0",
    "tool-cppcheck": "~1.260.0",
    "tool-clangtidy": "~1.120001.0",
    "tool-pvs-studio": "~7.14.0",
}

__check_internet_hosts__ = [
    "185.199.110.153",  # Github.com
    "88.198.170.159",  # platformio.org
    "github.com",
    "platformio.org",
]
<|endoftext|>


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

import sys

VERSION = (3, 5, "0rc8")
__version__ = ".".join([str(s) for s in VERSION])

__title__ = "platformio"
__description__ = ("An open source ecosystem for IoT development. "
                   "Cross-platform build system and library manager. "
                   "Continuous and IDE integration. "
                   "Arduino, ESP8266 and ARM mbed compatible")
__url__ = "http://platformio.org"

__author__ = "Ivan Kravets"
__email__ = "me@ikravets.com"

__license__ = "Apache Software License"
__copyright__ = "Copyright 2014-present PlatformIO"

__apiurl__ = "https://api.platformio.org"

if sys.version_info < (2, 7, 0) or sys.version_info >= (3, 0, 0):
    msg = ("PlatformIO Core v%s does not run under Python version %s.\n"
           "Minimum supported version is 2.7, please upgrade Python.\n"
           "Python 3 is not yet supported.\n")
    sys.stderr.write(msg % (__version__, sys.version.split()[0]))
    sys.exit(1)
<commit_msg>Bump version to 3.5.0rc9<commit_after># Copyright (c) 2014-present PlatformIO <contact@platformio.org>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import sys

VERSION = (3, 5, "0rc9")
__version__ = ".".join([str(s) for s in VERSION])

__title__ = "platformio"
__description__ = ("An open source ecosystem for IoT development. "
                   "Cross-platform build system and library manager. "
                   "Continuous and IDE integration. "
                   "Arduino, ESP8266 and ARM mbed compatible")
__url__ = "http://platformio.org"

__author__ = "Ivan Kravets"
__email__ = "me@ikravets.com"

__license__ = "Apache Software License"
__copyright__ = "Copyright 2014-present PlatformIO"

__apiurl__ = "https://api.platformio.org"

if sys.version_info < (2, 7, 0) or sys.version_info >= (3, 0, 0):
    msg = ("PlatformIO Core v%s does not run under Python version %s.\n"
           "Minimum supported version is 2.7, please upgrade Python.\n"
           "Python 3 is not yet supported.\n")
    sys.stderr.write(msg % (__version__, sys.version.split()[0]))
    sys.exit(1)
<|endoftext|>


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

def check_file_generic(f, get_num):
    print "Evaluating %s for non-monotonicity" % f

    lines = open(f).readlines()
    times = []
    for line in lines:
        t = get_num(line)
        if t is not None:
            times.append(get_num(line))

    for i,x in enumerate(times):
        if i > 0 and times[i] < times[i-1]:
            print "%f: %f" % (times[i-1], times[i] - times[i-1])

def check_file_intnw(f):
    def get_timestamp(line):
        import re
        m = re.search("^\[([0-9]+\.[0-9]+)\]", line)
        if m:
            return float(m.group(1))
        return None

    check_file_generic(f, get_timestamp)

def check_file_trace_replayer(f):
    def get_timestamp(line):
        try:
            return float(line.split()[0])
        except (ValueError, IndexError):
            return None

    check_file_generic(f, get_timestamp)

from argparse import ArgumentParser
import os.path
import sys

if __name__ == '__main__':
    parser = ArgumentParser()
    parser.add_argument("filename")
    args = parser.parse_args()

    choices = ['intnw.log', 'trace_replayer.log']

    # trim leading path
    file_base = os.path.basename(args.filename)
    if file_base not in choices:
        print "Invalid filename %s should be one of %s" % (file_base, choices)
        sys.exit(1)

    # trim .log extension
    func = locals()["check_file_" + file_base[:-4]]
    func(args.filename)
<commit_msg>Added checking of timing.log.<commit_after>#!/usr/bin/env python2.7

def check_file_generic(f, get_num):
    print "Evaluating %s for non-monotonicity" % f

    lines = open(f).readlines()
    times = []
    for line in lines:
        t = get_num(line)
        if t is not None:
            times.append(get_num(line))

    # times is a list of (timestamp_string, timestamp_float) tuples
    for i in xrange(len(times)):
        if i > 0 and times[i][1] < times[i-1][1]:
            print "%s: %f" % (times[i-1][0], times[i][1] - times[i-1][1])

_unix_float_timestamp = "([0-9]+\.[0-9]+)"
import re

def check_file_intnw(f):
    def get_timestamp(line):
        m = re.search("^\[%s\]" % _unix_float_timestamp, line)
        if m:
            ts_str = m.group(1)
            return ts_str, float(ts_str)
        return None

    check_file_generic(f, get_timestamp)

def check_file_trace_replayer(f):
    def get_timestamp(line):
        try:
            ts_str = line.split()[0]
            m = re.search(_unix_float_timestamp, ts_str)
            if m:
                return ts_str, float(ts_str)
        except (ValueError, IndexError):
            pass # fall through
        return None

    check_file_generic(f, get_timestamp)

def check_file_timing(f):
    def get_timestamp(line):
        from dateutil import parser
        fields = line.strip().split()
        if len(fields) < 6:
            return None
        datestr = " ".join(fields)

        try:
            d = parser.parse(datestr)
            return datestr, time.mktime(d.timetuple())
        except ValueError:
            return None

    check_file_generic(f, get_timestamp);

from argparse import ArgumentParser
import os.path
import sys

if __name__ == '__main__':
    parser = ArgumentParser()
    parser.add_argument("filename")
    args = parser.parse_args()

    choices = ['intnw.log', 'trace_replayer.log', 'timing.log']

    # trim leading path
    file_base = os.path.basename(args.filename)
    if file_base not in choices:
        print "Invalid filename %s should be one of %s" % (file_base, choices)
        sys.exit(1)

    # trim .log extension
    func = locals()["check_file_" + file_base[:-4]]
    func(args.filename)
<|endoftext|>


<commit_before>__author__  = "Alexan Mardigian"
__version__ = "0.1.0"

from argparse import ArgumentParser

import json
import sys
import traceback
import urllib
import urllib2

PWNED_API_URL = "https://haveibeenpwned.com/api/v2/%s/%s"

EMAILINDEX = 0
PWNEDINDEX = 1
DATAINDEX  = 2

BREACHED = "breachedaccount"
PASTEBIN = "pasteaccount"

class PwnedArgParser(ArgumentParser):
	def error(self, message):
		sys.stderr.write('error: %s\n' %message)
		self.print_help()
		sys.exit(2)

def get_args():
	parser = PwnedArgParser()

	parser.add_argument('-b', action="store_true", dest='only_breaches', help='Return results for breaches only.')
	parser.add_argument('-i', dest='input_path',   help='Path to text file that lists email addresses.')
	parser.add_argument('-o', dest='output_path',  help='Path to output (tab deliminated) text file.')
        parser.add_argument('-p', action="store_true", dest='only_pwned', help='Print only the pwned email addresses.')
        parser.add_argument('-s', dest="single_email", help='Send query for just one email address.')
        parser.add_argument('-t', action="store_true", dest='only_pastebins', help='Return results for pastebins only.')

	if len(sys.argv) == 1:
		parser.print_help()
		sys.exit(1)

	return parser.parse_args()

#  Used for removing the trailing '\n' character on each email.
def clean_list(list_of_strings):
	return [str(x).strip() for x in list_of_strings]

def get_results(email_list, service, opts):
	results = []  # list of tuples (email adress, been pwned?, json data)

	for email in email_list:
		data = []
                req  = urllib2.Request(PWNED_API_URL % (urllib.quote(service), urllib.quote(email)))

                try:
                	response = urllib2.urlopen(req)  # This is a json object.
                        data     = json.loads(response.read())
			results.append( (email, True, data) )

                except urllib2.HTTPError as e:
                        if e.code == 400:
                                raise InvalidEmail("%s does not appear to be a valid email address.")
                        if e.code == 404 and not opts.only_pwned:
				results.append( (email, False, data) )

		if not opts.output_path:
			try:
				last_result = results[-1]

				if not last_result[PWNEDINDEX]:
					if service == BREACHED:
						print "Email address %s not pwned.  Yay!" % (email)
					else:
						print "Email address %s was not found in any pastes.  Yay!" %(email)
				elif data:
					print "\n%s pwned!\n==========" % (email)
					print json.dumps(data, indent=4)
					print '\n'

			except IndexError:
				pass

	return results

def tab_delimited_string(data):
	DATACLASSES = 'DataClasses'

	begining_sub_str = data[EMAILINDEX] + '\t' + str(data[PWNEDINDEX])
        tab_string       = ""

	if data[DATAINDEX]:
		for bp in data[DATAINDEX]:  # bp stands for breaches and pastbins
			d = bp
			flat_data_classes = [str(x) for x in d[DATACLASSES]]
			d[DATACLASSES]    = flat_data_classes

			flat_d     = [str(x) for x in d.values()]
			tab_string = tab_string + begining_sub_str + '\t' + tab_string + "\t".join(flat_d) + '\n'
	else:
		tab_string = begining_sub_str

	return tab_string.rstrip()

def write_results_to_file(filename, results, opts):
	files = []

	if opts.only_breaches:
		files.append("_breaches.txt")
	elif opts.only_pastebins:
		files.append("_pastes.txt")
	else:
		files.append("_breaches.txt")
		files.append("_pastes.txt")

	if filename.rfind('.') > -1:
		filename = filename[:filename.rfind('.')]

	for res, f in zip(results, files):
		outfile = open(filename + f, 'w')

        	for r in res:
			outfile.write(tab_delimited_string(r) + '\n')

        	outfile.close()

def main():
	email_list = []
	opts = get_args()

	if opts.single_email:
		email_list = [opts.single_email]
	else:
		email_list_file = open(opts.input_path, 'r')
		email_list      = clean_list(email_list_file.readlines())

		email_list_file.close()

        results = []

        if opts.only_breaches:
		results.append(get_results(email_list, BREACHED, opts))
	elif opts.only_pastebins:
		results.append(get_results(email_list, PASTEBIN, opts))
	else:
		results.append(get_results(email_list, BREACHED, opts))
		results.append(get_results(email_list, PASTEBIN, opts))

	if opts.output_path:
		write_results_to_file(opts.output_path, results, opts)

if __name__ == '__main__':
	main()
<commit_msg>Now prints a header to the text files it creates.<commit_after>__author__  = "Alexan Mardigian"
__version__ = "0.2.0"

from argparse import ArgumentParser

import json
import sys
import traceback
import urllib
import urllib2

PWNED_API_URL = "https://haveibeenpwned.com/api/v2/%s/%s"

EMAILINDEX = 0
PWNEDINDEX = 1
DATAINDEX  = 2

BREACHED = "breachedaccount"
PASTEBIN = "pasteaccount"

class PwnedArgParser(ArgumentParser):
	def error(self, message):
		sys.stderr.write('error: %s\n' %message)
		self.print_help()
		sys.exit(2)

def get_args():
	parser = PwnedArgParser()

	parser.add_argument('-b', action="store_true", dest='only_breaches', help='Return results for breaches only.')
	parser.add_argument('-i', dest='input_path',   help='Path to text file that lists email addresses.')
	parser.add_argument('-o', dest='output_path',  help='Path to output (tab deliminated) text file.')
        parser.add_argument('-p', action="store_true", dest='only_pwned', help='Print only the pwned email addresses.')
        parser.add_argument('-s', dest="single_email", help='Send query for just one email address.')
        parser.add_argument('-t', action="store_true", dest='only_pastebins', help='Return results for pastebins only.')

	if len(sys.argv) == 1:  # If no arguments were provided, then print help and exit.
		parser.print_help()
		sys.exit(1)

	return parser.parse_args()

#  Used for removing the trailing '\n' character on each email.
def clean_list(list_of_strings):
	return [str(x).strip() for x in list_of_strings]

def get_results(email_list, service, opts):
	results = []  # list of tuples (email adress, been pwned?, json data)

	for email in email_list:
		email = email.strip()
		data = []
                req  = urllib2.Request(PWNED_API_URL % (urllib.quote(service), urllib.quote(email)))

                try:
                	response = urllib2.urlopen(req)  # This is a json object.
                        data     = json.loads(response.read())
			results.append( (email, True, data) )

                except urllib2.HTTPError as e:
                        if e.code == 400:
				print email
                                raise InvalidEmail("%s does not appear to be a valid email address.")
                        if e.code == 404 and not opts.only_pwned:
				results.append( (email, False, data) )

		if not opts.output_path:
			try:
				last_result = results[-1]

				if not last_result[PWNEDINDEX]:
					if service == BREACHED:
						print "Email address %s not pwned.  Yay!" % (email)
					else:
						print "Email address %s was not found in any pastes.  Yay!" %(email)
				elif data:
					print "\n%s pwned!\n==========" % (email)
					print json.dumps(data, indent=4)
					print '\n'

			except IndexError:
				pass

	return results

#  This function will convert every item, in dlist, into a string and
#  encode any unicode strings into an 8-bit string.
def clean_list(dlist):
	cleaned_list = []

	for d in dlist:
		try:
			cleaned_list.append(str(d))
		except UnicodeEncodeError:
			cleaned_list.append(str(d.encode('utf-8')))  # Clean the data.

	return cleaned_list

def tab_delimited_string(data):
	DATACLASSES = 'DataClasses'

	begining_sub_str = data[EMAILINDEX] + '\t' + str(data[PWNEDINDEX])
	output_list      = []

	if data[DATAINDEX]:
		for bp in data[DATAINDEX]:  # bp stands for breaches/pastbins
			d = bp

			try:
				flat_data_classes = [str(x) for x in d[DATACLASSES]]
				d[DATACLASSES]    = flat_data_classes
			except KeyError:
				pass  #  Not processing a string for a breach.

			flat_d = clean_list(d.values())
			output_list.append(begining_sub_str + '\t' + "\t".join(flat_d))
	else:
		output_list.append(begining_sub_str)

	return '\n'.join(output_list)

def write_results_to_file(filename, results, opts):
	BREACHESTXT = "_breaches.txt"
	PASTESTXT   = "_pastes.txt"
	files = []

	file_headers = {
			BREACHESTXT: "Email Address\tIs Pwned\tPwn Count\tDomain\tName\tTitle\tData Classes\tLogo Type\tBreach Date\tAdded Date\tIs Verified\tDescription",
			PASTESTXT:   "Email Address\tIs Pwned\tDate\tSource\tEmail Count\tID\tTitle",
	}

	if opts.only_breaches:
		files.append(BREACHESTXT)
	elif opts.only_pastebins:
		files.append(PASTESTXT)
	else:
		files.append(BREACHESTXT)
		files.append(PASTESTXT)

	if filename.rfind('.') > -1:
		filename = filename[:filename.rfind('.')]

	for res, f in zip(results, files):
		outfile = open(filename + f, 'w')

		outfile.write(file_headers[f] + '\n')

        	for r in res:
			outfile.write(tab_delimited_string(r) + '\n')

        	outfile.close()

def main():
	email_list = []
	opts = get_args()

	if opts.single_email:
		email_list = [opts.single_email]
	else:
		email_list_file = open(opts.input_path, 'r')
		email_list      = clean_list(email_list_file.readlines())

		email_list_file.close()

        results = []

        if opts.only_breaches:
		results.append(get_results(email_list, BREACHED, opts))
	elif opts.only_pastebins:
		results.append(get_results(email_list, PASTEBIN, opts))
	else:
		results.append(get_results(email_list, BREACHED, opts))
		results.append(get_results(email_list, PASTEBIN, opts))

	if opts.output_path:
		write_results_to_file(opts.output_path, results, opts)

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


<commit_before>import unittest
import collections
from decimal import Decimal
from money.money import Money, BABEL_AVAILABLE

class TestClass(unittest.TestCase):
    def test_new_instance_int_amount(self):
        self.assertIsInstance(Money(0, 'EUR'), Money)
        self.assertIsInstance(Money(12345, 'EUR'), Money)

    def test_new_instance_decimal_amount(self):
        self.assertIsInstance(Money(Decimal(12345), 'EUR'), Money)

    def test_new_instance_float_amount(self):
        self.assertIsInstance(Money(12345.12345, 'EUR'), Money)

    def test_new_instance_str_amount(self):
        self.assertIsInstance(Money('0', 'EUR'), Money)
        self.assertIsInstance(Money('12345.12345', 'EUR'), Money)

    def test_invalid_currency_none(self):
        with self.assertRaises(ValueError):
            money = Money('2.22', None)

    def test_invalid_currency_false(self):
        with self.assertRaises(ValueError):
            money = Money('2.22', False)

    def test_invalid_currency_empty(self):
        with self.assertRaises(ValueError):
            money = Money('2.22', '')

    def test_invalid_amount(self):
        with self.assertRaises(ValueError):
            money = Money('twenty', 'EUR')

    def test_not_hashable(self):
        money = Money('2.22', 'EUR')
        self.assertFalse(isinstance(money, collections.Hashable))

class TestMoneyRepresentations(unittest.TestCase):
    def test_repr(self):
        self.assertEqual(repr(Money('1234.567', 'EUR')), 'EUR 1234.567')

    def test_str(self):
        self.assertEqual(str(Money('1234.567', 'EUR')), 'EUR 1,234.57')

@unittest.skipUnless(BABEL_AVAILABLE, "requires Babel")
class TestMoneyFormatting(unittest.TestCase):
    def setUp(self):
        self.money = Money('-1234.567', 'USD')

    def test_custom_format_padding(self):
        self.assertEqual(self.money.format('en_US', '¤000000.00'), '-$001234.57')

    def test_custom_format_custom_negative(self):
        self.assertEqual(self.money.format('en_US', '¤#,##0.00;<¤#,##0.00>'), '<$1,234.57>')

    def test_custom_format_grouping(self):
        self.assertEqual(self.money.format('en_US', '¤#,##0.00'), '-$1,234.57')
        self.assertEqual(self.money.format('de_DE', '#,##0.00 ¤'), '-1.234,57 $')
        self.assertEqual(self.money.format('en_US', '¤0.00'), '-$1234.57')
        self.assertEqual(self.money.format('de_DE', '0.00 ¤'), '-1234,57 $')

    def test_custom_format_decimals(self):
        self.assertEqual(self.money.format('en_US', '¤0.000'), '-$1234.567')
        self.assertEqual(self.money.format('en_US', '¤0'), '-$1235')

    def test_auto_format_locales(self):
        self.assertEqual(self.money.format('en_US'), '($1,234.57)')
        self.assertEqual(self.money.format('de_DE'), '-1.234,57\xa0$')
        self.assertEqual(self.money.format('es_CO'), '-1.234,57\xa0US$')

    def test_auto_format_locales_alias(self):
        self.assertEqual(self.money.format('en'), self.money.format('en_US'))
        self.assertEqual(self.money.format('de'), self.money.format('de_DE'))

class TestMoneyParser(unittest.TestCase):
    def test_loads_valid(self):
        self.assertEqual(Money.loads('EUR 2.22'), Money('2.22', 'EUR'))

    def test_loads_missing_currency(self):
        with self.assertRaises(ValueError):
            money = Money.loads('2.22')

    def test_loads_reversed_order(self):
        with self.assertRaises(ValueError):
            money = Money.loads('2.22 EUR')

    def test_loads_empty(self):
        with self.assertRaises(ValueError):
            money = Money.loads('')

class TestNumericOperations(unittest.TestCase):
    def test_lt(self):
        self.assertTrue(Money('2.219', 'EUR') < Money('2.22', 'EUR'))
        self.assertTrue(Money('-2.22', 'EUR') < Money('2.22', 'EUR'))

    def test_lt_none(self):
        with self.assertRaises(TypeError):
            Money(0, 'EUR') < None

    def test_le(self):
        self.assertTrue(Money('2.219', 'EUR') <= Money('2.22', 'EUR'))
        self.assertTrue(Money('-2.22', 'EUR') <= Money('2.22', 'EUR'))
        self.assertTrue(Money('2.220', 'EUR') <= Money('2.22', 'EUR'))

    def test_le_none(self):
        with self.assertRaises(TypeError):
            Money(0, 'EUR') <= None

    def test_eq(self):
        self.assertTrue(Money('2.220', 'EUR') == Money('2.22', 'EUR'))

    def test_nq(self):
        self.assertTrue(Money('2.219', 'EUR') != Money('2.22', 'EUR'))

    def test_nq_none(self):
        self.assertNotEqual(Money(0, 'EUR'), None)

    def test_gt(self):
        self.assertTrue(Money('2.22', 'EUR') > Money('2.219', 'EUR'))
        self.assertTrue(Money('2.22', 'EUR') > Money('-2.22', 'EUR'))

    def test_gt_none(self):
        with self.assertRaises(TypeError):
            Money(0, 'EUR') > None

    def test_ge(self):
        self.assertTrue(Money('2.22', 'EUR') > Money('2.219', 'EUR'))
        self.assertTrue(Money('2.22', 'EUR') > Money('-2.22', 'EUR'))
        self.assertTrue(Money('2.220', 'EUR') == Money('2.22', 'EUR'))

    def test_ge_none(self):
        with self.assertRaises(TypeError):
            Money(0, 'EUR') >= None

    def test_bool(self):
        self.assertTrue(Money('2.22', 'EUR'))
        self.assertTrue(Money('0', 'EUR'))
        self.assertTrue(Money('-1', 'EUR'))

    def test_add(self):
        result = Money('2', 'EUR') + Money('2', 'EUR')
        self.assertEqual(result, Money('4', 'EUR'))

    def test_add_none(self):
        with self.assertRaises(TypeError):
            Money(0, 'EUR') + None

    def test_sub(self):
        result = Money('2', 'EUR') - Money('2', 'EUR')
        self.assertEqual(result, Money('0', 'EUR'))

    def test_sub_none(self):
        with self.assertRaises(TypeError):
            Money(0, 'EUR') - None

    def test_mul_number(self):
        result = Money('2', 'EUR') * 2
        self.assertEqual(result, Money('4', 'EUR'))

    def test_mul_money(self):
        with self.assertRaises(TypeError):
            Money('2', 'EUR') * Money('2', 'EUR')

    def test_mul_none(self):
        with self.assertRaises(TypeError):
            Money(0, 'EUR') * None

    def test_truediv_number(self):
        result = Money('2.22', 'EUR') / 2
        self.assertEqual(result, Money('1.11', 'EUR'))

    def test_truediv_money(self):
        result = Money('2', 'EUR') / Money('2', 'EUR')
        self.assertEqual(result, Decimal('1'))

    def test_truediv_none(self):
        with self.assertRaises(TypeError):
            Money(0, 'EUR') / None

    def test_floordiv_number(self):
        result = Money('2.22', 'EUR') // 2
        self.assertEqual(result, Money('1', 'EUR'))

    def test_floordiv_money(self):
        result = Money('2.22', 'EUR') // Money('2', 'EUR')
        self.assertEqual(result, Decimal('1'))

    def test_floordiv_none(self):
        with self.assertRaises(TypeError):
            Money(0, 'EUR') // None

    def test_mod_number(self):
        result = Money('2.22', 'EUR') % 2
        self.assertEqual(result, Money('0.22', 'EUR'))

    def test_mod_money(self):
        with self.assertRaises(TypeError):
            Money('2.22', 'EUR') % Money('2', 'EUR')

    def test_mod_none(self):
        with self.assertRaises(TypeError):
            Money(0, 'EUR') % None

    def test_divmod_number(self):
        whole, remainder = divmod(Money('2.22', 'EUR'), 2)
        self.assertEqual(whole, Money('1', 'EUR'))
        self.assertEqual(remainder, Money('0.22', 'EUR'))

    def test_divmod_money(self):
        whole, remainder = divmod(Money('2.22', 'EUR'), Money('2', 'EUR'))
        self.assertEqual(whole, Decimal('1'))
        self.assertEqual(remainder, Decimal('0.22'))

    def test_divmod_none(self):
        with self.assertRaises(TypeError):
            divmod(Money(0, 'EUR'), None)

    def test_pow_number(self):
        result = Money('3', 'EUR') ** 2
        self.assertEqual(result, Money('9', 'EUR'))

    def test_pow_money(self):
        with self.assertRaises(TypeError):
            Money('3', 'EUR') ** Money('2', 'EUR')

    def test_pow_none(self):
        with self.assertRaises(TypeError):
            Money(0, 'EUR') ** None

    def test_neg(self):
        result = -Money('2.22', 'EUR')
        self.assertEqual(result, Money('-2.22', 'EUR'))

    def test_pos(self):
        result = +Money('2.22', 'EUR')
        self.assertEqual(result, Money('2.22', 'EUR'))

    def test_abs(self):
        result = abs(Money('-2.22', 'EUR'))
        self.assertEqual(result, Money('2.22', 'EUR'))

    def test_int(self):
        self.assertEqual(int(Money('-2.22', 'EUR')), -2)
        self.assertEqual(int(Money('2.22', 'EUR')), 2)

    def test_float(self):
        self.assertEqual(float(Money('-2.22', 'EUR')), -2.22)
        self.assertEqual(float(Money('2.22', 'EUR')), 2.22)

    def test_round(self):
        self.assertEqual(round(Money('-1.49', 'EUR')), Money('-1', 'EUR'))
        self.assertEqual(round(Money('1.50', 'EUR')), Money('2', 'EUR'))
        self.assertEqual(round(Money('1.234', 'EUR'), 2), Money('1.23', 'EUR'))

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

<commit_msg>Add tests for numeric operations against numbers<commit_after>import unittest
import collections
from decimal import Decimal
from money.money import Money, BABEL_AVAILABLE

class TestClass(unittest.TestCase):
    def test_new_instance_int_amount(self):
        self.assertIsInstance(Money(0, 'EUR'), Money)
        self.assertIsInstance(Money(12345, 'EUR'), Money)

    def test_new_instance_decimal_amount(self):
        self.assertIsInstance(Money(Decimal(12345), 'EUR'), Money)

    def test_new_instance_float_amount(self):
        self.assertIsInstance(Money(12345.12345, 'EUR'), Money)

    def test_new_instance_str_amount(self):
        self.assertIsInstance(Money('0', 'EUR'), Money)
        self.assertIsInstance(Money('12345.12345', 'EUR'), Money)

    def test_invalid_currency_none(self):
        with self.assertRaises(ValueError):
            money = Money('2.22', None)

    def test_invalid_currency_false(self):
        with self.assertRaises(ValueError):
            money = Money('2.22', False)

    def test_invalid_currency_empty(self):
        with self.assertRaises(ValueError):
            money = Money('2.22', '')

    def test_invalid_amount(self):
        with self.assertRaises(ValueError):
            money = Money('twenty', 'EUR')

    def test_not_hashable(self):
        money = Money('2.22', 'EUR')
        self.assertFalse(isinstance(money, collections.Hashable))

class TestMoneyRepresentations(unittest.TestCase):
    def test_repr(self):
        self.assertEqual(repr(Money('1234.567', 'EUR')), 'EUR 1234.567')

    def test_str(self):
        self.assertEqual(str(Money('1234.567', 'EUR')), 'EUR 1,234.57')

@unittest.skipUnless(BABEL_AVAILABLE, "requires Babel")
class TestMoneyFormatting(unittest.TestCase):
    def setUp(self):
        self.money = Money('-1234.567', 'USD')

    def test_custom_format_padding(self):
        self.assertEqual(self.money.format('en_US', '¤000000.00'), '-$001234.57')

    def test_custom_format_custom_negative(self):
        self.assertEqual(self.money.format('en_US', '¤#,##0.00;<¤#,##0.00>'), '<$1,234.57>')

    def test_custom_format_grouping(self):
        self.assertEqual(self.money.format('en_US', '¤#,##0.00'), '-$1,234.57')
        self.assertEqual(self.money.format('de_DE', '#,##0.00 ¤'), '-1.234,57 $')
        self.assertEqual(self.money.format('en_US', '¤0.00'), '-$1234.57')
        self.assertEqual(self.money.format('de_DE', '0.00 ¤'), '-1234,57 $')

    def test_custom_format_decimals(self):
        self.assertEqual(self.money.format('en_US', '¤0.000'), '-$1234.567')
        self.assertEqual(self.money.format('en_US', '¤0'), '-$1235')

    def test_auto_format_locales(self):
        self.assertEqual(self.money.format('en_US'), '($1,234.57)')
        self.assertEqual(self.money.format('de_DE'), '-1.234,57\xa0$')
        self.assertEqual(self.money.format('es_CO'), '-1.234,57\xa0US$')

    def test_auto_format_locales_alias(self):
        self.assertEqual(self.money.format('en'), self.money.format('en_US'))
        self.assertEqual(self.money.format('de'), self.money.format('de_DE'))

class TestMoneyParser(unittest.TestCase):
    def test_loads_valid(self):
        self.assertEqual(Money.loads('EUR 2.22'), Money('2.22', 'EUR'))

    def test_loads_missing_currency(self):
        with self.assertRaises(ValueError):
            money = Money.loads('2.22')

    def test_loads_reversed_order(self):
        with self.assertRaises(ValueError):
            money = Money.loads('2.22 EUR')

    def test_loads_empty(self):
        with self.assertRaises(ValueError):
            money = Money.loads('')

class TestNumericOperations(unittest.TestCase):
    def test_lt_number(self):
        self.assertTrue(Money('2.22', 'EUR') < 3)
        self.assertTrue(Money('2.22', 'EUR') < 3.0)
        self.assertTrue(Money('2.22', 'EUR') < Decimal(3))

    def test_lt_money(self):
        self.assertTrue(Money('2.219', 'EUR') < Money('2.22', 'EUR'))
        self.assertTrue(Money('-2.22', 'EUR') < Money('2.22', 'EUR'))

    def test_lt_none(self):
        with self.assertRaises(TypeError):
            Money(0, 'EUR') < None

    def test_le_number(self):
        self.assertTrue(Money('2.219', 'EUR') <= 3)
        self.assertTrue(Money('2.219', 'EUR') <= 3.0)
        self.assertTrue(Money('-2.22', 'EUR') <= Decimal('3'))

    def test_le_money(self):
        self.assertTrue(Money('2.219', 'EUR') <= Money('2.22', 'EUR'))
        self.assertTrue(Money('-2.22', 'EUR') <= Money('2.22', 'EUR'))
        self.assertTrue(Money('2.220', 'EUR') <= Money('2.22', 'EUR'))

    def test_le_none(self):
        with self.assertRaises(TypeError):
            Money(0, 'EUR') <= None

    def test_eq_number(self):
        self.assertTrue(Money('2', 'EUR') == 2)
        self.assertTrue(Money('2', 'EUR') == Decimal(2))

    def test_eq_money(self):
        self.assertTrue(Money('2.220', 'EUR') == Money('2.22', 'EUR'))

    def test_nq_number(self):
        self.assertTrue(Money('2.219', 'EUR') != 3)
        self.assertTrue(Money('2.219', 'EUR') != Decimal('2.22'))

    def test_nq_money(self):
        self.assertTrue(Money('2.219', 'EUR') != Money('2.22', 'EUR'))

    def test_nq_none(self):
        self.assertNotEqual(Money(0, 'EUR'), None)

    def test_gt_number(self):
        self.assertTrue(Money('2.22', 'EUR') > 2)
        self.assertTrue(Money('2.22', 'EUR') > Decimal('2'))

    def test_gt_money(self):
        self.assertTrue(Money('2.22', 'EUR') > Money('2.219', 'EUR'))
        self.assertTrue(Money('2.22', 'EUR') > Money('-2.22', 'EUR'))

    def test_gt_none(self):
        with self.assertRaises(TypeError):
            Money(0, 'EUR') > None

    def test_ge_number(self):
        self.assertTrue(Money('2', 'EUR') >= 1)
        self.assertTrue(Money('2', 'EUR') >= 2)
        self.assertTrue(Money('2', 'EUR') >= Decimal('1'))
        self.assertTrue(Money('2', 'EUR') >= Decimal('2'))

    def test_ge_money(self):
        self.assertTrue(Money('2.22', 'EUR') > Money('2.219', 'EUR'))
        self.assertTrue(Money('2.22', 'EUR') > Money('-2.22', 'EUR'))
        self.assertTrue(Money('2.220', 'EUR') == Money('2.22', 'EUR'))

    def test_ge_none(self):
        with self.assertRaises(TypeError):
            Money(0, 'EUR') >= None

    def test_bool(self):
        self.assertTrue(Money('2.22', 'EUR'))
        self.assertTrue(Money('0', 'EUR'))
        self.assertTrue(Money('-1', 'EUR'))

    def test_add_number(self):
        result = Money('2', 'EUR') + 2
        self.assertEqual(result, Money('4', 'EUR'))
        result = Money('2', 'EUR') + Decimal('2')
        self.assertEqual(result, Money('4', 'EUR'))

    def test_add_money(self):
        result = Money('2', 'EUR') + Money('2', 'EUR')
        self.assertEqual(result, Money('4', 'EUR'))

    def test_add_none(self):
        with self.assertRaises(TypeError):
            Money(0, 'EUR') + None

    def test_sub_number(self):
        result = Money('2', 'EUR') - 2
        self.assertEqual(result, Money('0', 'EUR'))
        result = Money('2', 'EUR') - Decimal(2)
        self.assertEqual(result, Money('0', 'EUR'))

    def test_sub_money(self):
        result = Money('2', 'EUR') - Money('2', 'EUR')
        self.assertEqual(result, Money('0', 'EUR'))

    def test_sub_none(self):
        with self.assertRaises(TypeError):
            Money(0, 'EUR') - None

    def test_mul_number(self):
        result = Money('2', 'EUR') * 2
        self.assertEqual(result, Money('4', 'EUR'))

    def test_mul_money(self):
        with self.assertRaises(TypeError):
            Money('2', 'EUR') * Money('2', 'EUR')

    def test_mul_none(self):
        with self.assertRaises(TypeError):
            Money(0, 'EUR') * None

    def test_truediv_number(self):
        result = Money('2.22', 'EUR') / 2
        self.assertEqual(result, Money('1.11', 'EUR'))

    def test_truediv_money(self):
        result = Money('2', 'EUR') / Money('2', 'EUR')
        self.assertEqual(result, Decimal('1'))

    def test_truediv_none(self):
        with self.assertRaises(TypeError):
            Money(0, 'EUR') / None

    def test_floordiv_number(self):
        result = Money('2.22', 'EUR') // 2
        self.assertEqual(result, Money('1', 'EUR'))

    def test_floordiv_money(self):
        result = Money('2.22', 'EUR') // Money('2', 'EUR')
        self.assertEqual(result, Decimal('1'))

    def test_floordiv_none(self):
        with self.assertRaises(TypeError):
            Money(0, 'EUR') // None

    def test_mod_number(self):
        result = Money('2.22', 'EUR') % 2
        self.assertEqual(result, Money('0.22', 'EUR'))

    def test_mod_money(self):
        with self.assertRaises(TypeError):
            Money('2.22', 'EUR') % Money('2', 'EUR')

    def test_mod_none(self):
        with self.assertRaises(TypeError):
            Money(0, 'EUR') % None

    def test_divmod_number(self):
        whole, remainder = divmod(Money('2.22', 'EUR'), 2)
        self.assertEqual(whole, Money('1', 'EUR'))
        self.assertEqual(remainder, Money('0.22', 'EUR'))

    def test_divmod_money(self):
        whole, remainder = divmod(Money('2.22', 'EUR'), Money('2', 'EUR'))
        self.assertEqual(whole, Decimal('1'))
        self.assertEqual(remainder, Decimal('0.22'))

    def test_divmod_none(self):
        with self.assertRaises(TypeError):
            divmod(Money(0, 'EUR'), None)

    def test_pow_number(self):
        result = Money('3', 'EUR') ** 2
        self.assertEqual(result, Money('9', 'EUR'))

    def test_pow_money(self):
        with self.assertRaises(TypeError):
            Money('3', 'EUR') ** Money('2', 'EUR')

    def test_pow_none(self):
        with self.assertRaises(TypeError):
            Money(0, 'EUR') ** None

    def test_neg(self):
        result = -Money('2.22', 'EUR')
        self.assertEqual(result, Money('-2.22', 'EUR'))

    def test_pos(self):
        result = +Money('2.22', 'EUR')
        self.assertEqual(result, Money('2.22', 'EUR'))

    def test_abs(self):
        result = abs(Money('-2.22', 'EUR'))
        self.assertEqual(result, Money('2.22', 'EUR'))

    def test_int(self):
        self.assertEqual(int(Money('-2.22', 'EUR')), -2)
        self.assertEqual(int(Money('2.22', 'EUR')), 2)

    def test_float(self):
        self.assertEqual(float(Money('-2.22', 'EUR')), -2.22)
        self.assertEqual(float(Money('2.22', 'EUR')), 2.22)

    def test_round(self):
        self.assertEqual(round(Money('-1.49', 'EUR')), Money('-1', 'EUR'))
        self.assertEqual(round(Money('1.50', 'EUR')), Money('2', 'EUR'))
        self.assertEqual(round(Money('1.234', 'EUR'), 2), Money('1.23', 'EUR'))

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

<|endoftext|>


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

import unittest
from os import path

from eulcore.xmlmap  import load_xmlobject_from_file, load_xmlobject_from_string
#from eulcore.xmlmap.eadmap import EncodedArchivalDescription, ArchivalDescription, ControlledAccessHeadings, Section, Heading, SubordinateComponents, Component
from eulcore.xmlmap.eadmap import *
from testcore import main

class TestEad(unittest.TestCase):
    FIXTURE_FILE = path.join(path.dirname(path.abspath(__file__)) ,
                             'fixtures', 'heaney653.xml')
    def setUp(self):
        self.ead = load_xmlobject_from_file(self.FIXTURE_FILE, EncodedArchivalDescription)

    def testInit(self):
        self.assert_(isinstance(self.ead, EncodedArchivalDescription))

    def testBasicFields(self):
        self.assertEqual(unicode(self.ead.title), "Seamus Heaney collection, 1972-1997")
        self.assertEqual(unicode(self.ead.eadid), u'heaney653')
        self.assertEqual(self.ead.id, "heaney653-011")
        self.assertEqual(self.ead.author, "Manuscript, Archives, and Rare Book Library, Emory University")
        # whitespace makes fields with tags a bit messier...
        self.assert_("Seamus Heaney collection," in unicode(self.ead.unittitle))
        self.assert_("1972-2005" in unicode(self.ead.unittitle))
        # several different extents in the physical description;
        # FIXME: all smashed together
        self.assert_("1 linear ft." in self.ead.physical_desc)
        self.assert_("(3 boxes)" in self.ead.physical_desc)
        self.assert_("12 oversized papers (OP)" in self.ead.physical_desc)
        self.assert_("materials relating to Irish poet Seamus Heaney" in unicode(self.ead.abstract))

    def test_eadid(self):
        self.assert_(isinstance(self.ead.eadid, EadId))
        eadid = self.ead.eadid
        self.assertEqual('heaney653', eadid.eadid)
        self.assertEqual('heaney653.xml', eadid.identifier)
        self.assertEqual('us', eadid.country)
        self.assertEqual('geu-s', eadid.maintenance_agency)
        self.assertEqual('http://some.pid.org/ark:/1234/567', eadid.url)

    def test_ArchivalDescription(self):
        self.assert_(isinstance(self.ead.archdesc, ArchivalDescription))
        ad = self.ead.archdesc
        self.assertEqual("Heaney, Seamus, 1939-", ad.origination)
        self.assertEqual("Manuscript Collection No.653", ad.unitid)
        self.assertEqual("Manuscript Collection No.653", ad.unitid)
        self.assertEqual("1 linear ft.", ad.extent[0])
        self.assertEqual("(3 boxes)", ad.extent[1])
        self.assertEqual("12 oversized papers (OP)", ad.extent[2])
        self.assertEqual("Materials entirely in English.", ad.langmaterial)
        self.assertEqual("In the Archives.", ad.location)
        self.assert_(isinstance(ad.access_restriction, Section))
        self.assertEqual("Restrictions on access", ad.access_restriction.head)
        self.assert_("Special restrictions apply" in unicode(ad.access_restriction.content[0]))
        self.assert_(isinstance(ad.use_restriction, Section))
        self.assertEqual("Terms Governing Use and Reproduction", ad.use_restriction.head)
        self.assert_("limitations noted in departmental policies" in unicode(ad.use_restriction.content[0]))
        self.assert_(isinstance(ad.alternate_form, Section))
        self.assertEqual("Publication Note", ad.alternate_form.head)
        self.assert_("Published in" in unicode(ad.alternate_form.content[0]))
        self.assert_(isinstance(ad.originals_location, Section))
        self.assertEqual("Location of Originals", ad.originals_location.head)
        self.assert_("Suppressed chapter" in unicode(ad.originals_location.content[0]))
        self.assert_(isinstance(ad.related_material, Section))
        self.assertEqual("Related Materials in This Repository", ad.related_material.head)
        self.assert_("part of MSS" in unicode(ad.related_material.content[0]))
        self.assert_(isinstance(ad.separated_material, Section))
        self.assertEqual("Related Materials in This Repository", ad.separated_material.head)
        self.assert_("Ciaran Carson papers, Peter Fallon" in unicode(ad.separated_material.content[0]))
        self.assert_(isinstance(ad.acquisition_info, Section))
        self.assertEqual("Source", ad.acquisition_info.head)
        self.assert_("Collection assembled from various sources." in unicode(ad.acquisition_info.content[0]))
        self.assert_(isinstance(ad.custodial_history, Section))
        self.assertEqual("Custodial History", ad.custodial_history.head)
        self.assert_("Originally received as part of" in unicode(ad.custodial_history.content[0]))
        self.assert_(isinstance(ad.preferred_citation, Section))
        self.assertEqual("Citation", ad.preferred_citation.head)
        self.assert_("[after identification of item(s)" in unicode(ad.preferred_citation.content[0]))
        self.assert_(isinstance(ad.biography_history, Section))
        self.assertEqual("Biographical Note", ad.biography_history.head)
        self.assert_("born on April 13" in unicode(ad.biography_history.content[0]))
        self.assert_("While at St. Joseph's" in unicode(ad.biography_history.content[1]))
        self.assert_(isinstance(ad.bibliography, Section))
        self.assertEqual("Publication Note", ad.bibliography.head)
        self.assert_("Susan Jenkins Brown" in unicode(ad.bibliography.content[0]))
        self.assert_(isinstance(ad.scope_content, Section))
        self.assertEqual("Scope and Content Note", ad.scope_content.head)
        self.assert_("consists of materials relating" in unicode(ad.scope_content.content[0]))
        self.assert_(isinstance(ad.arrangement, Section))
        self.assertEqual("Arrangement Note", ad.arrangement.head)
        self.assert_("five series" in unicode(ad.arrangement.content[0]))
        self.assert_(isinstance(ad.other, Section))
        self.assertEqual("Finding Aid Note", ad.other.head)
        self.assert_("Index to selected correspondents" in unicode(ad.other.content[0]))

    def test_index_indexentry(self):
        ad = self.ead.archdesc
        # index and indexentry
        self.assertEqual(2, len(ad.index))
        index = ad.index[0]
        self.assert_(isinstance(index, Index))
        self.assertEqual("Index of Selected Correspondents", index.head)
        self.assertEqual("index1", index.id)
        self.assert_("relates to the correspondence in Series 1" in index.note.content[0])
        self.assertEqual(2, len(index.entry))
        self.assert_(isinstance(index.entry[0], IndexEntry))
        self.assertEqual("Batten, Guinn", index.entry[0].name)
        self.assert_(isinstance(index.entry[0].ptrgroup, PointerGroup))
        self.assertEqual(3, len(index.entry[0].ptrgroup.ref))
        self.assert_(isinstance(index.entry[0].ptrgroup.ref[0], Reference))
        self.assertEqual("simple", index.entry[0].ptrgroup.ref[0].type)
        self.assert_("1995 July" in index.entry[0].ptrgroup.ref[0].value)
        self.assertEqual("Belton, Neil", index.entry[1].name)
        self.assert_("1993 November 3" in index.entry[1].ptrgroup.ref[-1].value)

        # multiple indexes
        self.assert_(isinstance(ad.index[1], Index))
        self.assertEqual("Second Index", ad.index[1].head)
        self.assertEqual("index2", ad.index[1].id)

    def test_ControlledAccessHeadings(self):
        ca = self.ead.archdesc.controlaccess
        self.assert_(isinstance(ca, ControlledAccessHeadings))
        self.assertEqual("Selected Search Terms", ca.head)
        self.assert_(isinstance(ca.controlaccess[0], ControlledAccessHeadings))
        self.assertEqual("Personal Names", ca.controlaccess[0].head)
        self.assert_(isinstance(ca.controlaccess[0].person_name[0], Heading))
        self.assertEqual("Barker, Sebastian.", ca.controlaccess[0].person_name[0].value)
        self.assert_(isinstance(ca.controlaccess[0].family_name[0], Heading))
        self.assertEqual("Dozier family.", ca.controlaccess[0].family_name[0].value)
        self.assertEqual("English poetry--Irish authors--20th century.", ca.controlaccess[1].subject[0].value)
        self.assertEqual("Ireland.", ca.controlaccess[2].geographic_name[0].value)
        self.assertEqual("Manuscripts.", ca.controlaccess[3].genre_form[0].value)
        self.assertEqual("Poet.", ca.controlaccess[4].occupation[0].value)
        self.assert_(isinstance(ca.controlaccess[5].corporate_name[0], Heading))
        self.assertEqual("Irish Academy of Letters", ca.controlaccess[5].corporate_name[0].value)
        self.assert_(isinstance(ca.controlaccess[6].function[0], Heading))
        self.assertEqual("Law enforcing.", ca.controlaccess[6].function[0].value)
        self.assert_(isinstance(ca.controlaccess[7].title[0], Heading))
        self.assertEqual("New Yorker (New York, 1925-)", ca.controlaccess[7].title[0].value)

        # terms -  mapps to all types, mixed, in the order they appear
        all_terms = ca.controlaccess[8].terms
        self.assertEqual("title", all_terms[0].value)
        self.assertEqual("person", all_terms[1].value)
        self.assertEqual("family", all_terms[2].value)
        self.assertEqual("corp", all_terms[3].value)
        self.assertEqual("occupation", all_terms[4].value)
        self.assertEqual("subject", all_terms[5].value)
        self.assertEqual("geography", all_terms[6].value)
        self.assertEqual("genre", all_terms[7].value)
        self.assertEqual("function", all_terms[8].value)

    def test_SubordinateComponents(self):
        dsc = self.ead.dsc
        self.assert_(isinstance(dsc, SubordinateComponents))
        self.assertEqual("combined", dsc.type)
        self.assertEqual("Description of Series", dsc.head)
        # c01 - series
        self.assert_(isinstance(dsc.c[0], Component))
        self.assertEqual("series", dsc.c[0].level)
        self.assert_(isinstance(dsc.c[0].did, DescriptiveIdentification))
        self.assertEqual("Series 1", dsc.c[0].did.unitid)
        self.assertEqual("Writings by Seamus Heaney", unicode(dsc.c[0].did.unittitle))
        self.assertEqual("Box 1: folders 1-12", dsc.c[0].did.physdesc)
        # c02 - file
        self.assert_(isinstance(dsc.c[0].c[0], Component))
        self.assertEqual("file", dsc.c[0].c[0].level)
        self.assert_(isinstance(dsc.c[0].c[0].did, DescriptiveIdentification))
        self.assert_("holograph manuscript" in unicode(dsc.c[0].c[0].did.unittitle))
        self.assertEqual("box", dsc.c[0].c[0].did.container[0].type)
        self.assertEqual("1", dsc.c[0].c[0].did.container[0].value)
        self.assertEqual("folder", dsc.c[0].c[0].did.container[1].type)
        self.assertEqual("1", dsc.c[0].c[0].did.container[1].value)

        self.assertTrue(dsc.hasSeries())
        self.assertFalse(dsc.c[0].hasSubseries())

        # second series has a subseries
        self.assertTrue(dsc.c[1].hasSubseries())
        # access c03 level item
        self.assertEqual("file", dsc.c[1].c[0].c[0].level)
        self.assert_("Hilary Boyle" in unicode(dsc.c[1].c[0].c[0].did.unittitle))

    def test_SubordinateComponents_noseries(self):
        # simple finding aid with no series but only a container list
        simple_dsc = """<dsc><c01 level="file"/></dsc>"""
        dsc = load_xmlobject_from_string(simple_dsc, SubordinateComponents)
        self.assertFalse(dsc.hasSeries())

    def test_FileDescription(self):
        filedesc = self.ead.file_desc
        self.assert_(isinstance(filedesc, FileDescription))
        self.assert_(isinstance(filedesc.publication, PublicationStatement))
        self.assert_(isinstance(filedesc.publication.address, Address))
        self.assert_(isinstance(filedesc.publication.date, DateField))
        self.assertEqual("Emory University", filedesc.publication.publisher)
        self.assertEqual("Robert W. Woodruff Library", filedesc.publication.address.lines[0])
        self.assertEqual("404-727-6887", filedesc.publication.address.lines[3])
        self.assertEqual("marbl@emory.edu", filedesc.publication.address.lines[-1])

    def test_ProfileDescription(self):
        profiledesc = self.ead.profiledesc
        self.assert_(isinstance(profiledesc, ProfileDescription))
        self.assertEqual("English", profiledesc.languages[0])
        self.assertEqual("eng", profiledesc.language_codes[0])
        # profile creation date
        self.assert_(isinstance(profiledesc.date, DateField))
        self.assertEqual(u'May 5, 2005', unicode(profiledesc.date))
        self.assertEqual('2005-05-05', profiledesc.date.normalized)

    def test_DateField(self):
        date = self.ead.file_desc.publication.date
        self.assert_(isinstance(date, DateField))
        self.assertEqual("2005-05-05", date.normalized)
        self.assertEqual("May 5, 2005", unicode(date))
        self.assertEqual("ce", date.era)
        self.assertEqual("gregorian", date.calendar)

        unitdate = self.ead.dsc.c[1].c[0].did.unitdate
        self.assert_(isinstance(unitdate, DateField))
        self.assertEqual("1974/1986", unitdate.normalized)

if __name__ == '__main__':
    main()
<commit_msg>correct eadid test for xmlobject change<commit_after>#!/usr/bin/env python

import unittest
from os import path

from eulcore.xmlmap  import load_xmlobject_from_file, load_xmlobject_from_string
#from eulcore.xmlmap.eadmap import EncodedArchivalDescription, ArchivalDescription, ControlledAccessHeadings, Section, Heading, SubordinateComponents, Component
from eulcore.xmlmap.eadmap import *
from testcore import main

class TestEad(unittest.TestCase):
    FIXTURE_FILE = path.join(path.dirname(path.abspath(__file__)) ,
                             'fixtures', 'heaney653.xml')
    def setUp(self):
        self.ead = load_xmlobject_from_file(self.FIXTURE_FILE, EncodedArchivalDescription)

    def testInit(self):
        self.assert_(isinstance(self.ead, EncodedArchivalDescription))

    def testBasicFields(self):
        self.assertEqual(unicode(self.ead.title), "Seamus Heaney collection, 1972-1997")
        self.assertEqual(unicode(self.ead.eadid), u'heaney653')
        self.assertEqual(self.ead.id, "heaney653-011")
        self.assertEqual(self.ead.author, "Manuscript, Archives, and Rare Book Library, Emory University")
        # whitespace makes fields with tags a bit messier...
        self.assert_("Seamus Heaney collection," in unicode(self.ead.unittitle))
        self.assert_("1972-2005" in unicode(self.ead.unittitle))
        # several different extents in the physical description;
        # FIXME: all smashed together
        self.assert_("1 linear ft." in self.ead.physical_desc)
        self.assert_("(3 boxes)" in self.ead.physical_desc)
        self.assert_("12 oversized papers (OP)" in self.ead.physical_desc)
        self.assert_("materials relating to Irish poet Seamus Heaney" in unicode(self.ead.abstract))

    def test_eadid(self):
        self.assert_(isinstance(self.ead.eadid, EadId))
        eadid = self.ead.eadid
        self.assertEqual('heaney653', eadid.value)
        self.assertEqual('heaney653.xml', eadid.identifier)
        self.assertEqual('us', eadid.country)
        self.assertEqual('geu-s', eadid.maintenance_agency)
        self.assertEqual('http://some.pid.org/ark:/1234/567', eadid.url)

    def test_ArchivalDescription(self):
        self.assert_(isinstance(self.ead.archdesc, ArchivalDescription))
        ad = self.ead.archdesc
        self.assertEqual("Heaney, Seamus, 1939-", ad.origination)
        self.assertEqual("Manuscript Collection No.653", ad.unitid)
        self.assertEqual("Manuscript Collection No.653", ad.unitid)
        self.assertEqual("1 linear ft.", ad.extent[0])
        self.assertEqual("(3 boxes)", ad.extent[1])
        self.assertEqual("12 oversized papers (OP)", ad.extent[2])
        self.assertEqual("Materials entirely in English.", ad.langmaterial)
        self.assertEqual("In the Archives.", ad.location)
        self.assert_(isinstance(ad.access_restriction, Section))
        self.assertEqual("Restrictions on access", ad.access_restriction.head)
        self.assert_("Special restrictions apply" in unicode(ad.access_restriction.content[0]))
        self.assert_(isinstance(ad.use_restriction, Section))
        self.assertEqual("Terms Governing Use and Reproduction", ad.use_restriction.head)
        self.assert_("limitations noted in departmental policies" in unicode(ad.use_restriction.content[0]))
        self.assert_(isinstance(ad.alternate_form, Section))
        self.assertEqual("Publication Note", ad.alternate_form.head)
        self.assert_("Published in" in unicode(ad.alternate_form.content[0]))
        self.assert_(isinstance(ad.originals_location, Section))
        self.assertEqual("Location of Originals", ad.originals_location.head)
        self.assert_("Suppressed chapter" in unicode(ad.originals_location.content[0]))
        self.assert_(isinstance(ad.related_material, Section))
        self.assertEqual("Related Materials in This Repository", ad.related_material.head)
        self.assert_("part of MSS" in unicode(ad.related_material.content[0]))
        self.assert_(isinstance(ad.separated_material, Section))
        self.assertEqual("Related Materials in This Repository", ad.separated_material.head)
        self.assert_("Ciaran Carson papers, Peter Fallon" in unicode(ad.separated_material.content[0]))
        self.assert_(isinstance(ad.acquisition_info, Section))
        self.assertEqual("Source", ad.acquisition_info.head)
        self.assert_("Collection assembled from various sources." in unicode(ad.acquisition_info.content[0]))
        self.assert_(isinstance(ad.custodial_history, Section))
        self.assertEqual("Custodial History", ad.custodial_history.head)
        self.assert_("Originally received as part of" in unicode(ad.custodial_history.content[0]))
        self.assert_(isinstance(ad.preferred_citation, Section))
        self.assertEqual("Citation", ad.preferred_citation.head)
        self.assert_("[after identification of item(s)" in unicode(ad.preferred_citation.content[0]))
        self.assert_(isinstance(ad.biography_history, Section))
        self.assertEqual("Biographical Note", ad.biography_history.head)
        self.assert_("born on April 13" in unicode(ad.biography_history.content[0]))
        self.assert_("While at St. Joseph's" in unicode(ad.biography_history.content[1]))
        self.assert_(isinstance(ad.bibliography, Section))
        self.assertEqual("Publication Note", ad.bibliography.head)
        self.assert_("Susan Jenkins Brown" in unicode(ad.bibliography.content[0]))
        self.assert_(isinstance(ad.scope_content, Section))
        self.assertEqual("Scope and Content Note", ad.scope_content.head)
        self.assert_("consists of materials relating" in unicode(ad.scope_content.content[0]))
        self.assert_(isinstance(ad.arrangement, Section))
        self.assertEqual("Arrangement Note", ad.arrangement.head)
        self.assert_("five series" in unicode(ad.arrangement.content[0]))
        self.assert_(isinstance(ad.other, Section))
        self.assertEqual("Finding Aid Note", ad.other.head)
        self.assert_("Index to selected correspondents" in unicode(ad.other.content[0]))

    def test_index_indexentry(self):
        ad = self.ead.archdesc
        # index and indexentry
        self.assertEqual(2, len(ad.index))
        index = ad.index[0]
        self.assert_(isinstance(index, Index))
        self.assertEqual("Index of Selected Correspondents", index.head)
        self.assertEqual("index1", index.id)
        self.assert_("relates to the correspondence in Series 1" in index.note.content[0])
        self.assertEqual(2, len(index.entry))
        self.assert_(isinstance(index.entry[0], IndexEntry))
        self.assertEqual("Batten, Guinn", index.entry[0].name)
        self.assert_(isinstance(index.entry[0].ptrgroup, PointerGroup))
        self.assertEqual(3, len(index.entry[0].ptrgroup.ref))
        self.assert_(isinstance(index.entry[0].ptrgroup.ref[0], Reference))
        self.assertEqual("simple", index.entry[0].ptrgroup.ref[0].type)
        self.assert_("1995 July" in index.entry[0].ptrgroup.ref[0].value)
        self.assertEqual("Belton, Neil", index.entry[1].name)
        self.assert_("1993 November 3" in index.entry[1].ptrgroup.ref[-1].value)

        # multiple indexes
        self.assert_(isinstance(ad.index[1], Index))
        self.assertEqual("Second Index", ad.index[1].head)
        self.assertEqual("index2", ad.index[1].id)

    def test_ControlledAccessHeadings(self):
        ca = self.ead.archdesc.controlaccess
        self.assert_(isinstance(ca, ControlledAccessHeadings))
        self.assertEqual("Selected Search Terms", ca.head)
        self.assert_(isinstance(ca.controlaccess[0], ControlledAccessHeadings))
        self.assertEqual("Personal Names", ca.controlaccess[0].head)
        self.assert_(isinstance(ca.controlaccess[0].person_name[0], Heading))
        self.assertEqual("Barker, Sebastian.", ca.controlaccess[0].person_name[0].value)
        self.assert_(isinstance(ca.controlaccess[0].family_name[0], Heading))
        self.assertEqual("Dozier family.", ca.controlaccess[0].family_name[0].value)
        self.assertEqual("English poetry--Irish authors--20th century.", ca.controlaccess[1].subject[0].value)
        self.assertEqual("Ireland.", ca.controlaccess[2].geographic_name[0].value)
        self.assertEqual("Manuscripts.", ca.controlaccess[3].genre_form[0].value)
        self.assertEqual("Poet.", ca.controlaccess[4].occupation[0].value)
        self.assert_(isinstance(ca.controlaccess[5].corporate_name[0], Heading))
        self.assertEqual("Irish Academy of Letters", ca.controlaccess[5].corporate_name[0].value)
        self.assert_(isinstance(ca.controlaccess[6].function[0], Heading))
        self.assertEqual("Law enforcing.", ca.controlaccess[6].function[0].value)
        self.assert_(isinstance(ca.controlaccess[7].title[0], Heading))
        self.assertEqual("New Yorker (New York, 1925-)", ca.controlaccess[7].title[0].value)

        # terms -  mapps to all types, mixed, in the order they appear
        all_terms = ca.controlaccess[8].terms
        self.assertEqual("title", all_terms[0].value)
        self.assertEqual("person", all_terms[1].value)
        self.assertEqual("family", all_terms[2].value)
        self.assertEqual("corp", all_terms[3].value)
        self.assertEqual("occupation", all_terms[4].value)
        self.assertEqual("subject", all_terms[5].value)
        self.assertEqual("geography", all_terms[6].value)
        self.assertEqual("genre", all_terms[7].value)
        self.assertEqual("function", all_terms[8].value)

    def test_SubordinateComponents(self):
        dsc = self.ead.dsc
        self.assert_(isinstance(dsc, SubordinateComponents))
        self.assertEqual("combined", dsc.type)
        self.assertEqual("Description of Series", dsc.head)
        # c01 - series
        self.assert_(isinstance(dsc.c[0], Component))
        self.assertEqual("series", dsc.c[0].level)
        self.assert_(isinstance(dsc.c[0].did, DescriptiveIdentification))
        self.assertEqual("Series 1", dsc.c[0].did.unitid)
        self.assertEqual("Writings by Seamus Heaney", unicode(dsc.c[0].did.unittitle))
        self.assertEqual("Box 1: folders 1-12", dsc.c[0].did.physdesc)
        # c02 - file
        self.assert_(isinstance(dsc.c[0].c[0], Component))
        self.assertEqual("file", dsc.c[0].c[0].level)
        self.assert_(isinstance(dsc.c[0].c[0].did, DescriptiveIdentification))
        self.assert_("holograph manuscript" in unicode(dsc.c[0].c[0].did.unittitle))
        self.assertEqual("box", dsc.c[0].c[0].did.container[0].type)
        self.assertEqual("1", dsc.c[0].c[0].did.container[0].value)
        self.assertEqual("folder", dsc.c[0].c[0].did.container[1].type)
        self.assertEqual("1", dsc.c[0].c[0].did.container[1].value)

        self.assertTrue(dsc.hasSeries())
        self.assertFalse(dsc.c[0].hasSubseries())

        # second series has a subseries
        self.assertTrue(dsc.c[1].hasSubseries())
        # access c03 level item
        self.assertEqual("file", dsc.c[1].c[0].c[0].level)
        self.assert_("Hilary Boyle" in unicode(dsc.c[1].c[0].c[0].did.unittitle))

    def test_SubordinateComponents_noseries(self):
        # simple finding aid with no series but only a container list
        simple_dsc = """<dsc><c01 level="file"/></dsc>"""
        dsc = load_xmlobject_from_string(simple_dsc, SubordinateComponents)
        self.assertFalse(dsc.hasSeries())

    def test_FileDescription(self):
        filedesc = self.ead.file_desc
        self.assert_(isinstance(filedesc, FileDescription))
        self.assert_(isinstance(filedesc.publication, PublicationStatement))
        self.assert_(isinstance(filedesc.publication.address, Address))
        self.assert_(isinstance(filedesc.publication.date, DateField))
        self.assertEqual("Emory University", filedesc.publication.publisher)
        self.assertEqual("Robert W. Woodruff Library", filedesc.publication.address.lines[0])
        self.assertEqual("404-727-6887", filedesc.publication.address.lines[3])
        self.assertEqual("marbl@emory.edu", filedesc.publication.address.lines[-1])

    def test_ProfileDescription(self):
        profiledesc = self.ead.profiledesc
        self.assert_(isinstance(profiledesc, ProfileDescription))
        self.assertEqual("English", profiledesc.languages[0])
        self.assertEqual("eng", profiledesc.language_codes[0])
        # profile creation date
        self.assert_(isinstance(profiledesc.date, DateField))
        self.assertEqual(u'May 5, 2005', unicode(profiledesc.date))
        self.assertEqual('2005-05-05', profiledesc.date.normalized)

    def test_DateField(self):
        date = self.ead.file_desc.publication.date
        self.assert_(isinstance(date, DateField))
        self.assertEqual("2005-05-05", date.normalized)
        self.assertEqual("May 5, 2005", unicode(date))
        self.assertEqual("ce", date.era)
        self.assertEqual("gregorian", date.calendar)

        unitdate = self.ead.dsc.c[1].c[0].did.unitdate
        self.assert_(isinstance(unitdate, DateField))
        self.assertEqual("1974/1986", unitdate.normalized)

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