<commit_before>import pytest
import subprocess
import os
import sys
import StringIO
import struct

prefix = '.'
for i in range(0,3):
    if os.path.exists(os.path.join(prefix, 'pyiso.py')):
        sys.path.insert(0, prefix)
        break
    else:
        prefix = '../' + prefix

import pyiso

from common import *

def test_new_nofiles():
    # Create a new ISO.
    iso = pyiso.PyIso()
    iso.new()

    out = StringIO.StringIO()
    iso.write(out)

    check_nofile(iso, len(out.getvalue()))

def test_new_onefile():
    # Now open up the ISO with pyiso and check some things out.
    iso = pyiso.PyIso()
    iso.new()
    # Add a new file.
    mystr = "foo\n"
    iso.add_fp(StringIO.StringIO(mystr), len(mystr), "/FOO.;1")

    out = StringIO.StringIO()
    iso.write(out)

    check_onefile(iso, len(out.getvalue()))

    # Now make sure we can re-open the written ISO.
    pyiso.PyIso().open(out)

def test_new_onedir():
    # Create a new ISO.
    iso = pyiso.PyIso()
    iso.new()
    # Add a directory.
    iso.add_directory("/DIR1")

    out = StringIO.StringIO()
    iso.write(out)

    check_onedir(iso, len(out.getvalue()))

    # Now make sure we can re-open the written ISO.
    pyiso.PyIso().open(out)

def test_new_twofiles():
    # Create a new ISO.
    iso = pyiso.PyIso()
    iso.new()
    # Add new files.
    foostr = "foo\n"
    iso.add_fp(StringIO.StringIO(foostr), len(foostr), "/FOO.;1")
    barstr = "bar\n"
    iso.add_fp(StringIO.StringIO(barstr), len(barstr), "/BAR.;1")

    out = StringIO.StringIO()
    iso.write(out)

    check_twofile(iso, len(out.getvalue()))

    # Now make sure we can re-open the written ISO.
    pyiso.PyIso().open(out)

def test_new_onefileonedir():
    # Create a new ISO.
    iso = pyiso.PyIso()
    iso.new()
    # Add new file.
    foostr = "foo\n"
    iso.add_fp(StringIO.StringIO(foostr), len(foostr), "/FOO.;1")
    # Add new directory.
    iso.add_directory("/DIR1")

    out = StringIO.StringIO()
    iso.write(out)

    check_onefileonedir(iso, len(out.getvalue()))

    # Now make sure we can re-open the written ISO.
    pyiso.PyIso().open(out)

def test_new_onefile_onedirwithfile():
    # Create a new ISO.
    iso = pyiso.PyIso()
    iso.new()
    # Add new file.
    foostr = "foo\n"
    iso.add_fp(StringIO.StringIO(foostr), len(foostr), "/FOO.;1")
    # Add new directory.
    iso.add_directory("/DIR1")
    # Add new sub-file.
    barstr = "bar\n"
    iso.add_fp(StringIO.StringIO(barstr), len(barstr), "/DIR1/BAR.;1")

    out = StringIO.StringIO()
    iso.write(out)

    check_onefile_onedirwithfile(iso, len(out.getvalue()))

    # Now make sure we can re-open the written ISO.
    pyiso.PyIso().open(out)

def test_new_tendirs():
    numdirs = 10

    # Create a new ISO.
    iso = pyiso.PyIso()
    iso.new()

    for i in range(1, 1+numdirs):
        iso.add_directory("/DIR%d" % i)

    out = StringIO.StringIO()
    iso.write(out)

    check_tendirs(iso, len(out.getvalue()))

    # Now make sure we can re-open the written ISO.
    pyiso.PyIso().open(out)

def test_new_dirs_overflow_ptr_extent():
    numdirs = 295

    # Create a new ISO.
    iso = pyiso.PyIso()
    iso.new()

    for i in range(1, 1+numdirs):
        iso.add_directory("/DIR%d" % i)

    out = StringIO.StringIO()
    iso.write(out)

    check_dirs_overflow_ptr_extent(iso, len(out.getvalue()))

    # Now make sure we can re-open the written ISO.
    pyiso.PyIso().open(out)

def test_new_dirs_just_short_ptr_extent():
    numdirs = 293

    # Create a new ISO.
    iso = pyiso.PyIso()
    iso.new()

    for i in range(1, 1+numdirs):
        iso.add_directory("/DIR%d" % i)
    # Now add two more to push it over the boundary
    iso.add_directory("/DIR294")
    iso.add_directory("/DIR295")

    # Now remove them to put it back down below the boundary.
    iso.rm_directory("/DIR295")
    iso.rm_directory("/DIR294")

    out = StringIO.StringIO()
    iso.write(out)

    check_dirs_just_short_ptr_extent(iso, len(out.getvalue()))

    # Now make sure we can re-open the written ISO.
    pyiso.PyIso().open(out)

def test_parse_twoextentfile():
    # Create a new ISO.
    iso = pyiso.PyIso()
    iso.new()

    outstr = ""
    for j in range(0, 8):
        for i in range(0, 256):
            outstr += struct.pack("=B", i)
    outstr += struct.pack("=B", 0)

    iso.add_fp(StringIO.StringIO(outstr), len(outstr), "/BIGFILE.;1")

    check_twoextentfile(iso, outstr)

    # Now make sure we can re-open the written ISO.
    out = StringIO.StringIO()
    iso.write(out)
    pyiso.PyIso().open(out)

def test_new_twoleveldeepdir():
    # Create a new ISO.
    iso = pyiso.PyIso()
    iso.new()

    # Add new directory.
    iso.add_directory("/DIR1")
    iso.add_directory("/DIR1/SUBDIR1")

    out = StringIO.StringIO()
    iso.write(out)

    check_twoleveldeepdir(iso, len(out.getvalue()))

    # Now make sure we can re-open the written ISO.
    pyiso.PyIso().open(out)

def test_new_twoleveldeepfile():
    # Create a new ISO.
    iso = pyiso.PyIso()
    iso.new()

    # Add new directory.
    iso.add_directory("/DIR1")
    iso.add_directory("/DIR1/SUBDIR1")
    mystr = "foo\n"
    iso.add_fp(StringIO.StringIO(mystr), len(mystr), "/DIR1/SUBDIR1/FOO.;1")

    out = StringIO.StringIO()
    iso.write(out)

    check_twoleveldeepfile(iso, len(out.getvalue()))

    # Now make sure we can re-open the written ISO.
    pyiso.PyIso().open(out)

def test_new_dirs_overflow_ptr_extent_reverse():
    numdirs = 295

    # Create a new ISO.
    iso = pyiso.PyIso()
    iso.new()

    for i in reversed(range(1, 1+numdirs)):
        iso.add_directory("/DIR%d" % i)

    out = StringIO.StringIO()
    iso.write(out)

    check_dirs_overflow_ptr_extent(iso, len(out.getvalue()))

    # Now make sure we can re-open the written ISO.
    pyiso.PyIso().open(out)

def test_new_toodeepdir():
    # Create a new ISO.
    iso = pyiso.PyIso()
    iso.new()
    # Add a directory.
    iso.add_directory("/DIR1")
    iso.add_directory("/DIR1/DIR2")
    iso.add_directory("/DIR1/DIR2/DIR3")
    iso.add_directory("/DIR1/DIR2/DIR3/DIR4")
    iso.add_directory("/DIR1/DIR2/DIR3/DIR4/DIR5")
    iso.add_directory("/DIR1/DIR2/DIR3/DIR4/DIR5/DIR6")
    iso.add_directory("/DIR1/DIR2/DIR3/DIR4/DIR5/DIR6/DIR7")
    with pytest.raises(pyiso.PyIsoException):
        iso.add_directory("/DIR1/DIR2/DIR3/DIR4/DIR5/DIR6/DIR7/DIR8")

    # Now make sure we can re-open the written ISO.
    out = StringIO.StringIO()
    iso.write(out)
    pyiso.PyIso().open(out)

def test_new_removefile():
    # Create a new ISO.
    iso = pyiso.PyIso()
    iso.new()

    # Add new file.
    foostr = "foo\n"
    iso.add_fp(StringIO.StringIO(foostr), len(foostr), "/FOO.;1")

    # Add second new file.
    barstr = "bar\n"
    iso.add_fp(StringIO.StringIO(barstr), len(barstr), "/BAR.;1")

    # Remove the second file.
    iso.rm_file("/BAR.;1")

    out = StringIO.StringIO()
    iso.write(out)

    check_onefile(iso, len(out.getvalue()))

    # Now make sure we can re-open the written ISO.
    pyiso.PyIso().open(out)

def test_new_removedir():
    # Create a new ISO.
    iso = pyiso.PyIso()
    iso.new()

    # Add new file.
    foostr = "foo\n"
    iso.add_fp(StringIO.StringIO(foostr), len(foostr), "/FOO.;1")

    # Add new directory.
    iso.add_directory("/DIR1")

    # Remove the directory
    iso.rm_directory("/DIR1")

    out = StringIO.StringIO()
    iso.write(out)

    check_onefile(iso, len(out.getvalue()))

    # Now make sure we can re-open the written ISO.
    pyiso.PyIso().open(out)

def test_new_eltorito():
    # Create a new ISO.
    iso = pyiso.PyIso()
    iso.new()

    bootstr = "boot\n"
    iso.add_fp(StringIO.StringIO(bootstr), len(bootstr), "/BOOT.;1")
    iso.add_eltorito("/BOOT.;1", "/BOOT.CAT;1")

    out = StringIO.StringIO()
    iso.write(out)

    check_eltorito_nofile(iso, len(out.getvalue()))

def test_remove_eltorito():
    # Create a new ISO.
    iso = pyiso.PyIso()
    iso.new()

    bootstr = "boot\n"
    iso.add_fp(StringIO.StringIO(bootstr), len(bootstr), "/BOOT.;1")
    iso.add_eltorito("/BOOT.;1", "/BOOT.CAT;1")

    iso.remove_eltorito()
    iso.rm_file("/BOOT.;1")

    out = StringIO.StringIO()
    iso.write(out)

    check_nofile(iso, len(out.getvalue()))

def test_new_rr_nofiles():
    # Create a new ISO.
    iso = pyiso.PyIso()
    iso.new(rock_ridge=True)

    out = StringIO.StringIO()
    iso.write(out)

    check_rr_nofile(iso, len(out.getvalue()))

def test_new_rr_onefile():
    # Create a new ISO.
    iso = pyiso.PyIso()
    iso.new(rock_ridge=True)

    # Add a new file.
    mystr = "foo\n"
    iso.add_fp(StringIO.StringIO(mystr), len(mystr), "/FOO.;1", "/foo")

    out = StringIO.StringIO()
    iso.write(out)

    check_rr_onefile(iso, len(out.getvalue()))

def test_new_rr_twofile():
    # Create a new ISO.
    iso = pyiso.PyIso()
    iso.new(rock_ridge=True)

    # Add a new file.
    foostr = "foo\n"
    iso.add_fp(StringIO.StringIO(foostr), len(foostr), "/FOO.;1", "/foo")

    # Add a new file.
    barstr = "bar\n"
    iso.add_fp(StringIO.StringIO(barstr), len(barstr), "/BAR.;1", "/bar")

    out = StringIO.StringIO()
    iso.write(out)

    check_rr_twofile(iso, len(out.getvalue()))

def test_new_rr_onefileonedir():
    # Create a new ISO.
    iso = pyiso.PyIso()
    iso.new(rock_ridge=True)

    # Add a new file.
    foostr = "foo\n"
    iso.add_fp(StringIO.StringIO(foostr), len(foostr), "/FOO.;1", "/foo")

    # Add new directory.
    iso.add_directory("/DIR1", "/dir1")

    out = StringIO.StringIO()
    iso.write(out)

    check_rr_onefileonedir(iso, len(out.getvalue()))

def test_new_rr_onefileonedirwithfile():
    # Create a new ISO.
    iso = pyiso.PyIso()
    iso.new(rock_ridge=True)

    # Add a new file.
    foostr = "foo\n"
    iso.add_fp(StringIO.StringIO(foostr), len(foostr), "/FOO.;1", "/foo")

    # Add new directory.
    iso.add_directory("/DIR1", "/dir1")

    # Add a new file.
    barstr = "bar\n"
    iso.add_fp(StringIO.StringIO(barstr), len(barstr), "/DIR1/BAR.;1", "/dir1/bar")

    out = StringIO.StringIO()
    iso.write(out)

    check_rr_onefileonedirwithfile(iso, len(out.getvalue()))

