Best JavaScript code snippet using backstopjs
main.py
Source:main.py
...39 engine {[type]} -- [description]40 Keyword Arguments:41 client {[type]} -- [description] (default: {DATABASE})42 """43 engine = select_save_engine(engine)44 engine.QA_SU_save_stock_info(client=client)45def QA_SU_save_stock_info_tushare(engine="tushare", client=DATABASE):46 '''47 :param engine: tushare48 :param client:49 :return: None50 '''51 # only support the tushare52 engine = select_save_engine("tushare")53 engine.QA_SU_save_stock_info_tushare()54 pass55def QA_SU_save_stock_list(engine, client=DATABASE):56 """save stock_list57 Arguments:58 engine {[type]} -- [description]59 Keyword Arguments:60 client {[type]} -- [description] (default: {DATABASE})61 """62 engine = select_save_engine(engine)63 engine.QA_SU_save_stock_list(client=client)64def QA_SU_save_index_list(engine, client=DATABASE):65 """save index_list66 Arguments:67 engine {[type]} -- [description]68 Keyword Arguments:69 client {[type]} -- [description] (default: {DATABASE})70 """71 engine = select_save_engine(engine)72 engine.QA_SU_save_index_list(client=client)73def QA_SU_save_etf_list(engine, client=DATABASE):74 """save etf_list75 Arguments:76 engine {[type]} -- [description]77 Keyword Arguments:78 client {[type]} -- [description] (default: {DATABASE})79 """80 engine = select_save_engine(engine)81 engine.QA_SU_save_etf_list(client=client)82def QA_SU_save_future_list(engine, client=DATABASE):83 """save future_list84 Arguments:85 engine {[type]} -- [description]86 Keyword Arguments:87 client {[type]} -- [description] (default: {DATABASE})88 """89 engine = select_save_engine(engine)90 engine.QA_SU_save_future_list(client=client)91def QA_SU_save_single_future_day(code, engine, client=DATABASE, paralleled=False):92 """save single_future_day93 Arguments:94 code: stock code95 engine {[type]} -- [description]96 Keyword Arguments:97 client {[type]} -- [description] (default: {DATABASE})98 :param paralleled: æ¯å¦å¹¶è¡å¤ç(default: {True})99 """100 engine = select_save_engine(engine, paralleled=paralleled)101 engine.QA_SU_save_single_future_day(code=code, client=client)102def QA_SU_save_future_day(engine, client=DATABASE):103 """save future_day104 Arguments:105 engine {[type]} -- [description]106 Keyword Arguments:107 client {[type]} -- [description] (default: {DATABASE})108 """109 engine = select_save_engine(engine)110 engine.QA_SU_save_future_day(client=client)111def QA_SU_save_future_day_all(engine, client=DATABASE):112 """save future_day_all113 Arguments:114 engine {[type]} -- [description]115 Keyword Arguments:116 client {[type]} -- [description] (default: {DATABASE})117 """118 engine = select_save_engine(engine)119 engine.QA_SU_save_future_day_all(client=client)120def QA_SU_save_single_future_min(code, engine, client=DATABASE):121 """save single_future_min122 Arguments:123 engine {[type]} -- [description]124 Keyword Arguments:125 client {[type]} -- [description] (default: {DATABASE})126 """127 engine = select_save_engine(engine)128 engine.QA_SU_save_single_future_min(code=code, client=client)129def QA_SU_save_future_min(engine, client=DATABASE):130 """save future_min131 Arguments:132 engine {[type]} -- [description]133 Keyword Arguments:134 client {[type]} -- [description] (default: {DATABASE})135 """136 engine = select_save_engine(engine)137 engine.QA_SU_save_future_min(client=client)138def QA_SU_save_future_min_all(engine, client=DATABASE):139 """[summary]140 Arguments:141 engine {[type]} -- [description]142 Keyword Arguments:143 client {[type]} -- [description] (default: {DATABASE})144 """145 engine = select_save_engine(engine)146 engine.QA_SU_save_future_min_all(client=client)147@print_used_time148def QA_SU_save_stock_day(engine, client=DATABASE, paralleled=False):149 """save stock_day150 Arguments:151 engine {[type]} -- [description]152 Keyword Arguments:153 client {[type]} -- [description] (default: {DATABASE})154 :param paralleled: æ¯å¦å¹¶è¡å¤ç(default: {True})155 """156 engine = select_save_engine(engine, paralleled=paralleled)157 engine.QA_SU_save_stock_day(client=client)158def QA_SU_save_single_stock_day(code, engine, client=DATABASE, paralleled=False):159 """save stock_day160 Arguments:161 code: stock code162 engine {[type]} -- [description]163 Keyword Arguments:164 client {[type]} -- [description] (default: {DATABASE})165 :param paralleled: æ¯å¦å¹¶è¡å¤ç(default: {True})166 """167 engine = select_save_engine(engine, paralleled=paralleled)168 engine.QA_SU_save_single_stock_day(code=code, client=client)169def QA_SU_save_option_contract_list(engine, client=DATABASE):170 '''171 :param engine: 172 :param client: 173 :return: 174 '''175 engine = select_save_engine(engine)176 engine.QA_SU_save_option_contract_list(client=client)177def QA_SU_save_option_day_all(engine, client=DATABASE):178 '''179 :param engine:180 :param client:181 :return:182 '''183 engine = select_save_engine(engine)184 engine.QA_SU_save_option_day_all(client=client)185def QA_SU_save_option_min_all(engine, client=DATABASE):186 '''187 :param engine:188 :param client:189 :return:190 '''191 engine = select_save_engine(engine)192 engine.QA_SU_save_option_min_all(client=client)193def QA_SU_save_option_50etf_day(engine, client=DATABASE):194 '''195 :param engine:196 :param client:197 :return:198 '''199 engine = select_save_engine(engine)200 engine.QA_SU_save_option_50etf_day(client=client)201def QA_SU_save_option_50etf_min(engine, client=DATABASE):202 '''203 :param engine:204 :param client:205 :return:206 '''207 engine = select_save_engine(engine)208 engine.QA_SU_save_option_50etf_min(client=client)209def QA_SU_save_option_300etf_day(engine, client=DATABASE):210 '''211 :param engine:212 :param client:213 :return:214 '''215 engine = select_save_engine(engine)216 engine.QA_SU_save_option_300etf_day(client=client)217def QA_SU_save_option_300etf_min(engine, client=DATABASE):218 '''219 :param engine:220 :param client:221 :return:222 '''223 engine = select_save_engine(engine)224 engine.QA_SU_save_option_300etf_min(client=client)225def QA_SU_save_option_commodity_min(engine, client=DATABASE):226 '''227 :param engine:228 :param client:229 :return:230 '''231 engine = select_save_engine(engine)232 engine.QA_SU_save_option_commodity_min(client=client)233def QA_SU_save_option_commodity_day(engine, client=DATABASE):234 '''235 :param engine:236 :param client:237 :return:238 '''239 engine = select_save_engine(engine)240 engine.QA_SU_save_option_commodity_day(client=client)241def QA_SU_save_stock_min(engine, client=DATABASE):242 """save stock_min243 Arguments:244 engine {[type]} -- [description]245 Keyword Arguments:246 client {[type]} -- [description] (default: {DATABASE})247 """248 engine = select_save_engine(engine)249 engine.QA_SU_save_stock_min(client=client)250def QA_SU_save_stock_transaction(engine, client=DATABASE):251 """save stock_transaction252 Arguments:253 engine {[type]} -- [description]254 Keyword Arguments:255 client {[type]} -- [description] (default: {DATABASE})256 """257 engine = select_save_engine(engine)258 engine.QA_SU_save_stock_transaction(client=client)259def QA_SU_save_index_transaction(engine, client=DATABASE):260 """save index_transaction261 Arguments:262 engine {[type]} -- [description]263 Keyword Arguments:264 client {[type]} -- [description] (default: {DATABASE})265 """266 engine = select_save_engine(engine)267 engine.QA_SU_save_index_transaction(client=client)268def QA_SU_save_single_stock_min(code, engine, client=DATABASE):269 """save stock_min270 Arguments:271 engine {[type]} -- [description]272 Keyword Arguments:273 client {[type]} -- [description] (default: {DATABASE})274 """275 engine = select_save_engine(engine)276 engine.QA_SU_save_single_stock_min(code=code, client=client)277@print_used_time278def QA_SU_save_index_day(engine, client=DATABASE, paralleled=False):279 """save index_day280 Arguments:281 engine {[type]} -- [description]282 Keyword Arguments:283 client {[type]} -- [description] (default: {DATABASE})284 :param paralleled: æ¯å¦å¹¶è¡å¤ç(default: {True})285 """286 engine = select_save_engine(engine, paralleled=paralleled)287 engine.QA_SU_save_index_day(client=client)288def QA_SU_save_single_index_day(code, engine, client=DATABASE, paralleled=False):289 """save index_day290 Arguments:291 code: index code292 engine {[type]} -- [description]293 Keyword Arguments:294 client {[type]} -- [description] (default: {DATABASE})295 :param paralleled: æ¯å¦å¹¶è¡å¤ç(default: {True})296 """297 engine = select_save_engine(engine, paralleled=paralleled)298 engine.QA_SU_save_single_index_day(code=code, client=client)299def QA_SU_save_index_min(engine, client=DATABASE):300 """save index_min301 Arguments:302 engine {[type]} -- [description]303 Keyword Arguments:304 client {[type]} -- [description] (default: {DATABASE})305 """306 engine = select_save_engine(engine)307 engine.QA_SU_save_index_min(client=client)308def QA_SU_save_single_index_min(code, engine, client=DATABASE):309 """save index_min310 Arguments:311 engine {[type]} -- [description]312 Keyword Arguments:313 client {[type]} -- [description] (default: {DATABASE})314 """315 engine = select_save_engine(engine)316 engine.QA_SU_save_single_index_min(code=code, client=client)317@print_used_time318def QA_SU_save_etf_day(engine, client=DATABASE, paralleled=False):319 """save etf_day320 Arguments:321 engine {[type]} -- [description]322 Keyword Arguments:323 client {[type]} -- [description] (default: {DATABASE})324 """325 engine = select_save_engine(engine, paralleled=paralleled)326 engine.QA_SU_save_etf_day(client=client)327def QA_SU_save_single_etf_day(code, engine, client=DATABASE, paralleled=False):328 """save etf_day329 Arguments:330 code: etf code331 engine {[type]} -- [description]332 Keyword Arguments:333 client {[type]} -- [description] (default: {DATABASE})334 """335 engine = select_save_engine(engine, paralleled=paralleled)336 engine.QA_SU_save_single_etf_day(code=code, client=client)337def QA_SU_save_etf_min(engine, client=DATABASE):338 """save etf_min339 Arguments:340 engine {[type]} -- [description]341 Keyword Arguments:342 client {[type]} -- [description] (default: {DATABASE})343 """344 engine = select_save_engine(engine)345 engine.QA_SU_save_etf_min(client=client)346def QA_SU_save_single_etf_min(code, engine, client=DATABASE):347 """save etf_min348 Arguments:349 engine {[type]} -- [description]350 Keyword Arguments:351 client {[type]} -- [description] (default: {DATABASE})352 """353 engine = select_save_engine(engine)354 engine.QA_SU_save_single_etf_min(code=code, client=client)355def QA_SU_save_stock_xdxr(engine, client=DATABASE):356 """save stock_xdxr357 Arguments:358 engine {[type]} -- [description]359 Keyword Arguments:360 client {[type]} -- [description] (default: {DATABASE})361 """362 engine = select_save_engine(engine)363 engine.QA_SU_save_stock_xdxr(client=client)364def QA_SU_save_stock_block(engine, client=DATABASE):365 """save stock_block366 Arguments:367 engine {[type]} -- [description]368 Keyword Arguments:369 client {[type]} -- [description] (default: {DATABASE})370 """371 engine = select_save_engine(engine)372 engine.QA_SU_save_stock_block(client=client)373def select_save_engine(engine, paralleled=False):374 '''375 select save_engine , tushare ts Tushare ä½¿ç¨ Tushare å
è´¹æ°æ®æ¥å£ï¼ tdx 使ç¨é达信æ°æ®æ¥å£376 :param engine: å符串Str377 :param paralleled: æ¯å¦å¹¶è¡å¤çï¼é»è®¤ä¸ºFalse378 :return: sts means save_tushare_py or stdx means save_tdx_py379 '''380 if engine in ['tushare', 'ts', 'Tushare']:381 return sts382 elif engine in ['tdx']:383 if paralleled:384 return stdx_parallelism385 else:386 return stdx387 elif engine in ['gm', 'goldenminer']:388 return sgm389 elif engine in ['jq', 'joinquant']:390 return sjq391 else:392 print(393 'QA Error QASU.main.py call select_save_engine \394 with parameter %s is None of thshare, ts, Thshare, or tdx',395 engine)396def QA_SU_save_stock_min_5(file_dir, client=DATABASE):397 """save stock_min5398 Arguments:399 file_dir {[type]} -- [description]400 Keyword Arguments:401 client {[type]} -- [description] (default: {DATABASE})402 Returns:403 [type] -- [description]404 """405 return tdx_file.QA_save_tdx_to_mongo(file_dir, client)406def QA_SU_crawl_eastmoney(action="zjlx", stockCode=None):407 '''408 :param action: zjlx åææ¯æå
¶ä»çæä½ç±»å409 :param stockCode: è¡ç¥¨ä»£ç 410 :return:411 '''412 stockItems = QA_fetch_stock_list()413 if stockCode == "all":414 # 读åtushareè¡ç¥¨å表代ç 415 print("ðª ä¸å
±éè¦è·å %d 个è¡ç¥¨ç èµéæµå , éè¦å¤§æ¦ %d å°æ¶" %416 (len(stockItems), (len(stockItems) * 5) / 60 / 60))417 code_list = []418 for stock in stockItems:419 code_list.append(stock['code'])420 # print(stock['code'])421 crawl_eastmoney_file.QA_read_eastmoney_zjlx_web_page_to_sqllite(422 code_list)423 # print(stock)424 return425 else:426 # todo æ£æ¥è¡ç¥¨ä»£ç æ¯å¦åæ³427 # return crawl_eastmoney_file.QA_read_eastmoney_zjlx_web_page_to_sqllite(stockCode=stockCode)428 code_list = []429 code_list.append(stockCode)430 return crawl_eastmoney_file.QA_request_eastmoney_zjlx(431 param_stock_code_list=code_list)432def QA_SU_save_financialfiles():433 return save_financialfiles.QA_SU_save_financial_files()434def QA_SU_save_financialfiles_fromtdx():435 return save_financialfiles.QA_SU_save_financial_files(fromtdx=True)436def QA_SU_save_report_calendar_day():437 return save_financial_calendar.QA_SU_save_report_calendar_day()438def QA_SU_save_report_calendar_his():439 return save_financial_calendar.QA_SU_save_report_calendar_his()440def QA_SU_save_stock_divyield_day():441 return save_stock_divyield.QA_SU_save_stock_divyield_day()442def QA_SU_save_stock_divyield_his():443 return save_stock_divyield.QA_SU_save_stock_divyield_his()444def QA_SU_save_bond_list(engine, client=DATABASE):445 """save bond_list446 Arguments:447 engine {[type]} -- [description]448 Keyword Arguments:449 client {[type]} -- [description] (default: {DATABASE})450 """451 engine = select_save_engine(engine)452 engine.QA_SU_save_bond_list(client=client)453@print_used_time454def QA_SU_save_bond_day(engine, client=DATABASE, paralleled=False):455 """save bond_day456 Arguments:457 engine {[type]} -- [description]458 Keyword Arguments:459 client {[type]} -- [description] (default: {DATABASE})460 :param paralleled: æ¯å¦å¹¶è¡å¤ç(default: {True})461 """462 engine = select_save_engine(engine, paralleled=paralleled)463 engine.QA_SU_save_bond_day(client=client)464def QA_SU_save_single_bond_day(code, engine, client=DATABASE, paralleled=False):465 """save bond_day466 Arguments:467 code: bond code468 engine {[type]} -- [description]469 Keyword Arguments:470 client {[type]} -- [description] (default: {DATABASE})471 :param paralleled: æ¯å¦å¹¶è¡å¤ç(default: {True})472 """473 engine = select_save_engine(engine, paralleled=paralleled)474 engine.QA_SU_save_single_bond_day(code=code, client=client)475def QA_SU_save_bond_min(engine, client=DATABASE):476 """save bond_min477 Arguments:478 engine {[type]} -- [description]479 Keyword Arguments:480 client {[type]} -- [description] (default: {DATABASE})481 """482 engine = select_save_engine(engine)483 engine.QA_SU_save_bond_min(client=client)484def QA_SU_save_single_bond_min(code, engine, client=DATABASE):485 """save bond_min486 Arguments:487 code: bond code488 engine {[type]} -- [description]489 Keyword Arguments:490 client {[type]} -- [description] (default: {DATABASE})491 """492 engine = select_save_engine(engine)...
test_searchengine.py
Source:test_searchengine.py
1'''Test functions and SearchEngine class in SearchEngine.py.'''2# With mock replacements, the module does not use any gui widgets.3# The use of tk.Text is avoided (for now, until mock Text is improved)4# by patching instances with an index function returning what is needed.5# This works because mock Text.get does not use .index.6import re7import unittest8from test.test_support import requires9from Tkinter import BooleanVar, StringVar, TclError # ,Tk, Text10import tkMessageBox11from idlelib import SearchEngine as se12from idlelib.idle_test.mock_tk import Var, Mbox13from idlelib.idle_test.mock_tk import Text as mockText14def setUpModule():15 # Replace s-e module tkinter imports other than non-gui TclError.16 se.BooleanVar = Var17 se.StringVar = Var18 se.tkMessageBox = Mbox19def tearDownModule():20 # Restore 'just in case', though other tests should also replace.21 se.BooleanVar = BooleanVar22 se.StringVar = StringVar23 se.tkMessageBox = tkMessageBox24class Mock:25 def __init__(self, *args, **kwargs): pass26class GetTest(unittest.TestCase):27 # SearchEngine.get returns singleton created & saved on first call.28 def test_get(self):29 saved_Engine = se.SearchEngine30 se.SearchEngine = Mock # monkey-patch class31 try:32 root = Mock()33 engine = se.get(root)34 self.assertIsInstance(engine, se.SearchEngine)35 self.assertIs(root._searchengine, engine)36 self.assertIs(se.get(root), engine)37 finally:38 se.SearchEngine = saved_Engine # restore class to module39class GetLineColTest(unittest.TestCase):40 # Test simple text-independent helper function41 def test_get_line_col(self):42 self.assertEqual(se.get_line_col('1.0'), (1, 0))43 self.assertEqual(se.get_line_col('1.11'), (1, 11))44 self.assertRaises(ValueError, se.get_line_col, ('1.0 lineend'))45 self.assertRaises(ValueError, se.get_line_col, ('end'))46class GetSelectionTest(unittest.TestCase):47 # Test text-dependent helper function.48## # Need gui for text.index('sel.first/sel.last/insert').49## @classmethod50## def setUpClass(cls):51## requires('gui')52## cls.root = Tk()53##54## @classmethod55## def tearDownClass(cls):56## cls.root.destroy()57## del cls.root58 def test_get_selection(self):59 # text = Text(master=self.root)60 text = mockText()61 text.insert('1.0', 'Hello World!')62 # fix text.index result when called in get_selection63 def sel(s):64 # select entire text, cursor irrelevant65 if s == 'sel.first': return '1.0'66 if s == 'sel.last': return '1.12'67 raise TclError68 text.index = sel # replaces .tag_add('sel', '1.0, '1.12')69 self.assertEqual(se.get_selection(text), ('1.0', '1.12'))70 def mark(s):71 # no selection, cursor after 'Hello'72 if s == 'insert': return '1.5'73 raise TclError74 text.index = mark # replaces .mark_set('insert', '1.5')75 self.assertEqual(se.get_selection(text), ('1.5', '1.5'))76class ReverseSearchTest(unittest.TestCase):77 # Test helper function that searches backwards within a line.78 def test_search_reverse(self):79 Equal = self.assertEqual80 line = "Here is an 'is' test text."81 prog = re.compile('is')82 Equal(se.search_reverse(prog, line, len(line)).span(), (12, 14))83 Equal(se.search_reverse(prog, line, 14).span(), (12, 14))84 Equal(se.search_reverse(prog, line, 13).span(), (5, 7))85 Equal(se.search_reverse(prog, line, 7).span(), (5, 7))86 Equal(se.search_reverse(prog, line, 6), None)87class SearchEngineTest(unittest.TestCase):88 # Test class methods that do not use Text widget.89 def setUp(self):90 self.engine = se.SearchEngine(root=None)91 # Engine.root is only used to create error message boxes.92 # The mock replacement ignores the root argument.93 def test_is_get(self):94 engine = self.engine95 Equal = self.assertEqual96 Equal(engine.getpat(), '')97 engine.setpat('hello')98 Equal(engine.getpat(), 'hello')99 Equal(engine.isre(), False)100 engine.revar.set(1)101 Equal(engine.isre(), True)102 Equal(engine.iscase(), False)103 engine.casevar.set(1)104 Equal(engine.iscase(), True)105 Equal(engine.isword(), False)106 engine.wordvar.set(1)107 Equal(engine.isword(), True)108 Equal(engine.iswrap(), True)109 engine.wrapvar.set(0)110 Equal(engine.iswrap(), False)111 Equal(engine.isback(), False)112 engine.backvar.set(1)113 Equal(engine.isback(), True)114 def test_setcookedpat(self):115 engine = self.engine116 engine.setcookedpat('\s')117 self.assertEqual(engine.getpat(), '\s')118 engine.revar.set(1)119 engine.setcookedpat('\s')120 self.assertEqual(engine.getpat(), r'\\s')121 def test_getcookedpat(self):122 engine = self.engine123 Equal = self.assertEqual124 Equal(engine.getcookedpat(), '')125 engine.setpat('hello')126 Equal(engine.getcookedpat(), 'hello')127 engine.wordvar.set(True)128 Equal(engine.getcookedpat(), r'\bhello\b')129 engine.wordvar.set(False)130 engine.setpat('\s')131 Equal(engine.getcookedpat(), r'\\s')132 engine.revar.set(True)133 Equal(engine.getcookedpat(), '\s')134 def test_getprog(self):135 engine = self.engine136 Equal = self.assertEqual137 engine.setpat('Hello')138 temppat = engine.getprog()139 Equal(temppat.pattern, re.compile('Hello', re.IGNORECASE).pattern)140 engine.casevar.set(1)141 temppat = engine.getprog()142 Equal(temppat.pattern, re.compile('Hello').pattern, 0)143 engine.setpat('')144 Equal(engine.getprog(), None)145 engine.setpat('+')146 engine.revar.set(1)147 Equal(engine.getprog(), None)148 self.assertEqual(Mbox.showerror.message,149 'Error: nothing to repeat\nPattern: +')150 def test_report_error(self):151 showerror = Mbox.showerror152 Equal = self.assertEqual153 pat = '[a-z'154 msg = 'unexpected end of regular expression'155 Equal(self.engine.report_error(pat, msg), None)156 Equal(showerror.title, 'Regular expression error')157 expected_message = ("Error: " + msg + "\nPattern: [a-z")158 Equal(showerror.message, expected_message)159 Equal(self.engine.report_error(pat, msg, 5), None)160 Equal(showerror.title, 'Regular expression error')161 expected_message += "\nOffset: 5"162 Equal(showerror.message, expected_message)163class SearchTest(unittest.TestCase):164 # Test that search_text makes right call to right method.165 @classmethod166 def setUpClass(cls):167## requires('gui')168## cls.root = Tk()169## cls.text = Text(master=cls.root)170 cls.text = mockText()171 test_text = (172 'First line\n'173 'Line with target\n'174 'Last line\n')175 cls.text.insert('1.0', test_text)176 cls.pat = re.compile('target')177 cls.engine = se.SearchEngine(None)178 cls.engine.search_forward = lambda *args: ('f', args)179 cls.engine.search_backward = lambda *args: ('b', args)180## @classmethod181## def tearDownClass(cls):182## cls.root.destroy()183## del cls.root184 def test_search(self):185 Equal = self.assertEqual186 engine = self.engine187 search = engine.search_text188 text = self.text189 pat = self.pat190 engine.patvar.set(None)191 #engine.revar.set(pat)192 Equal(search(text), None)193 def mark(s):194 # no selection, cursor after 'Hello'195 if s == 'insert': return '1.5'196 raise TclError197 text.index = mark198 Equal(search(text, pat), ('f', (text, pat, 1, 5, True, False)))199 engine.wrapvar.set(False)200 Equal(search(text, pat), ('f', (text, pat, 1, 5, False, False)))201 engine.wrapvar.set(True)202 engine.backvar.set(True)203 Equal(search(text, pat), ('b', (text, pat, 1, 5, True, False)))204 engine.backvar.set(False)205 def sel(s):206 if s == 'sel.first': return '2.10'207 if s == 'sel.last': return '2.16'208 raise TclError209 text.index = sel210 Equal(search(text, pat), ('f', (text, pat, 2, 16, True, False)))211 Equal(search(text, pat, True), ('f', (text, pat, 2, 10, True, True)))212 engine.backvar.set(True)213 Equal(search(text, pat), ('b', (text, pat, 2, 10, True, False)))214 Equal(search(text, pat, True), ('b', (text, pat, 2, 16, True, True)))215class ForwardBackwardTest(unittest.TestCase):216 # Test that search_forward method finds the target.217## @classmethod218## def tearDownClass(cls):219## cls.root.destroy()220## del cls.root221 @classmethod222 def setUpClass(cls):223 cls.engine = se.SearchEngine(None)224## requires('gui')225## cls.root = Tk()226## cls.text = Text(master=cls.root)227 cls.text = mockText()228 # search_backward calls index('end-1c')229 cls.text.index = lambda index: '4.0'230 test_text = (231 'First line\n'232 'Line with target\n'233 'Last line\n')234 cls.text.insert('1.0', test_text)235 cls.pat = re.compile('target')236 cls.res = (2, (10, 16)) # line, slice indexes of 'target'237 cls.failpat = re.compile('xyz') # not in text238 cls.emptypat = re.compile('\w*') # empty match possible239 def make_search(self, func):240 def search(pat, line, col, wrap, ok=0):241 res = func(self.text, pat, line, col, wrap, ok)242 # res is (line, matchobject) or None243 return (res[0], res[1].span()) if res else res244 return search245 def test_search_forward(self):246 # search for non-empty match247 Equal = self.assertEqual248 forward = self.make_search(self.engine.search_forward)249 pat = self.pat250 Equal(forward(pat, 1, 0, True), self.res)251 Equal(forward(pat, 3, 0, True), self.res) # wrap252 Equal(forward(pat, 3, 0, False), None) # no wrap253 Equal(forward(pat, 2, 10, False), self.res)254 Equal(forward(self.failpat, 1, 0, True), None)255 Equal(forward(self.emptypat, 2, 9, True, ok=True), (2, (9, 9)))256 #Equal(forward(self.emptypat, 2, 9, True), self.res)257 # While the initial empty match is correctly ignored, skipping258 # the rest of the line and returning (3, (0,4)) seems buggy - tjr.259 Equal(forward(self.emptypat, 2, 10, True), self.res)260 def test_search_backward(self):261 # search for non-empty match262 Equal = self.assertEqual263 backward = self.make_search(self.engine.search_backward)264 pat = self.pat265 Equal(backward(pat, 3, 5, True), self.res)266 Equal(backward(pat, 2, 0, True), self.res) # wrap267 Equal(backward(pat, 2, 0, False), None) # no wrap268 Equal(backward(pat, 2, 16, False), self.res)269 Equal(backward(self.failpat, 3, 9, True), None)270 Equal(backward(self.emptypat, 2, 10, True, ok=True), (2, (9,9)))271 # Accepted because 9 < 10, not because ok=True.272 # It is not clear that ok=True is useful going back - tjr273 Equal(backward(self.emptypat, 2, 9, True), (2, (5, 9)))274if __name__ == '__main__':...
persistent_storage_spec.js
Source:persistent_storage_spec.js
1describe('PersistentStorage', function() {2 var engine, ls;3 // test suite is dependent on localStorage being available4 if (!window.localStorage) {5 console.warn('no localStorage support â skipping PersistentStorage suite');6 return;7 }8 // for good measure!9 localStorage.clear();10 beforeEach(function() {11 ls = {12 get length() { return localStorage.length; },13 key: spyThrough('key'),14 clear: spyThrough('clear'),15 getItem: spyThrough('getItem'),16 setItem: spyThrough('setItem'),17 removeItem: spyThrough('removeItem')18 };19 engine = new PersistentStorage('ns', ls);20 spyOn(Date.prototype, 'getTime').andReturn(0);21 });22 afterEach(function() {23 localStorage.clear();24 });25 // public methods26 // --------------27 describe('#get', function() {28 it('should access localStorage with prefixed key', function() {29 engine.get('key');30 expect(ls.getItem).toHaveBeenCalledWith('__ns__key');31 });32 it('should return undefined when key does not exist', function() {33 expect(engine.get('does not exist')).toEqual(undefined);34 });35 it('should return value as correct type', function() {36 engine.set('string', 'i am a string');37 engine.set('number', 42);38 engine.set('boolean', true);39 engine.set('null', null);40 engine.set('object', { obj: true });41 expect(engine.get('string')).toEqual('i am a string');42 expect(engine.get('number')).toEqual(42);43 expect(engine.get('boolean')).toEqual(true);44 expect(engine.get('null')).toBeNull();45 expect(engine.get('object')).toEqual({ obj: true });46 });47 it('should expire stale keys', function() {48 engine.set('key', 'value', -1);49 expect(engine.get('key')).toBeNull();50 expect(ls.getItem('__ns__key__ttl')).toBeNull();51 });52 });53 describe('#set', function() {54 it('should access localStorage with prefixed key', function() {55 engine.set('key', 'val');56 expect(ls.setItem.mostRecentCall.args[0]).toEqual('__ns__key');57 });58 it('should JSON.stringify value before storing', function() {59 engine.set('key', 'val');60 expect(ls.setItem.mostRecentCall.args[1]).toEqual(JSON.stringify('val'));61 });62 it('should store ttl if provided', function() {63 var ttl = 1;64 engine.set('key', 'value', ttl);65 expect(ls.setItem.argsForCall[0])66 .toEqual(['__ns__key__ttl__', ttl.toString()]);67 });68 it('should call clear if the localStorage limit has been reached', function() {69 var spy;70 ls.setItem.andCallFake(function() {71 var err = new Error();72 err.name = 'QuotaExceededError';73 throw err;74 });75 engine.clear = spy = jasmine.createSpy();76 engine.set('key', 'value', 1);77 expect(spy).toHaveBeenCalled();78 });79 it('should noop if the localStorage limit has been reached', function() {80 var get, set, remove, clear, isExpired;81 ls.setItem.andCallFake(function() {82 var err = new Error();83 err.name = 'QuotaExceededError';84 throw err;85 });86 get = engine.get;87 set = engine.set;88 remove = engine.remove;89 clear = engine.clear;90 isExpired = engine.isExpired;91 engine.set('key', 'value', 1);92 expect(engine.get).not.toBe(get);93 expect(engine.set).not.toBe(set);94 expect(engine.remove).not.toBe(remove);95 expect(engine.clear).not.toBe(clear);96 expect(engine.isExpired).not.toBe(isExpired);97 });98 });99 describe('#remove', function() {100 it('should remove key from storage', function() {101 engine.set('key', 'val');102 engine.remove('key');103 expect(engine.get('key')).toBeNull();104 });105 });106 describe('#clear', function() {107 it('should work with namespaces that contain regex characters', function() {108 engine = new PersistentStorage('ns?()');109 engine.set('key1', 'val1');110 engine.set('key2', 'val2');111 engine.clear();112 expect(engine.get('key1')).toEqual(undefined);113 expect(engine.get('key2')).toEqual(undefined);114 });115 it('should remove all keys that exist in namespace of engine', function() {116 engine.set('key1', 'val1');117 engine.set('key2', 'val2');118 engine.set('key3', 'val3');119 engine.set('key4', 'val4', 0);120 engine.clear();121 expect(engine.get('key1')).toEqual(undefined);122 expect(engine.get('key2')).toEqual(undefined);123 expect(engine.get('key3')).toEqual(undefined);124 expect(engine.get('key4')).toEqual(undefined);125 });126 it('should not affect keys with different namespace', function() {127 ls.setItem('diff_namespace', 'val');128 engine.clear();129 expect(ls.getItem('diff_namespace')).toEqual('val');130 });131 });132 describe('#isExpired', function() {133 it('should be false for keys without ttl', function() {134 engine.set('key', 'value');135 expect(engine.isExpired('key')).toBe(false);136 });137 it('should be false for fresh keys', function() {138 engine.set('key', 'value', 1);139 expect(engine.isExpired('key')).toBe(false);140 });141 it('should be true for stale keys', function() {142 engine.set('key', 'value', -1);143 expect(engine.isExpired('key')).toBe(true);144 });145 });146 // compatible across browsers147 function spyThrough(method) {148 return jasmine.createSpy().andCallFake(fake);149 function fake() {150 return localStorage[method].apply(localStorage, arguments);151 }152 }...
engines.py
Source:engines.py
1"""2Engines module3Describes different types of engines4"""5class Engine:6 """7 Base engine class8 """9 def __init__(self, engine_name, engine_power, engine_type):10 self.engine_name = engine_name11 self.engine_power = engine_power12 self.engine_type = engine_type13class CarEngine(Engine):14 """15 Class for car engines16 """17 engine = 'Car engine'18 def __str__(self):19 return f'{self.engine}: {self.engine_name}, ' \20 f'power: {self.engine_power} c.u., type: {self.engine_type}'21class TrainEngine(Engine):22 """23 Class for train engines24 """25 engine = 'Train engine'26 def __str__(self):27 return f'{self.engine}: {self.engine_name}, ' \28 f'power: {self.engine_power} c.u., type: {self.engine_type}'29class ShipEngine(Engine):30 """31 Class for ship engines32 """33 engine = 'Ship engine'34 def __str__(self):35 return f'{self.engine}: {self.engine_name}, ' \36 f'power: {self.engine_power} c.u., type: {self.engine_type}'37class AirplaneEngine(Engine):38 """39 Class for airplane engines40 """41 engine = 'Airplane engine'42 def __init__(self, engine_name, engine_power, engine_type, engines_num):43 super().__init__(engine_name, engine_power, engine_type)44 self.engines_num = engines_num45 def __str__(self):46 return f'{self.engine}: {self.engine_name}, power: {self.engine_power} c.u., ' \47 f'type: {self.engine_type}, number: {self.engines_num}, ' \...
Using AI Code Generation
1module.exports = {2 {3 },4 {5 },6 {7 }8 {9 }10};11module.exports = function (casper, scenario, vp) {12 casper.echo('onBefore.js has run for ' + vp.label);13};14module.exports = function (casper, scenario, vp) {15 casper.echo('onReady.js has run for ' + vp.label);16};17module.exports = function (casper, scenario, vp) {18 casper.echo(scenario.url);19 casper.echo(scenario.referenceUrl);20};21module.exports = function (casper, scenario, vp) {22 casper.echo(scenario.url);
Using AI Code Generation
1var backstop = require('backstopjs');2backstop('reference', { config: 'backstop.json' })3 .then(function() {4 return backstop('test', { config: 'backstop.json' });5 })6 .then(function() {7 console.log('done');8 })9 .catch(function(e) {10 console.log(e);11 });12{13 {14 },15 {16 },17 {18 }19 {20 }21 "paths": {22 },23 "engineOptions": {24 },25}
Using AI Code Generation
1module.exports = async (engine, scenario, vp) => {2 console.log('SCENARIO > ' + scenario.label);3 await engine.waitForSelector('#username');4 await engine.click('#username');5 await engine.type('#username', 'admin');6 await engine.waitForSelector('#password');7 await engine.click('#password');8 await engine.type('#password', 'admin');9 await engine.waitForSelector('#login');10 await engine.click('#login');11 await engine.waitForSelector('#logout');12};13{14 {15 }16}
Using AI Code Generation
1var engine = require('backstopjs');2engine('test', {config: 'backstop.json'});3{4 {5 },6 {7 },8 {9 },10 {11 },12 {13 }14 {15 }16 "paths": {17 },18 "engineOptions": {19 },20}
Using AI Code Generation
1var engine = require('backstopjs');2engine('test', { config: './backstop.json' })3.then(() => {4})5.catch((err) => {6});7{8 {9 },10 {11 },12 {13 },14 {15 }16 {17 }18 "paths": {19 },20 "engineOptions": {21 },22}
Using AI Code Generation
1const engine = require('backstopjs/core/command/engine');2engine.run({3}).then(() => {4 console.log('done');5}).catch((e) => {6 console.log(e);7});8{9 {10 }11 {12 }13 "paths": {14 },15 "engineOptions": {16 },17}
Using AI Code Generation
1var engine = require('backstopjs').engine;2engine('test', {config: './backstop.json'});3engine('reference', {config: './backstop.json'});4engine('approve', {config: './backstop.json'});5engine('test', {config: './backstop.json'});6engine('openReport', {config: './backstop.json'});7engine('approve', {config: './backstop.json'});8engine('test', {config: './backstop.json'});9engine('openReport', {config: './backstop.json'});10engine('approve', {config: './backstop.json'});11engine('test', {config: './backstop.json'});12engine('openReport', {config: './backstop.json'});13engine('approve', {config: './backstop.json'});14engine('test', {config: './backstop.json'});15engine('openReport', {config: './backstop.json'});16engine('approve', {config: './backstop.json'});17engine('test', {config: './backstop.json'});18engine('openReport', {config: './backstop.json'});19engine('approve', {config: './backstop.json'});20engine('test', {config: './backstop.json'});21engine('openReport', {config: './backstop.json'});22engine('approve', {config: './backstop.json
Using AI Code Generation
1var engine = require('backstopjs').engine;2engine('test', {3}).then(function (result) {4 console.log(result);5}).catch(function (err) {6 console.error(err);7});8{9 {10 }11}12var engine = require('backstopjs').engine;13engine('test', {14}).then(function (result) {15 console.log(result);16}).catch(function (err) {17 console.error(err);18});19var engine = require('backstopjs').engine;20var fs = require('fs');21engine('test', {22}).then(function (result) {23 fs.writeFileSync('backstop_results.json', JSON.stringify(result, null, 2));24}).catch(function (err) {25 console.error(err);26});
Using AI Code Generation
1var engine = require('backstopjs/engine');2engine('test', {config: './backstop.json'}).then(function() {3 console.log('done');4}).catch(function(err) {5 console.log(err);6});7{8 {9 },10 {11 },12 {13 }14 {15 }16 "paths": {17 },18}19module.exports = function (chromy, scenario) {20 console.log('onBefore.js has run for ' + scenario.label);21 require('./onReady')(chromy, scenario);22};23module.exports = function (chromy, scenario) {
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!!