How to use _open method in uiautomator

Best Python code snippet using uiautomator

JavCan.py

Source:JavCan.py Github

copy

Full Screen

1import method.algofuncs as _af2####------------------------------------------------------------------------------------------------------------#####3def convertToJapanCandle(ticker_data):4 ticker_data['Height'] = ticker_data.apply(lambda x: x['High'] - x['Low'], axis=1)5 ticker_data['Body'] = ticker_data.apply(lambda x: abs(x['Close'] - x['Open']), axis=1)6 ticker_data['UpShadow'] = ticker_data.apply(7 lambda x: (x['High'] - x['Close']) if (x['Close'] > x['Open']) else (x['High'] - x['Open']), axis=1)8 ticker_data['LowerShadow'] = ticker_data.apply(9 lambda x: (x['Open'] - x['Low']) if (x['Close'] > x['Open']) else (x['Close'] - x['Low']), axis=1)10 if 'Time' in ticker_data.columns:11 from datetime import datetime12 ticker_data['Date'] = ticker_data.apply(13 lambda x: datetime.fromtimestamp(x['Time']).strftime("%m/%d/%Y"), axis=1)14 return ticker_data15####------------------------------------------------------------------------------------------------------------#####16BIG_BODY_PRICE_RATE = 0.04 # 4%17SMALL_BODY_PRICE_RATE = 0.0118UP_SHADOW_HEIGHT_RATE_65 = 0.6519UP_SHADOW_HEIGHT_RATE_30 = 0.3020UP_SHADOW_HEIGHT_RATE_25 = 0.2521UP_SHADOW_HEIGHT_RATE_05 = 0.0522BODY_HEIGHT_RATE_85 = 0.85 # for compare 4/523BODY_HEIGHT_RATE_60 = 0.60 # for compare 1/224BODY_HEIGHT_RATE_45 = 0.45 # for compare 1/225BODY_HEIGHT_RATE_35 = 0.35 # for compare 1/326BODY_HEIGHT_RATE_30 = 0.3 # for compare 1/327BODY_HEIGHT_RATE_20 = 0.2 # for compare 1/428BODY_HEIGHT_RATE_05 = 0.05 # for compare 1/2029LOWER_SHADOW_HEIGHT_RATE_65 = 0.6530LOWER_SHADOW_HEIGHT_RATE_30 = 0.3031LOWER_SHADOW_HEIGHT_RATE_25 = 0.2532LOWER_SHADOW_HEIGHT_RATE_05 = 0.0533##### --------------------------------------------------------------------------------- #####34def isBodyOver85(body, height):35 return True if body > BODY_HEIGHT_RATE_85 * height else False36def isBodyOver60(body, height):37 return True if body > BODY_HEIGHT_RATE_60 * height else False38def isBodyOver45(body, height):39 return True if body > BODY_HEIGHT_RATE_45 * height else False40def isBigBody(body, height, _open, _close):41 maxPrice = _open if _open > _close else _close42 if isBodyOver45(body, height) and body > BIG_BODY_PRICE_RATE * maxPrice:43 return True44 return False45def isSmallBody(body, height, _open, _close):46 maxPrice = _open if _open > _close else _close47 if isBodyLess35(body, height) and body < SMALL_BODY_PRICE_RATE * maxPrice:48 return True49 return False50def isBodyLess45(body, height):51 return True if body < BODY_HEIGHT_RATE_45 * height else False52def isBodyLess35(body, height):53 return True if body < BODY_HEIGHT_RATE_35 * height else False54def isBodyLess20(body, height):55 return True if body < BODY_HEIGHT_RATE_20 * height else False56def isDoji(body, height):57 if body < BODY_HEIGHT_RATE_05 * height:58 return True59 return False60##### --------------------------------------------------------------------------------- #####61def isWhiteCandlestick(open_price, close_price):62 if close_price > open_price:63 return True64 return False65def isBlackCandlestick(open_price, close_price):66 if close_price < open_price:67 return True68 return False69def isSpinningTopCandlestick(body, height, up, bot):70 if body < BODY_HEIGHT_RATE_35 * height:71 if up > UP_SHADOW_HEIGHT_RATE_30 * height:72 if bot > LOWER_SHADOW_HEIGHT_RATE_30 * height:73 return True74 return False75def isHammer(body, height, up, bot):76 if up < UP_SHADOW_HEIGHT_RATE_05 * height:77 if body < BODY_HEIGHT_RATE_30 * height:78 if bot > LOWER_SHADOW_HEIGHT_RATE_65 * height:79 return True80 return False81def isInvertedHammer(body, height, up, bot):82 if up > UP_SHADOW_HEIGHT_RATE_65 * height:83 if body < BODY_HEIGHT_RATE_30 * height:84 if bot < LOWER_SHADOW_HEIGHT_RATE_05 * height:85 return True86 return False87def isShavenHead(height, up):88 """89 Nến cạo đầu90 :param height:91 :param up:92 :return:93 """94 if up < UP_SHADOW_HEIGHT_RATE_05 * height:95 return True96 return False97def isShavenBottom(height, bot):98 """99 Nến cạo đáy100 :param height:101 :param bot:102 :return:103 """104 if bot < LOWER_SHADOW_HEIGHT_RATE_05 * height:105 return True106 return False107def isUmbrellaCandlestick(body, height, up, bot):108 return isHammer(body, height, up, bot)109####------------------------------------------------------------------------------------------------------------#####110def isUpTrendV1(_open, _close, _high, _low, _body, _height, _up, _down):111 isUpTrend = False112 if _close[-2] > _close[-3] > _close[-4]:113 isUpTrend = True114 if _high[-2] > _high[-3] > _high[-4]:115 isUpTrend = True116 if isWhiteCandlestick(_open[-2], _close[-2]) \117 and isWhiteCandlestick(_open[-3], _close[-3]) \118 and isWhiteCandlestick(_open[-4], _close[-4]):119 isUpTrend = True120 k = 0121 for i in [-2, -3, -4, -5, -6, -7]:122 if isWhiteCandlestick(_open[i], _close[i]) is True:123 k = k + 1124 if k > 3:125 isUpTrend = True126 return isUpTrend127def isDownTrendV1(_open, _close, _high, _low, _body, _height, _up, _down):128 if isUpTrendV1(_open, _close, _high, _low, _body, _height, _up, _down):129 return False130 isDownTrend = False131 if _close[-2] < _close[-3] < _close[-4]:132 isDownTrend = True133 if _low[-2] < _low[-3] < _low[-4]:134 isDownTrend = True135 if isBlackCandlestick(_open[-2], _close[-2]) \136 and isBlackCandlestick(_open[-3], _close[-3]) \137 and isBlackCandlestick(_open[-4], _close[-4]):138 isDownTrend = True139 k = 0140 for i in [-2, -3, -4, -5, -6, -7]:141 if isBlackCandlestick(_open[i], _close[i]) is True:142 k = k + 1143 if k > 3:144 isDownTrend = True145 return isDownTrend146####------------------------------------------------------------------------------------------------------------#####147def isUpTrendV2ByRSI(_close):148 return True if _af.RSIV2(_close, 5) > 55 else False149def isDownTrendV2ByRSI(_close):150 # return True if _af.RSIV2(_close, 5) < 45 else False151 # RSI for 5 days152 rsi = _af.RSI(_close, 5).tail(1).item()153 return True if rsi < 45 else False154####------------------------------------------------------------------------------------------------------------#####155def isHammerModel(_open, _close, _high, _low, _body, _height, _up, _down):156 """157 # In a down trend158 # today is a hammer candlestick159 :param :160 :return bool:161 """162 isDownTrend = isDownTrendV2ByRSI(_close[:-2])163 _iuc = isHammer(_body[-1], _height[-1], _up[-1], _down[-1])164 # _iwc = isWhiteCandlestick(_open[-1], _close[-1])165 if isDownTrend is True and _iuc is True:166 return True167 else:168 return False169def isHangingManModel(_open, _close, _high, _low, _body, _height, _up, _down):170 """171 # In a up trend (base on High price)172 # Small body height (base on total height)173 # Small or none upper shadow174 :param :175 :return:176 """177 # isUpTrend = isUpTrendV1(_open, _close, _high, _low, _body, _height, _up, _down)178 isUpTrend = isUpTrendV2ByRSI(_close[:-2])179 _iuc = isUmbrellaCandlestick(_body[-1], _height[-1], _up[-1], _down[-1])180 if isUpTrend is True and _iuc is True:181 return True182 else:183 return False184def isBullishEngulfing(_open, _close, _high, _low, _body, _height, _up, _down):185 """186 :param _open numpy array:187 :param _close:188 :param _body:189 :param _height:190 :param _up:191 :param _down:192 :return:193 """194 todayHasBigBody = isBigBody(_body[-1], _height[-1], _open[-1], _close[-1])195 if todayHasBigBody is False:196 return False197 prevDayIsSpinningCandlestick = isSpinningTopCandlestick(_body[-2], _height[-2], _up[-2], _down[-2])198 if prevDayIsSpinningCandlestick is True and _body[-1] < 2 * _body[-2]:199 return False200 isDownTrend = isDownTrendV1(_open, _close, _high, _low, _body, _height, _up, _down)201 prevDayIsBlackCandlestick = isBlackCandlestick(_open[-2], _close[-2])202 prevDayMaxOpenClose = _open[-2] if _open[-2] > _close[-2] else _close[-2]203 prevDayMinOpenClose = _open[-2] if _open[-2] < _close[-2] else _close[-2]204 prevDayIsDoJi = isDoji(_body[-2], _height[-2])205 todayIsWhiteCandlestick = isWhiteCandlestick(_open[-1], _close[-1])206 todayMaxOpenClose = _open[-1] if _open[-1] > _close[-1] else _close[-1]207 todayMinOpenClose = _open[-1] if _open[-1] < _close[-1] else _close[-1]208 if isDownTrend is True \209 and (prevDayIsBlackCandlestick is True or prevDayIsDoJi is True) \210 and prevDayMaxOpenClose <= 0.96 * todayMaxOpenClose \211 and prevDayMinOpenClose >= todayMinOpenClose \212 and todayIsWhiteCandlestick is True:213 return True214 return False215def isBearishEngulfing(_open, _close, _high, _low, _body, _height, _up, _down):216 isUpTrend = isUpTrendV1(_open, _close, _high, _low, _body, _height, _up, _down)217 todayIsBlackCandlestick = isBlackCandlestick(_open[-1], _close[-1])218 prevDayMaxOpenClose = _open[-2] if _open[-2] > _close[-2] else _close[-2]219 prevDayMinOpenClose = _open[-2] if _open[-2] < _close[-2] else _close[-2]220 todayMaxOpenClose = _open[-1] if _open[-1] > _close[-1] else _close[-1]221 todayMinOpenClose = _open[-1] if _open[-1] < _close[-1] else _close[-1]222 if isUpTrend is True \223 and prevDayMaxOpenClose <= todayMaxOpenClose \224 and prevDayMinOpenClose >= todayMinOpenClose \225 and todayIsBlackCandlestick is True:226 return True227 return False228def isPiercingPattern(_open, _close, _high, _low, _body, _height, _up, _down):229 isDownTrend = isDownTrendV1(_open, _close, _high, _low, _body, _height, _up, _down)230 the1stDayIsBlackCandlestick = isBlackCandlestick(_open[-2], _close[-2])231 the1stDayHasBigBody = isBodyOver45(_body[-2], _height[-2])232 the2ndDayIsWhiteCandlestick = isWhiteCandlestick(_open[-1], _close[-1])233 the2ndDayHasBigBody = isBodyOver45(_body[-1], _height[-1])234 the2ndDayFallInThe1stDay = True if _open[-1] < _close[-2] < _close[-1] < _open[-2] else False235 if isDownTrend is True and the1stDayIsBlackCandlestick is True and the1stDayHasBigBody is True \236 and the2ndDayIsWhiteCandlestick is True and the2ndDayHasBigBody is True \237 and the2ndDayFallInThe1stDay is True :238 return True239 return False240def isDarkCloudCoverPattern(_open, _close, _high, _low, _body, _height, _up, _down):241 isUpTrend = isUpTrendV1(_open, _close, _high, _low, _body, _height, _up, _down)242 prevDayIsWhiteCandlestick = isWhiteCandlestick(_open[-2], _close[-2])243 prevDayHasBigBody = isBodyOver45(_body[-2], _height[-2])244 todayIsBlackCandlestick = isBlackCandlestick(_open[-1], _close[-1])245 todayHasBigBody = isBodyOver45(_body[-1], _height[-1])246 todayFallInYesterday = True if _open[-2] < _close[-1] < _close[-2] < _open[-1] else False247 if isUpTrend is True and prevDayIsWhiteCandlestick is True and prevDayHasBigBody is True \248 and todayIsBlackCandlestick is True and todayHasBigBody is True \249 and todayFallInYesterday is True:250 return True251 return False252def isMorningStarsPattern(_open, _close, _high, _low, _body, _height, _up, _down):253 the1stDayIsBlackCandlestick = isBlackCandlestick(_open[-3], _close[-3])254 the1stDayHasBigBody = isBodyOver45(_body[-3], _height[-3])255 the2ndDayIsSmallBody = isBodyLess35(_body[-2], _height[-2])256 the2ndMaxOpenClosePrice = _open[-2] if _open[-2] > _close[-2] else _close[-2]257 the2ndDayHasGap = True if the2ndMaxOpenClosePrice < _close[-3] else False258 todayIsWhiteCandlestick = isWhiteCandlestick(_open[-1], _close[-1])259 todayFallInThe1stDay = True if _open[-3] > _close[-1] > _close[-3] and _body[-1] > 2 * _body[-2] else False260 if the1stDayIsBlackCandlestick is True and the1stDayHasBigBody is True \261 and the2ndDayIsSmallBody is True and the2ndDayHasGap is True \262 and todayIsWhiteCandlestick is True and todayFallInThe1stDay is True:263 return True264 return False265def isEveningStarsPattern(_open, _close, _high, _low, _body, _height, _up, _down):266 the1stDayIsWhiteCandlestick = isWhiteCandlestick(_open[-3], _close[-3])267 the1stDayHasBigBody = isBodyOver45(_body[-3], _height[-3])268 the2ndDayIsSmallBody = isBodyLess35(_body[-2], _height[-2])269 the2ndMinOpenClosePrice = _open[-2] if _open[-2] < _close[-2] else _close[-2]270 the2ndDayHasGap = True if the2ndMinOpenClosePrice > _close[-3] else False271 todayIsBlackCandlestick = isBlackCandlestick(_open[-1], _close[-1])272 todayFallInThe1stDay = True if _open[-3] < _close[-1] < _close[-3] and _body[-1] > 2 * _body[-2] else False273 if the1stDayIsWhiteCandlestick is True and the1stDayHasBigBody is True \274 and the2ndDayIsSmallBody is True and the2ndDayHasGap is True \275 and todayIsBlackCandlestick is True and todayFallInThe1stDay is True:276 return True277 return False278def isThreeBlackCrowsPattern(_open, _close, _high, _low, _body, _height, _up, _down):279 the1stDayIsBlackCandlestick = isBlackCandlestick(_open[-3], _close[-3])280 the2ndDayIsBlackCandlestick = isBlackCandlestick(_open[-2], _close[-2])281 todayIsBlackCandlestick = isBlackCandlestick(_open[-1], _close[-1])282 if the1stDayIsBlackCandlestick is True and the2ndDayIsBlackCandlestick is True and todayIsBlackCandlestick is True:283 return True284 return False285def isBullishHarami(_open, _close, _high, _low, _body, _height, _up, _down):286 isDownTrend = isDownTrendV1(_open, _close, _high, _low, _body, _height, _up, _down)287 yesterdayIsBlackCandlestick = isBlackCandlestick(_open[-2], _close[-2])288 yesterdayIsBigBody = isBodyOver45(_body[-2], _height[-2])289 toDayHasSmallBody = isSmallBody(_body[-1], _height[-1], _open[-1], _close[-1])290 todayIsDeepInYesterday = True if (_open[-2] + _close[-2]) / 2 > _open[-1] > _close[-2] else False291 if isDownTrend is True and yesterdayIsBlackCandlestick is True and yesterdayIsBigBody is True \292 and toDayHasSmallBody is True and todayIsDeepInYesterday is True:293 return True294 return False295def isBearishHarami(_open, _close, _high, _low, _body, _height, _up, _down):296 isUpTrend = isUpTrendV1(_open, _close, _high, _low, _body, _height, _up, _down)297 yesterdayIsWhiteCandlestick = isWhiteCandlestick(_open[-2], _close[-2])298 yesterdayIsBigBody = isBodyOver45(_body[-2], _height[-2])299 toDayHasSmallBody = isSmallBody(_body[-1], _height[-1], _open[-1], _close[-1])300 todayIsDeepInYesterday = True if _open[-2] < _close[-1] < (_open[-2] + _close[-2]) / 2 else False301 if isUpTrend is True and yesterdayIsWhiteCandlestick is True and yesterdayIsBigBody is True \302 and toDayHasSmallBody is True and todayIsDeepInYesterday is True:303 return True304 return False305####------------------------------------------------------------------------------------------------------------#####306def customBuySignal01(_open, _close, _high, _low, _body, _height, _up, _down):307 isDownTrend = isDownTrendV1(_open, _close, _high, _low, _body, _height, _up, _down)308 _ibc = isSpinningTopCandlestick(_body[-2], _height[-2], _up[-2], _down[-2])309 _iwc = isWhiteCandlestick(_open[-1], _close[-1])310 _ibb = isBigBody(_body[-1], _height[-1], _open[-1], _close[-1])311 if isDownTrend is True and _ibc is True \312 and _iwc is True and _ibb is True \313 and _close[-1] > _close[-2]:314 return "hasBuySignal-01"315 return False316def customBuySignal02(_open, _close, _high, _low, _body, _height, _up, _down):317 isDownTrend = isDownTrendV1(_open, _close, _high, _low, _body, _height, _up, _down)318 the2ndDayIsDoji = isDoji(_body[-2], _height[-2])319 todayIsShavenHead = isShavenHead(_height[-1], _up[-1])320 todayIsWhite = isWhiteCandlestick(_open[-1], _close[-1])321 if isDownTrend is True and the2ndDayIsDoji is True and todayIsShavenHead is True and todayIsWhite is True:322 return "hasBuySignal-02"323 return False324def customBuySignal03(_open, _close, _high, _low, _body, _height, _up, _down):325 # isDownTrend = isDownTrendV1(_open, _close, _high, _low, _body, _height, _up, _down)326 prevDayIsShavenBottom = isShavenBottom(_height[-2], _down[-2])327 todayIsShavenHead = isShavenHead(_height[-1], _up[-1])328 todayIsWhite = isWhiteCandlestick(_open[-1], _close[-1])329 if prevDayIsShavenBottom is True and todayIsShavenHead is True and todayIsWhite is True:330 return "hasBuySignal-03"331 return False332def customBuySignal04(_open, _close, _high, _low, _body, _height, _up, _down):333 """ Optimize the Hammer pattern"""334 isDownTrend = isDownTrendV2ByRSI(_close[:-2])335 todayIsHammer = isHammer(_body[-1], _height[-1], _up[-1], _down[-1])336 todayIsWhite = isWhiteCandlestick(_open[-1], _close[-1])337 if isDownTrend is True and todayIsHammer is True and todayIsWhite is True:338 return "hasBuySignal-04"339 return False340def customSellSignal01(_open, _close, _high, _low, _body, _height, _up, _down):341 todayIsDoJi = isDoji(_body[-1], _height[-1])342 prevDayIsDoJi = isDoji(_body[-2], _height[-2])343 if todayIsDoJi is True and prevDayIsDoJi is True:344 return True345def customSellSignal02(_open, _close, _high, _low, _body, _height, _up, _down):346 yesterdayIsBlack = isBlackCandlestick(_open[-1], _close[-1])347 todayIsWhite = isWhiteCandlestick(_open[-1], _close[-1])348 bodyTodayX2Yesterday = True if _body[-1] > 1.5*_body[-2] else False349 if yesterdayIsBlack is True and todayIsWhite is True and bodyTodayX2Yesterday is True:350 return True351####------------------------------------------------------------------------------------------------------------#####352def hasBuySignal(_open, _close, _high, _low, _body, _height, _up, _down, _volume=0, _date=''):353 # Hammer Pattern not working fine with back test, bad result354 # _iHm = isHammerModel(_open, _close, _high, _low, _body, _height, _up, _down)355 # if _iHm is True:356 # return 'isHammerModel'357 _ibu = isBullishEngulfing(_open, _close, _high, _low, _body, _height, _up, _down)358 if _ibu is True:359 return 'isBullishEngulfing'360 _ipp = isPiercingPattern(_open, _close, _high, _low, _body, _height, _up, _down)361 isVolumeUp = True if _volume[-1] > 1.4 * _volume[-2] else False362 if _ipp is True and isVolumeUp is True:363 return 'isPiercingPattern'364 _ims = isMorningStarsPattern(_open, _close, _high, _low, _body, _height, _up, _down)365 if _ims is True:366 return 'isMorningStarsPattern'367 _cBS01 = customBuySignal01(_open, _close, _high, _low, _body, _height, _up, _down)368 if _cBS01 is True:369 return 'customBuySignal01'370 _cBS02 = customBuySignal02(_open, _close, _high, _low, _body, _height, _up, _down)371 if _cBS02 is True:372 return 'customBuySignal02'373 _cBS03 = customBuySignal03(_open, _close, _high, _low, _body, _height, _up, _down)374 if _cBS03 is True:375 return 'customBuySignal03'376 _cBS04 = customBuySignal04(_open, _close, _high, _low, _body, _height, _up, _down)377 if _cBS04 is not False:378 return _cBS04379 return False380def hasSellSignal(_open, _close, _high, _low, _body, _height, _up, _down, _volume=0, _date=''):381 _ibe = isBearishEngulfing(_open, _close, _high, _low, _body, _height, _up, _down)382 if _ibe is True:383 return 'isBearishEngulfing'384 _idc = isDarkCloudCoverPattern(_open, _close, _high, _low, _body, _height, _up, _down)385 if _idc is True:386 return 'isDarkCloudCoverPattern'387 _ies = isEveningStarsPattern(_open, _close, _high, _low, _body, _height, _up, _down)388 if _ies is True:389 return 'isEveningStarsPattern'390 _itb = isThreeBlackCrowsPattern(_open, _close, _high, _low, _body, _height, _up, _down)391 if _itb is True:392 return 'isThreeBlackCrowsPattern'393 _iha = isHangingManModel(_open, _close, _high, _low, _body, _height, _up, _down)394 if _iha is True:395 return 'isHangingManModel'396 _cSS01 = customSellSignal01(_open, _close, _high, _low, _body, _height, _up, _down)397 if _cSS01 is True:398 return 'customSellSignal01'399 _cSS02 = customSellSignal02(_open, _close, _high, _low, _body, _height, _up, _down)400 if _cSS02 is True:401 return 'customSellSignal02'402 return False403def hasCustomBuySignal(_open, _close, _high, _low, _body, _height, _up, _down, version=0):404 if version == 1 or version == 0:405 _cBS01 = customBuySignal01(_open, _close, _high, _low, _body, _height, _up, _down)406 if _cBS01 is True:407 return 'customBuySignal01'408 if version == 2 or version == 0:409 _cBS02 = customBuySignal02(_open, _close, _high, _low, _body, _height, _up, _down)410 if _cBS02 is True:411 return 'customBuySignal02'412 if version == 3 or version == 0:413 _cBS03 = customBuySignal03(_open, _close, _high, _low, _body, _height, _up, _down)414 if _cBS03 is True:415 return 'customBuySignal03'416 return False417def hasCustomSellSignal(_open, _close, _high, _low, _body, _height, _up, _down, version=0):418 todayIsDoJi = isDoji(_body[-1], _height[-1])419 prevDayIsDoJi = isDoji(_body[-2], _height[-2])420 if todayIsDoJi is True and prevDayIsDoJi is True:...