def test_new_rr_symlink():
    # Create a new ISO.
    iso = pyiso.PyIso()
    iso.new(rock_ridge=True)

    # Add a new file.
    foostr = "foo\n"
    iso.add_fp(StringIO.StringIO(foostr), len(foostr), "/FOO.;1", "/foo")

    iso.add_symlink("/SYM.;1", "sym", "/foo")

    out = StringIO.StringIO()
    iso.write(out)

    check_rr_symlink(iso, len(out.getvalue()))

def test_new_rr_symlink2():
    # Create a new ISO.
    iso = pyiso.PyIso()
    iso.new(rock_ridge=True)

    # Add new directory.
    iso.add_directory("/DIR1", "/dir1")

    # Add a new file.
    foostr = "foo\n"
    iso.add_fp(StringIO.StringIO(foostr), len(foostr), "/DIR1/FOO.;1", "/dir1/foo")

    iso.add_symlink("/SYM.;1", "sym", "/dir1/foo")

    out = StringIO.StringIO()
    iso.write(out)

    check_rr_symlink2(iso, len(out.getvalue()))

def test_new_rr_symlink_dot():
    # Create a new ISO.
    iso = pyiso.PyIso()
    iso.new(rock_ridge=True)

    iso.add_symlink("/SYM.;1", "sym", "/.")

    out = StringIO.StringIO()
    iso.write(out)

    check_rr_symlink_dot(iso, len(out.getvalue()))

def test_new_rr_symlink_broken():
    # Create a new ISO.
    iso = pyiso.PyIso()
    iso.new(rock_ridge=True)

    iso.add_symlink("/SYM.;1", "sym", "/foo")

    out = StringIO.StringIO()
    iso.write(out)

    check_rr_symlink_broken(iso, len(out.getvalue()))

# FIXME: add a test to write a file out, then write it out again and make sure
# everything still works.
<commit_msg>Make sure all the tests in "new" have new in the name.<commit_after>import pytest
import subprocess
import os
import sys
import StringIO
import struct

prefix = '.'
for i in range(0,3):
    if os.path.exists(os.path.join(prefix, 'pyiso.py')):
        sys.path.insert(0, prefix)
        break
    else:
        prefix = '../' + prefix

import pyiso

from common import *

def test_new_nofiles():
    # Create a new ISO.
    iso = pyiso.PyIso()
    iso.new()

    out = StringIO.StringIO()
    iso.write(out)

    check_nofile(iso, len(out.getvalue()))

def test_new_onefile():
    # Now open up the ISO with pyiso and check some things out.
    iso = pyiso.PyIso()
    iso.new()
    # Add a new file.
    mystr = "foo\n"
    iso.add_fp(StringIO.StringIO(mystr), len(mystr), "/FOO.;1")

    out = StringIO.StringIO()
    iso.write(out)

    check_onefile(iso, len(out.getvalue()))

    # Now make sure we can re-open the written ISO.
    pyiso.PyIso().open(out)

def test_new_onedir():
    # Create a new ISO.
    iso = pyiso.PyIso()
    iso.new()
    # Add a directory.
    iso.add_directory("/DIR1")

    out = StringIO.StringIO()
    iso.write(out)

    check_onedir(iso, len(out.getvalue()))

    # Now make sure we can re-open the written ISO.
    pyiso.PyIso().open(out)

def test_new_twofiles():
    # Create a new ISO.
    iso = pyiso.PyIso()
    iso.new()
    # Add new files.
    foostr = "foo\n"
    iso.add_fp(StringIO.StringIO(foostr), len(foostr), "/FOO.;1")
    barstr = "bar\n"
    iso.add_fp(StringIO.StringIO(barstr), len(barstr), "/BAR.;1")

    out = StringIO.StringIO()
    iso.write(out)

    check_twofile(iso, len(out.getvalue()))

    # Now make sure we can re-open the written ISO.
    pyiso.PyIso().open(out)

def test_new_onefileonedir():
    # Create a new ISO.
    iso = pyiso.PyIso()
    iso.new()
    # Add new file.
    foostr = "foo\n"
    iso.add_fp(StringIO.StringIO(foostr), len(foostr), "/FOO.;1")
    # Add new directory.
    iso.add_directory("/DIR1")

    out = StringIO.StringIO()
    iso.write(out)

    check_onefileonedir(iso, len(out.getvalue()))

    # Now make sure we can re-open the written ISO.
    pyiso.PyIso().open(out)

def test_new_onefile_onedirwithfile():
    # Create a new ISO.
    iso = pyiso.PyIso()
    iso.new()
    # Add new file.
    foostr = "foo\n"
    iso.add_fp(StringIO.StringIO(foostr), len(foostr), "/FOO.;1")
    # Add new directory.
    iso.add_directory("/DIR1")
    # Add new sub-file.
    barstr = "bar\n"
    iso.add_fp(StringIO.StringIO(barstr), len(barstr), "/DIR1/BAR.;1")

    out = StringIO.StringIO()
    iso.write(out)

    check_onefile_onedirwithfile(iso, len(out.getvalue()))

    # Now make sure we can re-open the written ISO.
    pyiso.PyIso().open(out)

def test_new_tendirs():
    numdirs = 10

    # Create a new ISO.
    iso = pyiso.PyIso()
    iso.new()

    for i in range(1, 1+numdirs):
        iso.add_directory("/DIR%d" % i)

    out = StringIO.StringIO()
    iso.write(out)

    check_tendirs(iso, len(out.getvalue()))

    # Now make sure we can re-open the written ISO.
    pyiso.PyIso().open(out)

def test_new_dirs_overflow_ptr_extent():
    numdirs = 295

    # Create a new ISO.
    iso = pyiso.PyIso()
    iso.new()

    for i in range(1, 1+numdirs):
        iso.add_directory("/DIR%d" % i)

    out = StringIO.StringIO()
    iso.write(out)

    check_dirs_overflow_ptr_extent(iso, len(out.getvalue()))

    # Now make sure we can re-open the written ISO.
    pyiso.PyIso().open(out)

def test_new_dirs_just_short_ptr_extent():
    numdirs = 293

    # Create a new ISO.
    iso = pyiso.PyIso()
    iso.new()

    for i in range(1, 1+numdirs):
        iso.add_directory("/DIR%d" % i)
    # Now add two more to push it over the boundary
    iso.add_directory("/DIR294")
    iso.add_directory("/DIR295")

    # Now remove them to put it back down below the boundary.
    iso.rm_directory("/DIR295")
    iso.rm_directory("/DIR294")

    out = StringIO.StringIO()
    iso.write(out)

    check_dirs_just_short_ptr_extent(iso, len(out.getvalue()))

    # Now make sure we can re-open the written ISO.
    pyiso.PyIso().open(out)

def test_new_twoextentfile():
    # Create a new ISO.
    iso = pyiso.PyIso()
    iso.new()

    outstr = ""
    for j in range(0, 8):
        for i in range(0, 256):
            outstr += struct.pack("=B", i)
    outstr += struct.pack("=B", 0)

    iso.add_fp(StringIO.StringIO(outstr), len(outstr), "/BIGFILE.;1")

    check_twoextentfile(iso, outstr)

    # Now make sure we can re-open the written ISO.
    out = StringIO.StringIO()
    iso.write(out)
    pyiso.PyIso().open(out)

def test_new_twoleveldeepdir():
    # Create a new ISO.
    iso = pyiso.PyIso()
    iso.new()

    # Add new directory.
    iso.add_directory("/DIR1")
    iso.add_directory("/DIR1/SUBDIR1")

    out = StringIO.StringIO()
    iso.write(out)

    check_twoleveldeepdir(iso, len(out.getvalue()))

    # Now make sure we can re-open the written ISO.
    pyiso.PyIso().open(out)

def test_new_twoleveldeepfile():
    # Create a new ISO.
    iso = pyiso.PyIso()
    iso.new()

    # Add new directory.
    iso.add_directory("/DIR1")
    iso.add_directory("/DIR1/SUBDIR1")
    mystr = "foo\n"
    iso.add_fp(StringIO.StringIO(mystr), len(mystr), "/DIR1/SUBDIR1/FOO.;1")

    out = StringIO.StringIO()
    iso.write(out)

    check_twoleveldeepfile(iso, len(out.getvalue()))

    # Now make sure we can re-open the written ISO.
    pyiso.PyIso().open(out)

def test_new_dirs_overflow_ptr_extent_reverse():
    numdirs = 295

    # Create a new ISO.
    iso = pyiso.PyIso()
    iso.new()

    for i in reversed(range(1, 1+numdirs)):
        iso.add_directory("/DIR%d" % i)

    out = StringIO.StringIO()
    iso.write(out)

    check_dirs_overflow_ptr_extent(iso, len(out.getvalue()))

    # Now make sure we can re-open the written ISO.
    pyiso.PyIso().open(out)

def test_new_toodeepdir():
    # Create a new ISO.
    iso = pyiso.PyIso()
    iso.new()
    # Add a directory.
    iso.add_directory("/DIR1")
    iso.add_directory("/DIR1/DIR2")
    iso.add_directory("/DIR1/DIR2/DIR3")
    iso.add_directory("/DIR1/DIR2/DIR3/DIR4")
    iso.add_directory("/DIR1/DIR2/DIR3/DIR4/DIR5")
    iso.add_directory("/DIR1/DIR2/DIR3/DIR4/DIR5/DIR6")
    iso.add_directory("/DIR1/DIR2/DIR3/DIR4/DIR5/DIR6/DIR7")
    with pytest.raises(pyiso.PyIsoException):
        iso.add_directory("/DIR1/DIR2/DIR3/DIR4/DIR5/DIR6/DIR7/DIR8")

    # Now make sure we can re-open the written ISO.
    out = StringIO.StringIO()
    iso.write(out)
    pyiso.PyIso().open(out)

def test_new_removefile():
    # Create a new ISO.
    iso = pyiso.PyIso()
    iso.new()

    # Add new file.
    foostr = "foo\n"
    iso.add_fp(StringIO.StringIO(foostr), len(foostr), "/FOO.;1")

    # Add second new file.
    barstr = "bar\n"
    iso.add_fp(StringIO.StringIO(barstr), len(barstr), "/BAR.;1")

    # Remove the second file.
    iso.rm_file("/BAR.;1")

    out = StringIO.StringIO()
    iso.write(out)

    check_onefile(iso, len(out.getvalue()))

    # Now make sure we can re-open the written ISO.
    pyiso.PyIso().open(out)

def test_new_removedir():
    # Create a new ISO.
    iso = pyiso.PyIso()
    iso.new()

    # Add new file.
    foostr = "foo\n"
    iso.add_fp(StringIO.StringIO(foostr), len(foostr), "/FOO.;1")

    # Add new directory.
    iso.add_directory("/DIR1")

    # Remove the directory
    iso.rm_directory("/DIR1")

    out = StringIO.StringIO()
    iso.write(out)

    check_onefile(iso, len(out.getvalue()))

    # Now make sure we can re-open the written ISO.
    pyiso.PyIso().open(out)

def test_new_eltorito():
    # Create a new ISO.
    iso = pyiso.PyIso()
    iso.new()

    bootstr = "boot\n"
    iso.add_fp(StringIO.StringIO(bootstr), len(bootstr), "/BOOT.;1")
    iso.add_eltorito("/BOOT.;1", "/BOOT.CAT;1")

    out = StringIO.StringIO()
    iso.write(out)

    check_eltorito_nofile(iso, len(out.getvalue()))

def test_new_remove_eltorito():
    # Create a new ISO.
    iso = pyiso.PyIso()
    iso.new()

    bootstr = "boot\n"
    iso.add_fp(StringIO.StringIO(bootstr), len(bootstr), "/BOOT.;1")
    iso.add_eltorito("/BOOT.;1", "/BOOT.CAT;1")

    iso.remove_eltorito()
    iso.rm_file("/BOOT.;1")

    out = StringIO.StringIO()
    iso.write(out)

    check_nofile(iso, len(out.getvalue()))

def test_new_rr_nofiles():
    # Create a new ISO.
    iso = pyiso.PyIso()
    iso.new(rock_ridge=True)

    out = StringIO.StringIO()
    iso.write(out)

    check_rr_nofile(iso, len(out.getvalue()))

def test_new_rr_onefile():
    # Create a new ISO.
    iso = pyiso.PyIso()
    iso.new(rock_ridge=True)

    # Add a new file.
    mystr = "foo\n"
    iso.add_fp(StringIO.StringIO(mystr), len(mystr), "/FOO.;1", "/foo")

    out = StringIO.StringIO()
    iso.write(out)

    check_rr_onefile(iso, len(out.getvalue()))

