<commit_before>import unittest
import os
import sys
from shutil import rmtree
sys.path.insert(0, os.path.abspath('..'))

import clients

class ParseConfTest(unittest.TestCase):

    def setUp(self):
        self.conf = './tests/files/server.conf'

    def testNetmask(self):
        result = clients.parse_server(self.conf)['netmask']
        expected = '255.255.255.0'
        self.assertEqual(expected, result)

    def testIP(self):
        result = clients.parse_server(self.conf)['ip']
        expected = '10.0.0.0'
        self.assertEqual(expected, result)

    def testCCD(self):
        result = clients.parse_server(self.conf)['ccd']
        expected = '/etc/openvpn/clients'
        self.assertEqual(expected, result)

    def testAddresses(self):
        result = clients.parse_server(self.conf)['addresses']
        # 256 in a /24 minus the broadcast, network, and server addresses
        expected = 253
        self.assertEqual(expected, len(result))

class UsedIPsTest(unittest.TestCase):

    def setUp(self):
        self.ccd = './tests/files/ccd'
        os.makedirs(self.ccd)
        netmask = '255.255.255.0'
        for i in range(2, 12):
            s = str(i)
            name = 'client' + s
            ip = '192.168.1.' + s
            clients.new_client(name, ip, netmask, self.ccd)

    def testUsedIPs(self):
        result = clients.used_ips(self.ccd)
        expected = 10
        self.assertEqual(expected, len(result))

    def tearDown(self):
        rmtree(self.ccd)

class ThereAreNoClientsTest(unittest.TestCase):

    def setUp(self):
        self.ccd = './tests/files/ccd_empty'
        os.makedirs(self.ccd)
        self.conf = './tests/files/server.conf'

    def testThereAreNoClients(self):
        expected = '10.0.0.2'
        result = clients.next_available_ip(conf=self.conf, ccd=self.ccd)
        self.assertEqual(expected, result)

    def tearDown(self):
        rmtree(self.ccd)

class ClientsHaveAnOpeningTest(unittest.TestCase):

    def setUp(self):
        self.ccd = './tests/files/ccd'
        os.makedirs(self.ccd)
        self.conf = './tests/files/server.conf'
        netmask = clients.parse_server(self.conf)['netmask']
        for i in range(2, 13):
            s = str(i)
            name = 'client' + s
            ip = '10.0.0.' + s
            clients.new_client(name, ip, netmask, self.ccd)
        clients.new_client('client1', '10.0.0.129', netmask, self.ccd)

    def test(self):
        expected = '10.0.0.13'
        result = clients.next_available_ip(self.conf, self.ccd)
        self.assertEqual(expected, result)

    def tearDown(self):
        rmtree(self.ccd)

class ThereAreNoIpsAvailableTest(unittest.TestCase):

    def setUp(self):
        self.ccd = './tests/files/ccd'
        os.makedirs(self.ccd)
        self.conf = './tests/files/server.conf'
        netmask = clients.parse_server(self.conf)['netmask']
        for i in range(2, 255):
            s = str(i)
            name = 'client' + s
            ip = '10.0.0.' + s
            clients.new_client(name, ip, netmask, self.ccd)

    def test(self):
        err = clients.IPsSaturatedError
        self.assertRaises(err, clients.next_available_ip, self.conf, self.ccd)

    def tearDown(self):
        rmtree(self.ccd)

class NewClientTest(unittest.TestCase):

    def setUp(self):
        self.ccd = './tests/clients/ccd'
        os.makedirs(self.ccd)

    def testNewClient(self):
        ip = '10.0.0.2'
        netmask = '255.255.255.0'
        name = 'dummy'
        expected = {
            'name':    name,
            'ip':      ip,
            'netmask': netmask,
            }
        result = clients.new_client(name, ip, netmask, ccd=self.ccd)
        self.assertEqual(expected, result)

    def testDupClient(self):
        ip = '10.0.0.2'
        netmask = '255.255.255.0'
        name = 'dummy'
        clients.new_client(name, ip, netmask, self.ccd)
        err = clients.DuplicateClientError
        self.assertRaises(err, clients.new_client, name, ip, netmask, self.ccd)

    def tearDown(self):
        rmtree(self.ccd)

class ParseClientTest(unittest.TestCase):

    def setUp(self):
        self.ccd = './tests/clients/ccd'
        os.makedirs(self.ccd)
        self.ip = '10.0.0.2'
        self.netmask = '255.255.255.0'
        self.name = 'dummy'
        clients.new_client(self.name, self.ip, self.netmask, ccd=self.ccd)

    def test(self):
        result = clients.parse_client(self.name, ccd=self.ccd)
        expected = {
            'name':    self.name,
            'ip':      self.ip,
            'netmask': self.netmask,
            }
        self.assertEqual(expected, result)

    def tearDown(self):
        rmtree(self.ccd)

if __name__ == '__main__':
    unittest.main
<commit_msg>add passing no client parse_client test<commit_after>import unittest
import os
import sys
from shutil import rmtree
sys.path.insert(0, os.path.abspath('..'))

import clients

class ParseConfTest(unittest.TestCase):

    def setUp(self):
        self.conf = './tests/files/server.conf'

    def testNetmask(self):
        result = clients.parse_server(self.conf)['netmask']
        expected = '255.255.255.0'
        self.assertEqual(expected, result)

    def testIP(self):
        result = clients.parse_server(self.conf)['ip']
        expected = '10.0.0.0'
        self.assertEqual(expected, result)

    def testCCD(self):
        result = clients.parse_server(self.conf)['ccd']
        expected = '/etc/openvpn/clients'
        self.assertEqual(expected, result)

    def testAddresses(self):
        result = clients.parse_server(self.conf)['addresses']
        # 256 in a /24 minus the broadcast, network, and server addresses
        expected = 253
        self.assertEqual(expected, len(result))

class UsedIPsTest(unittest.TestCase):

    def setUp(self):
        self.ccd = './tests/files/ccd'
        os.makedirs(self.ccd)
        netmask = '255.255.255.0'
        for i in range(2, 12):
            s = str(i)
            name = 'client' + s
            ip = '192.168.1.' + s
            clients.new_client(name, ip, netmask, self.ccd)

    def testUsedIPs(self):
        result = clients.used_ips(self.ccd)
        expected = 10
        self.assertEqual(expected, len(result))

    def tearDown(self):
        rmtree(self.ccd)

class ThereAreNoClientsTest(unittest.TestCase):

    def setUp(self):
        self.ccd = './tests/files/ccd_empty'
        os.makedirs(self.ccd)
        self.conf = './tests/files/server.conf'

    def testThereAreNoClients(self):
        expected = '10.0.0.2'
        result = clients.next_available_ip(conf=self.conf, ccd=self.ccd)
        self.assertEqual(expected, result)

    def tearDown(self):
        rmtree(self.ccd)

class ClientsHaveAnOpeningTest(unittest.TestCase):

    def setUp(self):
        self.ccd = './tests/files/ccd'
        os.makedirs(self.ccd)
        self.conf = './tests/files/server.conf'
        netmask = clients.parse_server(self.conf)['netmask']
        for i in range(2, 13):
            s = str(i)
            name = 'client' + s
            ip = '10.0.0.' + s
            clients.new_client(name, ip, netmask, self.ccd)
        clients.new_client('client1', '10.0.0.129', netmask, self.ccd)

    def test(self):
        expected = '10.0.0.13'
        result = clients.next_available_ip(self.conf, self.ccd)
        self.assertEqual(expected, result)

    def tearDown(self):
        rmtree(self.ccd)

class ThereAreNoIpsAvailableTest(unittest.TestCase):

    def setUp(self):
        self.ccd = './tests/files/ccd'
        os.makedirs(self.ccd)
        self.conf = './tests/files/server.conf'
        netmask = clients.parse_server(self.conf)['netmask']
        for i in range(2, 255):
            s = str(i)
            name = 'client' + s
            ip = '10.0.0.' + s
            clients.new_client(name, ip, netmask, self.ccd)

    def test(self):
        err = clients.IPsSaturatedError
        self.assertRaises(err, clients.next_available_ip, self.conf, self.ccd)

    def tearDown(self):
        rmtree(self.ccd)

class NewClientTest(unittest.TestCase):

    def setUp(self):
        self.ccd = './tests/clients/ccd'
        os.makedirs(self.ccd)

    def testNewClient(self):
        ip = '10.0.0.2'
        netmask = '255.255.255.0'
        name = 'dummy'
        expected = {
            'name':    name,
            'ip':      ip,
            'netmask': netmask,
            }
        result = clients.new_client(name, ip, netmask, ccd=self.ccd)
        self.assertEqual(expected, result)

    def testDupClient(self):
        ip = '10.0.0.2'
        netmask = '255.255.255.0'
        name = 'dummy'
        clients.new_client(name, ip, netmask, self.ccd)
        err = clients.DuplicateClientError
        self.assertRaises(err, clients.new_client, name, ip, netmask, self.ccd)

    def tearDown(self):
        rmtree(self.ccd)

class ParseClientTest(unittest.TestCase):

    def setUp(self):
        self.ccd = './tests/clients/ccd'
        os.makedirs(self.ccd)
        self.ip = '10.0.0.2'
        self.netmask = '255.255.255.0'
        self.name = 'dummy'
        clients.new_client(self.name, self.ip, self.netmask, ccd=self.ccd)

    def test(self):
        result = clients.parse_client(self.name, ccd=self.ccd)
        expected = {
            'name':    self.name,
            'ip':      self.ip,
            'netmask': self.netmask,
            }
        self.assertEqual(expected, result)

    def tearDown(self):
        rmtree(self.ccd)

class NoClientParseClientTest(unittest.TestCase):

    def test(self):
        name = 'does_not_exist'
        ccd = './tests/files/ccd'
        err = FileNotFoundError
        self.assertRaises(err, clients.parse_client, name, ccd)

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


<commit_before>import unittest
from solution import *

class Test_235_Intermediate(unittest.TestCase):
    def test_calculate_score(self):
        pass

if __name__ == "__main__":
    unittest.main()<commit_msg>Updated solution for challenge 235 Intermediate<commit_after>import unittest
from solution import *

class Test_235_Intermediate(unittest.TestCase):
    def test_calculate_score(self):
        self.assertEqual(calculate_score(['X', 'X', 'X' 'X', 'X', 'X', 'X', 'X', 'X', 'XXX']), 300)
        self.assertEqual(calculate_score(['X', '-/', 'X' '5-', '8/', '9-', 'X', '81', '1-', '4/X']), 137)
        self.assertEqual(calculate_score(['62', '71', 'X' '9-', '8/', 'X', 'X', '35', '72', '5/8']), 140)

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


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

'''
Active Archives Markdown init function
======================================
It gathers the various AA Extensions for Python-Markdown

Requires Python-Markdown 2.0+.
'''

import markdown
import mdx_semanticwikilinks
import mdx_semanticdata
import mdx_sectionedit
import mdx_addsections
import mdx_addsectionstoolbar
import mdx_timecodes
from aacore.utils import url_for_pagename
import urlparse

def make_link(rel, target, label, default_link_rel=None):
    """
    Custom implementation of the SemanticWikilinks make_link function.
    Returns ElementTree Element.
    """
    a = markdown.util.etree.Element('a')
    parts = urlparse.urlparse(target)
    if parts.scheme:
        href = target
    else:
        href = url_for_pagename(target)
    a.set('href', href)
    a.text = label or target
    if rel:
        a.set('rel', rel)
    elif default_link_rel:
        a.set('rel', default_link_rel)

    return a

#"""
#
#
#            this anthology
#
#
#
#"""
#def make_link (rel, target, label, default_link_rel=None):
#    """ More semantically complete version, asserts linktarget and label (if different) via nested spans. """
#    a = markdown.etree.Element('a')
#    href = url_for_pagename(target)
#    a.set('href', href)

#    if rel:
#        a.set('rel', rel)
#    elif default_link_rel:
#        a.set('rel', default_link_rel)

#    label = label or target
#    span = markdown.etree.Element('span')
#    span.set('about', href)
#    a.append(span)