Full Screen

Full Screen

test_espsecure.py

Source:test_espsecure.py Github

copy

Full Screen

...37 except subprocess.CalledProcessError as e:38 print(e.output)39 raise e40 def setUp(self):41 self.cleanup_files = [] # keep a list of files _open()ed by each test case42 def tearDown(self):43 for f in self.cleanup_files:44 f.close()45 def _open(self, image_file):46 f = open(os.path.join('secure_images', image_file), 'rb')47 self.cleanup_files.append(f)48 return f49class ESP32SecureBootloaderTests(EspSecureTestCase):50 def test_digest_bootloader(self):51 DBArgs = namedtuple('digest_bootloader_args', [52 'keyfile',53 'output',54 'iv',55 'image'])56 try:57 output_file = tempfile.NamedTemporaryFile(delete=False)58 output_file.close()59 args = DBArgs(self._open('256bit_key.bin'),60 output_file.name,61 self._open('256bit_iv.bin'),62 self._open('bootloader.bin'))63 espsecure.digest_secure_bootloader(args)64 with open(output_file.name, 'rb') as of:65 with self._open('bootloader_digested.bin') as ef:66 self.assertEqual(ef.read(), of.read())67 finally:68 os.unlink(output_file.name)69 def test_digest_rsa_public_key(self):70 DigestRSAArgs = namedtuple('digest_rsa_public_key_args', [71 'keyfile',72 'output'])73 try:74 output_file = tempfile.NamedTemporaryFile(delete=False)75 output_file.close()76 args = DigestRSAArgs(self._open('rsa_secure_boot_signing_key.pem'),77 output_file.name)78 espsecure.digest_rsa_public_key(args)79 with open(output_file.name, 'rb') as of:80 with self._open('rsa_public_key_digest.bin') as ef:81 self.assertEqual(ef.read(), of.read())82 finally:83 os.unlink(output_file.name)84class SigningTests(EspSecureTestCase):85 VerifyArgs = namedtuple('verify_signature_args', [86 'version',87 'keyfile',88 'datafile'])89 SignArgs = namedtuple('sign_data_args', [90 'version',91 'keyfile',92 'output',93 'append_signatures',94 'datafile'])95 def _test_sign_v1_data(self, key_name):96 try:97 output_file = tempfile.NamedTemporaryFile(delete=False)98 output_file.close()99 # Note: signing bootloader is not actually needed100 # for ESP32, it's just a handy file to sign101 args = self.SignArgs('1', [self._open(key_name)],102 output_file.name, None,103 self._open('bootloader.bin'))104 espsecure.sign_data(args)105 with open(output_file.name, 'rb') as of:106 with self._open('bootloader_signed.bin') as ef:107 self.assertEqual(ef.read(), of.read())108 finally:109 os.unlink(output_file.name)110 def test_sign_v1_data(self):111 self._test_sign_v1_data('ecdsa_secure_boot_signing_key.pem')112 def test_sign_v1_data_pkcs8(self):113 self._test_sign_v1_data('ecdsa_secure_boot_signing_key_pkcs8.pem')114 def test_sign_v2_data(self):115 with tempfile.NamedTemporaryFile() as output_file:116 args = self.SignArgs('2', [self._open('rsa_secure_boot_signing_key.pem')],117 output_file.name, False,118 self._open('bootloader_unsigned_v2.bin'))119 espsecure.sign_data(args)120 args = self.VerifyArgs('2', self._open('rsa_secure_boot_signing_key.pem'),121 output_file)122 espsecure.verify_signature(args)123 def test_sign_v2_multiple_keys(self):124 # 3 keys + Verify with 3rd key125 with tempfile.NamedTemporaryFile() as output_file:126 args = self.SignArgs('2', [self._open('rsa_secure_boot_signing_key.pem'),127 self._open('rsa_secure_boot_signing_key2.pem'),128 self._open('rsa_secure_boot_signing_key3.pem')],129 output_file.name, False,130 self._open('bootloader_unsigned_v2.bin'))131 espsecure.sign_data(args)132 args = self.VerifyArgs('2', self._open('rsa_secure_boot_signing_key3.pem'),133 output_file)134 espsecure.verify_signature(args)135 output_file.seek(0)136 args = self.VerifyArgs('2', self._open('rsa_secure_boot_signing_key2.pem'),137 output_file)138 espsecure.verify_signature(args)139 output_file.seek(0)140 args = self.VerifyArgs('2', self._open('rsa_secure_boot_signing_key.pem'),141 output_file)142 espsecure.verify_signature(args)143 def test_sign_v2_append_signatures(self):144 # Append signatures + Verify with an appended key (bootloader_signed_v2.bin already signed with rsa_secure_boot_signing_key.pem)145 with tempfile.NamedTemporaryFile() as output_file:146 args = self.SignArgs('2', [self._open('rsa_secure_boot_signing_key2.pem'),147 self._open('rsa_secure_boot_signing_key3.pem')],148 output_file.name, True,149 self._open('bootloader_signed_v2.bin'))150 espsecure.sign_data(args)151 args = self.VerifyArgs('2', self._open('rsa_secure_boot_signing_key.pem'),152 output_file)153 espsecure.verify_signature(args)154 output_file.seek(0)155 args = self.VerifyArgs('2', self._open('rsa_secure_boot_signing_key2.pem'),156 output_file)157 espsecure.verify_signature(args)158 output_file.seek(0)159 args = self.VerifyArgs('2', self._open('rsa_secure_boot_signing_key3.pem'),160 output_file)161 espsecure.verify_signature(args)162 def test_sign_v2_append_signatures_multiple_steps(self):163 # similar to previous test, but sign in two invocations164 with tempfile.NamedTemporaryFile() as output_file1, tempfile.NamedTemporaryFile() as output_file2:165 args = self.SignArgs('2', [self._open('rsa_secure_boot_signing_key2.pem')],166 output_file1.name, True,167 self._open('bootloader_signed_v2.bin'))168 espsecure.sign_data(args)169 args = self.SignArgs('2', [self._open('rsa_secure_boot_signing_key3.pem')],170 output_file2.name, True,171 output_file1)172 espsecure.sign_data(args)173 args = self.VerifyArgs('2', self._open('rsa_secure_boot_signing_key.pem'),174 output_file2)175 espsecure.verify_signature(args)176 output_file2.seek(0)177 args = self.VerifyArgs('2', self._open('rsa_secure_boot_signing_key2.pem'),178 output_file2)179 espsecure.verify_signature(args)180 output_file2.seek(0)181 args = self.VerifyArgs('2', self._open('rsa_secure_boot_signing_key3.pem'),182 output_file2)183 espsecure.verify_signature(args)184 def test_verify_signature_signing_key(self):185 # correct key v1186 args = self.VerifyArgs('1', self._open('ecdsa_secure_boot_signing_key.pem'),187 self._open('bootloader_signed.bin'))188 espsecure.verify_signature(args)189 # correct key v2190 args = self.VerifyArgs('2', self._open('rsa_secure_boot_signing_key.pem'),191 self._open('bootloader_signed_v2.bin'))192 espsecure.verify_signature(args)193 # wrong key v1194 args = self.VerifyArgs('1', self._open('ecdsa_secure_boot_signing_key2.pem'),195 self._open('bootloader_signed.bin'))196 with self.assertRaises(esptool.FatalError) as cm:197 espsecure.verify_signature(args)198 self.assertIn("Signature is not valid", str(cm.exception))199 # wrong key v2200 args = self.VerifyArgs('2', self._open('rsa_secure_boot_signing_key2.pem'),201 self._open('bootloader_signed_v2.bin'))202 with self.assertRaises(esptool.FatalError) as cm:203 espsecure.verify_signature(args)204 self.assertIn("Signature could not be verified with the provided key.", str(cm.exception))205 # multi-signed wrong key v2206 args = self.VerifyArgs('2', self._open('rsa_secure_boot_signing_key4.pem'),207 self._open('bootloader_multi_signed_v2.bin'))208 with self.assertRaises(esptool.FatalError) as cm:209 espsecure.verify_signature(args)210 self.assertIn("Signature could not be verified with the provided key.", str(cm.exception))211 def test_verify_signature_public_key(self):212 # correct key v1213 args = self.VerifyArgs('1', self._open('ecdsa_secure_boot_signing_pubkey.pem'),214 self._open('bootloader_signed.bin'))215 espsecure.verify_signature(args)216 # correct key v2217 args = self.VerifyArgs('2', self._open('rsa_secure_boot_signing_pubkey.pem'),218 self._open('bootloader_signed_v2.bin'))219 espsecure.verify_signature(args)220 # wrong key v1221 args = self.VerifyArgs('1', self._open('ecdsa_secure_boot_signing_pubkey2.pem'),222 self._open('bootloader_signed.bin'))223 with self.assertRaises(esptool.FatalError) as cm:224 espsecure.verify_signature(args)225 self.assertIn("Signature is not valid", str(cm.exception))226 # wrong key v2227 args = self.VerifyArgs('2', self._open('rsa_secure_boot_signing_pubkey2.pem'),228 self._open('bootloader_signed_v2.bin'))229 with self.assertRaises(esptool.FatalError) as cm:230 espsecure.verify_signature(args)231 self.assertIn("Signature could not be verified with the provided key.", str(cm.exception))232 # multi-signed wrong key v2233 args = self.VerifyArgs('2', self._open('rsa_secure_boot_signing_pubkey4.pem'),234 self._open('bootloader_multi_signed_v2.bin'))235 with self.assertRaises(esptool.FatalError) as cm:236 espsecure.verify_signature(args)237 self.assertIn("Signature could not be verified with the provided key.", str(cm.exception))238 def test_extract_binary_public_key(self):239 ExtractKeyArgs = namedtuple('extract_public_key_args',240 ['version', 'keyfile', 'public_keyfile'])241 with tempfile.NamedTemporaryFile() as pub_keyfile, tempfile.NamedTemporaryFile() as pub_keyfile2:242 args = ExtractKeyArgs('1', self._open('ecdsa_secure_boot_signing_key.pem'),243 pub_keyfile)244 espsecure.extract_public_key(args)245 args = ExtractKeyArgs('1', self._open('ecdsa_secure_boot_signing_key2.pem'),246 pub_keyfile2)247 espsecure.extract_public_key(args)248 pub_keyfile.seek(0)249 pub_keyfile2.seek(0)250 # use correct extracted public key to verify251 args = self.VerifyArgs('1', pub_keyfile, self._open('bootloader_signed.bin'))252 espsecure.verify_signature(args)253 # use wrong extracted public key to try and verify254 args = self.VerifyArgs('1', pub_keyfile2, self._open('bootloader_signed.bin'))255 with self.assertRaises(esptool.FatalError) as cm:256 espsecure.verify_signature(args)257 self.assertIn("Signature is not valid", str(cm.exception))258class ESP32FlashEncryptionTests(EspSecureTestCase):259 def test_encrypt_decrypt_bootloader(self):260 self._test_encrypt_decrypt('bootloader.bin',261 'bootloader-encrypted.bin',262 '256bit_key.bin',263 0x1000,264 0xf)265 def test_encrypt_decrypt_app(self):266 self._test_encrypt_decrypt('hello-world-signed.bin',267 'hello-world-signed-encrypted.bin',268 'ef-flashencryption-key.bin',269 0x20000,270 0xf)271 def test_encrypt_decrypt_non_default_conf(self):272 """ Try some non-default (non-recommended) flash_crypt_conf settings """273 for conf in [0x0, 0x3, 0x9, 0xc]:274 self._test_encrypt_decrypt('bootloader.bin',275 'bootloader-encrypted-conf%x.bin' % conf,276 '256bit_key.bin',277 0x1000,278 conf)279 def _test_encrypt_decrypt(self, input_plaintext, expected_ciphertext, key_path, offset, flash_crypt_conf=0xf):280 EncryptArgs = namedtuple('encrypt_flash_data_args',281 ['keyfile',282 'output',283 'address',284 'flash_crypt_conf',285 'plaintext_file'286 ])287 DecryptArgs = namedtuple('decrypt_flash_data_args',288 ['keyfile',289 'output',290 'address',291 'flash_crypt_conf',292 'encrypted_file'293 ])294 original_plaintext = self._open(input_plaintext)295 keyfile = self._open(key_path)296 ciphertext = io.BytesIO()297 args = EncryptArgs(keyfile,298 ciphertext,299 offset,300 flash_crypt_conf,301 original_plaintext)302 espsecure.encrypt_flash_data(args)303 original_plaintext.seek(0)304 self.assertNotEqual(original_plaintext.read(), ciphertext.getvalue())305 with self._open(expected_ciphertext) as f:306 self.assertEqual(f.read(), ciphertext.getvalue())307 ciphertext.seek(0)308 keyfile.seek(0)309 plaintext = io.BytesIO()310 args = DecryptArgs(keyfile,311 plaintext,312 offset,313 flash_crypt_conf,314 ciphertext)315 espsecure.decrypt_flash_data(args)316 original_plaintext.seek(0)317 self.assertEqual(original_plaintext.read(), plaintext.getvalue())318if __name__ == '__main__':319 print("Running espsecure tests...")...

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run uiautomator automation tests on LambdaTest cloud grid

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

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful