How to use linecomp method in Pytest

Best Python code snippet using pytest

pytest_terminal.py

Source:pytest_terminal.py Github

copy

Full Screen

1import py2import sys3class TerminalPlugin(object):4 """ Report a test run to a terminal. """5 def pytest_configure(self, config):6 if config.option.collectonly:7 self.reporter = CollectonlyReporter(config)8 else:9 self.reporter = TerminalReporter(config)10 # XXX see remote.py's XXX 11 for attr in 'pytest_terminal_hasmarkup', 'pytest_terminal_fullwidth':12 if hasattr(config, attr):13 #print "SETTING TERMINAL OPTIONS", attr, getattr(config, attr)14 name = attr.split("_")[-1]15 assert hasattr(self.reporter._tw, name), name16 setattr(self.reporter._tw, name, getattr(config, attr))17 config.bus.register(self.reporter)18class TerminalReporter:19 def __init__(self, config, file=None):20 self.config = config 21 self.stats = {} 22 self.curdir = py.path.local()23 if file is None:24 file = py.std.sys.stdout25 self._tw = py.io.TerminalWriter(file)26 self.currentfspath = None 27 self.gateway2info = {}28 def write_fspath_result(self, fspath, res):29 if fspath != self.currentfspath:30 self._tw.line()31 relpath = self.curdir.bestrelpath(fspath)32 self._tw.write(relpath + " ")33 self.currentfspath = fspath34 self._tw.write(res)35 def write_ensure_prefix(self, prefix, extra="", **kwargs):36 if self.currentfspath != prefix:37 self._tw.line()38 self.currentfspath = prefix 39 self._tw.write(prefix)40 if extra:41 self._tw.write(extra, **kwargs)42 self.currentfspath = -243 def ensure_newline(self):44 if self.currentfspath: 45 self._tw.line()46 self.currentfspath = None47 def write_line(self, line, **markup):48 line = str(line)49 self.ensure_newline()50 self._tw.line(line, **markup)51 def write_sep(self, sep, title=None, **markup):52 self.ensure_newline()53 self._tw.sep(sep, title, **markup)54 def getcategoryletterword(self, event):55 res = self.config.pytestplugins.call_firstresult("pytest_report_teststatus", event=event)56 if res:57 return res58 for cat in 'skipped failed passed ???'.split():59 if getattr(event, cat, None):60 break 61 return cat, self.getoutcomeletter(event), self.getoutcomeword(event)62 def getoutcomeletter(self, event):63 return event.shortrepr 64 def getoutcomeword(self, event):65 if event.passed: 66 return "PASS", dict(green=True)67 elif event.failed: 68 return "FAIL", dict(red=True)69 elif event.skipped: 70 return "SKIP"71 else: 72 return "???", dict(red=True)73 def pyevent_internalerror(self, event):74 for line in str(event.repr).split("\n"):75 self.write_line("InternalException: " + line)76 def pyevent_gwmanage_newgateway(self, gateway, rinfo):77 #self.write_line("%s instantiated gateway from spec %r" %(gateway.id, gateway.spec._spec))78 d = {}79 d['version'] = repr_pythonversion(rinfo.version_info)80 d['id'] = gateway.id81 d['spec'] = gateway.spec._spec 82 d['platform'] = rinfo.platform 83 if self.config.option.verbose:84 d['extra'] = "- " + rinfo.executable85 else:86 d['extra'] = ""87 d['cwd'] = rinfo.cwd88 infoline = ("%(id)s %(spec)s -- platform %(platform)s, "89 "Python %(version)s "90 "cwd: %(cwd)s"91 "%(extra)s" % d)92 self.write_line(infoline)93 self.gateway2info[gateway] = infoline94 def pyevent_gwmanage_rsyncstart(self, source, gateways):95 targets = ", ".join([gw.id for gw in gateways])96 msg = "rsyncstart: %s -> %s" %(source, targets)97 if not self.config.option.verbose:98 msg += " # use --verbose to see rsync progress"99 self.write_line(msg)100 def pyevent_gwmanage_rsyncfinish(self, source, gateways):101 targets = ", ".join([gw.id for gw in gateways])102 self.write_line("rsyncfinish: %s -> %s" %(source, targets))103 def pyevent_plugin_registered(self, plugin):104 if self.config.option.traceconfig: 105 msg = "PLUGIN registered: %s" %(plugin,)106 # XXX this event may happen during setup/teardown time 107 # which unfortunately captures our output here 108 # which garbles our output if we use self.write_line 109 self.write_line(msg)110 def pyevent_testnodeready(self, node):111 self.write_line("%s txnode ready to receive tests" %(node.gateway.id,))112 def pyevent_testnodedown(self, node, error):113 if error:114 self.write_line("%s node down, error: %s" %(node.gateway.id, error))115 def pyevent_trace(self, category, msg):116 if self.config.option.debug or \117 self.config.option.traceconfig and category.find("config") != -1:118 self.write_line("[%s] %s" %(category, msg))119 def pyevent_itemstart(self, item, node=None):120 if self.config.option.debug:121 info = item.repr_metainfo()122 line = info.verboseline(basedir=self.curdir) + " "123 extra = ""124 if node:125 extra = "-> " + str(node.gateway.id)126 self.write_ensure_prefix(line, extra)127 # in dist situations itemstart (currently only means we 128 # queued the item for testing, doesn't tell much129 elif self.config.option.verbose and self.config.option.dist == "no":130 # ensure that the path is printed before the 1st test of131 # a module starts running132 info = item.repr_metainfo()133 line = info.verboseline(basedir=self.curdir) + " "134 #self.write_fspath_result(fspath, "")135 self.write_ensure_prefix(line, "") 136 def pyevent_rescheduleitems(self, event):137 if self.config.option.debug:138 self.write_sep("!", "RESCHEDULING %s " %(event.items,))139 def pyevent_deselected(self, event):140 self.stats.setdefault('deselected', []).append(event)141 142 def pyevent_itemtestreport(self, event):143 fspath = event.colitem.fspath 144 cat, letter, word = self.getcategoryletterword(event)145 if isinstance(word, tuple):146 word, markup = word147 else:148 markup = {}149 self.stats.setdefault(cat, []).append(event)150 if not self.config.option.verbose:151 self.write_fspath_result(fspath, letter)152 else:153 info = event.colitem.repr_metainfo()154 line = info.verboseline(basedir=self.curdir) + " "155 if not hasattr(event, 'node'):156 self.write_ensure_prefix(line, word, **markup)157 else:158 self.ensure_newline()159 if hasattr(event, 'node'):160 self._tw.write("%s " % event.node.gateway.id)161 self._tw.write(word, **markup)162 self._tw.write(" " + line)163 self.currentfspath = -2164 def pyevent_collectionreport(self, event):165 if not event.passed:166 if event.failed:167 self.stats.setdefault("failed", []).append(event)168 msg = event.longrepr.reprcrash.message 169 self.write_fspath_result(event.colitem.fspath, "F")170 elif event.skipped:171 self.stats.setdefault("skipped", []).append(event)172 self.write_fspath_result(event.colitem.fspath, "S")173 def pyevent_testrunstart(self, event):174 self.write_sep("=", "test session starts", bold=True)175 self._sessionstarttime = py.std.time.time()176 verinfo = ".".join(map(str, sys.version_info[:3]))177 msg = "python: platform %s -- Python %s" % (sys.platform, verinfo)178 if self.config.option.verbose or self.config.option.debug:179 msg += " -- " + str(sys.executable)180 self.write_line(msg)181 rev = py.__pkg__.getrev()182 self.write_line("using py lib: %s <rev %s>" % (183 py.path.local(py.__file__).dirpath(), rev))184 if self.config.option.traceconfig:185 plugins = []186 for x in self.config.pytestplugins._plugins:187 if isinstance(x, str) and x.startswith("pytest_"):188 plugins.append(x[7:])189 else:190 plugins.append(str(x)) # XXX display conftest plugins more nicely 191 plugins = ", ".join(plugins) 192 self.write_line("active plugins: %s" %(plugins,))193 for i, testarg in py.builtin.enumerate(self.config.args):194 self.write_line("test object %d: %s" %(i+1, testarg))195 def pyevent_testrunfinish(self, event):196 self._tw.line("")197 if event.exitstatus in (0, 1, 2):198 self.summary_failures()199 self.summary_skips()200 self.config.pytestplugins.call_each("pytest_terminal_summary", terminalreporter=self)201 if event.excrepr is not None:202 self.summary_final_exc(event.excrepr)203 if event.exitstatus == 2:204 self.write_sep("!", "KEYBOARD INTERRUPT")205 self.summary_deselected()206 self.summary_stats()207 def pyevent_looponfailinfo(self, event):208 if event.failreports:209 self.write_sep("#", "LOOPONFAILING", red=True)210 for report in event.failreports:211 try:212 loc = report.longrepr.reprcrash213 except AttributeError:214 loc = str(report.longrepr)[:50]215 self.write_line(loc, red=True)216 self.write_sep("#", "waiting for changes")217 for rootdir in event.rootdirs:218 self.write_line("### Watching: %s" %(rootdir,), bold=True)219 #220 # summaries for TestrunFinish 221 #222 def summary_failures(self):223 if 'failed' in self.stats and self.config.option.tbstyle != "no":224 self.write_sep("=", "FAILURES")225 for ev in self.stats['failed']:226 self.write_sep("_", "FAILURES")227 if hasattr(ev, 'node'):228 self.write_line(self.gateway2info.get(229 ev.node.gateway, "node %r (platinfo not found? strange)")230 [:self._tw.fullwidth-1])231 ev.toterminal(self._tw)232 def summary_stats(self):233 session_duration = py.std.time.time() - self._sessionstarttime234 keys = "failed passed skipped deselected".split()235 parts = []236 for key in keys:237 val = self.stats.get(key, None)238 if val:239 parts.append("%d %s" %(len(val), key))240 line = ", ".join(parts)241 # XXX coloring242 self.write_sep("=", "%s in %.2f seconds" %(line, session_duration))243 def summary_deselected(self):244 if 'deselected' in self.stats:245 self.write_sep("=", "%d tests deselected by %r" %(246 len(self.stats['deselected']), self.config.option.keyword), bold=True)247 def summary_skips(self):248 if 'skipped' in self.stats:249 if 'failed' not in self.stats: # or self.config.option.showskipsummary:250 fskips = folded_skips(self.stats['skipped'])251 if fskips:252 self.write_sep("_", "skipped test summary")253 for num, fspath, lineno, reason in fskips:254 self._tw.line("%s:%d: [%d] %s" %(fspath, lineno, num, reason))255 def summary_final_exc(self, excrepr):256 self.write_sep("!")257 if self.config.option.verbose:258 excrepr.toterminal(self._tw)259 else:260 excrepr.reprcrash.toterminal(self._tw)261class CollectonlyReporter:262 INDENT = " "263 def __init__(self, config, out=None):264 self.config = config 265 if out is None:266 out = py.std.sys.stdout267 self.out = py.io.TerminalWriter(out)268 self.indent = ""269 self._failed = []270 def outindent(self, line):271 self.out.line(self.indent + str(line))272 def pyevent_collectionstart(self, event):273 self.outindent(event.collector)274 self.indent += self.INDENT 275 276 def pyevent_itemstart(self, item, node=None):277 self.outindent(item)278 def pyevent_collectionreport(self, event):279 if not event.passed:280 self.outindent("!!! %s !!!" % event.longrepr.reprcrash.message)281 self._failed.append(event)282 self.indent = self.indent[:-len(self.INDENT)]283 def pyevent_testrunfinish(self, event):284 if self._failed:285 self.out.sep("!", "collection failures")286 for event in self._failed:287 event.toterminal(self.out)288 289def folded_skips(skipped):290 d = {}291 for event in skipped:292 entry = event.longrepr.reprcrash 293 key = entry.path, entry.lineno, entry.message294 d.setdefault(key, []).append(event)295 l = []296 for key, events in d.iteritems(): 297 l.append((len(events),) + key)298 return l 299def repr_pythonversion(v=None):300 if v is None:301 v = sys.version_info302 try:303 return "%s.%s.%s-%s-%s" % v304 except (TypeError, ValueError):305 return str(v)306# ===============================================================================307#308# plugin tests 309#310# ===============================================================================311from py.__.test import event312from py.__.test.runner import basic_run_report313class TestTerminal:314 def test_pass_skip_fail(self, testdir, linecomp):315 modcol = testdir.getmodulecol("""316 import py317 def test_ok():318 pass319 def test_skip():320 py.test.skip("xx")321 def test_func():322 assert 0323 """)324 rep = TerminalReporter(modcol.config, file=linecomp.stringio)325 rep.config.bus.register(rep)326 rep.config.bus.notify("testrunstart", event.TestrunStart())327 328 for item in testdir.genitems([modcol]):329 ev = basic_run_report(item) 330 rep.config.bus.notify("itemtestreport", ev)331 linecomp.assert_contains_lines([332 "*test_pass_skip_fail.py .sF"333 ])334 rep.config.bus.notify("testrunfinish", event.TestrunFinish())335 linecomp.assert_contains_lines([336 " def test_func():",337 "> assert 0",338 "E assert 0",339 ])340 def test_pass_skip_fail_verbose(self, testdir, linecomp):341 modcol = testdir.getmodulecol("""342 import py343 def test_ok():344 pass345 def test_skip():346 py.test.skip("xx")347 def test_func():348 assert 0349 """, configargs=("-v",))350 rep = TerminalReporter(modcol.config, file=linecomp.stringio)351 rep.config.bus.register(rep)352 rep.config.bus.notify("testrunstart", event.TestrunStart())353 items = modcol.collect()354 rep.config.option.debug = True # 355 for item in items:356 rep.config.bus.notify("itemstart", item, None)357 s = linecomp.stringio.getvalue().strip()358 assert s.endswith(item.name)359 rep.config.bus.notify("itemtestreport", basic_run_report(item))360 linecomp.assert_contains_lines([361 "*test_pass_skip_fail_verbose.py:2: *test_ok*PASS*",362 "*test_pass_skip_fail_verbose.py:4: *test_skip*SKIP*",363 "*test_pass_skip_fail_verbose.py:6: *test_func*FAIL*",364 ])365 rep.config.bus.notify("testrunfinish", event.TestrunFinish())366 linecomp.assert_contains_lines([367 " def test_func():",368 "> assert 0",369 "E assert 0",370 ])371 def test_collect_fail(self, testdir, linecomp):372 modcol = testdir.getmodulecol("import xyz")373 rep = TerminalReporter(modcol.config, file=linecomp.stringio)374 rep.config.bus.register(rep)375 rep.config.bus.notify("testrunstart", event.TestrunStart())376 l = list(testdir.genitems([modcol]))377 assert len(l) == 0378 linecomp.assert_contains_lines([379 "*test_collect_fail.py F*"380 ])381 rep.config.bus.notify("testrunfinish", event.TestrunFinish())382 linecomp.assert_contains_lines([383 "> import xyz",384 "E ImportError: No module named xyz"385 ])386 def test_internalerror(self, testdir, linecomp):387 modcol = testdir.getmodulecol("def test_one(): pass")388 rep = TerminalReporter(modcol.config, file=linecomp.stringio)389 excinfo = py.test.raises(ValueError, "raise ValueError('hello')")390 rep.pyevent_internalerror(event.InternalException(excinfo))391 linecomp.assert_contains_lines([392 "InternalException: >*raise ValueError*"393 ])394 def test_gwmanage_events(self, testdir, linecomp):395 modcol = testdir.getmodulecol("""396 def test_one():397 pass398 """, configargs=("-v",))399 rep = TerminalReporter(modcol.config, file=linecomp.stringio)400 class gw1:401 id = "X1"402 spec = py.execnet.XSpec("popen")403 class gw2:404 id = "X2"405 spec = py.execnet.XSpec("popen")406 class rinfo:407 version_info = (2, 5, 1, 'final', 0)408 executable = "hello"409 platform = "xyz"410 cwd = "qwe"411 rep.pyevent_gwmanage_newgateway(gw1, rinfo)412 linecomp.assert_contains_lines([413 "X1*popen*xyz*2.5*"414 ])415 rep.pyevent_gwmanage_rsyncstart(source="hello", gateways=[gw1, gw2])416 linecomp.assert_contains_lines([417 "rsyncstart: hello -> X1, X2"418 ])419 rep.pyevent_gwmanage_rsyncfinish(source="hello", gateways=[gw1, gw2])420 linecomp.assert_contains_lines([421 "rsyncfinish: hello -> X1, X2"422 ])423 def test_writeline(self, testdir, linecomp):424 modcol = testdir.getmodulecol("def test_one(): pass")425 stringio = py.std.cStringIO.StringIO()426 rep = TerminalReporter(modcol.config, file=linecomp.stringio)427 rep.write_fspath_result(py.path.local("xy.py"), '.')428 rep.write_line("hello world")429 lines = linecomp.stringio.getvalue().split('\n')430 assert not lines[0]431 assert lines[1].endswith("xy.py .")432 assert lines[2] == "hello world"433 def test_looponfailreport(self, testdir, linecomp):434 modcol = testdir.getmodulecol("""435 def test_fail():436 assert 0437 def test_fail2():438 raise ValueError()439 """)440 rep = TerminalReporter(modcol.config, file=linecomp.stringio)441 reports = [basic_run_report(x) for x in modcol.collect()]442 rep.pyevent_looponfailinfo(event.LooponfailingInfo(reports, [modcol.config.topdir]))443 linecomp.assert_contains_lines([444 "*test_looponfailreport.py:2: assert 0",445 "*test_looponfailreport.py:4: ValueError*",446 "*waiting*", 447 "*%s*" % (modcol.config.topdir),448 ])449 def test_tb_option(self, testdir, linecomp):450 # XXX usage of testdir and event bus451 for tbopt in ["long", "short", "no"]:452 print 'testing --tb=%s...' % tbopt453 modcol = testdir.getmodulecol("""454 import py455 def g():456 raise IndexError457 def test_func():458 print 6*7459 g() # --calling--460 """, configargs=("--tb=%s" % tbopt,))461 rep = TerminalReporter(modcol.config, file=linecomp.stringio)462 rep.config.bus.register(rep)463 rep.config.bus.notify("testrunstart", event.TestrunStart())464 rep.config.bus.notify("testrunstart", event.TestrunStart())465 for item in testdir.genitems([modcol]):466 rep.config.bus.notify("itemtestreport", basic_run_report(item))467 rep.config.bus.notify("testrunfinish", event.TestrunFinish())468 s = linecomp.stringio.getvalue()469 if tbopt == "long":470 print s471 assert 'print 6*7' in s472 else:473 assert 'print 6*7' not in s474 if tbopt != "no":475 assert '--calling--' in s476 assert 'IndexError' in s477 else:478 assert 'FAILURES' not in s479 assert '--calling--' not in s480 assert 'IndexError' not in s481 linecomp.stringio.truncate(0)482 def test_show_path_before_running_test(self, testdir, linecomp):483 modcol = testdir.getmodulecol("""484 def test_foobar():485 pass486 """)487 rep = TerminalReporter(modcol.config, file=linecomp.stringio)488 modcol.config.bus.register(rep)489 l = list(testdir.genitems([modcol]))490 assert len(l) == 1491 modcol.config.option.debug = True492 rep.config.bus.notify("itemstart", l[0])493 linecomp.assert_contains_lines([494 "*test_show_path_before_running_test.py*"495 ])496 def pseudo_keyboard_interrupt(self, testdir, linecomp, verbose=False):497 modcol = testdir.getmodulecol("""498 def test_foobar():499 assert 0500 def test_spamegg():501 import py; py.test.skip('skip me please!')502 def test_interrupt_me():503 raise KeyboardInterrupt # simulating the user504 """, configargs=("-v",)*verbose)505 #""", configargs=("--showskipsummary",) + ("-v",)*verbose)506 rep = TerminalReporter(modcol.config, file=linecomp.stringio)507 modcol.config.bus.register(rep)508 bus = modcol.config.bus509 bus.notify("testrunstart", event.TestrunStart())510 try:511 for item in testdir.genitems([modcol]):512 bus.notify("itemtestreport", basic_run_report(item))513 except KeyboardInterrupt:514 excinfo = py.code.ExceptionInfo()515 else:516 py.test.fail("no KeyboardInterrupt??")517 s = linecomp.stringio.getvalue()518 if not verbose:519 assert s.find("_keyboard_interrupt.py Fs") != -1520 bus.notify("testrunfinish", event.TestrunFinish(exitstatus=2, excinfo=excinfo))521 text = linecomp.stringio.getvalue()522 linecomp.assert_contains_lines([523 " def test_foobar():",524 "> assert 0",525 "E assert 0",526 ])527 #assert "Skipped: 'skip me please!'" in text528 assert "_keyboard_interrupt.py:6: KeyboardInterrupt" in text529 see_details = "raise KeyboardInterrupt # simulating the user" in text530 assert see_details == verbose531 def test_keyboard_interrupt(self, testdir, linecomp):532 self.pseudo_keyboard_interrupt(testdir, linecomp)533 534 def test_verbose_keyboard_interrupt(self, testdir, linecomp):535 self.pseudo_keyboard_interrupt(testdir, linecomp, verbose=True)536 def test_skip_reasons_folding(self):537 class longrepr:538 class reprcrash:539 path = 'xyz'540 lineno = 3541 message = "justso"542 ev1 = event.CollectionReport(None, None)543 ev1.when = "execute"544 ev1.skipped = True545 ev1.longrepr = longrepr 546 547 ev2 = event.ItemTestReport(None, excinfo=longrepr)548 ev2.skipped = True549 l = folded_skips([ev1, ev2])550 assert len(l) == 1551 num, fspath, lineno, reason = l[0]552 assert num == 2553 assert fspath == longrepr.reprcrash.path554 assert lineno == longrepr.reprcrash.lineno555 assert reason == longrepr.reprcrash.message556class TestCollectonly:557 def test_collectonly_basic(self, testdir, linecomp):558 modcol = testdir.getmodulecol(configargs=['--collectonly'], source="""559 def test_func():560 pass561 """)562 rep = CollectonlyReporter(modcol.config, out=linecomp.stringio)563 modcol.config.bus.register(rep)564 indent = rep.indent565 rep.config.bus.notify("collectionstart", event.CollectionStart(modcol))566 linecomp.assert_contains_lines([567 "<Module 'test_collectonly_basic.py'>"568 ])569 item = modcol.join("test_func")570 rep.config.bus.notify("itemstart", item)571 linecomp.assert_contains_lines([572 " <Function 'test_func'>", 573 ])574 rep.config.bus.notify( "collectionreport", 575 event.CollectionReport(modcol, [], excinfo=None))576 assert rep.indent == indent 577 def test_collectonly_skipped_module(self, testdir, linecomp):578 modcol = testdir.getmodulecol(configargs=['--collectonly'], source="""579 import py580 py.test.skip("nomod")581 """)582 rep = CollectonlyReporter(modcol.config, out=linecomp.stringio)583 modcol.config.bus.register(rep)584 cols = list(testdir.genitems([modcol]))585 assert len(cols) == 0586 linecomp.assert_contains_lines("""587 <Module 'test_collectonly_skipped_module.py'>588 !!! Skipped: 'nomod' !!!589 """)590 def test_collectonly_failed_module(self, testdir, linecomp):591 modcol = testdir.getmodulecol(configargs=['--collectonly'], source="""592 raise ValueError(0)593 """)594 rep = CollectonlyReporter(modcol.config, out=linecomp.stringio)595 modcol.config.bus.register(rep)596 cols = list(testdir.genitems([modcol]))597 assert len(cols) == 0598 linecomp.assert_contains_lines("""599 <Module 'test_collectonly_failed_module.py'>600 !!! ValueError: 0 !!!601 """)602def test_repr_python_version():603 py.magic.patch(sys, 'version_info', (2, 5, 1, 'final', 0))604 try:605 assert repr_pythonversion() == "2.5.1-final-0"606 py.std.sys.version_info = x = (2,3)607 assert repr_pythonversion() == str(x) 608 finally: 609 py.magic.revert(sys, 'version_info') 610def test_generic(plugintester):611 plugintester.apicheck(TerminalPlugin)612 plugintester.apicheck(TerminalReporter)...