#    if label != target:
#        label_span = markdown.etree.Element('span')
#        label_span.set("property", "aa:linklabel")
#        label_span.text = label
#        span.append(label_span)

#        target_span = markdown.etree.Element('span')
#        target_span.set("property", "aa:linktarget")
#        target_span.set("content", target)
#        span.append(target_span)
#    else:
#        # Only include aa:linktarget
#        target_span = markdown.etree.Element('span')
#        target_span.set("property", "aa:linktarget")
#        target_span.text = target
#        span.append(target_span)

#    return a

def get_markdown(default_link_rel = "aa:link"):
    """
    This is a function to return a Active Archive markdown instance.
    Returns a Markdown instance.
    """
    return markdown.Markdown(extensions=[
            "extra",
            "meta",
            "toc",
            mdx_semanticwikilinks.makeExtension(configs=[
                ('make_link', make_link),
                ('default_link_rel', default_link_rel)]),
            mdx_semanticdata.makeExtension(),
            mdx_timecodes.makeExtension(),
            # mdx_sectionedit.makeExtension(),
            mdx_addsections.makeExtension(configs=[('class','section%(LEVEL)d'),]),
            # mdx_addsectionstoolbar.makeExtension(),
            ],
        )

def get_simple_markdown(default_link_rel = "aa:link"):
    """
    This is a function to return a Active Archive markdown instance.
    Returns a Markdown instance.
    """
    return markdown.Markdown(extensions=[
            "extra",
            "meta",
            "toc",
            mdx_semanticwikilinks.makeExtension(configs=[
                ('make_link', make_link),
                ('default_link_rel', default_link_rel)]),
            mdx_semanticdata.makeExtension(),
            ],
        )

if __name__ == "__main__":
    import doctest
    doctest.testmod()

<commit_msg>Changed markdown export format to HTML5<commit_after>#! /usr/bin/env python2

'''
Active Archives Markdown init function
======================================
It gathers the various AA Extensions for Python-Markdown

Requires Python-Markdown 2.0+.
'''

import markdown
import mdx_semanticwikilinks
import mdx_semanticdata
import mdx_sectionedit
import mdx_addsections
import mdx_addsectionstoolbar
import mdx_timecodes
from aacore.utils import url_for_pagename
import urlparse

def make_link(rel, target, label, default_link_rel=None):
    """
    Custom implementation of the SemanticWikilinks make_link function.
    Returns ElementTree Element.
    """
    a = markdown.util.etree.Element('a')
    parts = urlparse.urlparse(target)
    if parts.scheme:
        href = target
    else:
        href = url_for_pagename(target)
    a.set('href', href)
    a.text = label or target
    if rel:
        a.set('rel', rel)
    elif default_link_rel:
        a.set('rel', default_link_rel)

    return a

#"""
#
#
#            this anthology
#
#
#
#"""
#def make_link (rel, target, label, default_link_rel=None):
#    """ More semantically complete version, asserts linktarget and label (if different) via nested spans. """
#    a = markdown.etree.Element('a')
#    href = url_for_pagename(target)
#    a.set('href', href)

#    if rel:
#        a.set('rel', rel)
#    elif default_link_rel:
#        a.set('rel', default_link_rel)

#    label = label or target
#    span = markdown.etree.Element('span')
#    span.set('about', href)
#    a.append(span)

#    if label != target:
#        label_span = markdown.etree.Element('span')
#        label_span.set("property", "aa:linklabel")
#        label_span.text = label
#        span.append(label_span)

#        target_span = markdown.etree.Element('span')
#        target_span.set("property", "aa:linktarget")
#        target_span.set("content", target)
#        span.append(target_span)
#    else:
#        # Only include aa:linktarget
#        target_span = markdown.etree.Element('span')
#        target_span.set("property", "aa:linktarget")
#        target_span.text = target
#        span.append(target_span)

#    return a

def get_markdown(default_link_rel = "aa:link"):
    """
    This is a function to return a Active Archive markdown instance.
    Returns a Markdown instance.
    """
    return markdown.Markdown(output_format="html5", extensions=[
            "extra",
            "meta",
            "toc",
            mdx_semanticwikilinks.makeExtension(configs=[
                ('make_link', make_link),
                ('default_link_rel', default_link_rel)]),
            mdx_semanticdata.makeExtension(),
            mdx_timecodes.makeExtension(),
            # mdx_sectionedit.makeExtension(),
            mdx_addsections.makeExtension(configs=[('class','section%(LEVEL)d'),]),
            # mdx_addsectionstoolbar.makeExtension(),
            ],
        )

def get_simple_markdown(default_link_rel = "aa:link"):
    """
    This is a function to return a Active Archive markdown instance.
    Returns a Markdown instance.
    """
    return markdown.Markdown(output_format="html5", extensions=[
            "extra",
            "meta",
            "toc",
            mdx_semanticwikilinks.makeExtension(configs=[
                ('make_link', make_link),
                ('default_link_rel', default_link_rel)]),
            mdx_semanticdata.makeExtension(),
            ],
        )

if __name__ == "__main__":
    import doctest
    doctest.testmod()

<|endoftext|>


<commit_before>import unittest

from cassandra.cluster import Cluster

class ClusterTests(unittest.TestCase):

    def testBasic(self):
        cluster = Cluster()
        session = cluster.connect()
        result = session.execute(
            """
            CREATE KEYSPACE clustertests
            WITH replication = {'class': 'SimpleStrategy', 'replication_factor': '1'}
            """)
        self.assertEquals(None, result)

        result = session.execute(
            """
            CREATE TABLE clustertests.cf0 (
                a text,
                b text,
                c text,
                PRIMARY KEY (a, b)
            )
            """)
        self.assertEquals(None, result)

        result = session.execute(
            """
            INSERT INTO clustertests.cf0 (a, b, c) VALUES ('a', 'b', 'c')
            """)
        self.assertEquals(None, result)

        result = session.execute("SELECT * FROM clustertests.cf0")
        self.assertEquals([{'a': 'a', 'b': 'b', 'c': 'c'}], result)

        cluster.shutdown()
<commit_msg>Add test for submit_schema_refresh<commit_after>import unittest

from cassandra.cluster import Cluster

class ClusterTests(unittest.TestCase):

    def test_basic(self):
        cluster = Cluster()
        session = cluster.connect()
        result = session.execute(
            """
            CREATE KEYSPACE clustertests
            WITH replication = {'class': 'SimpleStrategy', 'replication_factor': '1'}
            """)
        self.assertEquals(None, result)

        result = session.execute(
            """
            CREATE TABLE clustertests.cf0 (
                a text,
                b text,
                c text,
                PRIMARY KEY (a, b)
            )
            """)
        self.assertEquals(None, result)

        result = session.execute(
            """
            INSERT INTO clustertests.cf0 (a, b, c) VALUES ('a', 'b', 'c')
            """)
        self.assertEquals(None, result)

        result = session.execute("SELECT * FROM clustertests.cf0")
        self.assertEquals([{'a': 'a', 'b': 'b', 'c': 'c'}], result)

        cluster.shutdown()

    def test_submit_schema_refresh(self):
        cluster = Cluster()
        cluster.connect()

        other_cluster = Cluster()
        session = other_cluster.connect()
        session.execute(
            """
            CREATE KEYSPACE newkeyspace WITH replication = {'class': 'SimpleStrategy', 'replication_factor': '1'}
            """)

        self.assertNotIn("newkeyspace", cluster.metadata.keyspaces)

        future = cluster.submit_schema_refresh()
        future.result()

        self.assertIn("newkeyspace", cluster.metadata.keyspaces)
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
"""
    Command line test
    ~~~~~~~~~~~~~~~~~

    :copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS.
    :license: BSD, see LICENSE for details.
"""

from __future__ import print_function

import io
import os
import sys
import tempfile
import unittest

from pygments import highlight
from pygments.util import StringIO, BytesIO
from pygments.cmdline import main as cmdline_main

import support

TESTFILE, TESTDIR = support.location(__file__)

def run_cmdline(*args):
    saved_stdout = sys.stdout
    saved_stderr = sys.stderr
    if sys.version_info > (3,):
        stdout_buffer = BytesIO()
        stderr_buffer = BytesIO()
        new_stdout = sys.stdout = io.TextIOWrapper(stdout_buffer, 'utf-8')
        new_stderr = sys.stderr = io.TextIOWrapper(stderr_buffer, 'utf-8')
    else:
        stdout_buffer = new_stdout = sys.stdout = StringIO()
        stderr_buffer = new_stderr = sys.stderr = StringIO()
    try:
        ret = cmdline_main(["pygmentize"] + list(args))
    finally:
        sys.stdout = saved_stdout
        sys.stderr = saved_stderr
    new_stdout.flush()
    new_stderr.flush()
    out, err = stdout_buffer.getvalue().decode('utf-8'), \
        stderr_buffer.getvalue().decode('utf-8')
    return (ret, out, err)

def run_cmdline_with_closed_stdout(*args):
    saved_stdout, saved_stderr = sys.stdout, sys.stderr
    sys.stdout, sys.stderr = StringIO(), StringIO()
    sys.stdout.buffer = sys.stdout
    sys.stdout.close()
    try:
        ret = cmdline_main(['pygmentize'] + list(args))
        err = sys.stderr.getvalue()
    finally:
        sys.stdout, sys.stderr = saved_stdout, saved_stderr
    return ret, err

class CmdLineTest(unittest.TestCase):

    def test_L_opt(self):
        c, o, e = run_cmdline("-L")
        self.assertEqual(c, 0)
        self.assertTrue("Lexers" in o and "Formatters" in o and
                        "Filters" in o and "Styles" in o)
        c, o, e = run_cmdline("-L", "lexer")
        self.assertEqual(c, 0)
        self.assertTrue("Lexers" in o and "Formatters" not in o)
        c, o, e = run_cmdline("-L", "lexers")
        self.assertEqual(c, 0)

    def test_O_opt(self):
        filename = TESTFILE
        c, o, e = run_cmdline("-Ofull=1,linenos=true,foo=bar",
                              "-fhtml", filename)
        self.assertEqual(c, 0)
        self.assertTrue("<html" in o)
        self.assertTrue('class="linenos"' in o)

    def test_P_opt(self):
        filename = TESTFILE
        c, o, e = run_cmdline("-Pfull", "-Ptitle=foo, bar=baz=,",
                              "-fhtml", filename)
        self.assertEqual(c, 0)
        self.assertTrue("<title>foo, bar=baz=,</title>" in o)

    def test_F_opt(self):
        filename = TESTFILE
        c, o, e = run_cmdline("-Fhighlight:tokentype=Name.Blubb,"
                              "names=TESTFILE filename",
                              "-fhtml", filename)
        self.assertEqual(c, 0)
        self.assertTrue('<span class="n-Blubb' in o)

    def test_H_opt(self):
        c, o, e = run_cmdline("-H", "formatter", "html")
        self.assertEqual(c, 0)
        self.assertTrue('HTML' in o)

    def test_S_opt(self):
        c, o, e = run_cmdline("-S", "default", "-f", "html", "-O", "linenos=1")
        self.assertEqual(c, 0)

    def test_invalid_opts(self):
        for opts in [("-L", "-lpy"), ("-L", "-fhtml"), ("-L", "-Ox"),
                     ("-a",), ("-Sst", "-lpy"), ("-H",),
                     ("-H", "formatter")]:
            self.assertTrue(run_cmdline(*opts)[0] == 2)

    def test_normal(self):
        # test that cmdline gives the same output as library api
        from pygments.lexers import PythonLexer
        from pygments.formatters import HtmlFormatter
        filename = TESTFILE
        with open(filename, 'rb') as fp:
            code = fp.read()

        output = highlight(code, PythonLexer(), HtmlFormatter())

        c, o, e = run_cmdline("-lpython", "-fhtml", filename)

        self.assertEqual(o, output)
        self.assertEqual(e, "")
        self.assertEqual(c, 0)

    def test_outfile(self):
        # test that output file works with and without encoding
        fd, name = tempfile.mkstemp()
        os.close(fd)
        for opts in [['-fhtml', '-o', name, TESTFILE],
                     ['-flatex', '-o', name, TESTFILE],
                     ['-fhtml', '-o', name, '-O', 'encoding=utf-8', TESTFILE]]:
            try:
                self.assertEqual(run_cmdline(*opts)[0], 0)
            finally:
                os.unlink(name)

    def check_failure(self, *cmdline):
        c, o, e = run_cmdline(*cmdline)
        self.assertEqual(c, 1)
        self.assertEqual(o, '')
        return e

    def test_errors(self):
        # input file not found
        e = self.check_failure('-lpython', 'nonexistent.py')
        self.assertIn('Error: cannot read infile', e)
        self.assertIn('nonexistent.py', e)

        # lexer not found
        e = self.check_failure('-lfooo', TESTFILE)
        self.assertIn('Error: no lexer for alias', e)

        # formatter not found
        e = self.check_failure('-lpython', '-ffoo', TESTFILE)
        self.assertIn('Error: no formatter found for name', e)

        # output file not writable
        e = self.check_failure('-o', os.path.join('nonexistent', 'dir', 'out.html'),
                               '-lpython', TESTFILE)
        self.assertIn('Error: cannot open outfile', e)
        self.assertIn('out.html', e)

        # unknown filter
        e = self.check_failure('-F', 'foo', TESTFILE)
        self.assertIn('Error: filter \'foo\' not found', e)

    def test_exception(self):
        # unexpected exception while highlighting
        # (we can force that by closing stdout)
        c, e = run_cmdline_with_closed_stdout('-lpython', TESTFILE)
        self.assertEqual(c, 1)
        self.assertIn('*** Error while highlighting:', e)