def test_new_rr_twofile():
    # Create a new ISO.
    iso = pyiso.PyIso()
    iso.new(rock_ridge=True)

    # Add a new file.
    foostr = "foo\n"
    iso.add_fp(StringIO.StringIO(foostr), len(foostr), "/FOO.;1", "/foo")

    # Add a new file.
    barstr = "bar\n"
    iso.add_fp(StringIO.StringIO(barstr), len(barstr), "/BAR.;1", "/bar")

    out = StringIO.StringIO()
    iso.write(out)

    check_rr_twofile(iso, len(out.getvalue()))

def test_new_rr_onefileonedir():
    # Create a new ISO.
    iso = pyiso.PyIso()
    iso.new(rock_ridge=True)

    # Add a new file.
    foostr = "foo\n"
    iso.add_fp(StringIO.StringIO(foostr), len(foostr), "/FOO.;1", "/foo")

    # Add new directory.
    iso.add_directory("/DIR1", "/dir1")

    out = StringIO.StringIO()
    iso.write(out)

    check_rr_onefileonedir(iso, len(out.getvalue()))

def test_new_rr_onefileonedirwithfile():
    # Create a new ISO.
    iso = pyiso.PyIso()
    iso.new(rock_ridge=True)

    # Add a new file.
    foostr = "foo\n"
    iso.add_fp(StringIO.StringIO(foostr), len(foostr), "/FOO.;1", "/foo")

    # Add new directory.
    iso.add_directory("/DIR1", "/dir1")

    # Add a new file.
    barstr = "bar\n"
    iso.add_fp(StringIO.StringIO(barstr), len(barstr), "/DIR1/BAR.;1", "/dir1/bar")

    out = StringIO.StringIO()
    iso.write(out)

    check_rr_onefileonedirwithfile(iso, len(out.getvalue()))

def test_new_rr_symlink():
    # Create a new ISO.
    iso = pyiso.PyIso()
    iso.new(rock_ridge=True)

    # Add a new file.
    foostr = "foo\n"
    iso.add_fp(StringIO.StringIO(foostr), len(foostr), "/FOO.;1", "/foo")

    iso.add_symlink("/SYM.;1", "sym", "/foo")

    out = StringIO.StringIO()
    iso.write(out)

    check_rr_symlink(iso, len(out.getvalue()))

def test_new_rr_symlink2():
    # Create a new ISO.
    iso = pyiso.PyIso()
    iso.new(rock_ridge=True)

    # Add new directory.
    iso.add_directory("/DIR1", "/dir1")

    # Add a new file.
    foostr = "foo\n"
    iso.add_fp(StringIO.StringIO(foostr), len(foostr), "/DIR1/FOO.;1", "/dir1/foo")

    iso.add_symlink("/SYM.;1", "sym", "/dir1/foo")

    out = StringIO.StringIO()
    iso.write(out)

    check_rr_symlink2(iso, len(out.getvalue()))

def test_new_rr_symlink_dot():
    # Create a new ISO.
    iso = pyiso.PyIso()
    iso.new(rock_ridge=True)

    iso.add_symlink("/SYM.;1", "sym", "/.")

    out = StringIO.StringIO()
    iso.write(out)

    check_rr_symlink_dot(iso, len(out.getvalue()))

def test_new_rr_symlink_broken():
    # Create a new ISO.
    iso = pyiso.PyIso()
    iso.new(rock_ridge=True)

    iso.add_symlink("/SYM.;1", "sym", "/foo")

    out = StringIO.StringIO()
    iso.write(out)

    check_rr_symlink_broken(iso, len(out.getvalue()))

# FIXME: add a test to write a file out, then write it out again and make sure
# everything still works.
<|endoftext|>


<commit_before>import datetime as dt
import requests

from botigo import app
from botigo import util

DATE_FORMAT = '%Y-%m-%d %H:%M:%S'

class LacubAPI(object):

    def __init__(self):
        self.api_key = app.config['LACUB_API_KEY']
        self.base_url = 'http://data.lacub.fr'

    def get_stops(self):
        """ Retrieve all stops. """

        payload = {
            'KEY': self.api_key,
            'SERVICE': 'WFS',
            'VERSION': '1.1.0',
            'REQUEST': 'GetFeature',
            'TYPENAME': 'bm:SV_ARRET_P',
            'SRSNAME': 'EPSG:4326'
        }

        response = requests.get('{}/wfs'.format(self.base_url), params=payload)
        stops = util.load_xml(response.content)
        return self._normalize(stops)

    def _normalize(self, stops):
        """ Normalize each feature parsed by BeautifulSoup. """

        extract = util.extract_element
        normalized = lambda stop: {
            'libelle': extract(stop, 'bm:libelle'),
            'gid': extract(stop, 'bm:gid'),
            'latitude': float(extract(stop, 'gml:pos').split(' ')[0]),
            'longitude': float(extract(stop, 'gml:pos').split(' ')[1]),
            'type': extract(stop, 'bm:type'),
            'cdate': dt.datetime.strptime(extract(stop, 'bm:cdate'), DATE_FORMAT).isoformat(),
            'mdate': dt.datetime.strptime(extract(stop, 'bm:mdate'), DATE_FORMAT).isoformat()
        }

        return [
            normalized(stop)
            for stop in stops.find_all('gml:featuremember')
        ]

if __name__ == '__main__':
    client = LacubAPI()
    stops = client.get_stops()
    print(len(stops))
<commit_msg>add wrapper @classmethod and @staticmethod<commit_after>import datetime as dt
import requests

from botigo import config
from botigo import util

DATE_FORMAT = '%Y-%m-%d %H:%M:%S'

class LacubAPI(object):

    API_KEY = config.LACUB_API_KEY
    BASE_URL = 'http://data.lacub.fr'

    @classmethod
    def get_stops(cls):
        """ Retrieve all stops. """

        print(cls.API_KEY)
        payload = {
            'KEY': cls.API_KEY,
            'SERVICE': 'WFS',
            'VERSION': '1.1.0',
            'REQUEST': 'GetFeature',
            'TYPENAME': 'bm:SV_ARRET_P',
            'SRSNAME': 'EPSG:4326'
        }

        response = requests.get('{}/wfs'.format(cls.BASE_URL), params=payload)
        stops = util.load_xml(response.content)
        return cls.normalize(stops)

    @staticmethod
    def normalize(stops):
        """ Normalize each feature parsed by BeautifulSoup. """

        extract = util.extract_element
        normalized = lambda stop: {
            'libelle': extract(stop, 'bm:libelle'),
            'gid': extract(stop, 'bm:gid'),
            'latitude': float(extract(stop, 'gml:pos').split(' ')[0]),
            'longitude': float(extract(stop, 'gml:pos').split(' ')[1]),
            'type': extract(stop, 'bm:type'),
            'cdate': dt.datetime.strptime(extract(stop, 'bm:cdate'), DATE_FORMAT).isoformat(),
            'mdate': dt.datetime.strptime(extract(stop, 'bm:mdate'), DATE_FORMAT).isoformat()
        }

        return [
            normalized(stop)
            for stop in stops.find_all('gml:featuremember')
        ]

if __name__ == '__main__':
    client = LacubAPI()
    stops = client.get_stops()
    print(len(stops))
<|endoftext|>


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

import unittest, sys, os, os.path as path

try:
    import xcp
except ImportError:
    print >>sys.stderr, "Must run with run-tests.sh"
    sys.exit(1)

from xcp.pci import PCI

class TestInvalid(unittest.TestCase):

    def test_invalid_types(self):

        self.assertRaises(TypeError, PCI, 0)
        self.assertRaises(TypeError, PCI, 0L)
        self.assertRaises(TypeError, PCI, (0,))
        self.assertRaises(TypeError, PCI, [])
        self.assertRaises(TypeError, PCI, {})

    def test_invalid_format(self):
        pass

class TestValid(unittest.TestCase):

    def test_null_with_segment(self):

        c = PCI("0000:00:00.0")

        self.assertEqual(c.segment, 0)
        self.assertEqual(c.bus, 0)
        self.assertEqual(c.device, 0)
        self.assertEqual(c.function, 0)

        self.assertEqual(c.integer, 0)

    def test_null_with_segment(self):

        c = PCI("00:00.0")

        self.assertEqual(c.segment, 0)
        self.assertEqual(c.bus, 0)
        self.assertEqual(c.device, 0)
        self.assertEqual(c.function, 0)

        self.assertEqual(c.integer, 0)

    def test_valid(self):

        c = PCI("8765:43:1f.3")

        self.assertEqual(c.segment, 0x8765)
        self.assertEqual(c.bus, 0x43)
        self.assertEqual(c.device, 0x1f)
        self.assertEqual(c.function, 0x3)

    def test_equality(self):

        self.assertEqual(PCI("0000:00:00.0"), PCI("00:00.0"))

if __name__ == "__main__":
    sys.exit(unittest.main())
<commit_msg>test_pci: rename a test whose name clashed with another<commit_after>#!/usr/bin/env python

import unittest, sys, os, os.path as path

try:
    import xcp
except ImportError:
    print >>sys.stderr, "Must run with run-tests.sh"
    sys.exit(1)

from xcp.pci import PCI

class TestInvalid(unittest.TestCase):

    def test_invalid_types(self):

        self.assertRaises(TypeError, PCI, 0)
        self.assertRaises(TypeError, PCI, 0L)
        self.assertRaises(TypeError, PCI, (0,))
        self.assertRaises(TypeError, PCI, [])
        self.assertRaises(TypeError, PCI, {})

    def test_invalid_format(self):
        pass

class TestValid(unittest.TestCase):

    def test_null_with_segment(self):

        c = PCI("0000:00:00.0")

        self.assertEqual(c.segment, 0)
        self.assertEqual(c.bus, 0)
        self.assertEqual(c.device, 0)
        self.assertEqual(c.function, 0)

        self.assertEqual(c.integer, 0)

    def test_null_without_segment(self):

        c = PCI("00:00.0")

        self.assertEqual(c.segment, 0)
        self.assertEqual(c.bus, 0)
        self.assertEqual(c.device, 0)
        self.assertEqual(c.function, 0)

        self.assertEqual(c.integer, 0)

    def test_valid(self):

        c = PCI("8765:43:1f.3")

        self.assertEqual(c.segment, 0x8765)
        self.assertEqual(c.bus, 0x43)
        self.assertEqual(c.device, 0x1f)
        self.assertEqual(c.function, 0x3)

    def test_equality(self):

        self.assertEqual(PCI("0000:00:00.0"), PCI("00:00.0"))

if __name__ == "__main__":
    sys.exit(unittest.main())
<|endoftext|>


<commit_before>import unittest

import time

import jax.numpy as np
from jax import grad, jit

class TestJAX(unittest.TestCase):
    def tanh(self, x):
        y = np.exp(-2.0 * x)
        return (1.0 - y) / (1.0 + y)

    @gpu_test
    def test_JAX(self):
        grad_tanh = grad(self.tanh)
        ag = grad_tanh(1.0)
        print(f'JAX autograd test: {ag}')
        assert ag==0.4199743
<commit_msg>move import statement inside gpu test<commit_after>import unittest

import time

class TestJAX(unittest.TestCase):
    def tanh(self, x):
        y = np.exp(-2.0 * x)
        return (1.0 - y) / (1.0 + y)

    @gpu_test
    def test_JAX(self):
        # importing inside the gpu-only test because these packages can't be
        # imported on the CPU image since they are not present there.
        import jax.numpy as np
        from jax import grad, jit

        grad_tanh = grad(self.tanh)
        ag = grad_tanh(1.0)
        print(f'JAX autograd test: {ag}')
        assert ag==0.4199743
<|endoftext|>


<commit_before>#! /usr/bin/env python
# test_spi.py, part of pyusbiss
# Copyright (c) 2016, 2018 Andrew Tolmie <andytheseeker@gmail.com>
# Licensed under the MIT License. See LICENSE file in the project root for full license information.
"""
Some tests for the SPI protocol controlled by USB-ISS.

Intended to be run on different platforms, to ensure portability of the code.

For all these tests a simple hardware is required.
Shortcut these pin pairs:
    IO2 <-> IO4

This script can be ran with a port identifier as an argument.
"""

import unittest
import time
import sys
from usbiss import spi

