1# -*- coding: utf-8 -*-
2
3import re
4import os
5import sys
6import shutil
7import contextlib
8from unittest import TestCase as BaseTestCase
9
10try:
11    import pytest
12except ImportError:
13    raise SystemExit("pytest missing: sudo apt-get install python-pytest")
14
15from mutagen._compat import PY3, StringIO
16from mutagen._senf import text2fsn, fsn2text, path2fsn, mkstemp, fsnative
17
18
19DATA_DIR = os.path.join(
20    os.path.dirname(os.path.realpath(path2fsn(__file__))), "data")
21assert isinstance(DATA_DIR, fsnative)
22
23
24if fsn2text(text2fsn(u"öäü")) != u"öäü":
25    raise RuntimeError("This test suite needs a unicode locale encoding. "
26                       "Try setting LANG=C.UTF-8")
27
28
29def get_temp_copy(path):
30    """Returns a copy of the file with the same extension"""
31
32    ext = os.path.splitext(path)[-1]
33    fd, filename = mkstemp(suffix=ext)
34    os.close(fd)
35    shutil.copy(path, filename)
36    return filename
37
38
39def get_temp_empty(ext=""):
40    """Returns an empty file with the extension"""
41
42    fd, filename = mkstemp(suffix=ext)
43    os.close(fd)
44    return filename
45
46
47@contextlib.contextmanager
48def capture_output():
49    """
50    with capture_output() as (stdout, stderr):
51        some_action()
52    print stdout.getvalue(), stderr.getvalue()
53    """
54
55    err = StringIO()
56    out = StringIO()
57    old_err = sys.stderr
58    old_out = sys.stdout
59    sys.stderr = err
60    sys.stdout = out
61
62    try:
63        yield (out, err)
64    finally:
65        sys.stderr = old_err
66        sys.stdout = old_out
67
68
69class TestCase(BaseTestCase):
70
71    def failUnlessRaisesRegexp(self, exc, re_, fun, *args, **kwargs):
72        def wrapped(*args, **kwargs):
73            try:
74                fun(*args, **kwargs)
75            except Exception as e:
76                self.failUnless(re.search(re_, str(e)))
77                raise
78        self.failUnlessRaises(exc, wrapped, *args, **kwargs)
79
80    # silence deprec warnings about useless renames
81    failUnless = BaseTestCase.assertTrue
82    failIf = BaseTestCase.assertFalse
83    failUnlessEqual = BaseTestCase.assertEqual
84    failUnlessRaises = BaseTestCase.assertRaises
85    failUnlessAlmostEqual = BaseTestCase.assertAlmostEqual
86    failIfEqual = BaseTestCase.assertNotEqual
87    failIfAlmostEqual = BaseTestCase.assertNotAlmostEqual
88    assertEquals = BaseTestCase.assertEqual
89    assertNotEquals = BaseTestCase.assertNotEqual
90    assert_ = BaseTestCase.assertTrue
91
92    def assertReallyEqual(self, a, b):
93        self.assertEqual(a, b)
94        self.assertEqual(b, a)
95        self.assertTrue(a == b)
96        self.assertTrue(b == a)
97        self.assertFalse(a != b)
98        self.assertFalse(b != a)
99        if not PY3:
100            self.assertEqual(0, cmp(a, b))
101            self.assertEqual(0, cmp(b, a))
102
103    def assertReallyNotEqual(self, a, b):
104        self.assertNotEqual(a, b)
105        self.assertNotEqual(b, a)
106        self.assertFalse(a == b)
107        self.assertFalse(b == a)
108        self.assertTrue(a != b)
109        self.assertTrue(b != a)
110        if not PY3:
111            self.assertNotEqual(0, cmp(a, b))
112            self.assertNotEqual(0, cmp(b, a))
113
114
115def check():
116    return pytest.main(args=[os.path.join("tests", "quality")])
117
118
119def unit(run=[], exitfirst=False, no_quality=False):
120    args = []
121
122    if run:
123        args.append("-k")
124        args.append(" or ".join(run))
125
126    if exitfirst:
127        args.append("-x")
128
129    if no_quality:
130        args.extend(["-m", "not quality"])
131
132    args.append("tests")
133
134    return pytest.main(args=args)
135