<commit_msg>Fix use of test methods not in 2.6.<commit_after># -*- coding: utf-8 -*-
"""
    Command line test
    ~~~~~~~~~~~~~~~~~

    :copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS.
    :license: BSD, see LICENSE for details.
"""

from __future__ import print_function

import io
import os
import sys
import tempfile
import unittest

from pygments import highlight
from pygments.util import StringIO, BytesIO
from pygments.cmdline import main as cmdline_main

import support

TESTFILE, TESTDIR = support.location(__file__)

def run_cmdline(*args):
    saved_stdout = sys.stdout
    saved_stderr = sys.stderr
    if sys.version_info > (3,):
        stdout_buffer = BytesIO()
        stderr_buffer = BytesIO()
        new_stdout = sys.stdout = io.TextIOWrapper(stdout_buffer, 'utf-8')
        new_stderr = sys.stderr = io.TextIOWrapper(stderr_buffer, 'utf-8')
    else:
        stdout_buffer = new_stdout = sys.stdout = StringIO()
        stderr_buffer = new_stderr = sys.stderr = StringIO()
    try:
        ret = cmdline_main(["pygmentize"] + list(args))
    finally:
        sys.stdout = saved_stdout
        sys.stderr = saved_stderr
    new_stdout.flush()
    new_stderr.flush()
    out, err = stdout_buffer.getvalue().decode('utf-8'), \
        stderr_buffer.getvalue().decode('utf-8')
    return (ret, out, err)

def run_cmdline_with_closed_stdout(*args):
    saved_stdout, saved_stderr = sys.stdout, sys.stderr
    sys.stdout, sys.stderr = StringIO(), StringIO()
    sys.stdout.buffer = sys.stdout
    sys.stdout.close()
    try:
        ret = cmdline_main(['pygmentize'] + list(args))
        err = sys.stderr.getvalue()
    finally:
        sys.stdout, sys.stderr = saved_stdout, saved_stderr
    return ret, err

class CmdLineTest(unittest.TestCase):

    def test_L_opt(self):
        c, o, e = run_cmdline("-L")
        self.assertEqual(c, 0)
        self.assertTrue("Lexers" in o and "Formatters" in o and
                        "Filters" in o and "Styles" in o)
        c, o, e = run_cmdline("-L", "lexer")
        self.assertEqual(c, 0)
        self.assertTrue("Lexers" in o and "Formatters" not in o)
        c, o, e = run_cmdline("-L", "lexers")
        self.assertEqual(c, 0)

    def test_O_opt(self):
        filename = TESTFILE
        c, o, e = run_cmdline("-Ofull=1,linenos=true,foo=bar",
                              "-fhtml", filename)
        self.assertEqual(c, 0)
        self.assertTrue("<html" in o)
        self.assertTrue('class="linenos"' in o)

    def test_P_opt(self):
        filename = TESTFILE
        c, o, e = run_cmdline("-Pfull", "-Ptitle=foo, bar=baz=,",
                              "-fhtml", filename)
        self.assertEqual(c, 0)
        self.assertTrue("<title>foo, bar=baz=,</title>" in o)

    def test_F_opt(self):
        filename = TESTFILE
        c, o, e = run_cmdline("-Fhighlight:tokentype=Name.Blubb,"
                              "names=TESTFILE filename",
                              "-fhtml", filename)
        self.assertEqual(c, 0)
        self.assertTrue('<span class="n-Blubb' in o)

    def test_H_opt(self):
        c, o, e = run_cmdline("-H", "formatter", "html")
        self.assertEqual(c, 0)
        self.assertTrue('HTML' in o)

    def test_S_opt(self):
        c, o, e = run_cmdline("-S", "default", "-f", "html", "-O", "linenos=1")
        self.assertEqual(c, 0)

    def test_invalid_opts(self):
        for opts in [("-L", "-lpy"), ("-L", "-fhtml"), ("-L", "-Ox"),
                     ("-a",), ("-Sst", "-lpy"), ("-H",),
                     ("-H", "formatter")]:
            self.assertTrue(run_cmdline(*opts)[0] == 2)

    def test_normal(self):
        # test that cmdline gives the same output as library api
        from pygments.lexers import PythonLexer
        from pygments.formatters import HtmlFormatter
        filename = TESTFILE
        with open(filename, 'rb') as fp:
            code = fp.read()

        output = highlight(code, PythonLexer(), HtmlFormatter())

        c, o, e = run_cmdline("-lpython", "-fhtml", filename)

        self.assertEqual(o, output)
        self.assertEqual(e, "")
        self.assertEqual(c, 0)

    def test_outfile(self):
        # test that output file works with and without encoding
        fd, name = tempfile.mkstemp()
        os.close(fd)
        for opts in [['-fhtml', '-o', name, TESTFILE],
                     ['-flatex', '-o', name, TESTFILE],
                     ['-fhtml', '-o', name, '-O', 'encoding=utf-8', TESTFILE]]:
            try:
                self.assertEqual(run_cmdline(*opts)[0], 0)
            finally:
                os.unlink(name)

    def check_failure(self, *cmdline):
        c, o, e = run_cmdline(*cmdline)
        self.assertEqual(c, 1)
        self.assertEqual(o, '')
        return e

    def test_errors(self):
        # input file not found
        e = self.check_failure('-lpython', 'nonexistent.py')
        self.assertTrue('Error: cannot read infile' in e)
        self.assertTrue('nonexistent.py' in e)

        # lexer not found
        e = self.check_failure('-lfooo', TESTFILE)
        self.assertTrue('Error: no lexer for alias' in e)

        # formatter not found
        e = self.check_failure('-lpython', '-ffoo', TESTFILE)
        self.assertTrue('Error: no formatter found for name' in e)

        # output file not writable
        e = self.check_failure('-o', os.path.join('nonexistent', 'dir', 'out.html'),
                               '-lpython', TESTFILE)
        self.assertTrue('Error: cannot open outfile' in e)
        self.assertTrue('out.html' in e)

        # unknown filter
        e = self.check_failure('-F', 'foo', TESTFILE)
        self.assertTrue('Error: filter \'foo\' not found' in e)

    def test_exception(self):
        # unexpected exception while highlighting
        # (we can force that by closing stdout)
        c, e = run_cmdline_with_closed_stdout('-lpython', TESTFILE)
        self.assertEqual(c, 1)
        self.assertTrue('*** Error while highlighting:' in e)
<|endoftext|>


<commit_before>import tox
import py

pytest_plugins = "pytester"

from tox._cmdline import Session
from tox._config import parseconfig

class TestSession:
    def test_make_sdist(self, initproj):
        initproj("example123-0.5", filedefs={
            'tests': {'test_hello.py': "def test_hello(): pass"},
            'tox.ini': '''
            '''
        })
        config = parseconfig([])
        session = Session(config)
        sdist = session.get_fresh_sdist()
        assert sdist.check()
        assert sdist == config.toxworkdir.join("dist", sdist.basename)
        sdist2 = session.get_fresh_sdist()
        assert sdist2 == sdist
        sdist.write("hello")
        assert sdist.stat().size < 10
        sdist_new = Session(config).get_fresh_sdist()
        assert sdist_new == sdist
        assert sdist_new.stat().size > 10

    def test_log_pcall(self, initproj, tmpdir, capfd):
        initproj("logexample123-0.5", filedefs={
            'tests': {'test_hello.py': "def test_hello(): pass"},
            'tox.ini': '''
            '''
        })
        config = parseconfig([])
        session = Session(config)
        assert not session.config.logdir.listdir()
        opts = {}
        capfd.readouterr()
        session.report.popen(["ls", ], log=None, opts=opts)
        out, err = capfd.readouterr()
        assert '0.log' in out
        assert 'stdout' in opts
        assert opts['stdout'].write
        assert opts['stderr'] == py.std.subprocess.STDOUT
        x = opts['stdout'].name
        assert x.startswith(str(session.config.logdir))

        opts={}
        session.report.popen(["ls", ], log=None, opts=opts)
        out, err = capfd.readouterr()
        assert '1.log' in out

        opts={}
        newlogdir = tmpdir.mkdir("newlogdir")
        cwd = newlogdir.dirpath()
        cwd.chdir()
        session.report.popen(["xyz",], log=newlogdir, opts=opts)
        l = newlogdir.listdir()
        assert len(l) == 1
        assert l[0].basename == "0.log"
        out, err = capfd.readouterr()
        relpath = l[0].relto(cwd)
        expect = ">%s/0.log" % (newlogdir.basename)
        assert expect in out

    def test_summary_status(self, initproj, capfd):
        initproj("logexample123-0.5", filedefs={
            'tests': {'test_hello.py': "def test_hello(): pass"},
            'tox.ini': '''
            [testenv:hello]
            [testenv:world]
            '''
        })
        config = parseconfig([])
        session = Session(config)
        envlist = ['hello', 'world']
        envs = session.venvlist
        assert len(envs) == 2
        env1, env2 = envs
        session.setenvstatus(env1, "FAIL XYZ")
        assert session.venvstatus[env1.path]
        session.setenvstatus(env2, 0)
        assert not session.venvstatus[env2.path]
        session._summary()
        out, err = capfd.readouterr()
        exp = "%s: FAIL XYZ" % env1.envconfig.envname
        assert exp in out
        exp = "%s: commands succeeded" % env2.envconfig.envname
        assert exp in out

# not sure we want this option ATM
def XXX_test_package(cmd, initproj):
    initproj("myproj-0.6", filedefs={
        'tests': {'test_hello.py': "def test_hello(): pass"},
        'MANIFEST.in': """
            include doc
            include myproj
            """,
        'tox.ini': ''
    })
    result = cmd.run("tox", "package")
    assert not result.ret
    result.stdout.fnmatch_lines([
        "*created sdist package at*",
    ])

def test_unknown_interpreter(cmd, initproj):
    initproj("interp123-0.5", filedefs={
        'tests': {'test_hello.py': "def test_hello(): pass"},
        'tox.ini': '''
            [testenv:python]
            basepython=xyz_unknown_interpreter
            [testenv]
            changedir=tests
        '''
    })
    result = cmd.run("tox")
    assert not result.ret
    result.stdout.fnmatch_lines([
        "*ERROR*InterpreterNotFound*xyz_unknown_interpreter*",
    ])

def test_unknown_dep(cmd, initproj):
    initproj("dep123-0.7", filedefs={
        'tests': {'test_hello.py': "def test_hello(): pass"},
        'tox.ini': '''
            [testenv]
            deps=qweqwe123
            changedir=tests
        '''
    })
    result = cmd.run("tox", )
    assert not result.ret
    result.stdout.fnmatch_lines([
        "*ERROR*could not install*qweqwe123*",
    ])