Full Screen

Full Screen

test_pytest_terminal.py

Source:test_pytest_terminal.py Github

copy

Full Screen

1"""2terminal reporting of the full testing process.3"""4import py5import sys6# ===============================================================================7# plugin tests 8#9# ===============================================================================10import pytest_runner as runner # XXX 11from pytest_terminal import TerminalReporter, CollectonlyReporter12from pytest_terminal import repr_pythonversion, folded_skips13def basic_run_report(item):14 return runner.call_and_report(item, "call", log=False)15class Option:16 def __init__(self, verbose=False, dist=None):17 self.verbose = verbose18 self.dist = dist19 def _getcmdargs(self):20 l = []21 if self.verbose:22 l.append('-v')23 if self.dist:24 l.append('--dist=%s' % self.dist)25 l.append('--tx=popen')26 return l27 def _getcmdstring(self):28 return " ".join(self._getcmdargs())29def pytest_generate_tests(metafunc):30 if "option" in metafunc.funcargnames:31 metafunc.addcall(32 id="default", 33 funcargs={'option': Option(verbose=False)}34 )35 metafunc.addcall(36 id="verbose", 37 funcargs={'option': Option(verbose=True)}38 )39 nodist = getattr(metafunc.function, 'nodist', False)40 if not nodist:41 metafunc.addcall(42 id="verbose-dist", 43 funcargs={'option': Option(dist='each', verbose=True)}44 )45class TestTerminal:46 def test_pass_skip_fail(self, testdir, option):47 p = testdir.makepyfile("""48 import py49 def test_ok():50 pass51 def test_skip():52 py.test.skip("xx")53 def test_func():54 assert 055 """)56 result = testdir.runpytest(*option._getcmdargs())57 if option.verbose:58 if not option.dist:59 result.stdout.fnmatch_lines([60 "*test_pass_skip_fail.py:2: *test_ok*PASS*",61 "*test_pass_skip_fail.py:4: *test_skip*SKIP*",62 "*test_pass_skip_fail.py:6: *test_func*FAIL*",63 ])64 else:65 expected = [66 "*PASS*test_pass_skip_fail.py:2: *test_ok*", 67 "*SKIP*test_pass_skip_fail.py:4: *test_skip*", 68 "*FAIL*test_pass_skip_fail.py:6: *test_func*", 69 ]70 for line in expected:71 result.stdout.fnmatch_lines([line])72 else:73 result.stdout.fnmatch_lines([74 "*test_pass_skip_fail.py .sF"75 ])76 result.stdout.fnmatch_lines([77 " def test_func():",78 "> assert 0",79 "E assert 0",80 ])81 def test_collect_fail(self, testdir, option):82 p = testdir.makepyfile("import xyz")83 result = testdir.runpytest(*option._getcmdargs())84 result.stdout.fnmatch_lines([85 "*test_collect_fail.py E*",86 "> import xyz",87 "E ImportError: No module named xyz",88 "*1 error*",89 ])90 def test_internalerror(self, testdir, linecomp):91 modcol = testdir.getmodulecol("def test_one(): pass")92 rep = TerminalReporter(modcol.config, file=linecomp.stringio)93 excinfo = py.test.raises(ValueError, "raise ValueError('hello')")94 rep.pytest_internalerror(excinfo.getrepr())95 linecomp.assert_contains_lines([96 "INTERNALERROR> *raise ValueError*"97 ])98 def test_gwmanage_events(self, testdir, linecomp):99 modcol = testdir.getmodulecol("""100 def test_one():101 pass102 """, configargs=("-v",))103 rep = TerminalReporter(modcol.config, file=linecomp.stringio)104 class gw1:105 id = "X1"106 spec = py.execnet.XSpec("popen")107 class gw2:108 id = "X2"109 spec = py.execnet.XSpec("popen")110 class rinfo:111 version_info = (2, 5, 1, 'final', 0)112 executable = "hello"113 platform = "xyz"114 cwd = "qwe"115 116 rep.pyexecnet_gwmanage_newgateway(gw1, rinfo)117 linecomp.assert_contains_lines([118 "X1*popen*xyz*2.5*"119 ])120 rep.pyexecnet_gwmanage_rsyncstart(source="hello", gateways=[gw1, gw2])121 linecomp.assert_contains_lines([122 "rsyncstart: hello -> X1, X2"123 ])124 rep.pyexecnet_gwmanage_rsyncfinish(source="hello", gateways=[gw1, gw2])125 linecomp.assert_contains_lines([126 "rsyncfinish: hello -> X1, X2"127 ])128 def test_writeline(self, testdir, linecomp):129 modcol = testdir.getmodulecol("def test_one(): pass")130 stringio = py.std.cStringIO.StringIO()131 rep = TerminalReporter(modcol.config, file=linecomp.stringio)132 rep.write_fspath_result(py.path.local("xy.py"), '.')133 rep.write_line("hello world")134 lines = linecomp.stringio.getvalue().split('\n')135 assert not lines[0]136 assert lines[1].endswith("xy.py .")137 assert lines[2] == "hello world"138 def test_looponfailreport(self, testdir, linecomp):139 modcol = testdir.getmodulecol("""140 def test_fail():141 assert 0142 def test_fail2():143 raise ValueError()144 """)145 rep = TerminalReporter(modcol.config, file=linecomp.stringio)146 reports = [basic_run_report(x) for x in modcol.collect()]147 rep.pytest_looponfailinfo(reports, [modcol.config.topdir])148 linecomp.assert_contains_lines([149 "*test_looponfailreport.py:2: assert 0",150 "*test_looponfailreport.py:4: ValueError*",151 "*waiting*", 152 "*%s*" % (modcol.config.topdir),153 ])154 def test_tb_option(self, testdir, option):155 p = testdir.makepyfile("""156 import py157 def g():158 raise IndexError159 def test_func():160 print 6*7161 g() # --calling--162 """)163 for tbopt in ["long", "short", "no"]:164 print 'testing --tb=%s...' % tbopt165 result = testdir.runpytest('--tb=%s' % tbopt)166 s = result.stdout.str()167 if tbopt == "long":168 assert 'print 6*7' in s169 else:170 assert 'print 6*7' not in s171 if tbopt != "no":172 assert '--calling--' in s173 assert 'IndexError' in s174 else:175 assert 'FAILURES' not in s176 assert '--calling--' not in s177 assert 'IndexError' not in s178 def test_show_path_before_running_test(self, testdir, linecomp):179 item = testdir.getitem("def test_func(): pass")180 tr = TerminalReporter(item.config, file=linecomp.stringio)181 item.config.pluginmanager.register(tr)182 tr.config.hook.pytest_itemstart(item=item)183 linecomp.assert_contains_lines([184 "*test_show_path_before_running_test.py*"185 ])186 def test_itemreport_reportinfo(self, testdir, linecomp):187 testdir.makeconftest("""188 import py189 class Function(py.test.collect.Function):190 def reportinfo(self):191 return "ABCDE", 42, "custom" 192 """)193 item = testdir.getitem("def test_func(): pass")194 tr = TerminalReporter(item.config, file=linecomp.stringio)195 item.config.pluginmanager.register(tr)196 tr.config.option.verbose = True197 tr.config.hook.pytest_itemstart(item=item)198 linecomp.assert_contains_lines([199 "*ABCDE:43: custom*"200 ])201 def test_itemreport_pytest_report_iteminfo(self, testdir, linecomp):202 item = testdir.getitem("def test_func(): pass")203 class Plugin:204 def pytest_report_iteminfo(self, item):205 return "FGHJ", 42, "custom"206 item.config.pluginmanager.register(Plugin()) 207 tr = TerminalReporter(item.config, file=linecomp.stringio)208 item.config.pluginmanager.register(tr)209 tr.config.option.verbose = True210 tr.config.hook.pytest_itemstart(item=item)211 linecomp.assert_contains_lines([212 "*FGHJ:43: custom*"213 ])214 def test_itemreport_subclasses_show_subclassed_file(self, testdir):215 p1 = testdir.makepyfile(test_p1="""216 class BaseTests:217 def test_p1(self):218 pass219 class TestClass(BaseTests):220 pass 221 """)222 p2 = testdir.makepyfile(test_p2="""223 from test_p1 import BaseTests224 class TestMore(BaseTests):225 pass226 """)227 result = testdir.runpytest(p2)228 assert result.stdout.fnmatch_lines([229 "*test_p2.py .",230 "*1 passed*",231 ])232 result = testdir.runpytest("-v", p2)233 result.stdout.fnmatch_lines([234 "*test_p2.py <- *test_p1.py:2: TestMore.test_p1*",235 ])236 def test_keyboard_interrupt_dist(self, testdir, option):237 p = testdir.makepyfile("""238 raise KeyboardInterrupt239 """)240 result = testdir.runpytest(*option._getcmdargs())241 assert result.ret == 2242 result.stdout.fnmatch_lines(['*KEYBOARD INTERRUPT*'])243 @py.test.mark.nodist244 def test_keyboard_interrupt(self, testdir, option):245 p = testdir.makepyfile("""246 def test_foobar():247 assert 0248 def test_spamegg():249 import py; py.test.skip('skip me please!')250 def test_interrupt_me():251 raise KeyboardInterrupt # simulating the user252 """)253 result = testdir.runpytest(*option._getcmdargs())254 result.stdout.fnmatch_lines([255 " def test_foobar():",256 "> assert 0",257 "E assert 0",258 "*_keyboard_interrupt.py:6: KeyboardInterrupt*", 259 ])260 if option.verbose:261 result.stdout.fnmatch_lines([262 "*raise KeyboardInterrupt # simulating the user*",263 ])264 result.stdout.fnmatch_lines(['*KEYBOARD INTERRUPT*'])265 def test_skip_reasons_folding(self):266 class longrepr:267 class reprcrash:268 path = 'xyz'269 lineno = 3270 message = "justso"271 ev1 = runner.CollectReport(None, None)272 ev1.when = "execute"273 ev1.skipped = True274 ev1.longrepr = longrepr 275 276 ev2 = runner.ItemTestReport(None, excinfo=longrepr)277 ev2.skipped = True278 l = folded_skips([ev1, ev2])279 assert len(l) == 1280 num, fspath, lineno, reason = l[0]281 assert num == 2282 assert fspath == longrepr.reprcrash.path283 assert lineno == longrepr.reprcrash.lineno284 assert reason == longrepr.reprcrash.message285class TestCollectonly:286 def test_collectonly_basic(self, testdir, linecomp):287 modcol = testdir.getmodulecol(configargs=['--collectonly'], source="""288 def test_func():289 pass290 """)291 rep = CollectonlyReporter(modcol.config, out=linecomp.stringio)292 modcol.config.pluginmanager.register(rep)293 indent = rep.indent294 rep.config.hook.pytest_collectstart(collector=modcol)295 linecomp.assert_contains_lines([296 "<Module 'test_collectonly_basic.py'>"297 ])298 item = modcol.join("test_func")299 rep.config.hook.pytest_itemstart(item=item)300 linecomp.assert_contains_lines([301 " <Function 'test_func'>", 302 ])303 rep.config.hook.pytest_collectreport(304 report=runner.CollectReport(modcol, [], excinfo=None))305 assert rep.indent == indent 306 def test_collectonly_skipped_module(self, testdir, linecomp):307 modcol = testdir.getmodulecol(configargs=['--collectonly'], source="""308 import py309 py.test.skip("nomod")310 """)311 rep = CollectonlyReporter(modcol.config, out=linecomp.stringio)312 modcol.config.pluginmanager.register(rep)313 cols = list(testdir.genitems([modcol]))314 assert len(cols) == 0315 linecomp.assert_contains_lines("""316 <Module 'test_collectonly_skipped_module.py'>317 !!! Skipped: 'nomod' !!!318 """)319 def test_collectonly_failed_module(self, testdir, linecomp):320 modcol = testdir.getmodulecol(configargs=['--collectonly'], source="""321 raise ValueError(0)322 """)323 rep = CollectonlyReporter(modcol.config, out=linecomp.stringio)324 modcol.config.pluginmanager.register(rep)325 cols = list(testdir.genitems([modcol]))326 assert len(cols) == 0327 linecomp.assert_contains_lines("""328 <Module 'test_collectonly_failed_module.py'>329 !!! ValueError: 0 !!!330 """)331 def test_collectonly_fatal(self, testdir):332 p1 = testdir.makeconftest("""333 def pytest_collectstart(collector):334 assert 0, "urgs" 335 """)336 result = testdir.runpytest("--collectonly") 337 result.stdout.fnmatch_lines([338 "*INTERNAL*args*"339 ])340 assert result.ret == 3341 def test_collectonly_simple(self, testdir):342 p = testdir.makepyfile("""343 def test_func1():344 pass345 class TestClass:346 def test_method(self):347 pass348 """)349 result = testdir.runpytest("--collectonly", p)350 stderr = result.stderr.str().strip()351 assert stderr.startswith("inserting into sys.path")352 assert result.ret == 0353 extra = result.stdout.fnmatch_lines(py.code.Source("""354 <Module '*.py'>355 <Function 'test_func1'*>356 <Class 'TestClass'>357 <Instance '()'>358 <Function 'test_method'*>359 """).strip())360 def test_collectonly_error(self, testdir):361 p = testdir.makepyfile("import Errlkjqweqwe")362 result = testdir.runpytest("--collectonly", p)363 stderr = result.stderr.str().strip()364 assert stderr.startswith("inserting into sys.path")365 assert result.ret == 1366 extra = result.stdout.fnmatch_lines(py.code.Source("""367 <Module '*.py'>368 *ImportError*369 !!!*failures*!!!370 *test_collectonly_error.py:1*371 """).strip())372def test_repr_python_version(monkeypatch):373 monkeypatch.setattr(sys, 'version_info', (2, 5, 1, 'final', 0))374 assert repr_pythonversion() == "2.5.1-final-0"375 py.std.sys.version_info = x = (2,3)376 assert repr_pythonversion() == str(x) 377class TestFixtureReporting:378 def test_setup_fixture_error(self, testdir):379 p = testdir.makepyfile("""380 def setup_function(function):381 print "setup func"382 assert 0383 def test_nada():384 pass385 """)386 result = testdir.runpytest()387 result.stdout.fnmatch_lines([388 "*ERROR at setup of test_nada*",389 "*setup_function(function):*",390 "*setup func*",391 "*assert 0*",392 "*1 error*",393 ])394 assert result.ret != 0395 396 def test_teardown_fixture_error(self, testdir):397 p = testdir.makepyfile("""398 def test_nada():399 pass400 def teardown_function(function):401 print "teardown func"402 assert 0403 """)404 result = testdir.runpytest()405 result.stdout.fnmatch_lines([406 "*ERROR at teardown*", 407 "*teardown_function(function):*",408 "*assert 0*",409 "*Captured stdout*",410 "*teardown func*",411 "*1 passed*1 error*",412 ])413 def test_teardown_fixture_error_and_test_failure(self, testdir):414 p = testdir.makepyfile("""415 def test_fail():416 assert 0, "failingfunc"417 def teardown_function(function):418 print "teardown func"419 assert False420 """)421 result = testdir.runpytest()422 result.stdout.fnmatch_lines([423 "*ERROR at teardown of test_fail*", 424 "*teardown_function(function):*",425 "*assert False*",426 "*Captured stdout*",427 "*teardown func*",428 "*test_fail*", 429 "*def test_fail():",430 "*failingfunc*",431 "*1 failed*1 error*",432 ])433class TestTerminalFunctional:434 def test_skipped_reasons(self, testdir):435 testdir.makepyfile(436 test_one="""437 from conftest import doskip438 def setup_function(func):439 doskip()440 def test_func():441 pass442 class TestClass:443 def test_method(self):444 doskip()445 """,446 test_two = """447 from conftest import doskip448 doskip()449 """,450 conftest = """451 import py452 def doskip():453 py.test.skip('test')454 """455 )456 result = testdir.runpytest() 457 extra = result.stdout.fnmatch_lines([458 "*test_one.py ss",459 "*test_two.py S",460 "___* skipped test summary *_", 461 "*conftest.py:3: *3* Skipped: 'test'", 462 ])463 assert result.ret == 0464 def test_deselected(self, testdir):465 testpath = testdir.makepyfile("""466 def test_one():467 pass468 def test_two():469 pass470 def test_three():471 pass472 """473 )474 result = testdir.runpytest("-k", "test_two:", testpath)475 extra = result.stdout.fnmatch_lines([476 "*test_deselected.py ..", 477 "=* 1 test*deselected by 'test_two:'*=", 478 ])479 assert result.ret == 0480 def test_no_skip_summary_if_failure(self, testdir):481 testdir.makepyfile("""482 import py483 def test_ok():484 pass485 def test_fail():486 assert 0487 def test_skip():488 py.test.skip("dontshow")489 """)490 result = testdir.runpytest() 491 assert result.stdout.str().find("skip test summary") == -1492 assert result.ret == 1493 def test_passes(self, testdir):494 p1 = testdir.makepyfile("""495 def test_passes():496 pass497 class TestClass:498 def test_method(self):499 pass500 """)501 old = p1.dirpath().chdir()502 try:503 result = testdir.runpytest()504 finally:505 old.chdir()506 extra = result.stdout.fnmatch_lines([507 "test_passes.py ..", 508 "* 2 pass*",509 ])510 assert result.ret == 0511 def test_header_trailer_info(self, testdir):512 p1 = testdir.makepyfile("""513 def test_passes():514 pass515 """)516 result = testdir.runpytest()517 verinfo = ".".join(map(str, py.std.sys.version_info[:3]))518 extra = result.stdout.fnmatch_lines([519 "*===== test session starts ====*",520 "python: platform %s -- Python %s*" %(521 py.std.sys.platform, verinfo), # , py.std.sys.executable),522 "*test_header_trailer_info.py .",523 "=* 1 passed in *.[0-9][0-9] seconds *=", 524 ])525 def test_traceback_failure(self, testdir):526 p1 = testdir.makepyfile("""527 def g():528 return 2529 def f(x):530 assert x == g()531 def test_onefails():532 f(3)533 """)534 result = testdir.runpytest(p1)535 result.stdout.fnmatch_lines([536 "*test_traceback_failure.py F", 537 "====* FAILURES *====",538 "____*____", 539 "",540 " def test_onefails():",541 "> f(3)",542 "",543 "*test_*.py:6: ",544 "_ _ _ *",545 #"",546 " def f(x):",547 "> assert x == g()",548 "E assert 3 == 2",549 "E + where 2 = g()",550 "",551 "*test_traceback_failure.py:4: AssertionError"552 ])553 def test_showlocals(self, testdir): 554 p1 = testdir.makepyfile("""555 def test_showlocals():556 x = 3557 y = "x" * 5000 558 assert 0559 """)560 result = testdir.runpytest(p1, '-l')561 result.stdout.fnmatch_lines([562 #"_ _ * Locals *", 563 "x* = 3",564 "y* = 'xxxxxx*"565 ])566 def test_verbose_reporting(self, testdir):567 p1 = testdir.makepyfile("""568 import py569 def test_fail():570 raise ValueError()571 def test_pass():572 pass573 class TestClass:574 def test_skip(self):575 py.test.skip("hello")576 def test_gen():577 def check(x):578 assert x == 1579 yield check, 0580 """)581 result = testdir.runpytest(p1, '-v')582 result.stdout.fnmatch_lines([583 "*test_verbose_reporting.py:2: test_fail*FAIL*", 584 "*test_verbose_reporting.py:4: test_pass*PASS*",585 "*test_verbose_reporting.py:7: TestClass.test_skip*SKIP*",586 "*test_verbose_reporting.py:10: test_gen*FAIL*",587 ])588 assert result.ret == 1589 result = testdir.runpytest(p1, '-v', '-n 1')590 result.stdout.fnmatch_lines([591 "*FAIL*test_verbose_reporting.py:2: test_fail*", 592 ])...