# on which port should the tests be performed:
# TODO: Cycle through available ports and attempt connection.
# TODO: Dinguish between platforms.
PORT = 'COM4'

# indirection via bytearray b/c bytes(range(256)) does something else in Pyhton 2.7
bytes_0to255 = list(bytes(bytearray(range(256))))

def segments(data, size=16):
    for a in range(0, len(data), size):
        yield data[a:a + size]

class SpiTestCase(unittest.TestCase):
    """SPI driver test case"""

    def setUp(self):
        self.cxn = spi.SPI(PORT)

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

    def test1_loopback(self):
        """
        Loopback test
        """
        for block in segments(bytes_0to255):
            self.assertEqual(self.cxn.xfer(block), block, "expected a {} which was written before".format(block))

if __name__ == '__main__':
    sys.stdout.write(__doc__)
    if len(sys.argv) > 1:
        PORT = sys.argv[1]
    sys.stdout.write("Testing port: {!r}\n".format(PORT))
    sys.argv[1:] = ['-v']
    # When this module is executed from the command-line, it runs all its tests
    unittest.main()
<commit_msg>Added a test for SPI modes<commit_after>#! /usr/bin/env python
# test_spi.py, part of pyusbiss
# Copyright (c) 2016, 2018 Andrew Tolmie <andytheseeker@gmail.com>
# Licensed under the MIT License. See LICENSE file in the project root for full license information.
"""
Some tests for the SPI protocol controlled by USB-ISS.

Intended to be run on different platforms, to ensure portability of the code.

For all these tests a simple hardware is required.
Shortcut these pin pairs:
    IO2 <-> IO4

This script can be ran with a port identifier as an argument.
"""

import unittest
import time
import sys
from usbiss import spi

# on which port should the tests be performed:
# TODO: Cycle through available ports and attempt connection.
# TODO: Dinguish between platforms.
PORT = 'COM4'

# indirection via bytearray b/c bytes(range(256)) does something else in Pyhton 2.7
bytes_0to255 = list(bytes(bytearray(range(256))))

def segments(data, size=16):
    for a in range(0, len(data), size):
        yield data[a:a + size]

class SpiTestCase(unittest.TestCase):
    """SPI driver test case"""

    def setUp(self):
        self.cxn = spi.SPI(PORT)

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

    def test0_modes(self):
        """
        Test SPI modes
        """
        for i in range(3):
            self.cxn.mode = i
            self.assertEqual(self.cxn.mode, i, "expected a {} which was written before".format(i))
            lookup_table = [0, 2, 1, 3]
            self.cxn._usbiss.get_iss_info()
            usbiss_mode = int(self.cxn._usbiss.cur_mode, 0) - self.cxn._usbiss.SPI_MODE
            self.assertEqual(usbiss_mode, lookup_table[i], "expected a {} which was written before".format(lookup_table[i]))

    def test1_loopback(self):
        """
        Loopback test
        """
        for block in segments(bytes_0to255):
            self.assertEqual(self.cxn.xfer(block), block, "expected a {} which was written before".format(block))

if __name__ == '__main__':
    sys.stdout.write(__doc__)
    if len(sys.argv) > 1:
        PORT = sys.argv[1]
    sys.stdout.write("Testing port: {!r}\n".format(PORT))
    sys.argv[1:] = ['-v']
    # When this module is executed from the command-line, it runs all its tests
    unittest.main()
<|endoftext|>


<commit_before>import cStringIO
import logging
import os
import sys
import tempfile
import unittest

from kiwi.log import Logger, set_log_file

class LogTest(unittest.TestCase):
    def setUp(self):
        self.filename = tempfile.mktemp()
        self.log = Logger('log')

    def tearDown(self):
        if os.path.exists(self.filename):
            os.unlink(self.filename)

    def testSetLogFile(self):
        set_log_file(self.filename, 'log')
        self.log.info("sliff")
        lines = open(self.filename).readlines()
        self.assertEqual(len(lines), 1)
        self.failUnless('sliff' in lines[0])

    def testStdErr(self):
        root = logging.getLogger()
        stream = root.handlers[0]
        fd = cStringIO.StringIO()
        stream.stream = fd
        self.log.warning("this is a warning")
        stream.stream = sys.stderr
        fd.seek(0)
        lines = fd.readlines()
        self.assertEqual(len(lines), 1)
        self.failUnless('this is a warning' in lines[0])
<commit_msg>Catch OSError for win32<commit_after>import cStringIO
import logging
import os
import sys
import tempfile
import unittest

from kiwi.log import Logger, set_log_file

class LogTest(unittest.TestCase):
    def setUp(self):
        self.filename = tempfile.mktemp()
        self.log = Logger('log')

    def tearDown(self):
        if os.path.exists(self.filename):
            try:
                os.unlink(self.filename)
            except OSError: # win32 permission error
                pass

    def testSetLogFile(self):
        set_log_file(self.filename, 'log')
        self.log.info("sliff")
        lines = open(self.filename).readlines()
        self.assertEqual(len(lines), 1)
        self.failUnless('sliff' in lines[0])

    def testStdErr(self):
        root = logging.getLogger()
        stream = root.handlers[0]
        fd = cStringIO.StringIO()
        stream.stream = fd
        self.log.warning("this is a warning")
        stream.stream = sys.stderr
        fd.seek(0)
        lines = fd.readlines()
        self.assertEqual(len(lines), 1)
        self.failUnless('this is a warning' in lines[0])
<|endoftext|>


<commit_before>"""
 Pylibui test suite.

"""

from pylibui.controls import Tab, Button
from tests.utils import WindowTestCase

class TabTest(WindowTestCase):

    def setUp(self):
        super().setUp()
        self.tab = Tab()

    def test_append_pages(self):
        """Tests that pages can be appended to a tab."""
        button = Button('my button')
        self.tab.append('my tab 1', button)

        button2 = Button('second button')
        self.tab.append('second tab', button2)

        self.assertEqual(self.tab.getNumPages(), 2)

    def test_append_page_at_index(self):
        """Tests that pages can be appended at a specified index."""
        button = Button('my button')
        self.tab.append('my tab 1', button)

        button2 = Button('second button')
        self.tab.insertAt('my tab 1', 0, button2)

        # TODO: should we do a check on indexes when user calls `insertAt` ?
        #       At the moment, the following code crashes:
        # button3 = Button('second button')
        # self.tab.insertAt('my tab 3', 10, button3) # non-existing page index

    def test_delete_pages(self):
        """Tests that we can delete pages from tab."""
        button = Button('my button')
        self.tab.append('my tab 1', button)
        self.assertEqual(self.tab.getNumPages(), 1)

        self.tab.delete(0)
        self.assertEqual(self.tab.getNumPages(), 0)

        # TODO: should we do a check on indexes when user calls `delete` ?
        #       At the moment, the following code crashes:
        # self.tab.delete(40) # non-existing page index

    def test_margins(self):
        """Tests that we can set/get the margins of the tab."""

        # we first have to add a page to the tab
        button = Button('my button')
        self.tab.append('my tab 1', button)

        self.assertEqual(self.tab.getMargined(0), 0)

        margin = 20
        self.tab.setMargined(0, margin)
        self.assertEqual(self.tab.getMargined(0), margin)

        # TODO: should we do a check on indexes when user calls `getMargined` +
        #       `setMargined` ? At the moment, the following code crashes:
        # self.tab.setMargined(40, margin) # non-existing page index
<commit_msg>updated tab tests<commit_after>"""
 Pylibui test suite.

"""

from pylibui.controls import Tab, Button
from tests.utils import WindowTestCase

class TabTest(WindowTestCase):

    def setUp(self):
        super().setUp()
        self.tab = Tab()

    def test_append_pages(self):
        """Tests that pages can be appended to a tab."""
        button = Button('my button')
        self.tab.append('my tab 1', button)

        button2 = Button('second button')
        self.tab.append('second tab', button2)

        self.assertEqual(self.tab.getNumPages(), 2)

    def test_append_page_at_index(self):
        """Tests that pages can be appended at a specified index."""
        button = Button('my button')
        self.tab.append('my tab 1', button)

        button2 = Button('second button')
        self.tab.insertAt('my tab 1', 0, button2)

        self.assertEqual(self.tab.getNumPages(), 2)

        # TODO: should we do a check on indexes when user calls `insertAt` ?
        #       At the moment, the following code crashes:
        # button3 = Button('second button')
        # self.tab.insertAt('my tab 3', 10, button3) # non-existing page index

    def test_delete_pages(self):
        """Tests that we can delete pages from tab."""
        button = Button('my button')
        self.tab.append('my tab 1', button)

        self.tab.delete(0)
        self.assertEqual(self.tab.getNumPages(), 0)

        # TODO: should we do a check on indexes when user calls `delete` ?
        #       At the moment, the following code crashes:
        # self.tab.delete(40) # non-existing page index

    def test_margins_initial_value(self):
        """Tests the tab's `margin` initial value is zero."""
        button = Button('my button')
        self.tab.append('my tab 1', button)

        self.assertEqual(self.tab.getMargined(0), 0)

    def test_margins_can_be_changed(self):
        """Tests the tab's `margin` attribute can be changed."""
        # we first have to add a page to the tab
        button = Button('my button')
        self.tab.append('my tab 1', button)

        margin = 20
        self.tab.setMargined(0, margin)
        self.assertEqual(self.tab.getMargined(0), margin)

        # TODO: should we do a check on indexes when user calls `getMargined` +
        #       `setMargined` ? At the moment, the following code crashes:
        # self.tab.setMargined(40, margin) # non-existing page index
<|endoftext|>


<commit_before>import re
import os
import json
import unittest

from lxml import etree
from lxml import objectify

from m2m import m2m

def xml_to_pretty_string(xml):
    objectify.deannotate(xml, xsi_nil=True)
    etree.cleanup_namespaces(xml)

    s = etree.tostring(xml, pretty_print=True)
    return b'<?xml version="1.0" encoding="UTF-8"?>\n' + s

class CSVToDictTests(unittest.TestCase):
    def test_csv_to_dict(self):
        csv_list = m2m.CSVToDict('tests/data/test.csv')
        self.assertIsInstance(csv_list, list)
        self.assertEqual(len(csv_list), 1)

class MetadataRecordTests(unittest.TestCase):

    def setUp(self):
        xml = b"""<?xml version='1.0' encoding='UTF-8'?>
            <metadata>
                <title />
                <meta qualifier='metadataCreator'></meta>
            </metadata>
        """
        self.tree = objectify.fromstring(xml)

        agent_xml = b"""<?xml version='1.0' encoding='UTF-8'?>
            <metadata>
                <creator>
                    <name />
                    <info />
                    <type />
                </creator>
                <meta />
            </metadata>
        """
        self.agent_tree = objectify.fromstring(agent_xml)

        pub_xml = b"""<?xml version='1.0' encoding='UTF-8'?>
            <metadata>
                <publisher>
                    <name />
                    <location />
                </publisher>
                <meta />
            </metadata>
        """
        self.pub_tree = objectify.fromstring(pub_xml)

    def test_metadata_record_setup(self):
        """Test that the creation of a record creates a MetadataRecord object."""

        record = m2m.MetadataRecord('mphillips')
        self.assertIsInstance(record, m2m.MetadataRecord)

        s = etree.fromstring(bytes(record))
        self.assertEqual(len(s.findall('meta[@qualifier="metadataCreator"]')), 1)

        creator_string = s.findall('meta[@qualifier="metadataCreator"]')[0].text
        self.assertEqual(creator_string, 'mphillips')

    def test_metadata_record_setup_with_date(self):

        record = m2m.MetadataRecord('mphillips', addDate=True)
        self.assertIsInstance(record, m2m.MetadataRecord)

        s = etree.fromstring(bytes(record))
        self.assertEqual(len(s.findall('meta[@qualifier="metadataCreationDate"]')), 1)

        date_string_regex = re.compile(r'\d\d\d\d-\d\d-\d\d, \d\d:\d\d:\d\d')
        meta_date_string = s.findall('meta[@qualifier="metadataCreationDate"]')[0].text
        self.assertTrue(date_string_regex.match(meta_date_string))

    def test_none_element_value_equals_none(self):

        record = m2m.MetadataRecord('mphillips')
        self.assertEqual(record.mapping('basic', 'title', None), None)

    def test_empty_element_value_equals_none(self):
        # if element value is empty for non-required elements
        # then map should return None.

        record = m2m.MetadataRecord('mphillips')
        self.assertEqual(record.mapping('basic', 'title', '', required=False), None)

    def test_set_base_directory(self):

        record = m2m.MetadataRecord('mphillips')
        record.setBaseDirectory('out')
        self.assertEqual(record.baseDirectory, 'out')

    def test_set_folder_name(self):

        record = m2m.MetadataRecord('mphillips')
        record.setFolderName('folder')
        self.assertEqual(record.foldername, 'folder')

    def test_element_not_in_field_type(self):

        record = m2m.MetadataRecord('mphillips')

        with self.assertRaises(m2m.MetadataConverterException) as cm:
            record.mapping('basic', 'author', 'text')

        expected_error = 'Element named "author" not in fieldTypes'
        self.assertEqual(str(cm.exception), expected_error)

    def test_unsupported_mapping_function_type(self):

        record = m2m.MetadataRecord('mphillips')

        with self.assertRaises(m2m.MetadataConverterException) as cm:
            record.mapping('simple', 'title', 'text')

        expected_error = 'Unsupported mapping function type, simple'
        self.assertEqual(str(cm.exception), expected_error)

    def test_missing_required_metadata_value(self):

        record = m2m.MetadataRecord('mphillips')

        with self.assertRaises(m2m.MetadataConverterException) as cm:
            record.mapping('basic', 'title', '')

        expected_error = 'Value required for element named "title"'
        self.assertEqual(str(cm.exception), expected_error)

    def test_incorrect_element_type_for_valid_element(self):

        record = m2m.MetadataRecord('mphillips')

        with self.assertRaises(m2m.MetadataConverterException) as cm:
            record.mapping('agent', 'title', 'test')

        expected_error = 'Element "title" should be of basic type, but you' \
                         ' are attempting to add it as "agent" type.'
        self.assertEqual(str(cm.exception), expected_error)

    def test_split_function_of_map(self):
        record = m2m.MetadataRecord('mphillips')
        record.mapping('basic', 'title', 'm|f', split='|')

        self.tree.title = ['m', 'f']
        self.tree.meta = 'mphillips'
        self.tree.meta.set('qualifier', 'metadataCreator')

        self.assertEqual(bytes(record), xml_to_pretty_string(self.tree))

    def test_empty_split_function_of_map(self):
        record = m2m.MetadataRecord('mphillips')
        record.mapping('basic', 'title', 'm|f', split='')

        self.tree.title = 'm|f'
        self.tree.meta = 'mphillips'
        self.tree.meta.set('qualifier', 'metadataCreator')

        self.assertEqual(bytes(record), xml_to_pretty_string(self.tree))

    def test_basic_map_unqualified_no_options(self):
        record = m2m.MetadataRecord('mphillips')
        record.mapping('basic', 'title', 'test_title')

        self.tree.title = 'test_title'
        self.tree.meta = 'mphillips'
        self.tree.meta.set('qualifier', 'metadataCreator')

        self.assertEqual(bytes(record), xml_to_pretty_string(self.tree))

    def test_basic_map_qualified_no_options(self):
        record = m2m.MetadataRecord('mphillips')
        record.mapping('basic', 'title', 'test_title', qualifier='officialtitle')

        self.tree.title = 'test_title'
        self.tree.title.set('qualifier', 'officialtitle')
        self.tree.meta = 'mphillips'
        self.tree.meta.set('qualifier', 'metadataCreator')

        self.assertEqual(bytes(record), xml_to_pretty_string(self.tree))

    def test_basic_map_empty_qualified_no_options(self):
        record = m2m.MetadataRecord('mphillips')
        record.mapping('basic', 'title', 'test_title', qualifier='')

        self.tree.title = 'test_title'
        self.tree.meta = 'mphillips'
        self.tree.meta.set('qualifier', 'metadataCreator')

        self.assertEqual(bytes(record), xml_to_pretty_string(self.tree))

    def test_basic_map_qualified_basic_with_function(self):
        record = m2m.MetadataRecord('mphillips')
        record.mapping('basic', 'title', 'test_title',
                       qualifier='officialtitle',
                       function=(lambda x: x.upper())
                       )

        self.tree.title = 'TEST_TITLE'
        self.tree.title.set('qualifier', 'officialtitle')
        self.tree.meta = 'mphillips'
        self.tree.meta.set('qualifier', 'metadataCreator')

        self.assertEqual(bytes(record), xml_to_pretty_string(self.tree))

    def test_agent_map_unqualified_no_options(self):
        record = m2m.MetadataRecord('mphillips')
        record.mapping('agent', 'creator', 'Phillips, Mark')

        self.agent_tree.creator.name = 'Phillips, Mark'
        del self.agent_tree.creator.info
        del self.agent_tree.creator.type
        self.agent_tree.meta = 'mphillips'
        self.agent_tree.meta.set('qualifier', 'metadataCreator')

        self.assertEqual(bytes(record), xml_to_pretty_string(self.agent_tree))

    def test_agent_map_qualified_with_function(self):
        record = m2m.MetadataRecord('mphillips')
        record.mapping('agent', 'creator', 'Phillips, Mark',
                       qualifier='aut',
                       function=(lambda x: x.upper())
                       )

        self.agent_tree.creator.name = 'PHILLIPS, MARK'
        del self.agent_tree.creator.info
        del self.agent_tree.creator.type
        self.agent_tree.creator.set('qualifier', 'aut')
        self.agent_tree.meta = 'mphillips'
        self.agent_tree.meta.set('qualifier', 'metadataCreator')

        self.assertEqual(bytes(record), xml_to_pretty_string(self.agent_tree))

    def test_agent_map_qualified_no_options(self):
        record = m2m.MetadataRecord('mphillips')
        record.mapping('agent', 'creator', 'Phillips, Mark', qualifier='aut')

        self.agent_tree.creator.name = 'Phillips, Mark'
        del self.agent_tree.creator.info
        del self.agent_tree.creator.type
        self.agent_tree.creator.set('qualifier', 'aut')
        self.agent_tree.meta = 'mphillips'
        self.agent_tree.meta.set('qualifier', 'metadataCreator')

        self.assertEqual(bytes(record), xml_to_pretty_string(self.agent_tree))

    def test_agent_map_qualified_info_only(self):
        record = m2m.MetadataRecord('mphillips')
        record.mapping('agent', 'creator', 'Phillips, Mark',
                       qualifier='aut', info='First Publication')

        self.agent_tree.creator.info = 'First Publication'
        self.agent_tree.creator.name = 'Phillips, Mark'
        del self.agent_tree.creator.type
        self.agent_tree.creator.set('qualifier', 'aut')
        self.agent_tree.meta = 'mphillips'
        self.agent_tree.meta.set('qualifier', 'metadataCreator')

        self.assertEqual(bytes(record), xml_to_pretty_string(self.agent_tree))

    def test_agent_map_qualified_info_and_agent_type(self):
        record = m2m.MetadataRecord('mphillips')
        record.mapping('agent', 'creator', 'Phillips, Mark',
                       qualifier='aut',
                       info='First Publication',
                       agent_type='per')

        self.agent_tree.creator.info = 'First Publication'
        self.agent_tree.creator.name = 'Phillips, Mark'
        self.agent_tree.creator.type = 'per'
        self.agent_tree.creator.set('qualifier', 'aut')
        self.agent_tree.meta = 'mphillips'
        self.agent_tree.meta.set('qualifier', 'metadataCreator')

        self.assertEqual(bytes(record), xml_to_pretty_string(self.agent_tree))

    def test_agent_map_qualified_with_location(self):
        record = m2m.MetadataRecord('mphillips')
        record.mapping('agent', 'publisher', 'UNT Libraries',
                       location='Denton, Texas')

        self.pub_tree.publisher.name = 'UNT Libraries'
        self.pub_tree.publisher.location = 'Denton, Texas'
        self.pub_tree.meta = 'mphillips'
        self.pub_tree.meta.set('qualifier', 'metadataCreator')

        self.assertEqual(bytes(record), xml_to_pretty_string(self.pub_tree))

    def test_agent_incorrect_use_of_location_that_is_not_publisher(self):

        record = m2m.MetadataRecord('mphillips')

        with self.assertRaises(m2m.MetadataConverterException) as cm:
            record.mapping('agent', 'creator', 'Phillips, Mark',
                           location='aut')

        expected_error = 'location can only be used on publisher element'
        self.assertEqual(str(cm.exception), expected_error)

    def test_write_xml_metadata_file(self):
        record = m2m.MetadataRecord('mphillips')
        record.mapping('agent', 'publisher', 'UNT Libraries',
                       location='Denton, Texas')
        record.setBaseDirectory('tests')
        record.setFolderName('test_data')

        record.writeTemplateFiles(record.baseDirectory, record.foldername)

        self.assertTrue(os.path.exists(record.baseDirectory))
        self.assertTrue(os.path.exists(os.path.join(
                                       record.baseDirectory, record.foldername)))
        self.assertTrue(os.path.exists(os.path.join(
                                       record.baseDirectory, record.foldername, 'metadata.xml')))

        self.pub_tree.publisher.name = 'UNT Libraries'
        self.pub_tree.publisher.location = 'Denton, Texas'
        self.pub_tree.meta = 'mphillips'
        self.pub_tree.meta.set('qualifier', 'metadataCreator')

        filename = os.path.join(record.baseDirectory, record.foldername, 'metadata.xml')
        record_from_file = open(filename, 'rb').read()
        self.assertEqual(record_from_file, xml_to_pretty_string(self.pub_tree))

        # remove test files that were written
        os.remove(os.path.join(record.baseDirectory, record.foldername, 'metadata.xml'))
        os.rmdir(os.path.join(record.baseDirectory, record.foldername))

    def test_write_json_metadata_file(self):
        record = m2m.MetadataRecord('mphillips')

        record.setBaseDirectory('tests')
        record.setFolderName('test_data')
        test_json_data = {'test': 'data'}

        record.writeJSONFile(record.baseDirectory, record.foldername, test_json_data)

        self.assertTrue(os.path.exists(record.baseDirectory))
        self.assertTrue(os.path.exists(os.path.join(
                                       record.baseDirectory, record.foldername)))
        self.assertTrue(os.path.exists(os.path.join(
                                       record.baseDirectory, record.foldername, 'metadata.json')))

        filename = os.path.join(record.baseDirectory, record.foldername, 'metadata.json')
        record_from_file = open(filename).read()

        self.assertEqual(json.loads(record_from_file), test_json_data)

        # remove test files that were written
        os.remove(os.path.join(record.baseDirectory, record.foldername, 'metadata.json'))
        os.rmdir(os.path.join(record.baseDirectory, record.foldername))

def suite():
    all_tests = unittest.TestSuite()
    all_tests.addTest(unittest.makeSuite(CSVToDictTests))
    all_tests.addTest(unittest.makeSuite(MetadataRecordTests))

    return all_tests

if __name__ == '__main__':
    unittest.main()
<commit_msg>Add the comment deleted by mistake back.<commit_after>import re
import os
import json
import unittest

from lxml import etree
from lxml import objectify

from m2m import m2m

def xml_to_pretty_string(xml):
    objectify.deannotate(xml, xsi_nil=True)
    etree.cleanup_namespaces(xml)

    s = etree.tostring(xml, pretty_print=True)
    return b'<?xml version="1.0" encoding="UTF-8"?>\n' + s

class CSVToDictTests(unittest.TestCase):
    def test_csv_to_dict(self):
        csv_list = m2m.CSVToDict('tests/data/test.csv')
        self.assertIsInstance(csv_list, list)
        self.assertEqual(len(csv_list), 1)

class MetadataRecordTests(unittest.TestCase):

    def setUp(self):
        xml = b"""<?xml version='1.0' encoding='UTF-8'?>
            <metadata>
                <title />
                <meta qualifier='metadataCreator'></meta>
            </metadata>
        """
        self.tree = objectify.fromstring(xml)

        agent_xml = b"""<?xml version='1.0' encoding='UTF-8'?>
            <metadata>
                <creator>
                    <name />
                    <info />
                    <type />
                </creator>
                <meta />
            </metadata>
        """
        self.agent_tree = objectify.fromstring(agent_xml)

        pub_xml = b"""<?xml version='1.0' encoding='UTF-8'?>
            <metadata>
                <publisher>
                    <name />
                    <location />
                </publisher>
                <meta />
            </metadata>
        """
        self.pub_tree = objectify.fromstring(pub_xml)

    def test_metadata_record_setup(self):
        """Test that the creation of a record creates a MetadataRecord object."""

        record = m2m.MetadataRecord('mphillips')
        self.assertIsInstance(record, m2m.MetadataRecord)

        s = etree.fromstring(bytes(record))
        self.assertEqual(len(s.findall('meta[@qualifier="metadataCreator"]')), 1)

        creator_string = s.findall('meta[@qualifier="metadataCreator"]')[0].text
        self.assertEqual(creator_string, 'mphillips')

    def test_metadata_record_setup_with_date(self):

        record = m2m.MetadataRecord('mphillips', addDate=True)
        self.assertIsInstance(record, m2m.MetadataRecord)

        s = etree.fromstring(bytes(record))
        self.assertEqual(len(s.findall('meta[@qualifier="metadataCreationDate"]')), 1)

        date_string_regex = re.compile(r'\d\d\d\d-\d\d-\d\d, \d\d:\d\d:\d\d')
        meta_date_string = s.findall('meta[@qualifier="metadataCreationDate"]')[0].text
        self.assertTrue(date_string_regex.match(meta_date_string))

    def test_none_element_value_equals_none(self):
        # if element value is None then it should return None.

        record = m2m.MetadataRecord('mphillips')
        self.assertEqual(record.mapping('basic', 'title', None), None)

    def test_empty_element_value_equals_none(self):
        # if element value is empty for non-required elements
        # then map should return None.

        record = m2m.MetadataRecord('mphillips')
        self.assertEqual(record.mapping('basic', 'title', '', required=False), None)

    def test_set_base_directory(self):

        record = m2m.MetadataRecord('mphillips')
        record.setBaseDirectory('out')
        self.assertEqual(record.baseDirectory, 'out')

    def test_set_folder_name(self):

        record = m2m.MetadataRecord('mphillips')
        record.setFolderName('folder')
        self.assertEqual(record.foldername, 'folder')

    def test_element_not_in_field_type(self):

        record = m2m.MetadataRecord('mphillips')

        with self.assertRaises(m2m.MetadataConverterException) as cm:
            record.mapping('basic', 'author', 'text')

        expected_error = 'Element named "author" not in fieldTypes'
        self.assertEqual(str(cm.exception), expected_error)

    def test_unsupported_mapping_function_type(self):

        record = m2m.MetadataRecord('mphillips')

        with self.assertRaises(m2m.MetadataConverterException) as cm:
            record.mapping('simple', 'title', 'text')

        expected_error = 'Unsupported mapping function type, simple'
        self.assertEqual(str(cm.exception), expected_error)

    def test_missing_required_metadata_value(self):

        record = m2m.MetadataRecord('mphillips')

        with self.assertRaises(m2m.MetadataConverterException) as cm:
            record.mapping('basic', 'title', '')

        expected_error = 'Value required for element named "title"'
        self.assertEqual(str(cm.exception), expected_error)

    def test_incorrect_element_type_for_valid_element(self):

        record = m2m.MetadataRecord('mphillips')

        with self.assertRaises(m2m.MetadataConverterException) as cm:
            record.mapping('agent', 'title', 'test')

        expected_error = 'Element "title" should be of basic type, but you' \
                         ' are attempting to add it as "agent" type.'
        self.assertEqual(str(cm.exception), expected_error)

    def test_split_function_of_map(self):
        record = m2m.MetadataRecord('mphillips')
        record.mapping('basic', 'title', 'm|f', split='|')

        self.tree.title = ['m', 'f']
        self.tree.meta = 'mphillips'
        self.tree.meta.set('qualifier', 'metadataCreator')

        self.assertEqual(bytes(record), xml_to_pretty_string(self.tree))

    def test_empty_split_function_of_map(self):
        record = m2m.MetadataRecord('mphillips')
        record.mapping('basic', 'title', 'm|f', split='')

        self.tree.title = 'm|f'
        self.tree.meta = 'mphillips'
        self.tree.meta.set('qualifier', 'metadataCreator')

        self.assertEqual(bytes(record), xml_to_pretty_string(self.tree))

    def test_basic_map_unqualified_no_options(self):
        record = m2m.MetadataRecord('mphillips')
        record.mapping('basic', 'title', 'test_title')

        self.tree.title = 'test_title'
        self.tree.meta = 'mphillips'
        self.tree.meta.set('qualifier', 'metadataCreator')

        self.assertEqual(bytes(record), xml_to_pretty_string(self.tree))

    def test_basic_map_qualified_no_options(self):
        record = m2m.MetadataRecord('mphillips')
        record.mapping('basic', 'title', 'test_title', qualifier='officialtitle')

        self.tree.title = 'test_title'
        self.tree.title.set('qualifier', 'officialtitle')
        self.tree.meta = 'mphillips'
        self.tree.meta.set('qualifier', 'metadataCreator')

        self.assertEqual(bytes(record), xml_to_pretty_string(self.tree))

    def test_basic_map_empty_qualified_no_options(self):
        record = m2m.MetadataRecord('mphillips')
        record.mapping('basic', 'title', 'test_title', qualifier='')

        self.tree.title = 'test_title'
        self.tree.meta = 'mphillips'
        self.tree.meta.set('qualifier', 'metadataCreator')

        self.assertEqual(bytes(record), xml_to_pretty_string(self.tree))

    def test_basic_map_qualified_basic_with_function(self):
        record = m2m.MetadataRecord('mphillips')
        record.mapping('basic', 'title', 'test_title',
                       qualifier='officialtitle',
                       function=(lambda x: x.upper())
                       )

        self.tree.title = 'TEST_TITLE'
        self.tree.title.set('qualifier', 'officialtitle')
        self.tree.meta = 'mphillips'
        self.tree.meta.set('qualifier', 'metadataCreator')

        self.assertEqual(bytes(record), xml_to_pretty_string(self.tree))

    def test_agent_map_unqualified_no_options(self):
        record = m2m.MetadataRecord('mphillips')
        record.mapping('agent', 'creator', 'Phillips, Mark')

        self.agent_tree.creator.name = 'Phillips, Mark'
        del self.agent_tree.creator.info
        del self.agent_tree.creator.type
        self.agent_tree.meta = 'mphillips'
        self.agent_tree.meta.set('qualifier', 'metadataCreator')

        self.assertEqual(bytes(record), xml_to_pretty_string(self.agent_tree))

    def test_agent_map_qualified_with_function(self):
        record = m2m.MetadataRecord('mphillips')
        record.mapping('agent', 'creator', 'Phillips, Mark',
                       qualifier='aut',
                       function=(lambda x: x.upper())
                       )

        self.agent_tree.creator.name = 'PHILLIPS, MARK'
        del self.agent_tree.creator.info
        del self.agent_tree.creator.type
        self.agent_tree.creator.set('qualifier', 'aut')
        self.agent_tree.meta = 'mphillips'
        self.agent_tree.meta.set('qualifier', 'metadataCreator')

        self.assertEqual(bytes(record), xml_to_pretty_string(self.agent_tree))

    def test_agent_map_qualified_no_options(self):
        record = m2m.MetadataRecord('mphillips')
        record.mapping('agent', 'creator', 'Phillips, Mark', qualifier='aut')

        self.agent_tree.creator.name = 'Phillips, Mark'
        del self.agent_tree.creator.info
        del self.agent_tree.creator.type
        self.agent_tree.creator.set('qualifier', 'aut')
        self.agent_tree.meta = 'mphillips'
        self.agent_tree.meta.set('qualifier', 'metadataCreator')

        self.assertEqual(bytes(record), xml_to_pretty_string(self.agent_tree))

    def test_agent_map_qualified_info_only(self):
        record = m2m.MetadataRecord('mphillips')
        record.mapping('agent', 'creator', 'Phillips, Mark',
                       qualifier='aut', info='First Publication')

        self.agent_tree.creator.info = 'First Publication'
        self.agent_tree.creator.name = 'Phillips, Mark'
        del self.agent_tree.creator.type
        self.agent_tree.creator.set('qualifier', 'aut')
        self.agent_tree.meta = 'mphillips'
        self.agent_tree.meta.set('qualifier', 'metadataCreator')

        self.assertEqual(bytes(record), xml_to_pretty_string(self.agent_tree))

    def test_agent_map_qualified_info_and_agent_type(self):
        record = m2m.MetadataRecord('mphillips')
        record.mapping('agent', 'creator', 'Phillips, Mark',
                       qualifier='aut',
                       info='First Publication',
                       agent_type='per')

        self.agent_tree.creator.info = 'First Publication'
        self.agent_tree.creator.name = 'Phillips, Mark'
        self.agent_tree.creator.type = 'per'
        self.agent_tree.creator.set('qualifier', 'aut')
        self.agent_tree.meta = 'mphillips'
        self.agent_tree.meta.set('qualifier', 'metadataCreator')

        self.assertEqual(bytes(record), xml_to_pretty_string(self.agent_tree))

    def test_agent_map_qualified_with_location(self):
        record = m2m.MetadataRecord('mphillips')
        record.mapping('agent', 'publisher', 'UNT Libraries',
                       location='Denton, Texas')

        self.pub_tree.publisher.name = 'UNT Libraries'
        self.pub_tree.publisher.location = 'Denton, Texas'
        self.pub_tree.meta = 'mphillips'
        self.pub_tree.meta.set('qualifier', 'metadataCreator')

        self.assertEqual(bytes(record), xml_to_pretty_string(self.pub_tree))

    def test_agent_incorrect_use_of_location_that_is_not_publisher(self):

        record = m2m.MetadataRecord('mphillips')

        with self.assertRaises(m2m.MetadataConverterException) as cm:
            record.mapping('agent', 'creator', 'Phillips, Mark',
                           location='aut')

        expected_error = 'location can only be used on publisher element'
        self.assertEqual(str(cm.exception), expected_error)

    def test_write_xml_metadata_file(self):
        record = m2m.MetadataRecord('mphillips')
        record.mapping('agent', 'publisher', 'UNT Libraries',
                       location='Denton, Texas')
        record.setBaseDirectory('tests')
        record.setFolderName('test_data')

        record.writeTemplateFiles(record.baseDirectory, record.foldername)

        self.assertTrue(os.path.exists(record.baseDirectory))
        self.assertTrue(os.path.exists(os.path.join(
                                       record.baseDirectory, record.foldername)))
        self.assertTrue(os.path.exists(os.path.join(
                                       record.baseDirectory, record.foldername, 'metadata.xml')))

        self.pub_tree.publisher.name = 'UNT Libraries'
        self.pub_tree.publisher.location = 'Denton, Texas'
        self.pub_tree.meta = 'mphillips'
        self.pub_tree.meta.set('qualifier', 'metadataCreator')

        filename = os.path.join(record.baseDirectory, record.foldername, 'metadata.xml')
        record_from_file = open(filename, 'rb').read()
        self.assertEqual(record_from_file, xml_to_pretty_string(self.pub_tree))

        # remove test files that were written
        os.remove(os.path.join(record.baseDirectory, record.foldername, 'metadata.xml'))
        os.rmdir(os.path.join(record.baseDirectory, record.foldername))

    def test_write_json_metadata_file(self):
        record = m2m.MetadataRecord('mphillips')

        record.setBaseDirectory('tests')
        record.setFolderName('test_data')
        test_json_data = {'test': 'data'}

        record.writeJSONFile(record.baseDirectory, record.foldername, test_json_data)

        self.assertTrue(os.path.exists(record.baseDirectory))
        self.assertTrue(os.path.exists(os.path.join(
                                       record.baseDirectory, record.foldername)))
        self.assertTrue(os.path.exists(os.path.join(
                                       record.baseDirectory, record.foldername, 'metadata.json')))

        filename = os.path.join(record.baseDirectory, record.foldername, 'metadata.json')
        record_from_file = open(filename).read()

        self.assertEqual(json.loads(record_from_file), test_json_data)

        # remove test files that were written
        os.remove(os.path.join(record.baseDirectory, record.foldername, 'metadata.json'))
        os.rmdir(os.path.join(record.baseDirectory, record.foldername))

def suite():
    all_tests = unittest.TestSuite()
    all_tests.addTest(unittest.makeSuite(CSVToDictTests))
    all_tests.addTest(unittest.makeSuite(MetadataRecordTests))

    return all_tests

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


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

import pytest

# Check that the plugin has been properly installed before proceeding
assert pytest.config.pluginmanager.hasplugin("vcr")

def test_iana_example(testdir):
    testdir.makepyfile(**{'subdir/test_iana_example': """
        import pytest
        try:
            from urllib.request import urlopen
        except ImportError:
            from urllib2 import urlopen

        @pytest.mark.vcr
        def test_iana():
            response = urlopen('http://www.iana.org/domains/reserved').read()
            assert b'Example domains' in response
    """})

    result = testdir.runpytest('-v')
    result.assert_outcomes(1, 0, 0)

    cassette_path = testdir.tmpdir.join(
        'subdir', 'cassettes', 'test_iana.yaml')
    assert cassette_path.size() > 50