def test_unknown_environment(cmd, initproj):
    initproj("env123-0.7", filedefs={
        'tox.ini': ''
    })
    result = cmd.run("tox", "-e", "qpwoei")
    assert result.ret
    result.stdout.fnmatch_lines([
        "*ERROR*unknown*environment*qpwoei*",
    ])

def test_sdist_fails(cmd, initproj):
    initproj("pkg123-0.7", filedefs={
        'tests': {'test_hello.py': "def test_hello(): pass"},
        'setup.py': """
            syntax error
        """
        ,
        'tox.ini': '',
    })
    result = cmd.run("tox", )
    assert result.ret
    result.stdout.fnmatch_lines([
        "*FAIL*could not package project*",
    ])

def test_package_install_fails(cmd, initproj):
    initproj("pkg123-0.7", filedefs={
        'tests': {'test_hello.py': "def test_hello(): pass"},
        'setup.py': """
            from setuptools import setup
            setup(
                name='pkg123',
                description='pkg123 project',
                version='0.7',
                license='GPLv2 or later',
                platforms=['unix', 'win32'],
                packages=['pkg123',],
                install_requires=['qweqwe123'],
                )
            """
        ,
        'tox.ini': '',
    })
    result = cmd.run("tox", )
    assert not result.ret
    result.stdout.fnmatch_lines([
        "*FAIL*could not install package*",
    ])

def test_test_simple(cmd, initproj):
    initproj("example123-0.5", filedefs={
        'tests': {'test_hello.py': """
            def test_hello(pytestconfig):
                pytestconfig.mktemp("hello")
            """,
        },
        'tox.ini': '''
            [testenv]
            changedir=tests
            commands=
                py.test --basetemp={envtmpdir} --junitxml=junit-{envname}.xml []
            deps=py
        '''
    })
    result = cmd.run("tox")
    assert not result.ret
    result.stdout.fnmatch_lines([
        "*junit-python.xml*",
        "*1 passed*",
    ])
    result = cmd.run("tox", "--env=python", )
    assert not result.ret
    result.stdout.fnmatch_lines([
        "*1 passed*",
        "*summary*",
        "*python: commands succeeded"
    ])
    # see that things work with a different CWD
    cmd.tmpdir.chdir()
    result = cmd.run("tox", "-c", "example123/tox.ini")
    assert not result.ret
    result.stdout.fnmatch_lines([
        "*1 passed*",
        "*summary*",
        "*python: commands succeeded"
    ])

def test_test_piphelp(initproj, cmd):
    initproj("example123", filedefs={'tox.ini': """
        # content of: tox.ini
        [testenv]
        commands=pip -h
        [testenv:py25]
        basepython=python2.5
        [testenv:py26]
        basepython=python2.6
    """})
    result = cmd.run("tox")
    assert not result.ret

def test_notest(initproj, cmd):
    initproj("example123", filedefs={'tox.ini': """
        # content of: tox.ini
        [testenv:py25]
        basepython=python2.5
        [testenv:py26]
        basepython=python2.6
    """})
    result = cmd.run("tox", "--notest")
    assert not result.ret
    assert "tox summary" not in result.stdout.str()
    result = cmd.run("tox", "--notest", "--env=py25")
    assert not result.ret
    result.stdout.fnmatch_lines([
        "*reusing*py25",
    ])
    result = cmd.run("tox", "--notest", "--env=py25,py26")
    assert not result.ret
    result.stdout.fnmatch_lines([
        "*reusing*py25",
        "*reusing*py26",
    ])

<commit_msg>fix test on windows<commit_after>import tox
import py

pytest_plugins = "pytester"

from tox._cmdline import Session
from tox._config import parseconfig

class TestSession:
    def test_make_sdist(self, initproj):
        initproj("example123-0.5", filedefs={
            'tests': {'test_hello.py': "def test_hello(): pass"},
            'tox.ini': '''
            '''
        })
        config = parseconfig([])
        session = Session(config)
        sdist = session.get_fresh_sdist()
        assert sdist.check()
        assert sdist == config.toxworkdir.join("dist", sdist.basename)
        sdist2 = session.get_fresh_sdist()
        assert sdist2 == sdist
        sdist.write("hello")
        assert sdist.stat().size < 10
        sdist_new = Session(config).get_fresh_sdist()
        assert sdist_new == sdist
        assert sdist_new.stat().size > 10

    def test_log_pcall(self, initproj, tmpdir, capfd):
        initproj("logexample123-0.5", filedefs={
            'tests': {'test_hello.py': "def test_hello(): pass"},
            'tox.ini': '''
            '''
        })
        config = parseconfig([])
        session = Session(config)
        assert not session.config.logdir.listdir()
        opts = {}
        capfd.readouterr()
        session.report.popen(["ls", ], log=None, opts=opts)
        out, err = capfd.readouterr()
        assert '0.log' in out
        assert 'stdout' in opts
        assert opts['stdout'].write
        assert opts['stderr'] == py.std.subprocess.STDOUT
        x = opts['stdout'].name
        assert x.startswith(str(session.config.logdir))

        opts={}
        session.report.popen(["ls", ], log=None, opts=opts)
        out, err = capfd.readouterr()
        assert '1.log' in out

        opts={}
        newlogdir = tmpdir.mkdir("newlogdir")
        cwd = newlogdir.dirpath()
        cwd.chdir()
        session.report.popen(["xyz",], log=newlogdir, opts=opts)
        l = newlogdir.listdir()
        assert len(l) == 1
        assert l[0].basename == "0.log"
        out, err = capfd.readouterr()
        relpath = l[0].relto(cwd)
        expect = ">%s%s0.log" % (newlogdir.basename, newlogdir.sep)
        assert expect in out

    def test_summary_status(self, initproj, capfd):
        initproj("logexample123-0.5", filedefs={
            'tests': {'test_hello.py': "def test_hello(): pass"},
            'tox.ini': '''
            [testenv:hello]
            [testenv:world]
            '''
        })
        config = parseconfig([])
        session = Session(config)
        envlist = ['hello', 'world']
        envs = session.venvlist
        assert len(envs) == 2
        env1, env2 = envs
        session.setenvstatus(env1, "FAIL XYZ")
        assert session.venvstatus[env1.path]
        session.setenvstatus(env2, 0)
        assert not session.venvstatus[env2.path]
        session._summary()
        out, err = capfd.readouterr()
        exp = "%s: FAIL XYZ" % env1.envconfig.envname
        assert exp in out
        exp = "%s: commands succeeded" % env2.envconfig.envname
        assert exp in out

# not sure we want this option ATM
def XXX_test_package(cmd, initproj):
    initproj("myproj-0.6", filedefs={
        'tests': {'test_hello.py': "def test_hello(): pass"},
        'MANIFEST.in': """
            include doc
            include myproj
            """,
        'tox.ini': ''
    })
    result = cmd.run("tox", "package")
    assert not result.ret
    result.stdout.fnmatch_lines([
        "*created sdist package at*",
    ])

def test_unknown_interpreter(cmd, initproj):
    initproj("interp123-0.5", filedefs={
        'tests': {'test_hello.py': "def test_hello(): pass"},
        'tox.ini': '''
            [testenv:python]
            basepython=xyz_unknown_interpreter
            [testenv]
            changedir=tests
        '''
    })
    result = cmd.run("tox")
    assert not result.ret
    result.stdout.fnmatch_lines([
        "*ERROR*InterpreterNotFound*xyz_unknown_interpreter*",
    ])

def test_unknown_dep(cmd, initproj):
    initproj("dep123-0.7", filedefs={
        'tests': {'test_hello.py': "def test_hello(): pass"},
        'tox.ini': '''
            [testenv]
            deps=qweqwe123
            changedir=tests
        '''
    })
    result = cmd.run("tox", )
    assert not result.ret
    result.stdout.fnmatch_lines([
        "*ERROR*could not install*qweqwe123*",
    ])

def test_unknown_environment(cmd, initproj):
    initproj("env123-0.7", filedefs={
        'tox.ini': ''
    })
    result = cmd.run("tox", "-e", "qpwoei")
    assert result.ret
    result.stdout.fnmatch_lines([
        "*ERROR*unknown*environment*qpwoei*",
    ])

def test_sdist_fails(cmd, initproj):
    initproj("pkg123-0.7", filedefs={
        'tests': {'test_hello.py': "def test_hello(): pass"},
        'setup.py': """
            syntax error
        """
        ,
        'tox.ini': '',
    })
    result = cmd.run("tox", )
    assert result.ret
    result.stdout.fnmatch_lines([
        "*FAIL*could not package project*",
    ])

def test_package_install_fails(cmd, initproj):
    initproj("pkg123-0.7", filedefs={
        'tests': {'test_hello.py': "def test_hello(): pass"},
        'setup.py': """
            from setuptools import setup
            setup(
                name='pkg123',
                description='pkg123 project',
                version='0.7',
                license='GPLv2 or later',
                platforms=['unix', 'win32'],
                packages=['pkg123',],
                install_requires=['qweqwe123'],
                )
            """
        ,
        'tox.ini': '',
    })
    result = cmd.run("tox", )
    assert not result.ret
    result.stdout.fnmatch_lines([
        "*FAIL*could not install package*",
    ])

def test_test_simple(cmd, initproj):
    initproj("example123-0.5", filedefs={
        'tests': {'test_hello.py': """
            def test_hello(pytestconfig):
                pytestconfig.mktemp("hello")
            """,
        },
        'tox.ini': '''
            [testenv]
            changedir=tests
            commands=
                py.test --basetemp={envtmpdir} --junitxml=junit-{envname}.xml []
            deps=py
        '''
    })
    result = cmd.run("tox")
    assert not result.ret
    result.stdout.fnmatch_lines([
        "*junit-python.xml*",
        "*1 passed*",
    ])
    result = cmd.run("tox", "--env=python", )
    assert not result.ret
    result.stdout.fnmatch_lines([
        "*1 passed*",
        "*summary*",
        "*python: commands succeeded"
    ])
    # see that things work with a different CWD
    cmd.tmpdir.chdir()
    result = cmd.run("tox", "-c", "example123/tox.ini")
    assert not result.ret
    result.stdout.fnmatch_lines([
        "*1 passed*",
        "*summary*",
        "*python: commands succeeded"
    ])

def test_test_piphelp(initproj, cmd):
    initproj("example123", filedefs={'tox.ini': """
        # content of: tox.ini
        [testenv]
        commands=pip -h
        [testenv:py25]
        basepython=python2.5
        [testenv:py26]
        basepython=python2.6
    """})
    result = cmd.run("tox")
    assert not result.ret

def test_notest(initproj, cmd):
    initproj("example123", filedefs={'tox.ini': """
        # content of: tox.ini
        [testenv:py25]
        basepython=python2.5
        [testenv:py26]
        basepython=python2.6
    """})
    result = cmd.run("tox", "--notest")
    assert not result.ret
    assert "tox summary" not in result.stdout.str()
    result = cmd.run("tox", "--notest", "--env=py25")
    assert not result.ret
    result.stdout.fnmatch_lines([
        "*reusing*py25",
    ])
    result = cmd.run("tox", "--notest", "--env=py25,py26")
    assert not result.ret
    result.stdout.fnmatch_lines([
        "*reusing*py25",
        "*reusing*py26",
    ])

<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
"""
    Command line test
    ~~~~~~~~~~~~~~~~~

    :copyright: 2006-2007 by Georg Brandl.
    :license: BSD, see LICENSE for more details.
"""

# Test the command line interface

import sys, os
import unittest
import StringIO

from pygments import cmdline_main, highlight

def run_cmdline(*args):
    saved_stdout = sys.stdout
    saved_stderr = sys.stderr
    new_stdout = sys.stdout = StringIO.StringIO()
    new_stderr = sys.stderr = StringIO.StringIO()
    try:
        ret = cmdline_main(["pygmentize"] + list(args))
    finally:
        sys.stdout = saved_stdout
        sys.stderr = saved_stderr
    return (ret, new_stdout.getvalue(), new_stderr.getvalue())