Full Screen

Full Screen

create_kitti_semantic_eval.py

Source:create_kitti_semantic_eval.py Github

copy

Full Screen

1import glob2import numpy as np3import os4import random5import argparse6def generateKittySemanticSplit(datasetLoc, splitFileLoc):7 val_fineList = list()8 for imagePath in glob.glob(os.path.join(datasetLoc, "training", "image_2", "*")):9 val_fineList.append(imagePath)10 random.shuffle(val_fineList)11 fileTrain = open(os.path.join(splitFileLoc, "train_files.txt"), "w+")12 fileTrain.close()13 fileVal = open(os.path.join(splitFileLoc, "val_files.txt"), "w+")14 for index, imagePath in enumerate(val_fineList):15 split_comp = imagePath.split("/")16 writeComp1 = os.path.join(split_comp[-3], split_comp[-2])17 writeComp2 = split_comp[-1]18 writeComp3 = 'l'19 writel = writeComp1 + '/' + writeComp2.split('.')[0] + " " + format(index, '010') + " " + writeComp3 + "\n"20 fileVal.writelines(writel)21 fileVal.close()22def generateKittiSemanDepthSplit(mappingFileLoc, splitFileLoc):23 with open('/media/shengjie/other/sceneUnderstanding/monodepth2/splits/train_mapping.txt') as f:24 mapping = f.readlines()25 mapping = [x.strip() for x in mapping]26 fileTrain = open(os.path.join(splitFileLoc, "train_files.txt"), "w+")27 for line in mapping:28 if len(line) > 1:29 lineComp = line.split(' ')30 writel = lineComp[0] + '/' + lineComp[1] + ' ' + str(int(lineComp[2])) + ' ' + 'l\n'31 fileTrain.writelines(writel)32 fileTrain.close()33 fileVal = open(os.path.join(splitFileLoc, "val_files.txt"), "w+")34 for line in mapping:35 if len(line) > 1:36 lineComp = line.split(' ')37 writel = lineComp[0] + '/' + lineComp[1] + ' ' + str(int(lineComp[2])) + ' ' + 'l\n'38 fileVal.writelines(writel)39 fileVal.close()40def generateKittiToyExaple(mappingFileLoc, splitFileLoc):41 repeatTime = 500042 with open('/media/shengjie/other/sceneUnderstanding/monodepth2/splits/train_mapping.txt') as f:43 mapping = f.readlines()44 mapping = [x.strip() for x in mapping]45 fileTrain = open(os.path.join(splitFileLoc, "train_files.txt"), "w+")46 for i in range(repeatTime):47 line = mapping[2]48 lineComp = line.split(' ')49 if random.random() > 0.5:50 writel = lineComp[0] + '/' + lineComp[1] + ' ' + str(int(lineComp[2])) + ' ' + 'l\n'51 else:52 writel = lineComp[0] + '/' + lineComp[1] + ' ' + str(int(lineComp[2])) + ' ' + 'r\n'53 fileTrain.writelines(writel)54 fileTrain.close()55 fileVal = open(os.path.join(splitFileLoc, "val_files.txt"), "w+")56 for i in range(repeatTime):57 line = mapping[2]58 lineComp = line.split(' ')59 writel = lineComp[0] + '/' + lineComp[1] + ' ' + str(int(lineComp[2])) + ' ' + 'l\n'60 fileVal.writelines(writel)61 fileVal.close()62def generateKittiWithSemanticPredictions(splitFileLoc, kitti_dataset_root):63 fileTrain = open(os.path.join(splitFileLoc, "train_files.txt"), "w+")64 fileVal = open(os.path.join(splitFileLoc, "val_files.txt"), "w+")65 img_dir_names = glob.glob(kitti_dataset_root + '/*/')66 for img_dir_name in img_dir_names:67 img_subdir_names = glob.glob(os.path.join(kitti_dataset_root, img_dir_name) + '/*/')68 for img_subdir_name in img_subdir_names:69 inspected_rng_02 = os.path.join(kitti_dataset_root, img_dir_name, img_subdir_name, 'image_02', 'data')70 inspected_rng_03 = os.path.join(kitti_dataset_root, img_dir_name, img_subdir_name, 'image_03', 'data')71 for rgb_path in glob.glob(os.path.join(inspected_rng_02, '*.png')):72 semantic_rgb_path = rgb_path.replace('image_02/data', 'semantic_prediction/image_02')73 if os.path.isfile(semantic_rgb_path):74 path_components = semantic_rgb_path.split('/')75 to_write = os.path.join(path_components[-5], path_components[-4]) + ' ' + str(int(path_components[-1].split('.')[0])) + ' ' + 'l' + '\n'76 fileTrain.writelines(to_write)77 fileVal.writelines(to_write)78 for rgb_path in glob.glob(os.path.join(inspected_rng_03, '*.png')):79 semantic_rgb_path = rgb_path.replace('image_03/data', 'semantic_prediction/image_03')80 if os.path.isfile(semantic_rgb_path):81 path_components = semantic_rgb_path.split('/')82 to_write = os.path.join(path_components[-5], path_components[-4]) + ' ' + str(int(path_components[-1].split('.')[0])) + ' ' + 'l' + '\n'83 fileTrain.writelines(to_write)84 fileVal.writelines(to_write)85 fileTrain.close()86 fileVal.close()87parser = argparse.ArgumentParser(description='evaluation')88parser.add_argument('--kitti_dataset_root', type=str)89parser.add_argument('--splitFileLoc', type=str)90args = parser.parse_args()91if __name__ == "__main__":92 # datasetLoc = "/media/shengjie/other/sceneUnderstanding/monodepth2/kitti_data/kitti_semantics"93 # splitFileLoc = "/media/shengjie/other/sceneUnderstanding/monodepth2/splits/kitti_semantic_eval"94 # generateKittiSemanDepthSplit(datasetLoc, splitFileLoc)95 # mappingFileLoc = "/media/shengjie/other/sceneUnderstanding/monodepth2/kitti_data/kitti_semantics"96 # splitFileLoc = "/media/shengjie/other/sceneUnderstanding/monodepth2/splits/kitti_seman_mapped2depth"97 # generateKittiSemanDepthSplit(mappingFileLoc, splitFileLoc)98 # mappingFileLoc = "/media/shengjie/other/sceneUnderstanding/monodepth2/kitti_data/kitti_semantics"99 # splitFileLoc = "/media/shengjie/other/sceneUnderstanding/monodepth2/splits/kitti_seman_mapped_toy"100 # generateKittiToyExaple(mappingFileLoc, splitFileLoc)...

