def test_count(self): lst = [1, 2, 2, 3, 2] expr = Expression(lst) for x in lst + [max(lst) + 1]: i = lst.count(x) j = expr.count(Expression(x)) assert_equal(i, j)
def test_choice_field(self): # Have to use create here because of how field generation works choice = ChoiceOptionFactory.create() field = choice.field dj_field = field.get_django_field() assert_true(isinstance(dj_field, forms.ChoiceField)) assert_equal(choice.name, dj_field.choices[-1][1])
def test_nonexistent_ja(self): skip_unless_c_messages() skip_unless_translation_exists('ja_JP.UTF-8') path = '__nonexistent__' context = Context() try: with interim_locale(LC_ALL='ja_JP.UTF-8'): os.stat(path) except OSError as ex: c_message = ex.args[1] else: raise OSError(errno.EEXIST, os.strerror(errno.EEXIST), path) try: c_message.encode('ASCII') except UnicodeError: pass else: raise AssertionError( 'ja_JP error message is ASCII-only: {msg!r}'.format(msg=c_message) ) with interim_locale(LC_ALL='ja_JP.UTF-8'): with assert_raises(JobFailed): context.new_document(FileUri(path)) message = context.get_message() assert_equal(type(message), ErrorMessage) assert_equal(type(message.message), unicode) assert_equal( message.message, u("[1-11711] Failed to open '{path}': {msg}.".format(path=path, msg=c_message)) ) assert_equal( str(message), "[1-11711] Failed to open '{path}': {msg}.".format(path=path, msg=c_message) ) assert_equal(unicode(message), message.message)
def test_limits(self): assert_equal(Expression((1 << 29) - 1).value, (1 << 29) - 1) assert_equal(Expression(-1 << 29).value, -1 << 29) with assert_raises_str(ValueError, 'value not in range(-2 ** 29, 2 ** 29)'): Expression(1 << 29) with assert_raises_str(ValueError, 'value not in range(-2 ** 29, 2 ** 29)'): Expression((-1 << 29) - 1)
def test_packed_bits(self): pf = PixelFormatPackedBits('<') assert_repr(pf, "djvu.decode.PixelFormatPackedBits('<')") assert_equal(pf.bpp, 1) pf = PixelFormatPackedBits('>') assert_repr(pf, "djvu.decode.PixelFormatPackedBits('>')") assert_equal(pf.bpp, 1)
def test_nonexistent_ja(self): skip_unless_c_messages() skip_unless_translation_exists('ja_JP.UTF-8') path = '__nonexistent__' context = Context() try: with interim_locale(LC_ALL='ja_JP.UTF-8'): os.stat(path) except OSError as ex: c_message = ex.args[1] else: raise OSError(errno.EEXIST, os.strerror(errno.EEXIST), path) try: c_message.encode('ASCII') except UnicodeError: pass else: raise AssertionError( 'ja_JP error message is ASCII-only: {msg!r}'.format( msg=c_message)) with interim_locale(LC_ALL='ja_JP.UTF-8'): with assert_raises(JobFailed): context.new_document(FileUri(path)) message = context.get_message() assert_equal(type(message), ErrorMessage) assert_equal(type(message.message), unicode) assert_equal( message.message, u("[1-11711] Failed to open '{path}': {msg}.".format( path=path, msg=c_message))) assert_equal( str(message), "[1-11711] Failed to open '{path}': {msg}.".format( path=path, msg=c_message)) assert_equal(unicode(message), message.message)
def assert_pickle_equal(obj): for pickle_module in pickle, cpickle: if pickle_module is None: continue for protocol in range(pickle.HIGHEST_PROTOCOL + 1): pickled_obj = pickle_module.dumps(obj, protocol=protocol) repickled_obj = pickle_module.loads(pickled_obj) assert_equal(obj, repickled_obj)
def test_manpage(self): path = os.path.join(srcdir, 'doc', 'manpage.xml') for dummy_event, elem in etree.iterparse(path): if elem.tag == 'refmiscinfo' and elem.get('class') == 'version': assert_equal(elem.text, self.changelog_version) break else: assert_fail("missing <refmiscinfo class='version'>")
def test_insert(self): lst = [] expr = Expression(()) for pos in [-8, 4, 6, -5, -7, 5, 7, 2, -3, 8, 10, -2, 1, -9, -10, -4, -6, 0, 9, 3, -1]: lst.insert(pos, pos) assert_is(expr.insert(pos, pos), None) assert_equal(expr, Expression(lst)) assert_equal(expr.lvalue, lst)
def test_file_io_text_8(self): if py3k: fp = tempfile.TemporaryFile(mode='w+t', encoding='UTF-16-LE') else: fp = tempfile.TemporaryFile(mode='w+t') with fp: self.expr.print_into(fp, escape_unicode=False) fp.seek(0) assert_equal(fp.read(), self.urepr)
def _test(self, method, n): self.pdf2djvu('--dpi=72', '--fg-colors={method}'.format(method=method)).assert_() r = self.decode() r.assert_(stdout=None) r = self.decode(mode='foreground') r.assert_(stdout=None) colors = count_ppm_colors(r.stdout) assert_equal(len(colors), n)
def test_codecs_io_text_8(self): tmpdir = tempfile.mkdtemp() try: path = os.path.join(tmpdir, 'tmp') with codecs.open(path, mode='w+', encoding='UTF-16-LE') as fp: self.expr.print_into(fp, escape_unicode=False) fp.seek(0) assert_equal(fp.read(), u(self.urepr)) finally: shutil.rmtree(tmpdir)
def test_widget_layout(self): widget = WidgetFactory.create() field1 = FieldFactory.create(widget=widget) field2 = FieldFactory.create(widget=widget, form=field1.form) layout = field1.form.get_layout() assert_equal(len(layout), 1) assert_true(isinstance(layout[0], Div)) assert_equal(layout[0].css_class, widget.widget_type) assert_true(field1.key in layout[0].fields) assert_true(field2.key in layout[0].fields)
def test_extend(self): lst = [] expr = Expression(()) for ext in [1], [], [2, 3]: lst.extend(ext) expr.extend(ext) assert_equal(expr, Expression(lst)) assert_equal(expr.lvalue, lst) with assert_raises_str(TypeError, "'int' object is not iterable"): expr.extend(0)
def test1(self): x = Expression(()) assert_repr(x, "Expression([])") y = Expression(x) assert_is(x, y) assert_equal(x.value, ()) assert_equal(x.lvalue, []) assert_equal(len(x), 0) assert_equal(bool(x), False) assert_equal(list(x), [])
def test_inplace_add(self): lst = [] expr0 = expr = Expression(()) for ext in [], [1], [], [2, 3]: lst += ext expr += ext assert_equal(expr, Expression(lst)) assert_equal(expr.lvalue, lst) assert_is(expr, expr0) with assert_raises_str(TypeError, "'int' object is not iterable"): expr += 0
def _test(self, method, n): self.pdf2djvu( '--dpi=72', '--fg-colors={method}'.format(method=method) ).assert_() r = self.decode() r.assert_(stdout=None) r = self.decode(mode='foreground') r.assert_(stdout=None) colors = count_ppm_colors(r.stdout) assert_equal(len(colors), n)
def test_insert(self): lst = [] expr = Expression(()) for pos in [ -8, 4, 6, -5, -7, 5, 7, 2, -3, 8, 10, -2, 1, -9, -10, -4, -6, 0, 9, 3, -1 ]: lst.insert(pos, pos) assert_is(expr.insert(pos, pos), None) assert_equal(expr, Expression(lst)) assert_equal(expr.lvalue, lst)
def test_index(self): expr = Expression(()) with assert_raises_str(ValueError, 'value not in list'): expr.index(Expression(42)) lst = [1, 2, 3] expr = Expression(lst) for x in lst: i = lst.index(x) j = expr.index(Expression(x)) assert_equal(i, j) with assert_raises_str(ValueError, 'value not in list'): expr.index(Expression(max(lst) + 1))
def test_overwrite(self): pdf_path = self.get_pdf_path() with open(pdf_path, 'rb') as pdf_file: pdf_before = pdf_file.read() cmdline = (self.get_pdf2djvu_command() + ('-q', self.get_pdf_path(), '-o', self.get_pdf_path())) r = self.run(*cmdline) r.assert_(stderr=re.compile('Input file is the same as output file:'), rc=1) with open(pdf_path, 'rb') as pdf_file: pdf_after = pdf_file.read() assert_equal(pdf_before, pdf_after)
def test_no_verbatim(self): self.require_feature('Exiv2') self.pdf2djvu().assert_() xmp = self.extract_xmp() xmp = etree.fromstring(xmp) dcformat = xml_find_text(xmp, 'dc:format') assert_equal(dcformat, 'image/vnd.djvu') instance_id = xml_find_text(xmp, 'xmpMM:InstanceID') document_id = xml_find_text(xmp, 'xmpMM:DocumentID') assert_not_equal(instance_id, document_id) assert_uuid_urn(instance_id) assert_uuid_urn(document_id)
def test_comparison2(self): assert_equal(self.zones, sorted(self.zones, reverse=True)) assert_equal([[cmp(z1, z2) for z1 in self.zones] for z2 in self.zones], [ [0, -1, -1, -1, -1, -1, -1], [+1, 0, -1, -1, -1, -1, -1], [+1, +1, 0, -1, -1, -1, -1], [+1, +1, +1, 0, -1, -1, -1], [+1, +1, +1, +1, 0, -1, -1], [+1, +1, +1, +1, +1, 0, -1], [+1, +1, +1, +1, +1, +1, 0], ])
def t(i, n): self.require_feature('GraphicsMagick') self.pdf2djvu('--dpi=72', '--fg-colors={0}'.format(i)).assert_() r = self.decode() r.assert_(stdout=None) r = self.decode(mode='foreground') r.assert_(stdout=None) colors = count_ppm_colors(r.stdout) if isinstance(n, tuple): assert_in(len(colors), n) else: assert_equal(len(colors), n)
def test_string_expressions(): x = Expression('eggs') assert_repr(x, "Expression('eggs')") assert_is(x, Expression(x)) assert_equal(x.value, 'eggs') assert_equal(x.lvalue, 'eggs') assert_equal(str(x), '"eggs"') assert_repr(x, repr(Expression.from_string(str(x)))) assert_equal(x, Expression('eggs')) assert_not_equal(x, Expression(Symbol('eggs'))) assert_not_equal(x, 'eggs') assert_equal(hash(x), hash('eggs')) assert_pickle_equal(x)
def test_palette(self): with assert_raises(KeyError) as ecm: pf = PixelFormatPalette({}) assert_equal(ecm.exception.args, ((0, 0, 0), )) data = dict(((i, j, k), i + 7 * j + 37 + k) for i in range(6) for j in range(6) for k in range(6)) pf = PixelFormatPalette(data) data_repr = ', '.join('{k!r}: 0x{v:02x}'.format(k=k, v=v) for k, v in sorted(data.items())) assert_equal( repr(pf), 'djvu.decode.PixelFormatPalette({{{data}}}, bpp = 8)'.format( data=data_repr))
def test_context_cache(): context = Context() assert_equal(context.cache_size, 10 << 20) for n in -100, 0, 1 << 31: with assert_raises_str(ValueError, '0 < cache_size < (2 ** 31) must be satisfied'): context.cache_size = n with assert_raises_str(ValueError, '0 < cache_size < (2 ** 31) must be satisfied'): context.cache_size = 0 n = 1 while n < (1 << 31): context.cache_size = n assert_equal(context.cache_size, n) n = (n + 1) * 2 - 1 context.clear_cache()
def t(i, n): self.require_feature('GraphicsMagick') self.pdf2djvu( '--dpi=72', '--fg-colors={0}'.format(i) ).assert_() r = self.decode() r.assert_(stdout=None) r = self.decode(mode='foreground') r.assert_(stdout=None) colors = count_ppm_colors(r.stdout) if isinstance(n, tuple): assert_in(len(colors), n) else: assert_equal(len(colors), n)
def test_palette(self): with assert_raises(KeyError) as ecm: pf = PixelFormatPalette({}) assert_equal( ecm.exception.args, ((0, 0, 0),) ) data = dict(((i, j, k), i + 7 * j + 37 + k) for i in range(6) for j in range(6) for k in range(6)) pf = PixelFormatPalette(data) data_repr = ', '.join( '{k!r}: 0x{v:02x}'.format(k=k, v=v) for k, v in sorted(data.items()) ) assert_equal( repr(pf), 'djvu.decode.PixelFormatPalette({{{data}}}, bpp = 8)'.format(data=data_repr) )
def create_djvu(commands='', sexpr=''): skip_unless_command_exists('djvused') if sexpr: commands += '\nset-ant\n{sexpr}\n.\n'.format(sexpr=sexpr) file = tempfile.NamedTemporaryFile(prefix='test', suffix='djvu') file.seek(0) file.write( b'\x41\x54\x26\x54\x46\x4F\x52\x4D\x00\x00\x00\x22\x44\x4A\x56\x55' b'\x49\x4E\x46\x4F\x00\x00\x00\x0A\x00\x01\x00\x01\x18\x00\x2C\x01' b'\x16\x01\x53\x6A\x62\x7A\x00\x00\x00\x04\xBC\x73\x1B\xD7' ) file.flush() (stdout, stderr) = run('djvused', '-s', file.name, stdin=commands.encode(locale_encoding)) assert_equal(stdout, ''.encode(locale_encoding)) assert_equal(stderr, ''.encode(locale_encoding)) return file
def test_reverse(self): for lst in (), (1, 2, 3): expr = Expression(lst) assert_equal(Expression(reversed(expr)), Expression(reversed(lst))) assert_equal( Expression(reversed(expr)).value, tuple(reversed(lst))) assert_is(expr.reverse(), None) assert_equal(expr, Expression(reversed(lst))) assert_equal(expr.value, tuple(reversed(lst)))
def create_djvu(commands='', sexpr=''): skip_unless_command_exists('djvused') if sexpr: commands += '\nset-ant\n{sexpr}\n.\n'.format(sexpr=sexpr) file = tempfile.NamedTemporaryFile(prefix='test', suffix='djvu') file.seek(0) file.write( b'\x41\x54\x26\x54\x46\x4F\x52\x4D\x00\x00\x00\x22\x44\x4A\x56\x55' b'\x49\x4E\x46\x4F\x00\x00\x00\x0A\x00\x01\x00\x01\x18\x00\x2C\x01' b'\x16\x01\x53\x6A\x62\x7A\x00\x00\x00\x04\xBC\x73\x1B\xD7') file.flush() (stdout, stderr) = run('djvused', '-s', file.name, stdin=commands.encode(locale_encoding)) assert_equal(stdout, ''.encode(locale_encoding)) assert_equal(stderr, ''.encode(locale_encoding)) return file
def t(self, name, sname=None): if sname is None: sname = name if py3k: [uname, bname] = [sname, sname.encode('UTF-8')] else: [uname, bname] = [sname.decode('UTF-8'), sname] symbol = Symbol(name) assert_equal(type(symbol), Symbol) assert_equal(symbol, Symbol(name)) assert_is(symbol, Symbol(name)) assert_equal(str(symbol), sname) assert_equal(unicode(symbol), uname) assert_not_equal(symbol, bname) assert_not_equal(symbol, uname) assert_equal(hash(symbol), hash(bname)) assert_pickle_equal(symbol) return symbol
def test_remove(self): expr = Expression([0, 1, 2, 3, 4, 5, 6]) expr.remove(Expression(0)) assert_equal(expr, Expression([1, 2, 3, 4, 5, 6])) with assert_raises_str(IndexError, 'item not in list'): expr.remove(Expression(0)) expr.remove(Expression(6)) assert_equal(expr, Expression([1, 2, 3, 4, 5])) expr.remove(Expression(5)) assert_equal(expr, Expression([1, 2, 3, 4])) expr.remove(Expression(3)) assert_equal(expr, Expression([1, 2, 4])) expr.remove(Expression(2)) assert_equal(expr, Expression([1, 4])) expr.remove(Expression(4)) expr.remove(Expression(1)) with assert_raises_str(IndexError, 'item not in list'): expr.remove(Expression(-1))
def test_bad_file_io(self): ecm = None path = '/dev/full' try: os.stat(path) except OSError as exc: raise SkipTest('{exc.filename}: {exc.strerror}'.format(exc=exc)) fp = open(path, 'w', buffering=2) expr = Expression(23) try: with assert_raises(IOError) as ecm: for i in range(10000): expr.print_into(fp) finally: try: fp.close() except IOError: if ecm is None: raise assert_equal(ecm.exception.errno, errno.ENOSPC)
def test_nonexistent(self): path = '__nonexistent__' try: os.stat(path) except OSError as ex: c_message = ex.args[1] else: raise OSError(errno.EEXIST, os.strerror(errno.EEXIST), path) c_message.encode('ASCII') skip_unless_c_messages() context = Context() with assert_raises(JobFailed): context.new_document(FileUri(path)) message = context.get_message() assert_equal(type(message), ErrorMessage) assert_equal(type(message.message), unicode) assert_equal( message.message, "[1-11711] Failed to open '{path}': {msg}.".format(path=path, msg=c_message) ) assert_equal(str(message), message.message) assert_equal(unicode(message), message.message)
def test_nonexistent(self): path = '__nonexistent__' try: os.stat(path) except OSError as ex: c_message = ex.args[1] else: raise OSError(errno.EEXIST, os.strerror(errno.EEXIST), path) c_message.encode('ASCII') skip_unless_c_messages() context = Context() with assert_raises(JobFailed): context.new_document(FileUri(path)) message = context.get_message() assert_equal(type(message), ErrorMessage) assert_equal(type(message.message), unicode) assert_equal( message.message, "[1-11711] Failed to open '{path}': {msg}.".format(path=path, msg=c_message)) assert_equal(str(message), message.message) assert_equal(unicode(message), message.message)
def test_reverse(self): for lst in (), (1, 2, 3): expr = Expression(lst) assert_equal( Expression(reversed(expr)), Expression(reversed(lst)) ) assert_equal( Expression(reversed(expr)).value, tuple(reversed(lst)) ) assert_is(expr.reverse(), None) assert_equal( expr, Expression(reversed(lst)) ) assert_equal( expr.value, tuple(reversed(lst)) )
def t(self, n, x=None): if x is None: x = Expression(n) assert_is(x, Expression(x)) # __repr__(): assert_repr(x, 'Expression({n})'.format(n=int(n))) # value: v = x.value assert_equal(type(v), int) assert_equal(v, n) # lvalue: v = x.lvalue assert_equal(type(v), int) assert_equal(v, n) # __int__(): i = int(x) assert_equal(type(i), int) assert_equal(i, n) # __long__(): i = long(x) assert_equal(type(i), long) assert_equal(i, n) # __float__(): i = float(x) assert_equal(type(i), float) assert_equal(i, n) # __str__(): s = str(x) assert_equal(s, str(n)) # __unicode__(): s = unicode(x) assert_equal(s, str(n)) # __eq__(), __ne__(): assert_equal(x, Expression(n)) assert_not_equal(x, n) assert_not_equal(x, Expression(n + 37)) # __hash__(): assert_equal(hash(x), n) # __bool__() / __nonzero__(): obj = object() if n: assert_is(x and obj, obj) assert_is(x or obj, x) else: assert_is(x and obj, x) assert_is(x or obj, obj) # pickle: assert_pickle_equal(x)
def test_verbatim(self): self.pdf2djvu('--verbatim-metadata').assert_() xmp = self.extract_xmp() xmp = etree.fromstring(xmp) dcformat = xml_find_text(xmp, 'dc:format') assert_equal(dcformat, 'application/pdf')
def test_version(): assert_is_instance(__version__, str) assert_equal(__version__, get_changelog_version())
def test_type(self): for zone in self.zones: assert_equal(type(zone), TextZoneType) assert_is_instance(zone, Symbol)