class CmdLineTest(unittest.TestCase):

    def test_L_opt(self):
        c, o, e = run_cmdline("-L")
        self.assertEquals(c, 0)
        self.assert_("Lexers" in o and "Formatters" in o and
                     "Filters" in o and "Styles" in o)
        c, o, e = run_cmdline("-L", "lexer")
        self.assertEquals(c, 0)
        self.assert_("Lexers" in o and "Formatters" not in o)
        c, o, e = run_cmdline("-L", "lexers")
        self.assertEquals(c, 0)

    def test_O_opt(self):
        filename = os.path.join(testdir, testfile)
        c, o, e = run_cmdline("-Ofull=1,linenos=true,foo=bar", "-fhtml", filename)
        self.assertEquals(c, 0)
        self.assert_("<html" in o)
        self.assert_('class="linenos"' in o)

    def test_F_opt(self):
        filename = os.path.join(testdir, testfile)
        c, o, e = run_cmdline("-Fhighlight:tokentype=Name.Blubb,names=testfile testdir",
                              "-fhtml", filename)
        self.assertEquals(c, 0)
        self.assert_('<span class="n-Blubb' in o)

    def test_H_opt(self):
        c, o, e = run_cmdline("-H", "formatter", "html")
        self.assertEquals(c, 0)
        self.assert_('HTML' in o)

    def test_invalid_opts(self):
        for opts in [("-L", "-lpy"), ("-L", "-fhtml"), ("-L", "-Ox"),
                     ("-a",), ("-Sst", "-lpy"), ("-H",),
                     ("-H", "formatter"),]:
            self.assert_(run_cmdline(*opts)[0] == 2)

    def test_normal(self):
        # test that cmdline gives the same output as library api
        from pygments.lexers import PythonLexer
        from pygments.formatters import HtmlFormatter
        filename = os.path.join(testdir, testfile)
        code = file(filename).read()

        output = highlight(code, PythonLexer(), HtmlFormatter())

        c, o, e = run_cmdline("-lpython", "-fhtml", filename)

        self.assertEquals(o, output)
        self.assertEquals(e, "")
        self.assertEquals(c, 0)

if __name__ == '__main__':
    unittest.main()
<commit_msg>[svn] Fix test_cmdline.<commit_after># -*- coding: utf-8 -*-
"""
    Command line test
    ~~~~~~~~~~~~~~~~~

    :copyright: 2006-2007 by Georg Brandl.
    :license: BSD, see LICENSE for more details.
"""

# Test the command line interface

import sys, os
import unittest
import StringIO

from pygments import highlight
from pygments.cmdline import main as cmdline_main

def run_cmdline(*args):
    saved_stdout = sys.stdout
    saved_stderr = sys.stderr
    new_stdout = sys.stdout = StringIO.StringIO()
    new_stderr = sys.stderr = StringIO.StringIO()
    try:
        ret = cmdline_main(["pygmentize"] + list(args))
    finally:
        sys.stdout = saved_stdout
        sys.stderr = saved_stderr
    return (ret, new_stdout.getvalue(), new_stderr.getvalue())

class CmdLineTest(unittest.TestCase):

    def test_L_opt(self):
        c, o, e = run_cmdline("-L")
        self.assertEquals(c, 0)
        self.assert_("Lexers" in o and "Formatters" in o and
                     "Filters" in o and "Styles" in o)
        c, o, e = run_cmdline("-L", "lexer")
        self.assertEquals(c, 0)
        self.assert_("Lexers" in o and "Formatters" not in o)
        c, o, e = run_cmdline("-L", "lexers")
        self.assertEquals(c, 0)

    def test_O_opt(self):
        filename = os.path.join(testdir, testfile)
        c, o, e = run_cmdline("-Ofull=1,linenos=true,foo=bar", "-fhtml", filename)
        self.assertEquals(c, 0)
        self.assert_("<html" in o)
        self.assert_('class="linenos"' in o)

    def test_F_opt(self):
        filename = os.path.join(testdir, testfile)
        c, o, e = run_cmdline("-Fhighlight:tokentype=Name.Blubb,names=testfile testdir",
                              "-fhtml", filename)
        self.assertEquals(c, 0)
        self.assert_('<span class="n-Blubb' in o)

    def test_H_opt(self):
        c, o, e = run_cmdline("-H", "formatter", "html")
        self.assertEquals(c, 0)
        self.assert_('HTML' in o)

    def test_invalid_opts(self):
        for opts in [("-L", "-lpy"), ("-L", "-fhtml"), ("-L", "-Ox"),
                     ("-a",), ("-Sst", "-lpy"), ("-H",),
                     ("-H", "formatter"),]:
            self.assert_(run_cmdline(*opts)[0] == 2)

    def test_normal(self):
        # test that cmdline gives the same output as library api
        from pygments.lexers import PythonLexer
        from pygments.formatters import HtmlFormatter
        filename = os.path.join(testdir, testfile)
        code = file(filename).read()

        output = highlight(code, PythonLexer(), HtmlFormatter())

        c, o, e = run_cmdline("-lpython", "-fhtml", filename)

        self.assertEquals(o, output)
        self.assertEquals(e, "")
        self.assertEquals(c, 0)

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


<commit_before># -*- coding: utf-8 -*-
"""
    Command line test
    ~~~~~~~~~~~~~~~~~

    :copyright: 2006 by Georg Brandl.
    :license: BSD, see LICENSE for more details.
"""

# Test the command line interface

import sys, os
import unittest
import StringIO

from pygments import cmdline_main, highlight

def run_cmdline(*args):
    saved_stdout = sys.stdout
    saved_stderr = sys.stderr
    new_stdout = sys.stdout = StringIO.StringIO()
    new_stderr = sys.stderr = StringIO.StringIO()
    try:
        ret = cmdline_main(["pygmentize"] + list(args))
    finally:
        sys.stdout = saved_stdout
        sys.stderr = saved_stderr
    return (ret, new_stdout.getvalue(), new_stderr.getvalue())

class CmdLineTest(unittest.TestCase):

    def test_L_opt(self):
        c, o, e = run_cmdline("-L")
        self.assert_(c == 0)
        self.assert_(o.find("Lexers") and o.find("Formatters"))

    def test_invalid_opts(self):
        for opts in [("-L", "-lpy"), ("-L", "-fhtml"), ("-L", "-Ox"),
                     ("-a",), ("-Sst", "-lpy")]:
            self.assert_(run_cmdline(*opts)[0] == 2)

    def test_normal(self):
        # test that cmdline gives the same output as library api
        from pygments.lexers import PythonLexer
        from pygments.formatters import HtmlFormatter
        filename = os.path.join(testdir, testfile)
        code = file(filename).read()

        output = highlight(code, PythonLexer(), HtmlFormatter())

        c, o, e = run_cmdline("-lpython", "-fhtml", filename)

        self.assertEquals(o, output)
        self.assertEquals(e, "")
        self.assertEquals(c, 0)

if __name__ == '__main__':
    unittest.main()
<commit_msg>[svn] Add a test case for -O option.<commit_after># -*- coding: utf-8 -*-
"""
    Command line test
    ~~~~~~~~~~~~~~~~~

    :copyright: 2006 by Georg Brandl.
    :license: BSD, see LICENSE for more details.
"""

# Test the command line interface

import sys, os
import unittest
import StringIO

from pygments import cmdline_main, highlight

def run_cmdline(*args):
    saved_stdout = sys.stdout
    saved_stderr = sys.stderr
    new_stdout = sys.stdout = StringIO.StringIO()
    new_stderr = sys.stderr = StringIO.StringIO()
    try:
        ret = cmdline_main(["pygmentize"] + list(args))
    finally:
        sys.stdout = saved_stdout
        sys.stderr = saved_stderr
    return (ret, new_stdout.getvalue(), new_stderr.getvalue())

class CmdLineTest(unittest.TestCase):

    def test_L_opt(self):
        c, o, e = run_cmdline("-L")
        self.assert_(c == 0)
        self.assert_(o.find("Lexers") and o.find("Formatters"))

    def test_O_opt(self):
        filename = os.path.join(testdir, testfile)
        c, o, e = run_cmdline("-Ofull=1,linenos=true", "-fhtml", filename)
        self.assertEquals(c, 0)
        self.assert_("<html" in o)
        self.assert_('class="linenos"' in o)

    def test_invalid_opts(self):
        for opts in [("-L", "-lpy"), ("-L", "-fhtml"), ("-L", "-Ox"),
                     ("-a",), ("-Sst", "-lpy")]:
            self.assert_(run_cmdline(*opts)[0] == 2)

    def test_normal(self):
        # test that cmdline gives the same output as library api
        from pygments.lexers import PythonLexer
        from pygments.formatters import HtmlFormatter
        filename = os.path.join(testdir, testfile)
        code = file(filename).read()

        output = highlight(code, PythonLexer(), HtmlFormatter())

        c, o, e = run_cmdline("-lpython", "-fhtml", filename)

        self.assertEquals(o, output)
        self.assertEquals(e, "")
        self.assertEquals(c, 0)

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


<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Arne Neumann <discoursegraphs.programming@arne.cl>

import pkgutil
from tempfile import NamedTemporaryFile

import pytest

import discoursegraphs as dg
from discoursegraphs.corpora import pcc

maz_1423 = pcc['maz-1423']

def test_write_brackets():
    """convert a PCC document into a brackets file."""
    temp_file = NamedTemporaryFile()
    temp_file.close()
    dg.write_brackets(maz_1423, temp_file.name)

def test_write_brat():
    """convert a PCC document into a brat file."""
    temp_file = NamedTemporaryFile()
    temp_file.close()
    dg.write_brat(maz_1423, temp_file.name)

def test_write_conll():
    """convert a PCC coreference document into a conll file."""
    coref_file = dg.corpora.pcc.get_files_by_layer('coreference')[0]
    cdg = dg.read_mmax2(coref_file)

    temp_file = NamedTemporaryFile()
    temp_file.close()
    dg.write_conll(cdg, temp_file.name)

@pytest.mark.skipif(pkgutil.find_loader("pygraphviz") == None,
                    reason="requires pygraphviz")
# pygraphviz may be hard to install on Ubuntu
# http://stackoverflow.com/questions/32885486/pygraphviz-importerror-undefined-symbol-agundirected
def test_write_dot():
    """convert a PCC document into a dot file."""
    temp_file = NamedTemporaryFile()
    temp_file.close()
    dg.write_dot(maz_1423, temp_file.name)

def test_write_exb():
    """convert a PCC document into a exb file."""
    temp_file = NamedTemporaryFile()
    temp_file.close()
    dg.write_exb(maz_1423, temp_file.name)

def test_write_gml():
    """convert a PCC document into a gml file."""
    temp_file = NamedTemporaryFile()
    temp_file.close()
    dg.write_gml(maz_1423, temp_file.name)

def test_write_graphml():
    """convert a PCC document into a graphml file."""
    temp_file = NamedTemporaryFile()
    temp_file.close()
    dg.write_graphml(maz_1423, temp_file.name)

def test_write_gexf():
    """convert a PCC document into a gexf file."""
    temp_file = NamedTemporaryFile()
    temp_file.close()
    dg.write_gexf(maz_1423, temp_file.name)

def test_write_geoff():
    """convert a PCC document into a geoff file."""
    temp_file = NamedTemporaryFile()
    temp_file.close()
    dg.write_geoff(maz_1423, temp_file.name)

def test_write_paula():
    """convert a PCC document into a paula file."""
    temp_file = NamedTemporaryFile()
    temp_file.close()
    dg.write_paula(maz_1423, temp_file.name)

@pytest.mark.slowtest
def test_pcc():
    """
    create document graphs for all PCC documents containing all annotation
    layers.
    """
    assert len(pcc.document_ids) == 176

    for doc_id in pcc.document_ids:
        docgraph = pcc[doc_id]
        assert isinstance(docgraph, dg.DiscourseDocumentGraph)
<commit_msg>skip test_write_gml() for now<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Arne Neumann <discoursegraphs.programming@arne.cl>

import pkgutil
from tempfile import NamedTemporaryFile

