Commit 9d5c9d3640fb96967b8c4da7c596a78cf512694a

Authored by Christian Herdtweck
1 parent 56e35a60

tests: create unittests for unicode checker

tests/common/test_encoding_handler.py 0 → 100644
  1 +"""Test common.ensure_stdout_handles_unicode"""
  2 +
  3 +import unittest
  4 +import sys
  5 +from subprocess import check_call
  6 +from tempfile import mkstemp
  7 +import os
  8 +from os.path import isfile
  9 +
  10 +
  11 +class TestEncodingHandler(unittest.TestCase):
  12 + """Tests replacing stdout encoding in various scenarios"""
  13 +
  14 + def test_base(self):
  15 + """Test regular unicode output not raise error"""
  16 + check_call('{python} {this_file} print'.format(python=sys.executable,
  17 + this_file=__file__),
  18 + shell=True)
  19 +
  20 + def test_redirect(self):
  21 + """
  22 + Test redirection of unicode output to files does not raise error
  23 +
  24 + TODO: test this on non-linux OSs
  25 + """
  26 + tmp_handle = None
  27 + tmp_name = None
  28 + try:
  29 + tmp_handle, tmp_name = mkstemp()
  30 + check_call('{python} {this_file} print > {tmp_file}'
  31 + .format(python=sys.executable, this_file=__file__,
  32 + tmp_file=tmp_file),
  33 + shell=True)
  34 + except Exception:
  35 + raise
  36 + finally:
  37 + if tmp_handle is not None:
  38 + os.close(tmp_handle)
  39 + if tmp_name is not None and isfile(tmp_name):
  40 + os.unlink(tmp_name)
  41 +
  42 + @unittest.skipIf(not sys.platform.startswith('linux'),
  43 + 'Only tested on linux sofar')
  44 + def test_no_lang(self):
  45 + """
  46 + Test redirection of unicode output to files does not raise error
  47 +
  48 + TODO: Adapt this for other OSs; for win create batch script
  49 + """
  50 + check_call('LANG=C {python} {this_file} print'
  51 + .format(python=sys.executable, this_file=__file__),
  52 + shell=True)
  53 +
  54 +def run_print():
  55 + """This is called from test_read* tests as script. Prints & logs unicode"""
  56 + # hack required to import common from parent dir, not system-wide one
  57 + # (usually unittest seems to do that for us)
  58 + from os.path import abspath, dirname, join
  59 + ole_base = dirname(dirname(dirname(abspath(__file__))))
  60 + sys.path.insert(0, ole_base)
  61 +
  62 + from oletools import common
  63 + common.ensure_stdout_handles_unicode()
  64 + print(u'\u2713') # print check mark
  65 +
  66 +
  67 +# tests call this file as script
  68 +if __name__ == '__main__':
  69 + if len(sys.argv) < 2:
  70 + sys.exit(unittest.main())
  71 + if sys.argv[1] == 'print':
  72 + if len(sys.argv) > 2:
  73 + print('Expect no arg for "print"', file=sys.stderr)
  74 + sys.exit(2)
  75 + sys.exit(run_print())
  76 + else:
  77 + print('Unexpected argument: {}'.format(sys.argv[1]), file=sys.stderr)
  78 + sys.exit(2)
... ...