Example #1
0
File: io.py Project: yphus/checkbox
 def __enter__(self):
     # Remember the real objects that we'll replace
     self._real_stdin = sys.stdin
     self._real_stdout = sys.stdout
     self._real_stderr = sys.stderr
     # Create fake objects. In combined mode the output is more similar to
     # what a user at a console would see (stdout and stderr are
     # intertwined)
     self._fake_stdin = StringIO(self._input)
     if self._combined:
         self._fake_combined = StringIO()
     else:
         self._fake_stdout = StringIO()
         self._fake_stderr = StringIO()
     # Stub-away .close()
     if self._combined:
         self._fake_combined.close = lambda: None
     else:
         self._fake_stdout.close = lambda: None
         self._fake_stderr.close = lambda: None
     # Lastly replace the real objects
     sys.stdin = self._fake_stdin
     if self._combined:
         sys.stdout = self._fake_combined
         sys.stderr = self._fake_combined
     else:
         sys.stdout = self._fake_stdout
         sys.stderr = self._fake_stderr
     return self
Example #2
0
class CommandTestCase(ChevahTestCase):
    """A test case that catches sys.exit, sys.stdout and sys.stderr.

    It is designed to be used for testing command line tools.
    """

    def setUp(self):
        """Monkey patch the sys.stdout and sys.exit."""
        super(CommandTestCase, self).setUp()

        def _fake_exit(exit_code):
            """Method for monkey patching sys.exit."""
            self.exit_code = exit_code

        self.exit_code = None
        self.test_stdout = StringIO()
        self.test_stderr = StringIO()
        self.sys_exit = sys.exit
        sys.exit = _fake_exit
        sys.stdout = self.test_stdout
        sys.stderr = self.test_stderr

    def tearDown(self):
        self.test_stdout.close()
        sys.stdout = sys.__stdout__
        sys.stderr = sys.__stderr__
        sys.exit = self.sys_exit
        super(CommandTestCase, self).tearDown()
Example #3
0
 def setUp(self):
     map_content = StringIO("3 2\n. # &\n+ . *")
     map_content.name = "map0.txt"
     self.world = World(map_content, False)
     self.player1 = Player(1, self.world)
     self.world.add_player(self.player1)
     self.world.game_start()
Example #4
0
    def test_help_output_redirect(self):
        # issue 940286, if output is set in Helper, then all output from
        # Helper.help should be redirected
        old_pattern = expected_text_pattern
        getpager_old = pydoc.getpager
        getpager_new = lambda: (lambda x: x)
        self.maxDiff = None

        buf = StringIO()
        helper = pydoc.Helper(output=buf)
        unused, doc_loc = get_pydoc_text(pydoc_mod)
        module = "test.pydoc_mod"
        help_header = """
        Help on module test.pydoc_mod in test:

        """.lstrip()
        help_header = textwrap.dedent(help_header)
        expected_help_pattern = help_header + expected_text_pattern

        pydoc.getpager = getpager_new
        try:
            with captured_output("stdout") as output, captured_output("stderr") as err:
                helper.help(module)
                result = buf.getvalue().strip()
                expected_text = expected_help_pattern % (
                    (doc_loc,) + expected_text_data_docstrings + (inspect.getabsfile(pydoc_mod),)
                )
                self.assertEqual("", output.getvalue())
                self.assertEqual("", err.getvalue())
                self.assertEqual(expected_text, result)
        finally:
            pydoc.getpager = getpager_old