def test_disable_vcr(testdir):
    testdir.makepyfile(**{'subdir/test_iana_example': """
        import pytest
        try:
            from urllib.request import urlopen
        except ImportError:
            from urllib2 import urlopen

        @pytest.fixture
        def vcr(vcr):
            # Make sure that modifying the VCR instance does not break anything
            vcr.register_matcher('xx', lambda x: x)
            vcr.record_mode = vcr.record_mode
            return vcr

        @pytest.mark.vcr
        def test_disable_vcr_iana_marking():
            response = urlopen('http://www.iana.org/domains/reserved').read()
            assert b'Example domains' in response

        def test_disable_vcr_iana_fixture(vcr_cassette):
            response = urlopen('http://www.iana.org/domains/reserved').read()
            assert b'Example domains' in response

        def test_disable_vcr_iana_vcr(vcr_cassette, vcr):
            with vcr.use_cassette('test_disable_vcr_iana_vcr'):
                response = urlopen('http://www.iana.org/domains/reserved').read()
            assert b'Example domains' in response
    """})

    result = testdir.runpytest('--vcr-record=none', '-v')
    result.assert_outcomes(0, 0, 3)

    result = testdir.runpytest('--disable-vcr', '--vcr-record=none', '-v')
    result.assert_outcomes(3, 0, 0)

    cassette_dir_path = testdir.tmpdir.join('subdir', 'cassettes')
    assert not cassette_dir_path.check()

def test_disable_vcr_with_existing_cassette(testdir):
    testdir.makepyfile(**{'subdir/test_iana_example': """
        import pytest
        try:
            from urllib.request import urlopen
        except ImportError:
            from urllib2 import urlopen

        @pytest.fixture(scope='module')
        def vcr(vcr):
            # Make sure that modifying the VCR instance does not break anything
            vcr.register_matcher('xx', lambda x: x)
            vcr.record_mode = vcr.record_mode
            return vcr

        @pytest.mark.vcr
        def test_disable_vcr_iana_marking():
            response = urlopen('http://www.iana.org/domains/reserved').read()
            assert b'Example domains' in response

        def test_disable_vcr_iana_fixture(vcr_cassette):
            response = urlopen('http://www.iana.org/domains/reserved').read()
            assert b'Example domains' in response

        def test_disable_vcr_iana_vcr(vcr_cassette, vcr):
            with vcr.use_cassette('test_disable_vcr_iana_vcr'):
                response = urlopen('http://www.iana.org/domains/reserved').read()
            assert b'Example domains' in response
    """})

    cassette_content = '''
version: 1
interactions:
- request:
    body: null
    headers: {}
    method: GET
    uri: http://httpbin.org/ip
  response:
    body: {string: !!python/unicode "From cassette fixture"}
    headers: {}
    status: {code: 200, message: OK}'''

    cassette_dir_path = testdir.tmpdir.join('subdir', 'cassettes').mkdir()
    cassette_dir_path.join('test_disable_vcr_iana_marking.yaml').write(cassette_content)
    cassette_dir_path.join('test_disable_vcr_iana_fixture.yaml').write(cassette_content)
    cassette_dir_path.join('test_disable_vcr_iana_vcr.yaml').write(cassette_content)

    t0 = cassette_dir_path.join('test_disable_vcr_iana_marking.yaml').mtime()

    result = testdir.runpytest('--vcr-record=none', '-v')
    result.assert_outcomes(0, 0, 3)

    result = testdir.runpytest('--disable-vcr', '--vcr-record=none', '-v')
    result.assert_outcomes(3, 0, 0)

    t1 = cassette_dir_path.join('test_disable_vcr_iana_marking.yaml').mtime()
    # Check that the cassette file is unmodified
    assert t0 == t1

def test_custom_matchers(testdir):
    testdir.makepyfile("""
        import pytest
        try:
            from urllib.request import urlopen
        except ImportError:
            from urllib2 import urlopen

        @pytest.fixture(scope='module')
        def vcr(vcr):
            vcr.register_matcher('my_matcher', lambda a, b: True)
            vcr.match_on = ['my_matcher']
            return vcr

        @pytest.mark.vcr
        def test_custom_matchers_iana():
            response = urlopen('http://www.iana.org/domains/reserved').read()
            assert b'From cassette fixture' in response
    """)

    testdir.tmpdir.mkdir('cassettes').join('test_custom_matchers_iana.yaml') \
        .write('''
version: 1
interactions:
- request:
    body: null
    headers: {}
    method: GET
    uri: http://httpbin.org/ip
  response:
    body: {string: !!python/unicode "From cassette fixture"}
    headers: {}
    status: {code: 200, message: OK}''')

    result = testdir.runpytest('-v', '-s', '--vcr-record=none')
    assert result.ret == 0

def test_overriding_cassette_path(testdir):
    testdir.makepyfile("""
        import pytest, os

        @pytest.fixture(scope='module')
        def vcr_cassette_dir():
            return 'vhs'

        @pytest.fixture
        def vcr_cassette_name(vcr_cassette_dir, request, vcr_cassette_name):
            # Put all cassettes in vhs/{module}/{test}.yaml
            return os.path.join(vcr_cassette_dir, request.module.__name__, vcr_cassette_name)

        @pytest.mark.vcr
        def test_show_cassette(vcr_cassette):
            print("Cassette: {}".format(vcr_cassette._path))
    """)

    result = testdir.runpytest('-s')
    result.assert_outcomes(1, 0, 0)
    result.stdout.fnmatch_lines(['*Cassette: vhs/*/test_show_cassette.yaml'])

def test_cassette_name_for_classes(testdir):
    testdir.makepyfile("""
        import pytest

        @pytest.mark.vcr
        class TestClass:
            def test_method(self, vcr_cassette_name):
                print("Cassette: {}".format(vcr_cassette_name))
    """)

    result = testdir.runpytest('-s')
    result.stdout.fnmatch_lines(['*Cassette: TestClass.test_method'])

def test_vcr_config(testdir):
    testdir.makepyfile("""
        import pytest

        @pytest.fixture(scope='module')
        def vcr_config():
            return {'record_mode': 'none'}

        @pytest.mark.vcr
        def test_method(vcr_cassette):
            print("Cassette record mode: {}".format(vcr_cassette.record_mode))
    """)

    result = testdir.runpytest('-s')
    result.assert_outcomes(1, 0, 0)
    result.stdout.fnmatch_lines(['*Cassette record mode: none'])

def test_marker_options(testdir):
    testdir.makepyfile("""
        import pytest

        @pytest.fixture(scope='module')
        def vcr_config():
            return {'record_mode': 'all'}

        @pytest.mark.vcr(record_mode='none')
        def test_method(vcr_cassette):
            print("Cassette record mode: {}".format(vcr_cassette.record_mode))
    """)

    result = testdir.runpytest('-s')
    result.assert_outcomes(1, 0, 0)
    result.stdout.fnmatch_lines(['*Cassette record mode: none'])

def test_overriding_record_mode(testdir):
    testdir.makepyfile("""
        import pytest

        @pytest.fixture(scope='module')
        def vcr_config():
            return {'record_mode': 'none'}

        @pytest.mark.vcr(record_mode='once')
        def test_method(vcr_cassette, vcr):
            print("Cassette record mode: {}".format(vcr_cassette.record_mode))
    """)

    result = testdir.runpytest('-s', '--vcr-record', 'all')
    result.assert_outcomes(1, 0, 0)
    result.stdout.fnmatch_lines(['*Cassette record mode: all'])

def test_deprecated_record_mode(testdir):
    testdir.makepyfile("""
        import pytest

        @pytest.fixture(scope='module')
        def vcr_config():
            return {'record_mode': 'none'}

        @pytest.mark.vcr(record_mode='once')
        def test_method(vcr_cassette):
            print("Cassette record mode: {}".format(vcr_cassette.record_mode))
    """)

    result = testdir.runpytest('-s', '--vcr-record-mode', 'all')
    result.assert_outcomes(1, 0, 0)
    result.stdout.fnmatch_lines(['*Cassette record mode: all',
                                 '*--vcr-record-mode has been deprecated*'])

def test_marking_whole_class(testdir):
    testdir.makepyfile("""
        import pytest

        has_cassette = False

        @pytest.yield_fixture
        def vcr_cassette(vcr_cassette):
            global has_cassette
            has_cassette = True
            yield vcr_cassette
            has_cassette = False

        @pytest.mark.vcr
        class TestClass(object):
            def test_method(self):
                assert has_cassette
    """)

    result = testdir.runpytest('-s')
    assert result.ret == 0

def test_separate_cassettes_for_parametrized_tests(testdir):
    testdir.makepyfile("""
        import pytest

        @pytest.mark.vcr
        @pytest.mark.parametrize('arg', ['a', 'b'])
        def test_parameters(arg, vcr_cassette_name):
            assert vcr_cassette_name == 'test_parameters[{}]'.format(arg)
    """)

    result = testdir.runpytest('-s')
    assert result.ret == 0

def test_use_in_function_scope_fixture(testdir):
    """Test that the VCR instance can be used from fixtures and that the cassettes
    land in the correct location."""
    testdir.makepyfile(**{'subdir/test_iana_example': """
        import pytest
        try:
            from urllib.request import urlopen
        except ImportError:
            from urllib2 import urlopen

        @pytest.fixture
        def iana_response(vcr):
            with vcr.use_cassette('iana_response_fixture'):
                response = urlopen('http://www.iana.org/domains/reserved').read()
            return response

        def test_with_fixture(iana_response):
            assert b'Example domains' in iana_response
    """})

    result = testdir.runpytest('-v')
    result.assert_outcomes(1, 0, 0)

    cassette_path = testdir.tmpdir.join(
        'subdir', 'cassettes', 'iana_response_fixture.yaml')
    assert cassette_path.size() > 50

def test_use_in_module_scope_fixture(testdir):
    testdir.makepyfile(**{'subdir/test_iana_example': """
        import pytest
        try:
            from urllib.request import urlopen
        except ImportError:
            from urllib2 import urlopen

        @pytest.fixture(scope='module')
        def iana_response(vcr):
            with vcr.use_cassette('iana_response_fixture'):
                response = urlopen('http://www.iana.org/domains/reserved').read()
            return response

        def test_with_fixture(iana_response):
            assert b'Example domains' in iana_response
    """})

    result = testdir.runpytest('-v')
    result.assert_outcomes(1, 0, 0)

    cassette_path = testdir.tmpdir.join(
        'subdir', 'cassettes', 'iana_response_fixture.yaml')
    assert cassette_path.size() > 50

@pytest.mark.xfail(reason="session-scoped fixtures are not supported")
def test_use_in_session_scope_fixture(testdir):
    testdir.makepyfile(**{'subdir/test_iana_example': """
        import pytest
        try:
            from urllib.request import urlopen
        except ImportError:
            from urllib2 import urlopen

        @pytest.fixture(scope='session')
        def vcr_cassette_dir():
            test_dir = dirname(abspath(__file__))
            return os.path.join(test_dir, 'cassettes')

        @pytest.fixture(scope='session')
        def iana_response(vcr):
            with vcr.use_cassette('iana_response_fixture'):
                response = urlopen('http://www.iana.org/domains/reserved').read()
            return response

        def test_with_fixture(iana_response):
            assert b'Example domains' in iana_response
    """})

    result = testdir.runpytest('-v')
    result.assert_outcomes(1, 0, 0)

    cassette_path = testdir.tmpdir.join(
        'subdir', 'cassettes', 'iana_response_fixture.yaml')
    assert cassette_path.size() > 50

def test_help_message(testdir):
    result = testdir.runpytest(
        '--help',
    )
    # fnmatch_lines does an assertion internally
    result.stdout.fnmatch_lines([
        'vcr:',
        '*--vcr-record={*}',
    ])

def test_marker_message(testdir):
    result = testdir.runpytest('--markers')
    result.stdout.fnmatch_lines([
        '@pytest.mark.vcr: Mark the test as using VCR.py.',
    ])
<commit_msg>Fix a minor bug in a test<commit_after># -*- coding: utf-8 -*-

import pytest

# Check that the plugin has been properly installed before proceeding
assert pytest.config.pluginmanager.hasplugin("vcr")

def test_iana_example(testdir):
    testdir.makepyfile(**{'subdir/test_iana_example': """
        import pytest
        try:
            from urllib.request import urlopen
        except ImportError:
            from urllib2 import urlopen

        @pytest.mark.vcr
        def test_iana():
            response = urlopen('http://www.iana.org/domains/reserved').read()
            assert b'Example domains' in response
    """})

    result = testdir.runpytest('-v')
    result.assert_outcomes(1, 0, 0)

    cassette_path = testdir.tmpdir.join(
        'subdir', 'cassettes', 'test_iana.yaml')
    assert cassette_path.size() > 50

def test_disable_vcr(testdir):
    testdir.makepyfile(**{'subdir/test_iana_example': """
        import pytest
        try:
            from urllib.request import urlopen
        except ImportError:
            from urllib2 import urlopen

        @pytest.fixture
        def vcr(vcr):
            # Make sure that modifying the VCR instance does not break anything
            vcr.register_matcher('xx', lambda x: x)
            vcr.record_mode = vcr.record_mode
            return vcr

        @pytest.mark.vcr
        def test_disable_vcr_iana_marking():
            response = urlopen('http://www.iana.org/domains/reserved').read()
            assert b'Example domains' in response

        def test_disable_vcr_iana_fixture(vcr_cassette):
            response = urlopen('http://www.iana.org/domains/reserved').read()
            assert b'Example domains' in response

        def test_disable_vcr_iana_vcr(vcr):
            with vcr.use_cassette('test_disable_vcr_iana_vcr'):
                response = urlopen('http://www.iana.org/domains/reserved').read()
            assert b'Example domains' in response
    """})

    result = testdir.runpytest('--vcr-record=none', '-v')
    result.assert_outcomes(0, 0, 3)

    result = testdir.runpytest('--disable-vcr', '--vcr-record=none', '-v')
    result.assert_outcomes(3, 0, 0)

    cassette_dir_path = testdir.tmpdir.join('subdir', 'cassettes')
    assert not cassette_dir_path.check()

def test_disable_vcr_with_existing_cassette(testdir):
    testdir.makepyfile(**{'subdir/test_iana_example': """
        import pytest
        try:
            from urllib.request import urlopen
        except ImportError:
            from urllib2 import urlopen

        @pytest.fixture(scope='module')
        def vcr(vcr):
            # Make sure that modifying the VCR instance does not break anything
            vcr.register_matcher('xx', lambda x: x)
            vcr.record_mode = vcr.record_mode
            return vcr

        @pytest.mark.vcr
        def test_disable_vcr_iana_marking():
            response = urlopen('http://www.iana.org/domains/reserved').read()
            assert b'Example domains' in response

        def test_disable_vcr_iana_fixture(vcr_cassette):
            response = urlopen('http://www.iana.org/domains/reserved').read()
            assert b'Example domains' in response

        def test_disable_vcr_iana_vcr(vcr_cassette, vcr):
            with vcr.use_cassette('test_disable_vcr_iana_vcr'):
                response = urlopen('http://www.iana.org/domains/reserved').read()
            assert b'Example domains' in response
    """})

    cassette_content = '''
version: 1
interactions:
- request:
    body: null
    headers: {}
    method: GET
    uri: http://httpbin.org/ip
  response:
    body: {string: !!python/unicode "From cassette fixture"}
    headers: {}
    status: {code: 200, message: OK}'''

    cassette_dir_path = testdir.tmpdir.join('subdir', 'cassettes').mkdir()
    cassette_dir_path.join('test_disable_vcr_iana_marking.yaml').write(cassette_content)
    cassette_dir_path.join('test_disable_vcr_iana_fixture.yaml').write(cassette_content)
    cassette_dir_path.join('test_disable_vcr_iana_vcr.yaml').write(cassette_content)

    t0 = cassette_dir_path.join('test_disable_vcr_iana_marking.yaml').mtime()

    result = testdir.runpytest('--vcr-record=none', '-v')
    result.assert_outcomes(0, 0, 3)

    result = testdir.runpytest('--disable-vcr', '--vcr-record=none', '-v')
    result.assert_outcomes(3, 0, 0)

    t1 = cassette_dir_path.join('test_disable_vcr_iana_marking.yaml').mtime()
    # Check that the cassette file is unmodified
    assert t0 == t1

def test_custom_matchers(testdir):
    testdir.makepyfile("""
        import pytest
        try:
            from urllib.request import urlopen
        except ImportError:
            from urllib2 import urlopen

        @pytest.fixture(scope='module')
        def vcr(vcr):
            vcr.register_matcher('my_matcher', lambda a, b: True)
            vcr.match_on = ['my_matcher']
            return vcr

        @pytest.mark.vcr
        def test_custom_matchers_iana():
            response = urlopen('http://www.iana.org/domains/reserved').read()
            assert b'From cassette fixture' in response
    """)

    testdir.tmpdir.mkdir('cassettes').join('test_custom_matchers_iana.yaml') \
        .write('''
version: 1
interactions:
- request:
    body: null
    headers: {}
    method: GET
    uri: http://httpbin.org/ip
  response:
    body: {string: !!python/unicode "From cassette fixture"}
    headers: {}
    status: {code: 200, message: OK}''')

    result = testdir.runpytest('-v', '-s', '--vcr-record=none')
    assert result.ret == 0

def test_overriding_cassette_path(testdir):
    testdir.makepyfile("""
        import pytest, os

        @pytest.fixture(scope='module')
        def vcr_cassette_dir():
            return 'vhs'

        @pytest.fixture
        def vcr_cassette_name(vcr_cassette_dir, request, vcr_cassette_name):
            # Put all cassettes in vhs/{module}/{test}.yaml
            return os.path.join(vcr_cassette_dir, request.module.__name__, vcr_cassette_name)

        @pytest.mark.vcr
        def test_show_cassette(vcr_cassette):
            print("Cassette: {}".format(vcr_cassette._path))
    """)

    result = testdir.runpytest('-s')
    result.assert_outcomes(1, 0, 0)
    result.stdout.fnmatch_lines(['*Cassette: vhs/*/test_show_cassette.yaml'])

def test_cassette_name_for_classes(testdir):
    testdir.makepyfile("""
        import pytest

        @pytest.mark.vcr
        class TestClass:
            def test_method(self, vcr_cassette_name):
                print("Cassette: {}".format(vcr_cassette_name))
    """)

    result = testdir.runpytest('-s')
    result.stdout.fnmatch_lines(['*Cassette: TestClass.test_method'])

def test_vcr_config(testdir):
    testdir.makepyfile("""
        import pytest

        @pytest.fixture(scope='module')
        def vcr_config():
            return {'record_mode': 'none'}

        @pytest.mark.vcr
        def test_method(vcr_cassette):
            print("Cassette record mode: {}".format(vcr_cassette.record_mode))
    """)

    result = testdir.runpytest('-s')
    result.assert_outcomes(1, 0, 0)
    result.stdout.fnmatch_lines(['*Cassette record mode: none'])

def test_marker_options(testdir):
    testdir.makepyfile("""
        import pytest

        @pytest.fixture(scope='module')
        def vcr_config():
            return {'record_mode': 'all'}

        @pytest.mark.vcr(record_mode='none')
        def test_method(vcr_cassette):
            print("Cassette record mode: {}".format(vcr_cassette.record_mode))
    """)

    result = testdir.runpytest('-s')
    result.assert_outcomes(1, 0, 0)
    result.stdout.fnmatch_lines(['*Cassette record mode: none'])

def test_overriding_record_mode(testdir):
    testdir.makepyfile("""
        import pytest

        @pytest.fixture(scope='module')
        def vcr_config():
            return {'record_mode': 'none'}

        @pytest.mark.vcr(record_mode='once')
        def test_method(vcr_cassette, vcr):
            print("Cassette record mode: {}".format(vcr_cassette.record_mode))
    """)

    result = testdir.runpytest('-s', '--vcr-record', 'all')
    result.assert_outcomes(1, 0, 0)
    result.stdout.fnmatch_lines(['*Cassette record mode: all'])

def test_deprecated_record_mode(testdir):
    testdir.makepyfile("""
        import pytest

        @pytest.fixture(scope='module')
        def vcr_config():
            return {'record_mode': 'none'}

        @pytest.mark.vcr(record_mode='once')
        def test_method(vcr_cassette):
            print("Cassette record mode: {}".format(vcr_cassette.record_mode))
    """)

    result = testdir.runpytest('-s', '--vcr-record-mode', 'all')
    result.assert_outcomes(1, 0, 0)
    result.stdout.fnmatch_lines(['*Cassette record mode: all',
                                 '*--vcr-record-mode has been deprecated*'])

def test_marking_whole_class(testdir):
    testdir.makepyfile("""
        import pytest

        has_cassette = False

        @pytest.yield_fixture
        def vcr_cassette(vcr_cassette):
            global has_cassette
            has_cassette = True
            yield vcr_cassette
            has_cassette = False

        @pytest.mark.vcr
        class TestClass(object):
            def test_method(self):
                assert has_cassette
    """)

    result = testdir.runpytest('-s')
    assert result.ret == 0

def test_separate_cassettes_for_parametrized_tests(testdir):
    testdir.makepyfile("""
        import pytest

        @pytest.mark.vcr
        @pytest.mark.parametrize('arg', ['a', 'b'])
        def test_parameters(arg, vcr_cassette_name):
            assert vcr_cassette_name == 'test_parameters[{}]'.format(arg)
    """)

    result = testdir.runpytest('-s')
    assert result.ret == 0

def test_use_in_function_scope_fixture(testdir):
    """Test that the VCR instance can be used from fixtures and that the cassettes
    land in the correct location."""
    testdir.makepyfile(**{'subdir/test_iana_example': """
        import pytest
        try:
            from urllib.request import urlopen
        except ImportError:
            from urllib2 import urlopen

        @pytest.fixture
        def iana_response(vcr):
            with vcr.use_cassette('iana_response_fixture'):
                response = urlopen('http://www.iana.org/domains/reserved').read()
            return response

        def test_with_fixture(iana_response):
            assert b'Example domains' in iana_response
    """})

    result = testdir.runpytest('-v')
    result.assert_outcomes(1, 0, 0)

    cassette_path = testdir.tmpdir.join(
        'subdir', 'cassettes', 'iana_response_fixture.yaml')
    assert cassette_path.size() > 50

def test_use_in_module_scope_fixture(testdir):
    testdir.makepyfile(**{'subdir/test_iana_example': """
        import pytest
        try:
            from urllib.request import urlopen
        except ImportError:
            from urllib2 import urlopen

        @pytest.fixture(scope='module')
        def iana_response(vcr):
            with vcr.use_cassette('iana_response_fixture'):
                response = urlopen('http://www.iana.org/domains/reserved').read()
            return response

        def test_with_fixture(iana_response):
            assert b'Example domains' in iana_response
    """})

    result = testdir.runpytest('-v')
    result.assert_outcomes(1, 0, 0)

    cassette_path = testdir.tmpdir.join(
        'subdir', 'cassettes', 'iana_response_fixture.yaml')
    assert cassette_path.size() > 50

@pytest.mark.xfail(reason="session-scoped fixtures are not supported")
def test_use_in_session_scope_fixture(testdir):
    testdir.makepyfile(**{'subdir/test_iana_example': """
        import pytest
        try:
            from urllib.request import urlopen
        except ImportError:
            from urllib2 import urlopen

        @pytest.fixture(scope='session')
        def vcr_cassette_dir():
            test_dir = dirname(abspath(__file__))
            return os.path.join(test_dir, 'cassettes')

        @pytest.fixture(scope='session')
        def iana_response(vcr):
            with vcr.use_cassette('iana_response_fixture'):
                response = urlopen('http://www.iana.org/domains/reserved').read()
            return response

        def test_with_fixture(iana_response):
            assert b'Example domains' in iana_response
    """})

    result = testdir.runpytest('-v')
    result.assert_outcomes(1, 0, 0)

    cassette_path = testdir.tmpdir.join(
        'subdir', 'cassettes', 'iana_response_fixture.yaml')
    assert cassette_path.size() > 50

def test_help_message(testdir):
    result = testdir.runpytest(
        '--help',
    )
    # fnmatch_lines does an assertion internally
    result.stdout.fnmatch_lines([
        'vcr:',
        '*--vcr-record={*}',
    ])

def test_marker_message(testdir):
    result = testdir.runpytest('--markers')
    result.stdout.fnmatch_lines([
        '@pytest.mark.vcr: Mark the test as using VCR.py.',
    ])
<|endoftext|>