Full Screen

Full Screen

callhome_get_1_best.py

Source:callhome_get_1_best.py Github

copy

Full Screen

1#!/usr/bin/env python2# Copyright 2014 Gaurav Kumar. Apache 2.03# Extracts one best output for a set of files4# The list of files in the conversations for which 1 best output has to be extracted5# words.txt 6import os7import sys8def findTranscription(timeDetail):9 file1 = open('exp/tri5a/decode_callhome_dev/scoring/13.tra')10 file2 = open('exp/tri5a/decode_callhome_train/scoring/13.tra')11 for line in file1:12 lineComp = line.split()13 if lineComp[0] == timeDetail:14 return " ".join(lineComp[1:])15 for line in file2:16 lineComp = line.split()17 if lineComp[0] == timeDetail:18 return " ".join(lineComp[1:])19 # No result found20 return -121wordsFile = open('exp/tri5a/graph/words.txt')22words = {}23# Extract word list24for line in wordsFile:25 lineComp = line.split()26 words[int(lineComp[1])] = lineComp[0].strip()27# Now read list of files in conversations28fileList = []29#conversationList = open('/export/a04/gkumar/corpora/fishcall/joshkal-splits/provisional_dev')30conversationList = open('/export/a04/gkumar/corpora/fishcall/jack-splits/split-callhome/train')31for line in conversationList: 32 line = line.strip()33 line = line[:-4]34 fileList.append(line)35# IN what order were the conversations added to the spanish files?36# TODO: Make sure they match the order in which these english files are being written37# Now get timing information to concatenate the ASR outputs38if not os.path.exists('exp/tri5a/one-best/ch_train'):39 os.makedirs('exp/tri5a/one-best/ch_train')40#provFile = open('/export/a04/gkumar/corpora/fishcall/fisher_provisional_dev.es', 'w+')41provFile = open('/export/a04/gkumar/corpora/fishcall/jack-splits/split-callhome/asr.train', 'w+')42for item in fileList:43 timingFile = open('/export/a04/gkumar/corpora/fishcall/callhome/tim/' + item + '.es')44 newFile = open('exp/tri5a/one-best/ch_train/' + item + '.es', 'w+')45 for line in timingFile:46 timeInfo = line.split()47 mergedTranslation = ""48 for timeDetail in timeInfo:49 #Locate this in ASR dev/test, this is going to be very slow50 tmp = findTranscription(timeDetail)51 if tmp != -1:52 mergedTranslation = mergedTranslation + " " + tmp53 mergedTranslation = mergedTranslation.strip()54 transWords = [words[int(x)] for x in mergedTranslation.split()]55 newFile.write(" ".join(transWords) + "\n")56 provFile.write(" ".join(transWords) + "\n")57 newFile.close()58provFile.close()...