Example #5
0
def fix_typehint():
    th_path = "C:\\Users\\PBS Biotech\\Documents\\Personal\\PBS_Office\\MSOffice\\typehint.py"
    from io import StringIO, SEEK_END

    # buf = StringIO()
    with open(th_path, "r") as f:
        buf = StringIO(f.read())

    buf.seek(0, SEEK_END)

    write = buf.write

    write("\n\n")

    th_dir = "C:\\Users\\PBS Biotech\\Documents\\Personal\\PBS_Office\\MSOffice\\officelib\\xllib\\typehint"
    from os import listdir
    from os.path import splitext
    from importlib import import_module

    import_str = "officelib.xllib.typehint.%s.%s"

    for f in listdir(th_dir):
        path = "\\".join((th_dir, f))
        try:
            for module in listdir(path):

                module = splitext(module)[0]
                mod_str = import_str % (f, module)
                if "__" in mod_str:
                    continue
                m = import_module(mod_str)
                cls_list = [attr for attr in dir(m) if not "__" in attr and isinstance(getattr(m, attr), type)]
                try:
                    cls_list.remove("DispatchBaseClass")
                except:
                    pass
                attr_str = ", ".join(cls_list)
                if attr_str:

                    write("# noinspection PyUnresolvedReferences\n")
                    write("".join(("from ", mod_str, " import ", attr_str, "\n")))

        except NotADirectoryError:
            continue

    new = buf.getvalue()

    derp = False

    if derp:
        stream = open(th_path, "w")
    else:
        import sys

        stream = sys.stdout

    print(new, file=stream)

    if derp:
        stream.close()
Example #6
0
 def test_flush_pipes_data_between_streams(self):
     a = StringIO(u"food")
     b = StringIO()
     pump = io.Pump(a, b)
     pump.flush(3)
     expect(a.read(1)).to(equal("d"))
     expect(b.getvalue()).to(equal("foo"))
Example #7
0
def cypher_repr(obj):
    """ Generate the Cypher representation of an object.
    """
    string = StringIO()
    writer = CypherWriter(string)
    writer.write(obj)
    return string.getvalue()
Example #8
0
    def test_pwd_shows_os_getcwd(self):
        stdout = StringIO()
        mon = Monitor(stdout=stdout)
        mon.do_pwd()

        out = stdout.getvalue()
        self.assertEqual("%s\n" % os.getcwd(), out)
Example #9
0
 def test_registers_updates_single_register(self):
     stdout = StringIO()
     mon = Monitor(stdout=stdout)
     mon.do_registers("x=42")
     out = stdout.getvalue()
     self.assertEqual("", out)
     self.assertEqual(0x42, mon._mpu.x)
Example #10
0
    def test_help_assemble(self):
        stdout = StringIO()
        mon = Monitor(stdout=stdout)
        mon.help_assemble()

        out = stdout.getvalue()
        self.assertTrue(out.startswith("assemble <address>"))
Example #11
0
    def test_shortcut_gt_for_fill(self):
        stdout = StringIO()
        mon = Monitor(stdout=stdout)
        mon.do_help(">")

        out = stdout.getvalue()
        self.assertTrue(out.startswith("fill"))
Example #12
0
    def test_do_assemble_passes_addr_for_relative_branch_calc(self):
        stdout = StringIO()
        mon = Monitor(stdout=stdout)
        mon.do_assemble("4000 bvs $4005")

        out = stdout.getvalue()
        self.assertEqual("$4000  70 03     BVS $4005\n", out)
Example #13
0
    def test_do_assemble_shows_bad_statement_error(self):
        stdout = StringIO()
        mon = Monitor(stdout=stdout)
        mon.do_assemble("c000 foo")

        out = stdout.getvalue()
        self.assertEqual("Assemble failed: foo\n", out)
Example #14
0
    def test_do_assemble_shows_bad_label_error(self):
        stdout = StringIO()
        mon = Monitor(stdout=stdout)
        mon.do_assemble("nonexistant rts")

        out = stdout.getvalue()
        self.assertEqual("Bad label: nonexistant\n", out)
Example #15
0
File: utils.py Project: pybee/voc
    def assertBlock(self, python, java):
        self.maxDiff = None
        dump = False

        py_block = PyBlock(parent=PyModule("test", "test.py"))
        if python:
            python = adjust(python)
            code = compile(python, "<test>", "exec")
            py_block.extract(code, debug=dump)

        java_code = py_block.transpile()

        out = BytesIO()
        constant_pool = ConstantPool()
        java_code.resolve(constant_pool)

        constant_pool.add(Utf8("test"))
        constant_pool.add(Utf8("Code"))
        constant_pool.add(Utf8("LineNumberTable"))

        writer = ClassFileWriter(out, constant_pool)
        java_code.write(writer)

        debug = StringIO()
        reader = ClassFileReader(BytesIO(out.getbuffer()), constant_pool, debug=debug)
        JavaCode.read(reader, dump=0)

        if dump:
            print(debug.getvalue())

        java = adjust(java)
        self.assertEqual(debug.getvalue(), java[1:])
Example #16
0
    def test_shortcut_for_return(self):
        stdout = StringIO()
        mon = Monitor(stdout=stdout)
        mon.do_help("ret")

        out = stdout.getvalue()
        self.assertTrue(out.startswith("return"))
Example #17
0
    def response(self, pdu):
        if _debug:
            PickleActorMixIn._debug("response %r", pdu)

        # add the data to our buffer
        self.pickleBuffer += pdu.pduData

        # build a file-like object around the buffer
        strm = StringIO(self.pickleBuffer)

        pos = 0
        while pos < strm.len:
            try:
                # try to load something
                msg = pickle.load(strm)
            except:
                break

            # got a message
            rpdu = PDU(msg)
            rpdu.update(pdu)

            super(PickleActorMixIn, self).response(rpdu)

            # see where we are
            pos = strm.tell()

        # save anything left over, if there is any
        if pos < strm.len:
            self.pickleBuffer = self.pickleBuffer[pos:]
        else:
            self.pickleBuffer = ""
Example #18
0
 def test_tilde_shortcut_without_space_for_vice_compatibility(self):
     stdout = StringIO()
     mon = Monitor(stdout=stdout)
     mon.onecmd("~$10")
     out = stdout.getvalue()
     expected = "+16\n$10\n0020\n00010000\n"
     self.assertEqual(expected, out)
Example #19
0
def expand_template(template_file, data, output_file, minimum_timestamp=None):
    output = StringIO()
    interpreter = em.Interpreter(output=output, options={em.BUFFERED_OPT: True, em.RAW_OPT: True}, globals=data)
    with open(template_file, "r") as h:
        try:
            interpreter.file(h)
        except Exception:
            if os.path.exists(output_file):
                os.remove(output_file)
            print("Exception when expanding '%s' into '%s'" % (template_file, output_file), file=sys.stderr)
            raise
    content = output.getvalue()
    interpreter.shutdown()

    # only overwrite file if necessary
    # which is either when the timestamp is too old or when the content is different
    if os.path.exists(output_file):
        timestamp = os.path.getmtime(output_file)
        if minimum_timestamp is None or timestamp > minimum_timestamp:
            with open(output_file, "r") as h:
                if h.read() == content:
                    return
    else:
        # create folder if necessary
        try:
            os.makedirs(os.path.dirname(output_file))
        except FileExistsError:
            pass

    with open(output_file, "w") as h:
        h.write(content)
Example #20
0
 def test_do_tilde(self):
     stdout = StringIO()
     mon = Monitor(stdout=stdout)
     mon.do_tilde("$10")
     out = stdout.getvalue()
     expected = "+16\n$10\n0020\n00010000\n"
     self.assertEqual(expected, out)
 def test_quiet(self):
     stdout = StringIO()
     stderr = StringIO()
     with patch.object(sys, "stdout", stdout), patch.object(sys, "stderr", stderr):
         install_labextension(self.src, self.name)
     self.assertEqual(stdout.getvalue(), "")
     self.assertEqual(stderr.getvalue(), "")
Example #22
0
    def test_shortcut_for_show_labels(self):
        stdout = StringIO()
        mon = Monitor(stdout=stdout)
        mon.do_help("shl")

        out = stdout.getvalue()
        self.assertTrue(out.startswith("show_labels"))
Example #23
0
def test_basic_filter_config():
    "Filter the file according to the config file."
    output = StringIO()
    python3(path2main, "test/program_output_config", config=config_file, _out=output)

    with open(program_output_filtered, "r") as correctly_filtered_output:
        assert correctly_filtered_output.read() == output.getvalue()
Example #24
0
 def test_help_show_labels(self):
     stdout = StringIO()
     mon = Monitor(stdout=stdout)
     mon._address_parser.labels = {"chrin": 0xFFC4, "chrout": 0xFFD2}
     mon.do_show_labels("")
     out = stdout.getvalue()
     self.assertEqual("ffc4: chrin\nffd2: chrout\n", out)
Example #25
0
def run_level36():
    f = """\
4
    2 1 1 2
   3 3 3 . .
  2 3 3 . 4 .
 . 2 . 2 4 3 2
  2 2 . . . 2
   4 3 4 . .
    3 2 3 3
"""
    order = DESCENDING
    strategy = Done.FIRST_STRATEGY
    output = StringIO()
    solve_file(f, strategy, order, output)
    expected = """\
   3 4 3 2 
  3 4 4 . 3 
 2 . . 3 4 3 
2 . 1 . 3 . 2 
 3 3 . 2 . 2 
  3 . 2 . 2 
   2 2 . 1 
"""
    if output.getvalue() != expected:
        raise AssertionError("got a wrong answer:\n%s" % output.getvalue())
Example #26
0
    def test_shortcut_for_assemble(self):
        stdout = StringIO()
        mon = Monitor(stdout=stdout)
        mon.do_help("a")

        out = stdout.getvalue()
        self.assertTrue(out.startswith("assemble"))
Example #27
0
class UnicodeWriter(object):
    """
    A CSV writer which will write rows to CSV file "f", which is encoded in
    the given encoding.

    """

    def __init__(self, f, encoding="utf-8", **kwds):
        # Redirect output to a queue
        self.queue = StringIO()
        self.writer = csv.writer(self.queue, **kwds)
        self.stream = f
        self.encoder = codecs.getencoder(encoding)

    def writerow(self, row):
        self.writer.writerow(row)
        data = self.queue.getvalue()
        # data now contains the csv data in unicode
        # ... and reencode it into the target encoding
        data, length = self.encoder(data)
        # write to the target stream
        self.stream.write(data)
        # empty queue, go to start position, then truncate
        self.queue.seek(0)
        self.queue.truncate(0)

    def writerows(self, rows):
        list(map(self.writerow, rows))

    def close(self):
        self.stream.close()
Example #28
0
    def test_do_assemble_outputs_disassembly(self):
        stdout = StringIO()
        mon = Monitor(stdout=stdout)
        mon.do_assemble("c000 lda #$ab")

        out = stdout.getvalue()
        self.assertEqual("$c000  a9 ab     LDA #$ab\n", out)
Example #29
0
    def test_extract(self):
        fake_f = StringIO(
            """
            <html>
                <head>
                    <meta charset="utf-8">
                    <meta name="haystack-test" content="test 1234">
                    <title>Test Title ☃&#x2603;</title>
                </head>
                    <body>foobar</body>
            </html>
        """
        )
        fake_f.name = "test.html"
        extracted = self.solr.extract(fake_f)

        # Verify documented response structure:
        self.assertIn("contents", extracted)
        self.assertIn("metadata", extracted)

        self.assertIn("foobar", extracted["contents"])

        m = extracted["metadata"]

        self.assertEqual([fake_f.name], m["stream_name"])

        self.assertIn("haystack-test", m, "HTML metadata should have been extracted!")
        self.assertEqual(["test 1234"], m["haystack-test"])

        # Note the underhanded use of a double snowman to verify both that Tika
        # correctly decoded entities and that our UTF-8 characters survived the
        # round-trip:
        self.assertEqual(["Test Title ☃☃"], m["title"])
Example #30
0
 def do_check(self, **check_dict):
     rst = "OK"
     try:
         output = StringIO()
         interp = Interpreter(writer=output, err_writer=output, use_numpy=False)
         interp.symtable["np"] = np
         interp.symtable["pd"] = pd
         ts = pd.Series(np.random.randn(10), index=pd.date_range(start="1/1/2016", periods=10))
         for param, param_value in check_dict.items():
             if param.startswith("p"):
                 device_id, term_id, item_id = param_value.split(":")
                 test_id = self.redis_client.hget("HS:TERM_ITEM:{}:{}".format(term_id, item_id), "device_id")
                 if not test_id or test_id != device_id:
                     raise Exception("parameter not found: %s=%s" % (param, param_value))
                 interp.symtable[param] = ts
         value = interp(check_dict["formula"])
         if len(interp.error) > 0:
             rst = output.getvalue()
         elif not isinstance(value, Number) and not isinstance(value, pd.Series):
             rst = "result type must be Number or Series!"
     except Exception as ee:
         logger.info("do_check failed: %s", repr(ee), exc_info=True)
         rst = ee.args[0]
     finally:
         return rst