1 # Copyright (c) 2008-2012 testtools developers. See LICENSE for details.
8 from testtools import TestCase
9 from testtools.compat import (
15 from testtools.content import (
25 from testtools.content_type import (
29 from testtools.matchers import (
35 from testtools.tests.helpers import an_exc_info
38 raises_value_error = Raises(MatchesException(ValueError))
41 class TestContent(TestCase):
43 def test___init___None_errors(self):
44 self.assertThat(lambda: Content(None, None), raises_value_error)
46 lambda: Content(None, lambda: ["traceback"]), raises_value_error)
48 lambda: Content(ContentType("text", "traceback"), None),
51 def test___init___sets_ivars(self):
52 content_type = ContentType("foo", "bar")
53 content = Content(content_type, lambda: ["bytes"])
54 self.assertEqual(content_type, content.content_type)
55 self.assertEqual(["bytes"], list(content.iter_bytes()))
57 def test___eq__(self):
58 content_type = ContentType("foo", "bar")
59 one_chunk = lambda: [_b("bytes")]
60 two_chunk = lambda: [_b("by"), _b("tes")]
61 content1 = Content(content_type, one_chunk)
62 content2 = Content(content_type, one_chunk)
63 content3 = Content(content_type, two_chunk)
64 content4 = Content(content_type, lambda: [_b("by"), _b("te")])
65 content5 = Content(ContentType("f", "b"), two_chunk)
66 self.assertEqual(content1, content2)
67 self.assertEqual(content1, content3)
68 self.assertNotEqual(content1, content4)
69 self.assertNotEqual(content1, content5)
71 def test___repr__(self):
72 content = Content(ContentType("application", "octet-stream"),
73 lambda: [_b("\x00bin"), _b("ary\xff")])
74 self.assertIn("\\x00binary\\xff", repr(content))
76 def test_iter_text_not_text_errors(self):
77 content_type = ContentType("foo", "bar")
78 content = Content(content_type, lambda: ["bytes"])
79 self.assertThat(content.iter_text, raises_value_error)
81 def test_iter_text_decodes(self):
82 content_type = ContentType("text", "strange", {"charset": "utf8"})
84 content_type, lambda: [_u("bytes\xea").encode("utf8")])
85 self.assertEqual([_u("bytes\xea")], list(content.iter_text()))
87 def test_iter_text_default_charset_iso_8859_1(self):
88 content_type = ContentType("text", "strange")
89 text = _u("bytes\xea")
90 iso_version = text.encode("ISO-8859-1")
91 content = Content(content_type, lambda: [iso_version])
92 self.assertEqual([text], list(content.iter_text()))
94 def test_as_text(self):
95 content_type = ContentType("text", "strange", {"charset": "utf8"})
97 content_type, lambda: [_u("bytes\xea").encode("utf8")])
98 self.assertEqual(_u("bytes\xea"), content.as_text())
100 def test_from_file(self):
101 fd, path = tempfile.mkstemp()
102 self.addCleanup(os.remove, path)
103 os.write(fd, _b('some data'))
105 content = content_from_file(path, UTF8_TEXT, chunk_size=2)
107 list(content.iter_bytes()),
108 Equals([_b('so'), _b('me'), _b(' d'), _b('at'), _b('a')]))
110 def test_from_nonexistent_file(self):
111 directory = tempfile.mkdtemp()
112 nonexistent = os.path.join(directory, 'nonexistent-file')
113 content = content_from_file(nonexistent)
114 self.assertThat(content.iter_bytes, raises(IOError))
116 def test_from_file_default_type(self):
117 content = content_from_file('/nonexistent/path')
118 self.assertThat(content.content_type, Equals(UTF8_TEXT))
120 def test_from_file_eager_loading(self):
121 fd, path = tempfile.mkstemp()
122 os.write(fd, _b('some data'))
124 content = content_from_file(path, UTF8_TEXT, buffer_now=True)
127 ''.join(content.iter_text()), Equals('some data'))
129 def test_from_file_with_simple_seek(self):
130 f = tempfile.NamedTemporaryFile()
131 f.write(_b('some data'))
133 self.addCleanup(f.close)
134 content = content_from_file(
135 f.name, UTF8_TEXT, chunk_size=50, seek_offset=5)
137 list(content.iter_bytes()), Equals([_b('data')]))
139 def test_from_file_with_whence_seek(self):
140 f = tempfile.NamedTemporaryFile()
141 f.write(_b('some data'))
143 self.addCleanup(f.close)
144 content = content_from_file(
145 f.name, UTF8_TEXT, chunk_size=50, seek_offset=-4, seek_whence=2)
147 list(content.iter_bytes()), Equals([_b('data')]))
149 def test_from_stream(self):
150 data = StringIO('some data')
151 content = content_from_stream(data, UTF8_TEXT, chunk_size=2)
153 list(content.iter_bytes()), Equals(['so', 'me', ' d', 'at', 'a']))
155 def test_from_stream_default_type(self):
156 data = StringIO('some data')
157 content = content_from_stream(data)
158 self.assertThat(content.content_type, Equals(UTF8_TEXT))
160 def test_from_stream_eager_loading(self):
161 fd, path = tempfile.mkstemp()
162 self.addCleanup(os.remove, path)
163 self.addCleanup(os.close, fd)
164 os.write(fd, _b('some data'))
165 stream = open(path, 'rb')
166 self.addCleanup(stream.close)
167 content = content_from_stream(stream, UTF8_TEXT, buffer_now=True)
168 os.write(fd, _b('more data'))
170 ''.join(content.iter_text()), Equals('some data'))
172 def test_from_stream_with_simple_seek(self):
173 data = BytesIO(_b('some data'))
174 content = content_from_stream(
175 data, UTF8_TEXT, chunk_size=50, seek_offset=5)
177 list(content.iter_bytes()), Equals([_b('data')]))
179 def test_from_stream_with_whence_seek(self):
180 data = BytesIO(_b('some data'))
181 content = content_from_stream(
182 data, UTF8_TEXT, chunk_size=50, seek_offset=-4, seek_whence=2)
184 list(content.iter_bytes()), Equals([_b('data')]))
186 def test_from_text(self):
187 data = _u("some data")
188 expected = Content(UTF8_TEXT, lambda: [data.encode('utf8')])
189 self.assertEqual(expected, text_content(data))
191 def test_json_content(self):
192 data = {'foo': 'bar'}
193 expected = Content(JSON, lambda: [_b('{"foo": "bar"}')])
194 self.assertEqual(expected, json_content(data))
197 class TestTracebackContent(TestCase):
199 def test___init___None_errors(self):
201 lambda: TracebackContent(None, None), raises_value_error)
203 def test___init___sets_ivars(self):
204 content = TracebackContent(an_exc_info, self)
205 content_type = ContentType("text", "x-traceback",
206 {"language": "python", "charset": "utf8"})
207 self.assertEqual(content_type, content.content_type)
208 result = unittest.TestResult()
209 expected = result._exc_info_to_string(an_exc_info, self)
210 self.assertEqual(expected, ''.join(list(content.iter_text())))
213 class TestAttachFile(TestCase):
215 def make_file(self, data):
216 # GZ 2011-04-21: This helper could be useful for methods above trying
217 # to use mkstemp, but should handle write failures and
218 # always close the fd. There must be a better way.
219 fd, path = tempfile.mkstemp()
220 self.addCleanup(os.remove, path)
221 os.write(fd, _b(data))
225 def test_simple(self):
226 class SomeTest(TestCase):
229 test = SomeTest('test_foo')
231 path = self.make_file(data)
232 my_content = text_content(data)
233 attach_file(test, path, name='foo')
234 self.assertEqual({'foo': my_content}, test.getDetails())
236 def test_optional_name(self):
237 # If no name is provided, attach_file just uses the base name of the
239 class SomeTest(TestCase):
242 test = SomeTest('test_foo')
243 path = self.make_file('some data')
244 base_path = os.path.basename(path)
245 attach_file(test, path)
246 self.assertEqual([base_path], list(test.getDetails()))
248 def test_lazy_read(self):
249 class SomeTest(TestCase):
252 test = SomeTest('test_foo')
253 path = self.make_file('some data')
254 attach_file(test, path, name='foo', buffer_now=False)
255 content = test.getDetails()['foo']
256 content_file = open(path, 'w')
257 content_file.write('new data')
259 self.assertEqual(''.join(content.iter_text()), 'new data')
261 def test_eager_read_by_default(self):
262 class SomeTest(TestCase):
265 test = SomeTest('test_foo')
266 path = self.make_file('some data')
267 attach_file(test, path, name='foo')
268 content = test.getDetails()['foo']
269 content_file = open(path, 'w')
270 content_file.write('new data')
272 self.assertEqual(''.join(content.iter_text()), 'some data')
276 from unittest import TestLoader
277 return TestLoader().loadTestsFromName(__name__)