import pytest

import discoursegraphs as dg
from discoursegraphs.corpora import pcc

maz_1423 = pcc['maz-1423']

def test_write_brackets():
    """convert a PCC document into a brackets file."""
    temp_file = NamedTemporaryFile()
    temp_file.close()
    dg.write_brackets(maz_1423, temp_file.name)

def test_write_brat():
    """convert a PCC document into a brat file."""
    temp_file = NamedTemporaryFile()
    temp_file.close()
    dg.write_brat(maz_1423, temp_file.name)

def test_write_conll():
    """convert a PCC coreference document into a conll file."""
    coref_file = dg.corpora.pcc.get_files_by_layer('coreference')[0]
    cdg = dg.read_mmax2(coref_file)

    temp_file = NamedTemporaryFile()
    temp_file.close()
    dg.write_conll(cdg, temp_file.name)

@pytest.mark.skipif(pkgutil.find_loader("pygraphviz") == None,
                    reason="requires pygraphviz")
# pygraphviz may be hard to install on Ubuntu
# http://stackoverflow.com/questions/32885486/pygraphviz-importerror-undefined-symbol-agundirected
def test_write_dot():
    """convert a PCC document into a dot file."""
    temp_file = NamedTemporaryFile()
    temp_file.close()
    dg.write_dot(maz_1423, temp_file.name)

def test_write_exb():
    """convert a PCC document into a exb file."""
    temp_file = NamedTemporaryFile()
    temp_file.close()
    dg.write_exb(maz_1423, temp_file.name)

@pytest.mark.skip(reason="node IDs must match '^[A-Za-z][0-9A-Za-z]*$'")
# cf. http://www.fim.uni-passau.de/fileadmin/files/lehrstuhl/brandenburg/projekte/gml/gml-technical-report.pdf
def test_write_gml():
    """convert a PCC document into a gml file."""
    temp_file = NamedTemporaryFile()
    temp_file.close()
    dg.write_gml(maz_1423, temp_file.name)

def test_write_graphml():
    """convert a PCC document into a graphml file."""
    temp_file = NamedTemporaryFile()
    temp_file.close()
    dg.write_graphml(maz_1423, temp_file.name)

def test_write_gexf():
    """convert a PCC document into a gexf file."""
    temp_file = NamedTemporaryFile()
    temp_file.close()
    dg.write_gexf(maz_1423, temp_file.name)

def test_write_geoff():
    """convert a PCC document into a geoff file."""
    temp_file = NamedTemporaryFile()
    temp_file.close()
    dg.write_geoff(maz_1423, temp_file.name)

def test_write_paula():
    """convert a PCC document into a paula file."""
    temp_file = NamedTemporaryFile()
    temp_file.close()
    dg.write_paula(maz_1423, temp_file.name)

@pytest.mark.slowtest
def test_pcc():
    """
    create document graphs for all PCC documents containing all annotation
    layers.
    """
    assert len(pcc.document_ids) == 176

    for doc_id in pcc.document_ids:
        docgraph = pcc[doc_id]
        assert isinstance(docgraph, dg.DiscourseDocumentGraph)
<|endoftext|>


<commit_before>import dateutil.parser
import time
import argparse
import matplotlib.pyplot as plt
from os.path import isdir, join
from operator import add
from datetime import datetime
from gensim import corpora, models, similarities

minute = 60
hour = 3600
cdict = "%scorpus.dict"
ccorpus = "%scorpus.mm"
corpus_model = "%s.%s"

def gen_graph(figure, x, y, subtitle, xlabel, ylabel, scale):
    figure.suptitle(subtitle, fontsize=14, fontweight='bold')
    ax = figure.add_subplot(111)
    figure.subplots_adjust(top=0.85)
    ax.set_xlabel(xlabel)
    ax.set_ylabel(ylabel)
    ax.set_yscale(scale)
    ax.plot(x, y, linestyle='--', marker='o')

def load_data(directory, sizes, algorithm):
    dict_file = join(directory, cdict)
    corp_file = join(directory, ccorpus)
    model_file = join(directory, corpus_model)

    dictionaries = [corpora.Dictionary.load(dict_file % size) for size in sizes]
    corpi = [corpora.MmCorpus(corp_file % size) for size in sizes]
    corpus_models = [models.ldamodel.LdaModel.load(model_file % (size, algorithm)) for size in sizes]
    dict_sizes = [len(x) for x in dictionaries]
    return dict_sizes, corpus_models, corpi, dictionaries

def read_logfile(path):
    train_times = list()
    build_times = list()
    with open(path) as log_file:
        for i, line in enumerate(log_file):
            bt_time = line.strip().split("\t")[-1]
            hours, mins, seconds = bt_time.split(":")
            total = (hour * int(hours)) + (minute * int(mins)) + float(seconds)
            if (i % 2) == 0:
                train_times.append(total)
            else:
                build_times.append(total)
    total_times = map(add, train_times, build_times)
    return total_times, train_times, build_times

def graph_results(directory, sizes, algorithm):
    corp_dict_size = plt.figure()
    corp_time = plt.figure()
    corp_build = plt.figure()
    total_time = plt.figure()
    total_times, train_times, build_times = read_logfile(join(directory, "runtimes.log"))
    dict_sizes, corpus_models, corpi, dictionaries = load_data(directory, sizes, algorithm)

    gen_graph(corp_dict_size, sizes, dict_sizes, 'Corpus size and dictionary features', "corpus size", "dictionary size", 'log')
    gen_graph(corp_time, sizes, train_times, 'Corpus size and train time', "corpus size", "training time", 'log')
    gen_graph(corp_build, sizes, build_times, 'Corpus size and build time', "corpus size", "build time", 'log')
    gen_graph(total_time, sizes, total_times, 'Corpus size and total time', "corpus size", "total time", 'log')

    plt.show()

def main():
    parser = argparse.ArgumentParser(description='Graph result from run_algorithm.py')
    parser.add_argument('sizes', metavar='N', type=int, nargs='+', help='size values for the corpus')
    parser.add_argument('directory', help='directory for the arxiv txt files')
    parser.add_argument('algorithm', help='algorithm to apply to the corpus')
    args = parser.parse_args()
    if isdir(args.directory):
        graph_results(args.directory, args.sizes, args.algorithm)
    else:
        print "Directory argument should be a valid directory"

if __name__ == "__main__":
    main()
<commit_msg>Add function to graph multiple algorithms<commit_after>import dateutil.parser
import time
import argparse
import matplotlib.pyplot as plt
from os.path import isdir, join
from operator import add
from datetime import datetime
from gensim import corpora, models, similarities

minute = 60
hour = 3600
cdict = "%scorpus.dict"
ccorpus = "%scorpus.mm"
corpus_model = "%s.%s"

def gen_graph(figure, x, y, subtitle, xlabel, ylabel, scale):
    figure.suptitle(subtitle, fontsize=14, fontweight='bold')
    ax = figure.add_subplot(111)
    figure.subplots_adjust(top=0.85)
    ax.set_xlabel(xlabel)
    ax.set_ylabel(ylabel)
    ax.set_yscale(scale)
    ax.plot(x, y, linestyle='--', marker='o')

def plt_multiple(figure, d1, d2, subtitle, xlabel, ylabel, scale):
    x1, y1 = d1
    x2, y2 = d2
    figure.suptitle(subtitle, fontsize=14, fontweight='bold')
    ax = figure.add_subplot(111)
    figure.subplots_adjust(top=0.85)
    ax.set_xlabel(xlabel)
    ax.set_ylabel(ylabel)
    ax.set_yscale(scale)
    ax.plot(x1, y1, 'r--', x2, y2, 'bs', linestyle='--', marker='o')

def load_data(directory, sizes, algorithm):
    dict_file = join(directory, cdict)
    corp_file = join(directory, ccorpus)
    # model_file = join(directory, corpus_model)

    dictionaries = [corpora.Dictionary.load(dict_file % size) for size in sizes]
    corpi = [corpora.MmCorpus(corp_file % size) for size in sizes]
    # corpus_models = [models.ldamodel.LdaModel.load(model_file % (size, algorithm)) for size in sizes]
    dict_sizes = [len(x) for x in dictionaries]
    return dict_sizes, corpi, dictionaries

def read_logfile(path):
    train_times = list()
    build_times = list()
    with open(path) as log_file:
        for i, line in enumerate(log_file):
            bt_time = line.strip().split("\t")[-1]
            hours, mins, seconds = bt_time.split(":")
            total = (hour * int(hours)) + (minute * int(mins)) + float(seconds)
            if (i % 2) == 0:
                train_times.append(total)
            else:
                build_times.append(total)
    total_times = map(add, train_times, build_times)
    return total_times, train_times, build_times

def graph_results(directory, sizes, algorithm):
    directory = join(directory, algorithm)
    corp_dict_size = plt.figure()
    corp_time = plt.figure()
    corp_build = plt.figure()
    total_time = plt.figure()
    total_times, train_times, build_times = read_logfile(join(directory, "runtimes.log"))
    dict_sizes, corpi, dictionaries = load_data(directory, sizes, algorithm)

    gen_graph(corp_dict_size, sizes, dict_sizes, 'Corpus size and dictionary features', "corpus size", "dictionary size", 'log')
    gen_graph(corp_time, sizes, train_times, 'Corpus size and train time', "corpus size", "training time", 'log')
    gen_graph(corp_build, sizes, build_times, 'Corpus size and build time', "corpus size", "build time", 'log')
    gen_graph(total_time, sizes, total_times, 'Corpus size and total time', "corpus size", "total time", 'log')
    plt.show()

def graph_multiple(directory, sizes):
    figure = plt.figure()
    dir1 = join(directory, "lda")
    dir2 = join(directory, "knn")
    total_times1, train_times1, build_times1 = read_logfile(join(dir1, "runtimes.log"))
    total_times2, train_times2, build_times2 = read_logfile(join(dir2, "runtimes.log"))
    dict_sizes1, corpi1, dictionaries1 = load_data(dir1, sizes, "lda")
    dict_sizes2, corpi2, dictionaries2 = load_data(dir2, sizes, "knn")
    # Slicing is a temporary hack until I read the sizes from the log file rather than the command line
    plt_multiple(figure, (train_times1[:len(sizes)], sizes), (train_times2[:len(sizes)], sizes), 'Corpus size and total time', "corpus size", "total time", 'linear')
    plt.show()

def main():
    parser = argparse.ArgumentParser(description='Graph result from run_algorithm.py')
    parser.add_argument('sizes', metavar='N', type=int, nargs='+', help='size values for the corpus')
    parser.add_argument('directory', help='directory for the arxiv txt files')
    parser.add_argument('algorithm', help='algorithm to apply to the corpus')
    args = parser.parse_args()
    if args.algorithm != "multiple" and isdir(args.directory):
        graph_results(args.directory, args.sizes, args.algorithm)
    else:
        graph_multiple(args.directory, args.sizes)

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


<commit_before># -*- coding: utf-8 -*-
from .base import CounterTestCase
from random import randint

class CounterTests(CounterTestCase):
    def test_mixin(self):
        for name in ('Builtin', 'Counter', 'Test'):
            u = self.User(username=name)
            u.save()
            u.age = randint(0, 99)
            u.save()
        # counter should only increases after the first save
        self.assertEqual(self.User.count(), 3)

    def test_initial(self):
        self.assertEqual(0, self.Counter.count('something-new'))

    def test_increase(self):
        k = 'another'
        self.assertEqual(1, self.Counter.increase(k))  # increase by 1

    def test_decrease(self):
        k = 'decrease'
        self.Counter.increase(k)  # increase by 1
        self.Counter.decrease(k)  # decrease by 1
        self.assertEqual(0, self.Counter.count(k))

    def test_change_by(self):
        k = 'more'
        self.assertEqual(3, self.Counter.change_by(k, 3))       # increase 0 by 3
        self.assertEqual(3 - 1, self.Counter.change_by(k, -1))  # decrease 3 by 1

    def test_base(self):
        # `increase_by_6` is implemented in the base class
        self.assertEqual(self.Counter.increase_by_6('Final'), 6)<commit_msg>test for counter exception<commit_after># -*- coding: utf-8 -*-
from .base import CounterTestCase
from random import randint

class CounterTests(CounterTestCase):
    def test_mixin(self):
        for name in ('Builtin', 'Counter', 'Test'):
            u = self.User(username=name)
            u.save()
            u.age = randint(0, 99)
            u.save()
        # counter should only increases after the first save
        self.assertEqual(self.User.count(), 3)

    def test_initial(self):
        self.assertEqual(0, self.Counter.count('something-new'))

    def test_increase(self):
        k = 'another'
        self.assertEqual(1, self.Counter.increase(k))  # increase by 1

    def test_decrease(self):
        k = 'decrease'
        self.Counter.increase(k)  # increase by 1
        self.Counter.decrease(k)  # decrease by 1
        self.assertEqual(0, self.Counter.count(k))

    def test_change_by(self):
        k = 'more'
        self.assertEqual(3, self.Counter.change_by(k, 3))       # increase 0 by 3
        self.assertEqual(3 - 1, self.Counter.change_by(k, -1))  # decrease 3 by 1

    def test_base(self):
        # `increase_by_6` is implemented in the base class
        self.assertEqual(self.Counter.increase_by_6('Final'), 6)

    def test_exception(self):
        # TODO: assert custom exception
        self.assertRaises(Exception, self.Counter.change_by, 'exception', -100)
<|endoftext|>


<commit_before>import json
import hashlib
import datetime
import numpy as np

import great_expectations as ge

import unittest

class TestDataset(unittest.TestCase):

    def test_dataset(self):

        D = ge.dataset.PandasDataSet({
            'x' : [1,2,4],
            'y' : [1,2,5],
            'z' : ['hello', 'jello', 'mello'],
        })

        # print D._expectations_config.keys()
        # print json.dumps(D._expectations_config, indent=2)

        self.assertEqual(
            D._expectations_config,
            {
                "dataset_name" : None,
                "expectations" : [{
                    "expectation_type" : "expect_column_to_exist",
                    "kwargs" : { "column" : "x" }
                },{
                    "expectation_type" : "expect_column_to_exist",
                    "kwargs" : { "column" : "y" }
                },{
                    "expectation_type" : "expect_column_to_exist",
                    "kwargs" : { "column" : "z" }
                }]
            }
        )

        self.maxDiff = None
        self.assertEqual(
            D.get_expectations_config(),
            {
                "dataset_name" : None,
                "expectations" : [{
                    "expectation_type" : "expect_column_to_exist",
                    "kwargs" : { "column" : "x" }
                },{
                    "expectation_type" : "expect_column_to_exist",
                    "kwargs" : { "column" : "y" }
                },{
                    "expectation_type" : "expect_column_to_exist",
                    "kwargs" : { "column" : "z" }
                }]
            }
        )

        #!!! Add tests for expectation and column_expectation
        #!!! Add tests for save_expectation

    def test_set_default_expectation_argument(self):
        df = ge.dataset.PandasDataSet({
            'x' : [1,2,4],
            'y' : [1,2,5],
            'z' : ['hello', 'jello', 'mello'],
        })

        self.assertEqual(
            df.get_default_expectation_arguments(),
            {
                "include_config" : False,
                "catch_exceptions" : False,
                "output_format" : 'BASIC',
            }
        )

        df.set_default_expectation_argument("output_format", "SUMMARY")

        self.assertEqual(
            df.get_default_expectation_arguments(),
            {
                "include_config" : False,
                "catch_exceptions" : False,
                "output_format" : 'SUMMARY',
            }
        )

if __name__ == "__main__":
    unittest.main()
<commit_msg>Add test_get_expectation_config<commit_after>import json
import hashlib
import datetime
import numpy as np

import great_expectations as ge

import unittest

class TestDataset(unittest.TestCase):

    def test_dataset(self):

        D = ge.dataset.PandasDataSet({
            'x' : [1,2,4],
            'y' : [1,2,5],
            'z' : ['hello', 'jello', 'mello'],
        })

        # print D._expectations_config.keys()
        # print json.dumps(D._expectations_config, indent=2)

        self.assertEqual(
            D._expectations_config,
            {
                "dataset_name" : None,
                "expectations" : [{
                    "expectation_type" : "expect_column_to_exist",
                    "kwargs" : { "column" : "x" }
                },{
                    "expectation_type" : "expect_column_to_exist",
                    "kwargs" : { "column" : "y" }
                },{
                    "expectation_type" : "expect_column_to_exist",
                    "kwargs" : { "column" : "z" }
                }]
            }
        )

        self.maxDiff = None
        self.assertEqual(
            D.get_expectations_config(),
            {
                "dataset_name" : None,
                "expectations" : [{
                    "expectation_type" : "expect_column_to_exist",
                    "kwargs" : { "column" : "x" }
                },{
                    "expectation_type" : "expect_column_to_exist",
                    "kwargs" : { "column" : "y" }
                },{
                    "expectation_type" : "expect_column_to_exist",
                    "kwargs" : { "column" : "z" }
                }]
            }
        )

        #!!! Add tests for expectation and column_expectation
        #!!! Add tests for save_expectation

    def test_set_default_expectation_argument(self):
        df = ge.dataset.PandasDataSet({
            'x' : [1,2,4],
            'y' : [1,2,5],
            'z' : ['hello', 'jello', 'mello'],
        })

        self.assertEqual(
            df.get_default_expectation_arguments(),
            {
                "include_config" : False,
                "catch_exceptions" : False,
                "output_format" : 'BASIC',
            }
        )

        df.set_default_expectation_argument("output_format", "SUMMARY")

        self.assertEqual(
            df.get_default_expectation_arguments(),
            {
                "include_config" : False,
                "catch_exceptions" : False,
                "output_format" : 'SUMMARY',
            }
        )

    def test_get_expectation_config(self):
        df = ge.dataset.PandasDataSet({
            'x' : [1,2,4],
            'y' : [1,2,5],
            'z' : ['hello', 'jello', 'mello'],
        })
        df.expect_column_values_to_be_in_set('x', [1,2,4])
        df.expect_column_values_to_be_in_set('y', [1,2,4])
        df.expect_column_values_to_match_regex('z', 'ello')

        self.assertEqual(
            df.get_expectations_config(),
            {
              "expectations": [
                {
                  "expectation_type": "expect_column_to_exist",
                  "kwargs": {
                    "column": "x"
                  }
                },
                {
                  "expectation_type": "expect_column_to_exist",
                  "kwargs": {
                    "column": "y"
                  }
                },
                {
                  "expectation_type": "expect_column_to_exist",
                  "kwargs": {
                    "column": "z"
                  }
                },
                {
                  "expectation_type": "expect_column_values_to_be_in_set",
                  "kwargs": {
                    "column": "x",
                    "values_set": [
                      1,
                      2,
                      4
                    ]
                  }
                },
                {
                  "expectation_type": "expect_column_values_to_match_regex",
                  "kwargs": {
                    "column": "z",
                    "regex": "ello"
                  }
                }
              ],
              "dataset_name": None
            }
        )

        self.assertEqual(
            df.get_expectations_config(
                discard_failed_expectations=False
            ),
            {
              "expectations": [
                {
                  "expectation_type": "expect_column_to_exist",
                  "kwargs": {
                    "column": "x"
                  }
                },
                {
                  "expectation_type": "expect_column_to_exist",
                  "kwargs": {
                    "column": "y"
                  }
                },
                {
                  "expectation_type": "expect_column_to_exist",
                  "kwargs": {
                    "column": "z"
                  }
                },
                {
                  "expectation_type": "expect_column_values_to_be_in_set",
                  "kwargs": {
                    "column": "x",
                    "values_set": [
                      1,
                      2,
                      4
                    ]
                  }
                },
                {
                  "expectation_type": "expect_column_values_to_be_in_set",
                  "kwargs": {
                    "column": "y",
                    "values_set": [
                      1,
                      2,
                      4
                    ]
                  }
                },
                {
                  "expectation_type": "expect_column_values_to_match_regex",
                  "kwargs": {
                    "column": "z",
                    "regex": "ello"
                  }
                }
              ],
              "dataset_name": None
            }
        )

        self.assertEqual(
            df.get_expectations_config(
                discard_output_format_kwargs=False,
                discard_include_configs_kwargs=False,
                discard_catch_exceptions_kwargs=False,
            ),
            {
              "expectations": [
                {
                  "expectation_type": "expect_column_to_exist",
                  "kwargs": {
                    "column": "x"
                  }
                },
                {
                  "expectation_type": "expect_column_to_exist",
                  "kwargs": {
                    "column": "y"
                  }
                },
                {
                  "expectation_type": "expect_column_to_exist",
                  "kwargs": {
                    "column": "z"
                  }
                },
                {
                  "expectation_type": "expect_column_values_to_be_in_set",
                  "kwargs": {
                    "column": "x",
                    "values_set": [
                      1,
                      2,
                      4
                    ],
                    "output_format": "BASIC"
                  }
                },
                {
                  "expectation_type": "expect_column_values_to_match_regex",
                  "kwargs": {
                    "column": "z",
                    "regex": "ello",
                    "output_format": "BASIC"
                  }
                }
              ],
              "dataset_name": None
            }
        )

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


<commit_before>from pytest import fixture
import testinfra.utils.ansible_runner

testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
    '.molecule/ansible_inventory').get_hosts('all')

# Adapted from
# http://www.axelspringerideas.de/blog/index.php/2016/08/16/continuously-delivering-infrastructure-part-1-ansible-molecule-and-testinfra/
#
# This is a little fancy for my taste. pytest fixtures are cool -- they're how
# the testinfra File and Package helpers are implemented, so I think the author
# was aiming for consistency -- but I'm not sure this one improves readability
# or maintainability. However, 1) I didn't have to write it and 2) I thought it
# might be instructive to show this approach. Contrast with the more direct
# approach I use in test_influxdb_repo_key_is_installed().
@fixture()
def Repository_exists(Command):
    """
    Tests if YUM Repo with specific Name exists and is enabled:
    - **repo** - repo name to look for
    **returns** - True if String is found
    """
    def f(repo):
        return (repo in Command.check_output("yum repolist"))
    return f

def test_influxdb_repo_is_installed(Repository_exists):
    assert Repository_exists("Influxdb upstream yum repo")

def test_influxdb_repo_key_is_installed(Command):
    # Adapted from https://wiki.centos.org/TipsAndTricks/YumAndRPM:
    # Show all installed GPG keys
    # Thanks to forum user babo for this one-liner to show all GPG keys along
    # with the corresponding repo information.
    rpm_keys = Command.check_output("rpm -q gpg-pubkey --qf '%{name}-%{version}-%{release} --> %{summary}\n'")
    assert "influxdb" in rpm_keys

def test_influxdb_package_is_installed(Package):
    pkg = Package("influxdb")
    assert pkg.is_installed

def test_influxdb_config_has_collectd_enabled(File):
    config = File("/etc/influxdb/influxdb.conf").content_string
    assert "# BEGIN ANSIBLE MANAGED BLOCK" in config
<commit_msg>Behavior-oriented test to verify collectd is enabled<commit_after>from pytest import fixture
import testinfra.utils.ansible_runner

testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
    '.molecule/ansible_inventory').get_hosts('all')

# Adapted from
# http://www.axelspringerideas.de/blog/index.php/2016/08/16/continuously-delivering-infrastructure-part-1-ansible-molecule-and-testinfra/
#
# This is a little fancy for my taste. pytest fixtures are cool -- they're how
# the testinfra File and Package helpers are implemented, so I think the author
# was aiming for consistency -- but I'm not sure this one improves readability
# or maintainability. However, 1) I didn't have to write it and 2) I thought it
# might be instructive to show this approach. Contrast with the more direct
# approach I use in test_influxdb_repo_key_is_installed().
@fixture()
def Repository_exists(Command):
    """
    Tests if YUM Repo with specific Name exists and is enabled:
    - **repo** - repo name to look for
    **returns** - True if String is found
    """
    def f(repo):
        return (repo in Command.check_output("yum repolist"))
    return f

def test_influxdb_repo_is_installed(Repository_exists):
    assert Repository_exists("Influxdb upstream yum repo")

def test_influxdb_repo_key_is_installed(Command):
    # Adapted from https://wiki.centos.org/TipsAndTricks/YumAndRPM:
    # Show all installed GPG keys
    # Thanks to forum user babo for this one-liner to show all GPG keys along
    # with the corresponding repo information.
    rpm_keys = Command.check_output("rpm -q gpg-pubkey --qf '%{name}-%{version}-%{release} --> %{summary}\n'")
    assert "influxdb" in rpm_keys

def test_influxdb_package_is_installed(Package):
    pkg = Package("influxdb")
    assert pkg.is_installed

def test_influxdb_config_has_collectd_enabled(File):
    config = File("/etc/influxdb/influxdb.conf").content_string
    assert "# BEGIN ANSIBLE MANAGED BLOCK" in config

def test_influxdb_has_collectd_database(Command):
    databases = Command.check_output("influx -execute 'show databases'")
    assert "collectd" in databases
<|endoftext|>


<commit_before># Purpose: test drawing
# Created: 12.03.2011, 2018 rewritten for pytest
# Copyright (C) 2011-2018, Manfred Moitzi
# License: MIT License
from __future__ import unicode_literals
import pytest
from ezdxf.lldxf.tagger import internal_tag_compiler
from ezdxf.drawing import Drawing
from ezdxf.templates import TemplateLoader
from ezdxf import is_dxf_file
from ezdxf import DXFValueError

def test_dxfversion_1():
    dwg = Drawing(internal_tag_compiler(TEST_HEADER))
    assert 'AC1009' == dwg.dxfversion

@pytest.fixture(scope='module')
def dwg_r12():
    return Drawing.new('AC1009')

def test_dxfversion_2(dwg_r12):
    assert 'AC1009' == dwg_r12.dxfversion

def test_acad_release(dwg_r12):
    assert 'R12' == dwg_r12.acad_release

def test_get_layer(dwg_r12):
    layer = dwg_r12.layers.get('0')
    assert '0' == layer.dxf.name

def test_error_getting_not_existing_layer(dwg_r12):
    with pytest.raises(DXFValueError):
        layer = dwg_r12.layers.get('TEST_NOT_EXISTING_LAYER')

def test_create_layer(dwg_r12):
    layer = dwg_r12.layers.new('TEST_NEW_LAYER')
    assert 'TEST_NEW_LAYER' == layer.dxf.name

def test_error_adding_existing_layer(dwg_r12):
    with pytest.raises(DXFValueError):
        layer = dwg_r12.layers.new('0')

def test_has_layer(dwg_r12):
    assert '0' in dwg_r12.layers

def test_has_not_layer(dwg_r12):
    assert 'TEST_LAYER_NOT_EXISTS' not in dwg_r12.layers

def test_removing_layer(dwg_r12):
    dwg_r12.layers.new('TEST_NEW_LAYER_2')
    assert 'TEST_NEW_LAYER_2' in dwg_r12.layers
    dwg_r12.layers.remove('TEST_NEW_LAYER_2')
    assert 'TEST_NEW_LAYER_2' not in dwg_r12.layers

def test_error_removing_not_existing_layer(dwg_r12):
    with pytest.raises(DXFValueError):
        dwg_r12.layers.remove('TEST_LAYER_NOT_EXISTS')

@pytest.fixture(scope='module')
def dwg_r2000():
    return Drawing.new('AC1015')

def test_r2000_dxfversion(dwg_r2000):
    assert 'AC1015' == dwg_r2000.dxfversion

def test_r2000_acad_release(dwg_r2000):
        assert 'R2000' == dwg_r2000.acad_release

def test_template():
    template_file = TemplateLoader().filepath('AC1009')
    assert is_dxf_file(template_file) is True

@pytest.fixture
def min_r12():
    return Drawing(internal_tag_compiler(MINIMALISTIC_DXF12))

def test_min_r12_header_section(min_r12):
    assert hasattr(min_r12, 'header')
    assert min_r12.header['$ACADVER'] == 'AC1009'
    assert min_r12.header['$DWGCODEPAGE'] == 'ANSI_1252'

def test_min_r12_layers_table(min_r12):
    assert hasattr(min_r12, 'layers')
    assert len(min_r12.layers) == 0

def test_min_r12_styles_table(min_r12):
    assert hasattr(min_r12, 'styles')
    assert len(min_r12.styles) == 0

def test_min_r12_linetypes_table(min_r12):
    assert hasattr(min_r12, 'linetypes')
    assert len(min_r12.linetypes) == 0

def test_min_r12_blocks_section(min_r12):
    assert hasattr(min_r12, 'blocks')
    assert len(min_r12.blocks) == 0

def test_min_r12_entity_section(min_r12):
    assert hasattr(min_r12, 'entities')
    assert len(min_r12.entities) == 0

def test_chain_layout_and_block(dwg_r12, dwg_r2000):
    for dwg in (dwg_r12, dwg_r2000):
        msp = dwg.modelspace()
        line_msp = msp.add_line((0, 0), (1, 1))
        blk = dwg.blocks.new('TEST_CHAIN')
        line_blk = blk.add_line((0, 0), (1, 1))

        handles = list(e.dxf.handle for e in dwg.chain_layouts_and_blocks())
        # check for unique handles
        assert len(handles) == len(set(handles))

        check = set([line_msp.dxf.handle, line_blk.dxf.handle])
        assert check.intersection(handles) == check

MINIMALISTIC_DXF12 = """  0
SECTION
  2
ENTITIES
  0
ENDSEC
  0
EOF
"""

TEST_HEADER = """  0
SECTION
  2
HEADER
  9
$ACADVER
  1
AC1009
  9
$DWGCODEPAGE
  3
ANSI_1252
  9
$HANDSEED
  5
FF
  0
ENDSEC
  0
SECTION
  2
ENTITIES
  0
ENDSEC
  0
EOF
"""

TESTCOPY = """  0
SECTION
  2
HEADER
  9
$ACADVER
  1
AC1018
  9
$DWGCODEPAGE
  3
ANSI_1252
  9
$TDUPDATE
 40
0.
  9
$HANDSEED
  5
FF
  0
ENDSEC
  0
SECTION
  2
OBJECTS
  0
ENDSEC
  0
SECTION
  2
FANTASYSECTION
  1
everything should be copied
  0
ENDSEC
  0
SECTION
  2
ALPHASECTION
  1
everything should be copied
  0
ENDSEC
  0
SECTION
  2
OMEGASECTION
  1
everything should be copied
  0
ENDSEC
  0
EOF
"""
<commit_msg>using set literal<commit_after># Purpose: test drawing
# Created: 12.03.2011, 2018 rewritten for pytest
# Copyright (C) 2011-2018, Manfred Moitzi
# License: MIT License
from __future__ import unicode_literals
import pytest
from ezdxf.lldxf.tagger import internal_tag_compiler
from ezdxf.drawing import Drawing
from ezdxf.templates import TemplateLoader
from ezdxf import is_dxf_file
from ezdxf import DXFValueError

def test_dxfversion_1():
    dwg = Drawing(internal_tag_compiler(TEST_HEADER))
    assert 'AC1009' == dwg.dxfversion

@pytest.fixture(scope='module')
def dwg_r12():
    return Drawing.new('AC1009')

def test_dxfversion_2(dwg_r12):
    assert 'AC1009' == dwg_r12.dxfversion

def test_acad_release(dwg_r12):
    assert 'R12' == dwg_r12.acad_release

def test_get_layer(dwg_r12):
    layer = dwg_r12.layers.get('0')
    assert '0' == layer.dxf.name

def test_error_getting_not_existing_layer(dwg_r12):
    with pytest.raises(DXFValueError):
        layer = dwg_r12.layers.get('TEST_NOT_EXISTING_LAYER')

def test_create_layer(dwg_r12):
    layer = dwg_r12.layers.new('TEST_NEW_LAYER')
    assert 'TEST_NEW_LAYER' == layer.dxf.name

def test_error_adding_existing_layer(dwg_r12):
    with pytest.raises(DXFValueError):
        layer = dwg_r12.layers.new('0')

def test_has_layer(dwg_r12):
    assert '0' in dwg_r12.layers

def test_has_not_layer(dwg_r12):
    assert 'TEST_LAYER_NOT_EXISTS' not in dwg_r12.layers

def test_removing_layer(dwg_r12):
    dwg_r12.layers.new('TEST_NEW_LAYER_2')
    assert 'TEST_NEW_LAYER_2' in dwg_r12.layers
    dwg_r12.layers.remove('TEST_NEW_LAYER_2')
    assert 'TEST_NEW_LAYER_2' not in dwg_r12.layers

def test_error_removing_not_existing_layer(dwg_r12):
    with pytest.raises(DXFValueError):
        dwg_r12.layers.remove('TEST_LAYER_NOT_EXISTS')

@pytest.fixture(scope='module')
def dwg_r2000():
    return Drawing.new('AC1015')

def test_r2000_dxfversion(dwg_r2000):
    assert 'AC1015' == dwg_r2000.dxfversion

def test_r2000_acad_release(dwg_r2000):
        assert 'R2000' == dwg_r2000.acad_release

def test_template():
    template_file = TemplateLoader().filepath('AC1009')
    assert is_dxf_file(template_file) is True

@pytest.fixture
def min_r12():
    return Drawing(internal_tag_compiler(MINIMALISTIC_DXF12))

def test_min_r12_header_section(min_r12):
    assert hasattr(min_r12, 'header')
    assert min_r12.header['$ACADVER'] == 'AC1009'
    assert min_r12.header['$DWGCODEPAGE'] == 'ANSI_1252'

def test_min_r12_layers_table(min_r12):
    assert hasattr(min_r12, 'layers')
    assert len(min_r12.layers) == 0

def test_min_r12_styles_table(min_r12):
    assert hasattr(min_r12, 'styles')
    assert len(min_r12.styles) == 0

def test_min_r12_linetypes_table(min_r12):
    assert hasattr(min_r12, 'linetypes')
    assert len(min_r12.linetypes) == 0

def test_min_r12_blocks_section(min_r12):
    assert hasattr(min_r12, 'blocks')
    assert len(min_r12.blocks) == 0

def test_min_r12_entity_section(min_r12):
    assert hasattr(min_r12, 'entities')
    assert len(min_r12.entities) == 0

def test_chain_layout_and_block(dwg_r12, dwg_r2000):
    for dwg in (dwg_r12, dwg_r2000):
        msp = dwg.modelspace()
        line_msp = msp.add_line((0, 0), (1, 1))
        blk = dwg.blocks.new('TEST_CHAIN')
        line_blk = blk.add_line((0, 0), (1, 1))

        handles = list(e.dxf.handle for e in dwg.chain_layouts_and_blocks())
        # check for unique handles
        assert len(handles) == len(set(handles))

        check = {line_msp.dxf.handle, line_blk.dxf.handle}
        assert check.intersection(handles) == check

MINIMALISTIC_DXF12 = """  0
SECTION
  2
ENTITIES
  0
ENDSEC
  0
EOF
"""

TEST_HEADER = """  0
SECTION
  2
HEADER
  9
$ACADVER
  1
AC1009
  9
$DWGCODEPAGE
  3
ANSI_1252
  9
$HANDSEED
  5
FF
  0
ENDSEC
  0
SECTION
  2
ENTITIES
  0
ENDSEC
  0
EOF
"""

TESTCOPY = """  0
SECTION
  2
HEADER
  9
$ACADVER
  1
AC1018
  9
$DWGCODEPAGE
  3
ANSI_1252
  9
$TDUPDATE
 40
0.
  9
$HANDSEED
  5
FF
  0
ENDSEC
  0
SECTION
  2
OBJECTS
  0
ENDSEC
  0
SECTION
  2
FANTASYSECTION
  1
everything should be copied
  0
ENDSEC
  0
SECTION
  2
ALPHASECTION
  1
everything should be copied
  0
ENDSEC
  0
SECTION
  2
OMEGASECTION
  1
everything should be copied
  0
ENDSEC
  0
EOF
"""
<|endoftext|>