Full Screen

Full Screen

Pytest Tutorial

Looking for an in-depth tutorial around pytest? LambdaTest covers the detailed pytest tutorial that has everything related to the pytest, from setting up the pytest framework to automation testing. Delve deeper into pytest testing by exploring advanced use cases like parallel testing, pytest fixtures, parameterization, executing multiple test cases from a single file, and more.

Chapters

  1. What is pytest
  2. Pytest installation: Want to start pytest from scratch? See how to install and configure pytest for Python automation testing.
  3. Run first test with pytest framework: Follow this step-by-step tutorial to write and run your first pytest script.
  4. Parallel testing with pytest: A hands-on guide to parallel testing with pytest to improve the scalability of your test automation.
  5. Generate pytest reports: Reports make it easier to understand the results of pytest-based test runs. Learn how to generate pytest reports.
  6. Pytest Parameterized tests: Create and run your pytest scripts while avoiding code duplication and increasing test coverage with parameterization.
  7. Pytest Fixtures: Check out how to implement pytest fixtures for your end-to-end testing needs.
  8. Execute Multiple Test Cases: Explore different scenarios for running multiple test cases in pytest from a single file.
  9. Stop Test Suite after N Test Failures: See how to stop your test suite after n test failures in pytest using the @pytest.mark.incremental decorator and maxfail command-line option.

YouTube

Skim our below pytest tutorial playlist to get started with automation testing using the pytest framework.

https://www.youtube.com/playlist?list=PLZMWkkQEwOPlcGgDmHl8KkXKeLF83XlrP

Run Pytest automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful