Best JavaScript code snippet using puppeteer
ldb_test.py
Source:ldb_test.py
1import os2import os.path3import shutil4import subprocess5import time6import unittest7import tempfile8def my_check_output(*popenargs, **kwargs):9 """10 If we had python 2.7, we should simply use subprocess.check_output.11 This is a stop-gap solution for python 2.612 """13 if 'stdout' in kwargs:14 raise ValueError('stdout argument not allowed, it will be overridden.')15 process = subprocess.Popen(stderr=subprocess.PIPE, stdout=subprocess.PIPE,16 *popenargs, **kwargs)17 output, unused_err = process.communicate()18 retcode = process.poll()19 if retcode:20 cmd = kwargs.get("args")21 if cmd is None:22 cmd = popenargs[0]23 raise Exception("Exit code is not 0. It is %d. Command: %s" %24 (retcode, cmd))25 return output26def run_err_null(cmd):27 return os.system(cmd + " 2>/dev/null ")28class LDBTestCase(unittest.TestCase):29 def setUp(self):30 self.TMP_DIR = tempfile.mkdtemp(prefix="ldb_test_")31 self.DB_NAME = "testdb"32 def tearDown(self):33 assert(self.TMP_DIR.strip() != "/"34 and self.TMP_DIR.strip() != "/tmp"35 and self.TMP_DIR.strip() != "/tmp/") #Just some paranoia36 shutil.rmtree(self.TMP_DIR)37 def dbParam(self, dbName):38 return "--db=%s" % os.path.join(self.TMP_DIR, dbName)39 def assertRunOKFull(self, params, expectedOutput, unexpected=False):40 """41 All command-line params must be specified.42 Allows full flexibility in testing; for example: missing db param.43 """44 output = my_check_output("./ldb %s |grep -v \"Created bg thread\"" %45 params, shell=True)46 if not unexpected:47 self.assertEqual(output.strip(), expectedOutput.strip())48 else:49 self.assertNotEqual(output.strip(), expectedOutput.strip())50 def assertRunFAILFull(self, params):51 """52 All command-line params must be specified.53 Allows full flexibility in testing; for example: missing db param.54 """55 try:56 my_check_output("./ldb %s >/dev/null 2>&1 |grep -v \"Created bg \57 thread\"" % params, shell=True)58 except Exception, e:59 return60 self.fail(61 "Exception should have been raised for command with params: %s" %62 params)63 def assertRunOK(self, params, expectedOutput, unexpected=False):64 """65 Uses the default test db.66 """67 self.assertRunOKFull("%s %s" % (self.dbParam(self.DB_NAME), params),68 expectedOutput, unexpected)69 def assertRunFAIL(self, params):70 """71 Uses the default test db.72 """73 self.assertRunFAILFull("%s %s" % (self.dbParam(self.DB_NAME), params))74 def testSimpleStringPutGet(self):75 print "Running testSimpleStringPutGet..."76 self.assertRunFAIL("put x1 y1")77 self.assertRunOK("put --create_if_missing x1 y1", "OK")78 self.assertRunOK("get x1", "y1")79 self.assertRunFAIL("get x2")80 self.assertRunOK("put x2 y2", "OK")81 self.assertRunOK("get x1", "y1")82 self.assertRunOK("get x2", "y2")83 self.assertRunFAIL("get x3")84 self.assertRunOK("scan --from=x1 --to=z", "x1 : y1\nx2 : y2")85 self.assertRunOK("put x3 y3", "OK")86 self.assertRunOK("scan --from=x1 --to=z", "x1 : y1\nx2 : y2\nx3 : y3")87 self.assertRunOK("scan", "x1 : y1\nx2 : y2\nx3 : y3")88 self.assertRunOK("scan --from=x", "x1 : y1\nx2 : y2\nx3 : y3")89 self.assertRunOK("scan --to=x2", "x1 : y1")90 self.assertRunOK("scan --from=x1 --to=z --max_keys=1", "x1 : y1")91 self.assertRunOK("scan --from=x1 --to=z --max_keys=2",92 "x1 : y1\nx2 : y2")93 self.assertRunOK("scan --from=x1 --to=z --max_keys=3",94 "x1 : y1\nx2 : y2\nx3 : y3")95 self.assertRunOK("scan --from=x1 --to=z --max_keys=4",96 "x1 : y1\nx2 : y2\nx3 : y3")97 self.assertRunOK("scan --from=x1 --to=x2", "x1 : y1")98 self.assertRunOK("scan --from=x2 --to=x4", "x2 : y2\nx3 : y3")99 self.assertRunFAIL("scan --from=x4 --to=z") # No results => FAIL100 self.assertRunFAIL("scan --from=x1 --to=z --max_keys=foo")101 self.assertRunOK("scan", "x1 : y1\nx2 : y2\nx3 : y3")102 self.assertRunOK("delete x1", "OK")103 self.assertRunOK("scan", "x2 : y2\nx3 : y3")104 self.assertRunOK("delete NonExistentKey", "OK")105 # It is weird that GET and SCAN raise exception for106 # non-existent key, while delete does not107 self.assertRunOK("checkconsistency", "OK")108 def dumpDb(self, params, dumpFile):109 return 0 == run_err_null("./ldb dump %s > %s" % (params, dumpFile))110 def loadDb(self, params, dumpFile):111 return 0 == run_err_null("cat %s | ./ldb load %s" % (dumpFile, params))112 def testStringBatchPut(self):113 print "Running testStringBatchPut..."114 self.assertRunOK("batchput x1 y1 --create_if_missing", "OK")115 self.assertRunOK("scan", "x1 : y1")116 self.assertRunOK("batchput x2 y2 x3 y3 \"x4 abc\" \"y4 xyz\"", "OK")117 self.assertRunOK("scan", "x1 : y1\nx2 : y2\nx3 : y3\nx4 abc : y4 xyz")118 self.assertRunFAIL("batchput")119 self.assertRunFAIL("batchput k1")120 self.assertRunFAIL("batchput k1 v1 k2")121 def testCountDelimDump(self):122 print "Running testCountDelimDump..."123 self.assertRunOK("batchput x.1 x1 --create_if_missing", "OK")124 self.assertRunOK("batchput y.abc abc y.2 2 z.13c pqr", "OK")125 self.assertRunOK("dump --count_delim", "x => count:1\tsize:5\ny => count:2\tsize:12\nz => count:1\tsize:8")126 self.assertRunOK("dump --count_delim=\".\"", "x => count:1\tsize:5\ny => count:2\tsize:12\nz => count:1\tsize:8")127 self.assertRunOK("batchput x,2 x2 x,abc xabc", "OK")128 self.assertRunOK("dump --count_delim=\",\"", "x => count:2\tsize:14\nx.1 => count:1\tsize:5\ny.2 => count:1\tsize:4\ny.abc => count:1\tsize:8\nz.13c => count:1\tsize:8")129 def testCountDelimIDump(self):130 print "Running testCountDelimIDump..."131 self.assertRunOK("batchput x.1 x1 --create_if_missing", "OK")132 self.assertRunOK("batchput y.abc abc y.2 2 z.13c pqr", "OK")133 self.assertRunOK("dump --count_delim", "x => count:1\tsize:5\ny => count:2\tsize:12\nz => count:1\tsize:8")134 self.assertRunOK("dump --count_delim=\".\"", "x => count:1\tsize:5\ny => count:2\tsize:12\nz => count:1\tsize:8")135 self.assertRunOK("batchput x,2 x2 x,abc xabc", "OK")136 self.assertRunOK("dump --count_delim=\",\"", "x => count:2\tsize:14\nx.1 => count:1\tsize:5\ny.2 => count:1\tsize:4\ny.abc => count:1\tsize:8\nz.13c => count:1\tsize:8")137 def testInvalidCmdLines(self):138 print "Running testInvalidCmdLines..."139 # db not specified140 self.assertRunFAILFull("put 0x6133 0x6233 --hex --create_if_missing")141 # No param called he142 self.assertRunFAIL("put 0x6133 0x6233 --he --create_if_missing")143 # max_keys is not applicable for put144 self.assertRunFAIL("put 0x6133 0x6233 --max_keys=1 --create_if_missing")145 # hex has invalid boolean value146 def testHexPutGet(self):147 print "Running testHexPutGet..."148 self.assertRunOK("put a1 b1 --create_if_missing", "OK")149 self.assertRunOK("scan", "a1 : b1")150 self.assertRunOK("scan --hex", "0x6131 : 0x6231")151 self.assertRunFAIL("put --hex 6132 6232")152 self.assertRunOK("put --hex 0x6132 0x6232", "OK")153 self.assertRunOK("scan --hex", "0x6131 : 0x6231\n0x6132 : 0x6232")154 self.assertRunOK("scan", "a1 : b1\na2 : b2")155 self.assertRunOK("get a1", "b1")156 self.assertRunOK("get --hex 0x6131", "0x6231")157 self.assertRunOK("get a2", "b2")158 self.assertRunOK("get --hex 0x6132", "0x6232")159 self.assertRunOK("get --key_hex 0x6132", "b2")160 self.assertRunOK("get --key_hex --value_hex 0x6132", "0x6232")161 self.assertRunOK("get --value_hex a2", "0x6232")162 self.assertRunOK("scan --key_hex --value_hex",163 "0x6131 : 0x6231\n0x6132 : 0x6232")164 self.assertRunOK("scan --hex --from=0x6131 --to=0x6133",165 "0x6131 : 0x6231\n0x6132 : 0x6232")166 self.assertRunOK("scan --hex --from=0x6131 --to=0x6132",167 "0x6131 : 0x6231")168 self.assertRunOK("scan --key_hex", "0x6131 : b1\n0x6132 : b2")169 self.assertRunOK("scan --value_hex", "a1 : 0x6231\na2 : 0x6232")170 self.assertRunOK("batchput --hex 0x6133 0x6233 0x6134 0x6234", "OK")171 self.assertRunOK("scan", "a1 : b1\na2 : b2\na3 : b3\na4 : b4")172 self.assertRunOK("delete --hex 0x6133", "OK")173 self.assertRunOK("scan", "a1 : b1\na2 : b2\na4 : b4")174 self.assertRunOK("checkconsistency", "OK")175 def testTtlPutGet(self):176 print "Running testTtlPutGet..."177 self.assertRunOK("put a1 b1 --ttl --create_if_missing", "OK")178 self.assertRunOK("scan --hex", "0x6131 : 0x6231", True)179 self.assertRunOK("dump --ttl ", "a1 ==> b1", True)180 self.assertRunOK("dump --hex --ttl ",181 "0x6131 ==> 0x6231\nKeys in range: 1")182 self.assertRunOK("scan --hex --ttl", "0x6131 : 0x6231")183 self.assertRunOK("get --value_hex a1", "0x6231", True)184 self.assertRunOK("get --ttl a1", "b1")185 self.assertRunOK("put a3 b3 --create_if_missing", "OK")186 # fails because timstamp's length is greater than value's187 self.assertRunFAIL("get --ttl a3")188 self.assertRunOK("checkconsistency", "OK")189 def testInvalidCmdLines(self):190 print "Running testInvalidCmdLines..."191 # db not specified192 self.assertRunFAILFull("put 0x6133 0x6233 --hex --create_if_missing")193 # No param called he194 self.assertRunFAIL("put 0x6133 0x6233 --he --create_if_missing")195 # max_keys is not applicable for put196 self.assertRunFAIL("put 0x6133 0x6233 --max_keys=1 --create_if_missing")197 # hex has invalid boolean value198 self.assertRunFAIL("put 0x6133 0x6233 --hex=Boo --create_if_missing")199 def testDumpLoad(self):200 print "Running testDumpLoad..."201 self.assertRunOK("batchput --create_if_missing x1 y1 x2 y2 x3 y3 x4 y4",202 "OK")203 self.assertRunOK("scan", "x1 : y1\nx2 : y2\nx3 : y3\nx4 : y4")204 origDbPath = os.path.join(self.TMP_DIR, self.DB_NAME)205 # Dump and load without any additional params specified206 dumpFilePath = os.path.join(self.TMP_DIR, "dump1")207 loadedDbPath = os.path.join(self.TMP_DIR, "loaded_from_dump1")208 self.assertTrue(self.dumpDb("--db=%s" % origDbPath, dumpFilePath))209 self.assertTrue(self.loadDb(210 "--db=%s --create_if_missing" % loadedDbPath, dumpFilePath))211 self.assertRunOKFull("scan --db=%s" % loadedDbPath,212 "x1 : y1\nx2 : y2\nx3 : y3\nx4 : y4")213 # Dump and load in hex214 dumpFilePath = os.path.join(self.TMP_DIR, "dump2")215 loadedDbPath = os.path.join(self.TMP_DIR, "loaded_from_dump2")216 self.assertTrue(self.dumpDb("--db=%s --hex" % origDbPath, dumpFilePath))217 self.assertTrue(self.loadDb(218 "--db=%s --hex --create_if_missing" % loadedDbPath, dumpFilePath))219 self.assertRunOKFull("scan --db=%s" % loadedDbPath,220 "x1 : y1\nx2 : y2\nx3 : y3\nx4 : y4")221 # Dump only a portion of the key range222 dumpFilePath = os.path.join(self.TMP_DIR, "dump3")223 loadedDbPath = os.path.join(self.TMP_DIR, "loaded_from_dump3")224 self.assertTrue(self.dumpDb(225 "--db=%s --from=x1 --to=x3" % origDbPath, dumpFilePath))226 self.assertTrue(self.loadDb(227 "--db=%s --create_if_missing" % loadedDbPath, dumpFilePath))228 self.assertRunOKFull("scan --db=%s" % loadedDbPath, "x1 : y1\nx2 : y2")229 # Dump upto max_keys rows230 dumpFilePath = os.path.join(self.TMP_DIR, "dump4")231 loadedDbPath = os.path.join(self.TMP_DIR, "loaded_from_dump4")232 self.assertTrue(self.dumpDb(233 "--db=%s --max_keys=3" % origDbPath, dumpFilePath))234 self.assertTrue(self.loadDb(235 "--db=%s --create_if_missing" % loadedDbPath, dumpFilePath))236 self.assertRunOKFull("scan --db=%s" % loadedDbPath,237 "x1 : y1\nx2 : y2\nx3 : y3")238 # Load into an existing db, create_if_missing is not specified239 self.assertTrue(self.dumpDb("--db=%s" % origDbPath, dumpFilePath))240 self.assertTrue(self.loadDb("--db=%s" % loadedDbPath, dumpFilePath))241 self.assertRunOKFull("scan --db=%s" % loadedDbPath,242 "x1 : y1\nx2 : y2\nx3 : y3\nx4 : y4")243 # Dump and load with WAL disabled244 dumpFilePath = os.path.join(self.TMP_DIR, "dump5")245 loadedDbPath = os.path.join(self.TMP_DIR, "loaded_from_dump5")246 self.assertTrue(self.dumpDb("--db=%s" % origDbPath, dumpFilePath))247 self.assertTrue(self.loadDb(248 "--db=%s --disable_wal --create_if_missing" % loadedDbPath,249 dumpFilePath))250 self.assertRunOKFull("scan --db=%s" % loadedDbPath,251 "x1 : y1\nx2 : y2\nx3 : y3\nx4 : y4")252 # Dump and load with lots of extra params specified253 extraParams = " ".join(["--bloom_bits=14", "--compression_type=bzip2",254 "--block_size=1024", "--auto_compaction=true",255 "--write_buffer_size=4194304",256 "--file_size=2097152"])257 dumpFilePath = os.path.join(self.TMP_DIR, "dump6")258 loadedDbPath = os.path.join(self.TMP_DIR, "loaded_from_dump6")259 self.assertTrue(self.dumpDb(260 "--db=%s %s" % (origDbPath, extraParams), dumpFilePath))261 self.assertTrue(self.loadDb(262 "--db=%s %s --create_if_missing" % (loadedDbPath, extraParams),263 dumpFilePath))264 self.assertRunOKFull("scan --db=%s" % loadedDbPath,265 "x1 : y1\nx2 : y2\nx3 : y3\nx4 : y4")266 # Dump with count_only267 dumpFilePath = os.path.join(self.TMP_DIR, "dump7")268 loadedDbPath = os.path.join(self.TMP_DIR, "loaded_from_dump7")269 self.assertTrue(self.dumpDb(270 "--db=%s --count_only" % origDbPath, dumpFilePath))271 self.assertTrue(self.loadDb(272 "--db=%s --create_if_missing" % loadedDbPath, dumpFilePath))273 # DB should have atleast one value for scan to work274 self.assertRunOKFull("put --db=%s k1 v1" % loadedDbPath, "OK")275 self.assertRunOKFull("scan --db=%s" % loadedDbPath, "k1 : v1")276 # Dump command fails because of typo in params277 dumpFilePath = os.path.join(self.TMP_DIR, "dump8")278 self.assertFalse(self.dumpDb(279 "--db=%s --create_if_missing" % origDbPath, dumpFilePath))280 def testMiscAdminTask(self):281 print "Running testMiscAdminTask..."282 # These tests need to be improved; for example with asserts about283 # whether compaction or level reduction actually took place.284 self.assertRunOK("batchput --create_if_missing x1 y1 x2 y2 x3 y3 x4 y4",285 "OK")286 self.assertRunOK("scan", "x1 : y1\nx2 : y2\nx3 : y3\nx4 : y4")287 origDbPath = os.path.join(self.TMP_DIR, self.DB_NAME)288 self.assertTrue(0 == run_err_null(289 "./ldb compact --db=%s" % origDbPath))290 self.assertRunOK("scan", "x1 : y1\nx2 : y2\nx3 : y3\nx4 : y4")291 self.assertTrue(0 == run_err_null(292 "./ldb reduce_levels --db=%s --new_levels=2" % origDbPath))293 self.assertRunOK("scan", "x1 : y1\nx2 : y2\nx3 : y3\nx4 : y4")294 self.assertTrue(0 == run_err_null(295 "./ldb reduce_levels --db=%s --new_levels=3" % origDbPath))296 self.assertRunOK("scan", "x1 : y1\nx2 : y2\nx3 : y3\nx4 : y4")297 self.assertTrue(0 == run_err_null(298 "./ldb compact --db=%s --from=x1 --to=x3" % origDbPath))299 self.assertRunOK("scan", "x1 : y1\nx2 : y2\nx3 : y3\nx4 : y4")300 self.assertTrue(0 == run_err_null(301 "./ldb compact --db=%s --hex --from=0x6131 --to=0x6134"302 % origDbPath))303 self.assertRunOK("scan", "x1 : y1\nx2 : y2\nx3 : y3\nx4 : y4")304 #TODO(dilip): Not sure what should be passed to WAL.Currently corrupted.305 self.assertTrue(0 == run_err_null(306 "./ldb dump_wal --db=%s --walfile=%s --header" % (307 origDbPath, os.path.join(origDbPath, "LOG"))))308 self.assertRunOK("scan", "x1 : y1\nx2 : y2\nx3 : y3\nx4 : y4")309 def testCheckConsistency(self):310 print "Running testCheckConsistency..."311 dbPath = os.path.join(self.TMP_DIR, self.DB_NAME)312 self.assertRunOK("put x1 y1 --create_if_missing", "OK")313 self.assertRunOK("put x2 y2", "OK")314 self.assertRunOK("get x1", "y1")315 self.assertRunOK("checkconsistency", "OK")316 sstFilePath = my_check_output("ls %s" % os.path.join(dbPath, "*.sst"),317 shell=True)318 # Modify the file319 my_check_output("echo 'evil' > %s" % sstFilePath, shell=True)320 self.assertRunFAIL("checkconsistency")321 # Delete the file322 my_check_output("rm -f %s" % sstFilePath, shell=True)323 self.assertRunFAIL("checkconsistency")324if __name__ == "__main__":...
test_query.py
Source:test_query.py
...33 def destroy(self):34 self.destroyed = True35 def test_entry_ok_blank(self):36 dialog = self.Dummy_Query(' ')37 self.assertEqual(dialog.entry_ok(), None)38 self.assertEqual((dialog.result, dialog.destroyed), (None, False))39 self.assertIn('blank line', dialog.entry_error['text'])40 def test_entry_ok_good(self):41 dialog = self.Dummy_Query(' good ')42 Equal = self.assertEqual43 Equal(dialog.entry_ok(), 'good')44 Equal((dialog.result, dialog.destroyed), (None, False))45 Equal(dialog.entry_error['text'], '')46 def test_ok_blank(self):47 dialog = self.Dummy_Query('')48 dialog.entry.focus_set = mock.Mock()49 self.assertEqual(dialog.ok(), None)50 self.assertTrue(dialog.entry.focus_set.called)51 del dialog.entry.focus_set52 self.assertEqual((dialog.result, dialog.destroyed), (None, False))53 def test_ok_good(self):54 dialog = self.Dummy_Query('good')55 self.assertEqual(dialog.ok(), None)56 self.assertEqual((dialog.result, dialog.destroyed), ('good', True))57 def test_cancel(self):58 dialog = self.Dummy_Query('does not matter')59 self.assertEqual(dialog.cancel(), None)60 self.assertEqual((dialog.result, dialog.destroyed), (None, True))61class SectionNameTest(unittest.TestCase):62 "Test SectionName subclass of Query."63 class Dummy_SectionName:64 entry_ok = query.SectionName.entry_ok # Function being tested.65 used_names = ['used']66 def __init__(self, dummy_entry):67 self.entry = Var(value=dummy_entry)68 self.entry_error = {'text': ''}69 def showerror(self, message):70 self.entry_error['text'] = message71 def test_blank_section_name(self):72 dialog = self.Dummy_SectionName(' ')73 self.assertEqual(dialog.entry_ok(), None)74 self.assertIn('no name', dialog.entry_error['text'])75 def test_used_section_name(self):76 dialog = self.Dummy_SectionName('used')77 self.assertEqual(dialog.entry_ok(), None)78 self.assertIn('use', dialog.entry_error['text'])79 def test_long_section_name(self):80 dialog = self.Dummy_SectionName('good'*8)81 self.assertEqual(dialog.entry_ok(), None)82 self.assertIn('longer than 30', dialog.entry_error['text'])83 def test_good_section_name(self):84 dialog = self.Dummy_SectionName(' good ')85 self.assertEqual(dialog.entry_ok(), 'good')86 self.assertEqual(dialog.entry_error['text'], '')87class ModuleNameTest(unittest.TestCase):88 "Test ModuleName subclass of Query."89 class Dummy_ModuleName:90 entry_ok = query.ModuleName.entry_ok # Function being tested.91 text0 = ''92 def __init__(self, dummy_entry):93 self.entry = Var(value=dummy_entry)94 self.entry_error = {'text': ''}95 def showerror(self, message):96 self.entry_error['text'] = message97 def test_blank_module_name(self):98 dialog = self.Dummy_ModuleName(' ')99 self.assertEqual(dialog.entry_ok(), None)100 self.assertIn('no name', dialog.entry_error['text'])101 def test_bogus_module_name(self):102 dialog = self.Dummy_ModuleName('__name_xyz123_should_not_exist__')103 self.assertEqual(dialog.entry_ok(), None)104 self.assertIn('not found', dialog.entry_error['text'])105 def test_c_source_name(self):106 dialog = self.Dummy_ModuleName('itertools')107 self.assertEqual(dialog.entry_ok(), None)108 self.assertIn('source-based', dialog.entry_error['text'])109 def test_good_module_name(self):110 dialog = self.Dummy_ModuleName('idlelib')111 self.assertTrue(dialog.entry_ok().endswith('__init__.py'))112 self.assertEqual(dialog.entry_error['text'], '')113class GotoTest(unittest.TestCase):114 "Test Goto subclass of Query."115 class Dummy_ModuleName:116 entry_ok = query.Goto.entry_ok # Function being tested.117 def __init__(self, dummy_entry):118 self.entry = Var(value=dummy_entry)119 self.entry_error = {'text': ''}120 def showerror(self, message):121 self.entry_error['text'] = message122 def test_bogus_goto(self):123 dialog = self.Dummy_ModuleName('a')124 self.assertEqual(dialog.entry_ok(), None)125 self.assertIn('not a base 10 integer', dialog.entry_error['text'])126 def test_bad_goto(self):127 dialog = self.Dummy_ModuleName('0')128 self.assertEqual(dialog.entry_ok(), None)129 self.assertIn('not a positive integer', dialog.entry_error['text'])130 def test_good_goto(self):131 dialog = self.Dummy_ModuleName('1')132 self.assertEqual(dialog.entry_ok(), 1)133 self.assertEqual(dialog.entry_error['text'], '')134# 3 HelpSource test classes each test one method.135class HelpsourceBrowsefileTest(unittest.TestCase):136 "Test browse_file method of ModuleName subclass of Query."137 class Dummy_HelpSource:138 browse_file = query.HelpSource.browse_file139 pathvar = Var()140 def test_file_replaces_path(self):141 dialog = self.Dummy_HelpSource()142 # Path is widget entry, either '' or something.143 # Func return is file dialog return, either '' or something.144 # Func return should override widget entry.145 # We need all 4 combinations to test all (most) code paths.146 for path, func, result in (147 ('', lambda a,b,c:'', ''),148 ('', lambda a,b,c: __file__, __file__),149 ('htest', lambda a,b,c:'', 'htest'),150 ('htest', lambda a,b,c: __file__, __file__)):151 with self.subTest():152 dialog.pathvar.set(path)153 dialog.askfilename = func154 dialog.browse_file()155 self.assertEqual(dialog.pathvar.get(), result)156class HelpsourcePathokTest(unittest.TestCase):157 "Test path_ok method of HelpSource subclass of Query."158 class Dummy_HelpSource:159 path_ok = query.HelpSource.path_ok160 def __init__(self, dummy_path):161 self.path = Var(value=dummy_path)162 self.path_error = {'text': ''}163 def showerror(self, message, widget=None):164 self.path_error['text'] = message165 orig_platform = query.platform # Set in test_path_ok_file.166 @classmethod167 def tearDownClass(cls):168 query.platform = cls.orig_platform169 def test_path_ok_blank(self):170 dialog = self.Dummy_HelpSource(' ')171 self.assertEqual(dialog.path_ok(), None)172 self.assertIn('no help file', dialog.path_error['text'])173 def test_path_ok_bad(self):174 dialog = self.Dummy_HelpSource(__file__ + 'bad-bad-bad')175 self.assertEqual(dialog.path_ok(), None)176 self.assertIn('not exist', dialog.path_error['text'])177 def test_path_ok_web(self):178 dialog = self.Dummy_HelpSource('')179 Equal = self.assertEqual180 for url in 'www.py.org', 'http://py.org':181 with self.subTest():182 dialog.path.set(url)183 self.assertEqual(dialog.path_ok(), url)184 self.assertEqual(dialog.path_error['text'], '')185 def test_path_ok_file(self):186 dialog = self.Dummy_HelpSource('')187 for platform, prefix in ('darwin', 'file://'), ('other', ''):188 with self.subTest():189 query.platform = platform190 dialog.path.set(__file__)191 self.assertEqual(dialog.path_ok(), prefix + __file__)192 self.assertEqual(dialog.path_error['text'], '')193class HelpsourceEntryokTest(unittest.TestCase):194 "Test entry_ok method of HelpSource subclass of Query."195 class Dummy_HelpSource:196 entry_ok = query.HelpSource.entry_ok197 entry_error = {}198 path_error = {}199 def item_ok(self):200 return self.name201 def path_ok(self):202 return self.path203 def test_entry_ok_helpsource(self):204 dialog = self.Dummy_HelpSource()205 for name, path, result in ((None, None, None),206 (None, 'doc.txt', None),207 ('doc', None, None),208 ('doc', 'doc.txt', ('doc', 'doc.txt'))):209 with self.subTest():210 dialog.name, dialog.path = name, path211 self.assertEqual(dialog.entry_ok(), result)212# 2 CustomRun test classes each test one method.213class CustomRunCLIargsokTest(unittest.TestCase):214 "Test cli_ok method of the CustomRun subclass of Query."215 class Dummy_CustomRun:216 cli_args_ok = query.CustomRun.cli_args_ok217 def __init__(self, dummy_entry):218 self.entry = Var(value=dummy_entry)219 self.entry_error = {'text': ''}220 def showerror(self, message):221 self.entry_error['text'] = message222 def test_blank_args(self):223 dialog = self.Dummy_CustomRun(' ')224 self.assertEqual(dialog.cli_args_ok(), [])225 def test_invalid_args(self):226 dialog = self.Dummy_CustomRun("'no-closing-quote")227 self.assertEqual(dialog.cli_args_ok(), None)228 self.assertIn('No closing', dialog.entry_error['text'])229 def test_good_args(self):230 args = ['-n', '10', '--verbose', '-p', '/path', '--name']231 dialog = self.Dummy_CustomRun(' '.join(args) + ' "my name"')232 self.assertEqual(dialog.cli_args_ok(), args + ["my name"])233 self.assertEqual(dialog.entry_error['text'], '')234class CustomRunEntryokTest(unittest.TestCase):235 "Test entry_ok method of the CustomRun subclass of Query."236 class Dummy_CustomRun:237 entry_ok = query.CustomRun.entry_ok238 entry_error = {}239 restartvar = Var()240 def cli_args_ok(self):241 return self.cli_args242 def test_entry_ok_customrun(self):243 dialog = self.Dummy_CustomRun()244 for restart in {True, False}:245 dialog.restartvar.set(restart)246 for cli_args, result in ((None, None),247 (['my arg'], (['my arg'], restart))):248 with self.subTest(restart=restart, cli_args=cli_args):249 dialog.cli_args = cli_args250 self.assertEqual(dialog.entry_ok(), result)251# GUI TESTS252class QueryGuiTest(unittest.TestCase):253 @classmethod254 def setUpClass(cls):255 requires('gui')256 cls.root = root = Tk()257 cls.root.withdraw()258 cls.dialog = query.Query(root, 'TEST', 'test', _utest=True)259 cls.dialog.destroy = mock.Mock()260 @classmethod261 def tearDownClass(cls):262 del cls.dialog.destroy263 del cls.dialog264 cls.root.destroy()265 del cls.root266 def setUp(self):267 self.dialog.entry.delete(0, 'end')268 self.dialog.result = None269 self.dialog.destroy.reset_mock()270 def test_click_ok(self):271 dialog = self.dialog272 dialog.entry.insert(0, 'abc')273 dialog.button_ok.invoke()274 self.assertEqual(dialog.result, 'abc')275 self.assertTrue(dialog.destroy.called)276 def test_click_blank(self):277 dialog = self.dialog278 dialog.button_ok.invoke()279 self.assertEqual(dialog.result, None)280 self.assertFalse(dialog.destroy.called)281 def test_click_cancel(self):282 dialog = self.dialog283 dialog.entry.insert(0, 'abc')284 dialog.button_cancel.invoke()...
views.py
Source:views.py
1from django.shortcuts import render2from django.http import HttpResponse3from django.http import JsonResponse4from datetime import datetime5from django.utils.dateparse import parse_datetime6import json7import requests8from kafka import SimpleProducer, KafkaClient9from elasticsearch import Elasticsearch10# Create your views here.11kafka = KafkaClient('kafka:9092')12producer = SimpleProducer(kafka)13es = Elasticsearch(['es'])14def ride_detail(request, ride):15 if request.method != 'GET':16 return JsonResponse({'ok': False, 'error': 'Wrong request type, should be GET'})17 r = requests.get('http://models-api:8000/models/get_ride/' + ride)18 ok = json.loads(r.text)['ok']19 if(ok != True):20 return JsonResponse({'ok':False})21 ride = json.loads(r.text)['car']22 details = json.loads(ride[1:-1])['fields']23 driver_pk = details['driver']24 vehicle_pk = details['car']25 r2 = requests.get('http://models-api:8000/models/get_user/' + str(driver_pk))26 ok = json.loads(r2.text)['ok']27 if(ok != True):28 driver = "Driver Not Found"29 else:30 driver_model = json.loads(r2.text)['user']31 driver_details = json.loads(driver_model)['fields']32 driver = driver_details['first'] + " " + driver_details['last']33 r3 = requests.get('http://models-api:8000/models/get_car/' + str(vehicle_pk))34 ok = json.loads(r3.text)['ok']35 if(ok != True):36 vMake = "Not Found"37 vModel = "Not Found"38 else:39 car_model = json.loads(r3.text)['car']40 car_details = json.loads(car_model)['fields']41 vMake = car_details['make']42 vModel = car_details['model']43 return JsonResponse({'ok':True, 'driver': driver, 'vMake': vMake, 'vModel': vModel, 'leave': details['leave_time'], 'start': details['start'], 'arrive': details['arrive_time'], 'Destination': details['destination']})44def home_detail(request):45 if request.method != 'GET':46 return JsonResponse({'ok': False, 'error': 'Wrong request type, should be GET'})47 r = requests.get('http://models-api:8000/models/all_rides')48 ok = json.loads(r.text)['ok']49 if(ok != True):50 return JsonResponse({'ok':False})51 ride = json.loads(r.text)['ride']52 result_set = []53 for r in ride:54 details = json.loads(r)['fields']55 pk = json.loads(r)['pk']56 driver_pk = details['driver']57 vehicle_pk = details['car']58 req_driver = requests.get('http://models-api:8000/models/get_user/' + str(driver_pk))59 req_vehicle = requests.get('http://models-api:8000/models/get_car/' + str(vehicle_pk))60 resp_driver = json.loads(json.loads(req_driver.text)['user'])['fields'] 61 resp_vehicle = json.loads(json.loads(req_vehicle.text)['car'])['fields']62 leavetime = parse_datetime(details['leave_time'])63 arrivetime = parse_datetime(details['arrive_time'])64 ride_info = {'ID':pk ,'driver':resp_driver['first'], 'vMake': resp_vehicle['make'], 'vModel':resp_vehicle['model'], 'leave': leavetime.strftime("%B %d %-I:%M:%S %p"), 'start': details['start'], 'arrive': arrivetime.strftime("%B %d %-I:%M:%S %p"), 'Destination': details['destination']}65 result_set.append(ride_info)66 return JsonResponse({'ok':True, 'result_set': result_set})67def create_user(request):68 if request.method != 'POST':69 return JsonResponse({'ok': False, 'error': 'Wrong request type, should be POST'})70 r = requests.post('http://models-api:8000/models/add_user', data=request.POST)71 ok = json.loads(r.text)['ok']72 if ok:73 userpass = {}74 userpass['username'] = request.POST['username']75 userpass['password'] = request.POST['password']76 r2 = requests.post('http://models-api:8000/models/get_auth', data=userpass)77 d2 = json.loads(r2.text)['ok']78 if d2:79 auth = json.loads(r2.text)['auth']80 else:81 return JsonResponse({'ok': False, 'error': 'Encountered error while authenticating'})82 else:83 return JsonResponse({'ok': False, 'error': 'Encountered error while creating user'})84 return JsonResponse({'ok': True, 'auth': auth, 'log': 'User Created'})85def login(request):86 if request.method != 'POST':87 return JsonResponse({'ok': False, 'error': 'Wrong request type, should be POST'})88 r = requests.post('http://models-api:8000/models/get_auth', data=request.POST)89 ok = json.loads(r.text)['ok']90 if ok:91 return JsonResponse({'ok': True, 'auth': json.loads(r.text)['auth']})92 else:93 return JsonResponse({'ok': False, 'error': 'Encountered error while authenticating'})94def logout(request):95 if request.method != 'POST':96 return JsonResponse({'ok': False, 'error': 'Wrong request type, should be POST'})97 r = requests.post('http://models-api:8000/models/revoke_auth', data=request.POST)98 ok = json.loads(r.text)['ok']99 if ok:100 return JsonResponse({'ok': True, 'log': 'Authenticator revoked'})101 else:102 return JsonResponse({'ok': False, 'error': 'Encountered error while removing auth'})103def add_new_ride(request):104 if request.method != 'POST':105 return JsonResponse({'ok': False, 'error': 'Wrong request type, should be POST'})106 auth = request.POST['auth']107 r = requests.post('http://models-api:8000/models/is_auth', data={'auth':auth})108 ok = json.loads(r.text)['ok']109 if ok:110 username = json.loads(r.text)['username']111 post_values = request.POST.copy()112 post_values['username'] = username113 r2 = requests.post('http://models-api:8000/models/add_ride', data=post_values)114 d2 = json.loads(r2.text)['ok']115 ride_id = json.loads(r2.text)['id']116 post_copy = request.POST.copy()117 post_copy['id'] = ride_id118 if d2:119 try:120 producer.send_messages(b'new-listings-topic', json.dumps(post_copy).encode('utf-8'))121 except Exception:122 #This is ugly, but if the topic doesn't exist we just try again. More than once is a problem though so we let that happen123 producer.send_messages(b'new-listings-topic', json.dumps(post_copy).encode('utf-8'))124 return JsonResponse({'ok': True, 'log': 'Created Ride'})125 else:126 return JsonResponse({'ok': False, 'error': 'Failed to create ride'})127 else:128 return JsonResponse({'ok': False, 'error': 'Invalid authentication to make ride'})129def add_new_vehicle(request):130 if request.method != 'POST':131 return JsonResponse({'ok': False, 'error': 'Wrong request type, should be POST'})132 auth = request.POST['auth']133 auth_req = requests.post('http://models-api:8000/models/is_auth', data={'auth':auth})134 ok = json.loads(auth_req.text)['ok']135 if ok:136 username = json.loads(auth_req.text)['username']137 post_values = request.POST.copy()138 post_values['username'] = username139 resp = requests.post('http://models-api:8000/models/add_vehicle', data=post_values)140 created = json.loads(resp.text)['ok']141 if created:142 return JsonResponse({'ok': True, 'log': 'Added vehicle'})143 else:144 return JsonResponse({'ok': False, 'error': 'Failed to create vehicle'})145 else:146 return JsonResponse({'ok': False, 'error': 'Invalid authentication to make vehicle'})147def search_result(request):148 if request.method != 'POST':149 return JsonResponse({'ok': False, 'error': 'Wrong request type, should be POST'})150 if 'query' not in request.POST:151 return JsonResponse({'ok': False, 'error': 'No query field'})152 results = es.search(index='listing_index', body={'query':{'query_string':{'query': request.POST['query']}}, 'size':10})...
cdif2rsf.py
Source:cdif2rsf.py
1# !/usr/bin/python2import os3from os import EX_OK, EX_USAGE, EX_UNAVAILABLE, EX_IOERR4import sys5##6# $Rev: 1155 $: Revision of last commit7# $Author: bdubois $: Author of last commit8# $Date: 2007-05-03 07:51:55 +0200 (Thu, 03 May 2007) $: Date of last commit9##10def convertToRsf(cdif_input_file_name, rsf_output_file_name):11 print "Reading from file", cdif_input_file_name + "..."12 13 print "\tFiles...",14 return_code = os.system("python ./writeFiles.py " + cdif_input_file_name)15 if return_code == EX_OK:16 print "[ok]"17 else:18 print "[failed]"19 return EX_UNAVAILABLE20 21 print "\tIncludes...",22 return_code = os.system("python ./writeIncludes.py " + cdif_input_file_name)23 if return_code == EX_OK:24 print "[ok]"25 else:26 print "[failed]"27 return EX_UNAVAILABLE28 29 print "\tConditional Compilation...",30 return_code = os.system("python ./writeCondComp.py " + cdif_input_file_name)31 if return_code == EX_OK:32 print "[ok]"33 else:34 print "[failed]"35 return EX_UNAVAILABLE36 37 print "\tClasses...",38 return_code = os.system("python ./writeClasses.py " + cdif_input_file_name)39 if return_code == EX_OK:40 print "[ok]"41 else:42 print "[failed]"43 return EX_UNAVAILABLE44 45 #print "\tTypeDefs...",46 #return_code = os.system("python ./writeTypedefs.py " + cdif_input_file_name)47 #if return_code == EX_OK:48 # print "[ok]"49 #else:50 print "[failed]"51 return EX_UNAVAILABLE52 53 print "\tInheritance...",54 return_code = os.system("python ./writeInheritance.py " + cdif_input_file_name)55 if return_code == EX_OK:56 print "[ok]"57 else:58 print "[failed]"59 return EX_UNAVAILABLE60 61 print "\tMethods...",62 return_code = os.system("python ./writeMethods.py " + cdif_input_file_name)63 if return_code == EX_OK:64 print "[ok]"65 else:66 print "[failed]"67 return EX_UNAVAILABLE68 69 print "\tAttributes...",70 return_code = os.system("python ./writeAttributes.py " + cdif_input_file_name)71 if return_code == EX_OK:72 print "[ok]"73 else:74 print "[failed]"75 return EX_UNAVAILABLE76 77 print "\tFunctions...",78 return_code = os.system("python ./writeFunctions.py " + cdif_input_file_name)79 if return_code == EX_OK:80 print "[ok]"81 else:82 print "[failed]"83 return EX_UNAVAILABLE84 85 print "\tGlobalVariables...",86 return_code = os.system("python ./writeGlobalVar.py " + cdif_input_file_name)87 if return_code == EX_OK:88 print "[ok]"89 else:90 print "[failed]"91 return EX_UNAVAILABLE92 93 print "\tAccesses...",94 return_code = os.system("python ./writeAccesses.py " + cdif_input_file_name)95 if return_code == EX_OK:96 print "[ok]"97 else:98 print "[failed]"99 return EX_UNAVAILABLE100 101 print "\tInvocations...",102 return_code = os.system("python ./writeInvocations.py " + cdif_input_file_name)103 if return_code == EX_OK:104 print "[ok]"105 else:106 print "[failed]"107 return EX_UNAVAILABLE108 109 print "\tAnnotations...",110 return_code = os.system("python ./writeAnnotations.py " + cdif_input_file_name)111 if return_code == EX_OK:112 print "[ok]"113 else:114 print "[failed]"115 return EX_UNAVAILABLE116 117 print "\tSize and Complexity Metrics...",118 return_code = os.system("python ./writeMetrics.py " + cdif_input_file_name)119 if return_code == EX_OK:120 print "[ok]"121 else:122 print "[failed]"123 return EX_UNAVAILABLE124 125 print "\tChange Frequency Metrics...",126 return_code = os.system("python ./writeCFMetrics.py " + cdif_input_file_name)127 if return_code == EX_OK:128 print "[ok]"129 else:130 print "[failed]"131 return EX_UNAVAILABLE132 133 print "Merging output...",134 return_code = os.system("python ./makeRsf.py " + rsf_output_file_name)135 if return_code == EX_OK:136 print "[ok]"137 else:138 print "[failed]"139 return EX_UNAVAILABLE140 141 remove_command = "rm -f accessesWithIDs.txt attributeBelongsToClass.txt \142 attributeHasClassAsType.txt attributesWithIDs.txt \143 classBelongsToFile.txt classesWithIDs.txt \144 conditionalCompilationBlocks.txt typedefsWithIDs.txt\145 fileBelongsToModule.txt filesWithIDs.txt \146 invokableEntityBelongsToFile.txt functionsWithIDs.txt \147 globalVarsWithIDs.txt globalVarHasClassAsType.txt \148 accessibleEntityBelongsToFile.txt \149 inheritanceWithIDs.txt invocationsWithIDs.txt \150 methodBelongsToClass.txt methodsWithIDs.txt \151 modulesWithIDs.txt metricsWithIDs.txt \152 moduleBelongsToModule.txt includeBelongsToFile.txt \153 methodHasClassAsReturnType.txt functionHasClassAsReturnType.txt \154 entityBelongsToBlock.txt methodVisibility.txt \155 methodSignature.txt attributeSignature.txt attributeVisibility.txt\156 accessesLocations.txt invocationLocations.txt \157 defsWithAssociation.txt cfMetricsWithIDs.txt \158 leftValueAccesses.txt annotations.txt \159 annotationBelongsToEntity.txt"160 161 return_code = os.system(remove_command)162 if return_code != EX_OK:163 print "Error cleaning up."164 return EX_IOERR165 166 print "Output written to", rsf_output_file_name167 168 return EX_OK169if __name__ == '__main__':170 if len(sys.argv) < 2:171 print "Usage:",sys.argv[0],"cdif-input-file-name rsf-output-file-name"172 sys.exit(EX_USAGE)173 174 input_file=sys.argv[1]175 176 cdif_input_file_name = sys.argv[1]177 rsf_output_file_name = sys.argv[2]178 179 exitCode = convertToRsf(cdif_input_file_name, rsf_output_file_name)180 ...
draw_line_chart.py
Source:draw_line_chart.py
1import os2import matplotlib.pyplot as plt3import numpy as np4'''5è¿ä¸ªä»£ç çä½ç¨æ¯ç»å¶åç±»æ线å¾6'''7class DrawLineChart():8 def __init__(self, fold:str, learn_rate:str, ng, ok, ng_list:list, ok_list:list):9 self.fold = fold10 self.learn_rate = learn_rate11 self.ng = ng # çå®çNGæ°é12 self.ok = ok # çå®çOKæ°é13 self.ng_list = ng_list14 self.ok_list = ok_list15 self.dilate = [0, 5, 9, 13, 17]16 def drawpillar(self):17 # plt.figure(figsize=(6.4, 4.8), dpi=300)18 fig, ax = plt.subplots(figsize=(6.4, 4.8), dpi=300)19 y_ticks = np.arange(0, 140, 10)20 rects1 = plt.plot(self.dilate,self.ng_list,color="blue",linewidth=2,linestyle=':',label='NG', marker='*')21 rects1 = plt.plot(self.dilate,self.ok_list,color="green",linewidth=2,linestyle=':',label='OK', marker='*')22 rects1 = plt.plot(self.dilate,self.ng,color="black",linewidth=2,linestyle='-',label='real NG', marker='.')23 rects1 = plt.plot(self.dilate,self.ok,color="black",linewidth=2,linestyle='-',label='real OK', marker='.')24 plt.xlabel('dilate', fontsize=20)25 plt.ylabel('images', fontsize=20)26 plt.title('fold_' + self.fold + '_learn_rate_' + self.learn_rate, fontsize=20)27 plt.xticks(self.dilate , ('0', '5', '9', '13', '17'), fontsize=16)28 plt.yticks(y_ticks,fontsize=16)29 plt.ylim(0, 140)30 plt.legend(fontsize=12, framealpha=0.8, frameon=True)31 plt.tight_layout()32 img_name = 'fold_' + self.fold + '_learn_rate_' + self.learn_rate + '.svg'33 img = plt.savefig(img_name)34 # plt.show()35 return img36if __name__ == "__main__":37 ng_list_fold_0 = [17.8, 17.6, 18.6, 18.4, 18.2]38 ok_list_fold_0 = [117.2, 117.4, 117, 116.6, 116.8]39 ng_list_fold_1 = [17, 17, 17, 17, 16.8]40 ok_list_fold_1 = [119, 119, 119, 119, 119.2]41 ng_list_fold_2 = [13.8, 13.6, 13.6, 14.2, 13.8]42 ok_list_fold_2 = [114.2, 114.4, 114.4, 113.8, 114.2]43 DrawLineChart('0', '0.01', [18]*5, [117]*5, ng_list_fold_0, ok_list_fold_0).drawpillar()44 DrawLineChart('1', '0.01', [18]*5, [118]*5, ng_list_fold_1, ok_list_fold_1).drawpillar()45 DrawLineChart('2', '0.01', [16]*5, [112]*5, ng_list_fold_2, ok_list_fold_2).drawpillar()46 ng_list_fold_0_2 = [18.8, 18.6, 19.2, 18.6, 18.8]47 ok_list_fold_0_2 = [116.2, 116.4, 115.8, 116.4, 116.2]48 ng_list_fold_1_2 = [17, 17, 17, 17, 17.2]49 ok_list_fold_1_2 = [119, 119, 119, 119, 118.8]50 ng_list_fold_2_2 = [14.4, 14.4, 14.2, 14, 14]51 ok_list_fold_2_2 = [113.6, 113.6, 113.8, 114, 114]52 DrawLineChart('0', '0.1', [18] * 5, [117] * 5, ng_list_fold_0_2, ok_list_fold_0_2).drawpillar()53 DrawLineChart('1', '0.1', [18] * 5, [118] * 5, ng_list_fold_1_2, ok_list_fold_1_2).drawpillar()54 DrawLineChart('2', '0.1', [16] * 5, [112] * 5, ng_list_fold_2_2, ok_list_fold_2_2).drawpillar()55 ng_list_fold_0_3 = [74.8, 18.4, 95.6, 33.6, 33.4]56 ok_list_fold_0_3 = [60.2, 116.6, 39.4, 101.4, 101.6]57 ng_list_fold_1_3 = [40.2, 34.4, 36.4, 40.8, 13]58 ok_list_fold_1_3 = [95.8, 101.6, 99.6, 95.2, 123]59 ng_list_fold_2_3 = [14, 24.8, 26.6, 26.8, 18.2]60 ok_list_fold_2_3 = [114, 103.2, 101.4, 101.2, 109.8]61 DrawLineChart('0', '0.5', [18] * 5, [117] * 5, ng_list_fold_0_3, ok_list_fold_0_3).drawpillar()62 DrawLineChart('1', '0.5', [18] * 5, [118] * 5, ng_list_fold_1_3, ok_list_fold_1_3).drawpillar()63 DrawLineChart('2', '0.5', [16] * 5, [112] * 5, ng_list_fold_2_3, ok_list_fold_2_3).drawpillar()64 ng_list_fold_0_4 = [134.8, 84.4, 57.2, 107.8, 90]65 ok_list_fold_0_4 = [0.2, 50.6, 77.8, 27.2, 45]66 ng_list_fold_1_4 = [136, 136, 125.2, 109, 83.2]67 ok_list_fold_1_4 = [0, 0, 10.8, 27, 52.8]68 ng_list_fold_2_4 = [92.6, 128, 79.6, 84.8, 78]69 ok_list_fold_2_4 = [35.4, 0, 48.4, 46.2, 50]70 DrawLineChart('0', '1', [18] * 5, [117] * 5, ng_list_fold_0_4, ok_list_fold_0_4).drawpillar()71 DrawLineChart('1', '1', [18] * 5, [118] * 5, ng_list_fold_1_4, ok_list_fold_1_4).drawpillar()...
split.py
Source:split.py
1import os2import shutil3folders = "E:/DATA/3_fold/"4sub_folders = os.listdir(folders)5ok = "E:/DATA/KolektorSDD_MOD/OK,negative/"6ng = "E:/DATA/KolektorSDD_MOD/NG,positive/"7images_ok = os.listdir(ok)8images_ng = os.listdir(ng)9for each_folder in sub_folders:10 path_sub = os.path.join(folders, each_folder)11 sub_files = os.listdir(path_sub)12 train_folder = os.path.join(path_sub,"train_set")13 test_folder = os.path.join(path_sub, "test_set")14 sub_ok_folder = os.path.join(train_folder, "OK,negative")15 sub_ng_folder = os.path.join(train_folder, "NG,positive")16 if not os.path.exists(sub_ok_folder):17 os.makedirs(sub_ok_folder)18 if not os.path.exists(sub_ng_folder):19 os.makedirs(sub_ng_folder)20 if not os.path.exists(test_folder):21 os.makedirs(test_folder)22 for p in sub_files:23 if p == "train_ids.txt":24 train_set = []25 p_path = os.path.join(path_sub, p)26 f = open(p_path)27 lines = f.readlines()28 count = 029 for line in lines:30 s = line.strip("\n").split("/")[-1]31 train_set.append(s)32 #print(train_set)33 for each_image_ok in images_ok:34 #print(each_image_ok)35 this_ok_image_path = os.path.join(ok, each_image_ok)36 print(this_ok_image_path)37 pre_fix = each_image_ok.split("_")[0]38 #print(pre_fix)39 if pre_fix in train_set:40 target_ok_path = os.path.join(sub_ok_folder, each_image_ok)41 #print(target_path)42 shutil.copy(this_ok_image_path, target_ok_path)43 for each_image_ng in images_ng:44 #print(each_image_ok)45 this_ng_image_path = os.path.join(ng, each_image_ng)46 #print(this_ng_image_path)47 pre_fix = each_image_ng.split("_")[0]48 #print(pre_fix)49 if pre_fix in train_set:50 target_ng_path = os.path.join(sub_ng_folder, each_image_ng)51 #print(target_path)52 shutil.copy(this_ng_image_path, target_ng_path)53 if p == "test_ids.txt":54 test_set = []55 p_path = os.path.join(path_sub, p)56 f = open(p_path)57 lines = f.readlines()58 count = 059 for line in lines:60 s = line.strip("\n").split("/")[-1]61 test_set.append(s)62 #print(train_set)63 for each_image_ok in images_ok:64 #print(each_image_ok)65 this_ok_image_path = os.path.join(ok, each_image_ok)66 print(this_ok_image_path)67 pre_fix = each_image_ok.split("_")[0]68 #print(pre_fix)69 if pre_fix in test_set:70 target_ok_path = test_folder71 #print(target_path)72 shutil.copy(this_ok_image_path, target_ok_path)73 for each_image_ng in images_ng:74 #print(each_image_ok)75 this_ng_image_path = os.path.join(ng, each_image_ng)76 #print(this_ng_image_path)77 pre_fix = each_image_ng.split("_")[0]78 #print(pre_fix)79 if pre_fix in test_set:80 target_ng_path = test_folder81 #print(target_path)...
check_dep.py
Source:check_dep.py
1#Bruno Iochins Grisci and Marcelo D. Poleto2#APRIL/20193#http://sbcb.inf.ufrgs.br/confid4# -*- coding:utf-8 -*-5def check(print_ok=False):6 if print_ok:7 print('Checking for needed packages and libs...')8 try:9 import os10 if print_ok:11 print('OK: os')12 except:13 print('ERROR: could not import os')14 try:15 import sys16 if print_ok:17 print('OK: sys')18 except:19 print('ERROR: could not import sys')20 try:21 import shutil22 if print_ok:23 print('OK: shutil')24 except:25 print('ERROR: could not import shutil') 26 try:27 import pprint28 if print_ok:29 print('OK: pprint')30 except:31 print('ERROR: could not import pprint')32 try:33 import re34 if print_ok:35 print('OK: re')36 except:37 print('ERROR: could not import re')38 try:39 import numpy as np40 if print_ok:41 print('OK: numpy')42 except:43 print('ERROR: could not import numpy')44 try:45 import operator46 if print_ok:47 print('OK: operator')48 except:49 print('ERROR: could not import operator')50 try:51 from collections import Counter52 if print_ok:53 print('OK: Counter from collections')54 except:55 print('ERROR: could not import Counter from collections')56 try:57 import timeit58 if print_ok:59 print('OK: timeit')60 except:61 print('ERROR: could not import timeit') 62 if not (sys.version_info >= (3, 0)):63 try:64 from itertools import imap65 if print_ok:66 print('OK: imap from itertools')67 except:68 print('WARNING: could not import imap from itertools, if using Python 3.x ignore this warning')69 if print_ok:70 print('Checking for optional packages and libs...')71 try:72 import graphviz73 if print_ok:74 print('OK: graphviz')75 except:76 print('WARNING: could not import graphviz')77 print('WARNING: graphviz is needed if PLOT_GRAPH is True.')78 try:79 import pydot80 if print_ok:81 print('OK: pydot')82 except:83 pass 84 try:85 import matplotlib.pyplot as plt86 if print_ok:87 print('OK: matplotlib.pyplot')88 except:89 print('WARNING: could not import matplotlib.pyplot')90 print('WARNING: matplotlib.pyplot is needed if TIME_DEPENDENT_STATS is True.')91 if print_ok:92 print('Finished.')93if __name__ == '__main__':...
ok.py
Source:ok.py
1"""Emoji2Available Commands:3.ok"""4from telethon import events5import asyncio6from ULTRA.utils import admin_cmd7@borg.on(admin_cmd("ok"))8async def _(event):9 if event.fwd_from:10 return11 animation_interval = 0.112 animation_ttl = range(0,36)13 #input_str = event.pattern_match.group(1)14 # if input_str == "ok":15 await event.edit("ok")16 animation_chars = [17 "OK",18 "BOSS",19 "OK MAN",20 "OK BITCH",21 "OK FUKCER",22 "OK SEXY BABE",23 "OK GAY",24 "OK SIR",25 "GO AND SAY OK",26 "OK LOL",27 "YAA OK",28 "FCUK",29 "OK",30 "Boss",31 "Yeahhhhhh",32 "O",33 "K",34 "Ok Boss! ð"35 ]36 for i in animation_ttl:37 38 await asyncio.sleep(animation_interval)...
Using AI Code Generation
1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch();4 const page = await browser.newPage();5 await page.screenshot({path: 'example.png'});6 await browser.close();7})();
Using AI Code Generation
1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch();4 const page = await browser.newPage();5 await page.screenshot({path: 'example.png'});6 await browser.close();7})();8const puppeteer = require('puppeteer');9(async () => {10 const browser = await puppeteer.launch();11 const page = await browser.newPage();12 await page.screenshot({path: 'example.png'});13 await browser.close();14})();15const puppeteer = require('puppeteer');16(async () => {17 const browser = await puppeteer.launch();18 const page = await browser.newPage();19 await page.screenshot({path: 'example.png'});20 await browser.close();21})();22const puppeteer = require('puppeteer');23(async () => {24 const browser = await puppeteer.launch();25 const page = await browser.newPage();26 await page.screenshot({path: 'example.png'});27 await browser.close();28})();29const puppeteer = require('puppeteer');30(async () => {31 const browser = await puppeteer.launch();32 const page = await browser.newPage();33 await page.screenshot({path: 'example.png'});34 await browser.close();35})();36const puppeteer = require('puppeteer');37(async () => {38 const browser = await puppeteer.launch();39 const page = await browser.newPage();40 await page.screenshot({path: 'example.png'});41 await browser.close();42})();43const puppeteer = require('puppeteer');44(async () => {45 const browser = await puppeteer.launch();46 const page = await browser.newPage();
Using AI Code Generation
1const puppeteer = require('puppeteer');2const assert = require('assert');3(async () => {4 const browser = await puppeteer.launch();5 const page = await browser.newPage();6 const title = await page.title();7 assert.ok(title === 'Google');8 await browser.close();9})();
Using AI Code Generation
1const puppeteer = require('puppeteer');2const assert = require('assert');3(async () => {4 const browser = await puppeteer.launch();5 const page = await browser.newPage();6 await page.screenshot({path: 'example.png'});7 await page.waitForSelector('h1');8 const h1 = await page.$eval('h1', h1 => h1.innerText);9 assert.ok(h1 === 'Example Domain');10 await browser.close();11})();12Hi, I am using puppeteer to automate my tests. I am trying to use assert.ok() method to check if my test passes or not. But the problem is that assert.ok() is not a function. I have tried to import it by using const assert = require('assert'); but I am still getting the same error. I am using the following code:Thank you13assert.ok() is a method of the assert module. You need to require the module first. For example:14const assert = require('assert');15assert.ok(new
Using AI Code Generation
1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch({headless: false});4 const page = await browser.newPage();5 await page.screenshot({path: 'example.png'});6 await browser.close();7})();8{9 "scripts": {10 },11 "dependencies": {12 }13}14const puppeteer = require('puppeteer');15(async () => {16 const browser = await puppeteer.launch({headless: false});17 const page = await browser.newPage();18 await page.screenshot({path: 'example.png'});19 await browser.close();20})();21{22 "scripts": {23 },24 "dependencies": {25 }26}27const puppeteer = require('puppeteer');28(async () => {29 const browser = await puppeteer.launch({headless: false});30 const page = await browser.newPage();31 await page.screenshot({path: 'example.png'});32 await browser.close();33})();34{35 "scripts": {
Using AI Code Generation
1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch();4 const page = await browser.newPage();5 const title = await page.title();6 await expect(title).toBe('Example Domain');7 await browser.close();8})();9const puppeteer = require('puppeteer');10(async () => {11 const browser = await puppeteer.launch();12 const page = await browser.newPage();13 const title = await page.title();14 expect(title).toBeTruthy();15 await browser.close();16})();17const puppeteer = require('puppeteer');18(async () => {19 const browser = await puppeteer.launch();20 const page = await browser.newPage();21 const title = await page.title();22 expect(title).toBeFalsy();23 await browser.close();24})();25const puppeteer = require('puppeteer');26(async () => {27 const browser = await puppeteer.launch();28 const page = await browser.newPage();29 const title = await page.title();30 expect(title).toBeDefined();31 await browser.close();32})();33const puppeteer = require('puppeteer');34(async () => {35 const browser = await puppeteer.launch();36 const page = await browser.newPage();37 const title = await page.title();38 expect(title).toBeUndefined();39 await browser.close();40})();41const puppeteer = require('puppeteer');42(async () => {43 const browser = await puppeteer.launch();44 const page = await browser.newPage();45 const title = await page.title();46 expect(title).toBeNull();47 await browser.close();48})();49const puppeteer = require('puppeteer');50(async () => {
Using AI Code Generation
1const assert = require('assert');2const { chromium } = require('playwright-chromium');3const { expect } = require('chai');4const { describe, it } = require('mocha');5describe('E2E tests', function () {6 this.timeout(6000);7 before(async () => { browser = await chromium.launch({ headless: false, slowMo: 500 }); });8 after(async () => { await browser.close(); });9 beforeEach(async () => { page = await browser.newPage(); });10 afterEach(async () => { await page.close(); });11 it('loads static page', async () => {12 await page.screenshot({ path: `index.png` });13 });14 it('loads static page', async () => {15 await page.screenshot({ path: `index.png` });16 const content = await page.textContent('.site-header');17 assert.equal(content, 'Team Manager');18 });19 it('has a heading "Team Manager"', async () => {20 await page.screenshot({ path: `index.png` });21 const content = await page.textContent('.site-header');22 expect(content).to.equal('Team Manager');23 });24 it('has a heading "Team Manager"', async () => {25 await page.screenshot({ path: `index.png` });26 const content = await page.textContent('.site-header');27 expect(content).to.equal('Team Manager');28 });29 it('has a heading "Team Manager"', async () => {30 await page.screenshot({ path: `index.png` });31 const content = await page.textContent('.site-header');32 expect(content).to.equal('Team Manager');33 });34 it('has a heading "Team Manager"', async () => {35 await page.screenshot({ path: `index.png` });36 const content = await page.textContent('.site-header');37 expect(content).to.equal('Team Manager');38 });39 it('has a heading "Team Manager"', async () => {
Using AI Code Generation
1await page.click('button');2await page.waitForSelector('#text');3const text = await page.$eval('#text', el => el.textContent);4expect(text).to.equal('Hello World');5});6await page.click('button');7await page.waitForSelector('#text');8const text = await page.$eval('#text', el => el.textContent);9expect(text).to.equal('Hello World');10});11await page.click('button');12await page.waitForSelector('#text');13const text = await page.$eval('#text', el => el.textContent);14expect(text).to.equal('Hello World');15});16await page.click('button');17await page.waitForSelector('#text');18const text = await page.$eval('#text', el => el.textContent);19expect(text).to.equal('Hello World');20});21await page.click('button');22await page.waitForSelector('#text');23const text = await page.$eval('#text', el => el.textContent);24expect(text).to.equal('Hello World');25});26await page.click('button');27await page.waitForSelector('#text');28const text = await page.$eval('#text', el => el.textContent);29expect(text).to.equal('Hello World');30});31await page.click('button');32await page.waitForSelector('#text');33const text = await page.$eval('#text', el => el.textContent);34expect(text).to.equal('Hello World');35});36await page.click('button');37await page.waitForSelector('#text');38const text = await page.$eval('#text', el => el.textContent);39expect(text).to.equal('Hello World');40});41await page.click('button');42await page.waitForSelector('#text');43const text = await page.$eval('#text', el => el.textContent);44expect(text).to.equal('Hello World');45});46await page.click('button');47await page.waitForSelector('#text');
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!