From 550be6e4ec569705079edb4ffa91221e9229824d Mon Sep 17 00:00:00 2001 From: "jai.s" Date: Wed, 16 Sep 2020 20:27:27 +0530 Subject: [PATCH] Solved all TestAPI issues --- src/api.py | 68 +++++++++++++---------------------- src/class_addressGenerator.py | 42 ++++++++++++++++------ src/tests/test_api.py | 58 +++++++++++++----------------- src/tests/test_process.py | 32 ----------------- 4 files changed, 80 insertions(+), 120 deletions(-) diff --git a/src/api.py b/src/api.py index acd8d4d9..7ab52c82 100755 --- a/src/api.py +++ b/src/api.py @@ -451,12 +451,13 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler): smallMessageDifficulty) else: raise APIError(0, 'Too many parameters!') - label = self._decode(label.data, "base64") + label = self._decode(label.data, "base64").decode() queues.apiAddressGeneratorReturnQueue.queue.clear() streamNumberForAddress = 1 queues.addressGeneratorQueue.put(( 'createRandomAddress', 4, streamNumberForAddress, label, 1, "", - eighteenByteRipe, nonceTrialsPerByte, payloadLengthExtraBytes + eighteenByteRipe, int(nonceTrialsPerByte), + int(payloadLengthExtraBytes) )) return queues.apiAddressGeneratorReturnQueue.get() @@ -575,7 +576,7 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler): queues.addressGeneratorQueue.put(( 'createDeterministicAddresses', addressVersionNumber, streamNumber, 'unused API address', numberOfAddresses, passphrase, - eighteenByteRipe, nonceTrialsPerByte, payloadLengthExtraBytes + eighteenByteRipe, int(nonceTrialsPerByte), int(payloadLengthExtraBytes) )) data = '{"addresses":[' queueReturn = queues.apiAddressGeneratorReturnQueue.get() @@ -595,7 +596,7 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler): eighteenByteRipe = False if not passphrase: raise APIError(1, 'The specified passphrase is blank.') - passphrase = self._decode(passphrase.data, "base64") + passphrase = self._decode(passphrase.data, "base64").decode() # if addressVersionNumber != 3 and addressVersionNumber != 4: if addressVersionNumber not in (3, 4): raise APIError( @@ -623,32 +624,19 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler): raise APIError(0, 'I need parameters.') elif len(params) == 1: passphrase, = params - passphrase = self._decode(passphrase.data, "base64") + passphrase = self._decode(passphrase.data, "base64").decode() if not passphrase: raise APIError(1, 'The specified passphrase is blank.') # It would be nice to make the label the passphrase but it is - # possible that the passphrase contains non-utf-8 characters. - # try: - # unicode(passphrase, 'utf-8') - # label = str_chan + ' ' + passphrase - # except BaseException: - label = str_chan + ' ' + passphrase.decode() + + label = str_chan + ' ' + passphrase addressVersionNumber = 4 streamNumber = 1 - try: - queues.addressGeneratorQueue.put(( - 'createChan', addressVersionNumber, streamNumber, label, - passphrase.decode(), True - )) - logger.info( - '@@@@@@@@ before printing the queueReturn @@@@@@@@@') - queueReturn = queues.apiAddressGeneratorReturnQueue.get() - logger.info('***********************************') - logger.info('queueReturn-{}'.format(queueReturn)) - logger.info('***********************************') - - except Exception as e: - logger.info(e) + queues.addressGeneratorQueue.put(( + 'createChan', addressVersionNumber, streamNumber, label, + passphrase, True + )) + queueReturn = queues.apiAddressGeneratorReturnQueue.get() if not queueReturn: raise APIError(24, 'Chan address is already present.') address = queueReturn[0] @@ -661,23 +649,17 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler): raise APIError(0, 'I need two parameters.') elif len(params) == 2: passphrase, suppliedAddress = params - passphrase = self._decode(passphrase.data, "base64") + passphrase = self._decode(passphrase.data, "base64").decode() if not passphrase: raise APIError(1, 'The specified passphrase is blank.') - # It would be nice to make the label the passphrase but it is - # possible that the passphrase contains non-utf-8 characters. - # try: - # unicode(passphrase, 'utf-8') - # label = str_chan + ' ' + passphrase - # except BaseException: - # label = str_chan + ' ' + repr(passphrase) - label = str_chan + ' ' + passphrase.decode() + label = str_chan + ' ' + passphrase status, addressVersionNumber, streamNumber, toRipe = ( self._verifyAddress(suppliedAddress)) suppliedAddress = addBMIfNotPresent(suppliedAddress) queues.apiAddressGeneratorReturnQueue.queue.clear() queues.addressGeneratorQueue.put(( - 'joinChan', suppliedAddress, label, passphrase, True + 'joinChan', suppliedAddress, label, + passphrase, True )) addressGeneratorReturnValue = \ queues.apiAddressGeneratorReturnQueue.get() @@ -707,7 +689,7 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler): 25, 'Specified address is not a chan address.' ' Use deleteAddress API call instead.') BMConfigParser().remove_section(address) - with open(state.appdata + 'keys.dat', 'wb') as configfile: + with open(state.appdata + 'keys.dat', 'w') as configfile: BMConfigParser().write(configfile) return 'success' @@ -725,7 +707,7 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler): raise APIError( 13, 'Could not find this address in your keys.dat file.') BMConfigParser().remove_section(address) - with open(state.appdata + 'keys.dat', 'wb') as configfile: + with open(state.appdata + 'keys.dat', 'w') as configfile: BMConfigParser().write(configfile) queues.UISignalQueue.put(('writeNewAddressToTable', ('', '', ''))) shared.reloadMyAddressHashes() @@ -1096,10 +1078,9 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler): def HandleSendBroadcast(self, params): """Handle a request to send a broadcast message""" - if not params: raise APIError(0, 'I need parameters!') - + logger.error('HandleSendBroadcast 1085') if len(params) == 3: fromAddress, subject, message = params encodingType = 2 @@ -1113,10 +1094,11 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler): if encodingType not in [2, 3]: raise APIError(6, 'The encoding type must be 2 or 3.') - - subject = self._decode(subject, "base64") - message = self._decode(message, "base64") + subject = self._decode(subject.data, "base64").decode() + message = self._decode(message.data, "base64").decode() + logger.error('HandleSendBroadcast 1106') if len(subject + message) > (2 ** 18 - 500): + logger.error('HandleSendBroadcast 1108') raise APIError(27, 'Message is too long.') if TTL < 60 * 60: TTL = 60 * 60 @@ -1133,7 +1115,6 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler): ackdata = genAckPayload(streamNumber, 0) toAddress = '[Broadcast subscribers]' ripe = '' - t = ('', toAddress, ripe, @@ -1150,7 +1131,6 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler): 2, TTL) helper_sent.insert(t) - toLabel = '[Broadcast subscribers]' queues.UISignalQueue.put(('displayNewSentMessage', ( toAddress, toLabel, fromAddress, subject, message, ackdata))) diff --git a/src/class_addressGenerator.py b/src/class_addressGenerator.py index ab0f9305..ae0effbc 100755 --- a/src/class_addressGenerator.py +++ b/src/class_addressGenerator.py @@ -118,22 +118,27 @@ class addressGenerator(StoppableThread): numberOfNullBytesDemandedOnFrontOfRipeHash = 1 elif len(queueValue) == 9: - logger.info( - '33333333333333333333333333333333333333') + logger.error('createRandomAddress 122') command, addressVersionNumber, streamNumber, label, \ numberOfAddressesToMake, deterministicPassphrase, \ eighteenByteRipe, nonceTrialsPerByte, \ payloadLengthExtraBytes = queueValue + logger.error('createRandomAddress 126') try: + logger.error('createRandomAddress 128') numberOfNullBytesDemandedOnFrontOfRipeHash = \ BMConfigParser().getint( 'bitmessagesettings', 'numberofnullbytesonaddress' ) + logger.error('createRandomAddress 134') except: + logger.error('createRandomAddress 136') if eighteenByteRipe: + logger.error('createRandomAddress 138') numberOfNullBytesDemandedOnFrontOfRipeHash = 2 else: + logger.error('createRandomAddress 141') # the default numberOfNullBytesDemandedOnFrontOfRipeHash = 1 elif queueValue[0] == 'stopThread': @@ -145,46 +150,63 @@ class addressGenerator(StoppableThread): 'Programming error: A structure with the wrong number' ' of values was passed into the addressGeneratorQueue.' ' Here is the queueValue: %r\n', queueValue) + logger.error('createRandomAddress 153') if addressVersionNumber < 3 or addressVersionNumber > 4: self.logger.error( 'Program error: For some reason the address generator' ' queue has been given a request to create at least' ' one version %s address which it cannot do.\n', addressVersionNumber) + logger.error('createRandomAddress 160') if nonceTrialsPerByte == 0: logger.error('++++++++++++170++++++++++++') nonceTrialsPerByte = BMConfigParser().getint( 'bitmessagesettings', 'defaultnoncetrialsperbyte') - if nonceTrialsPerByte < \ - defaults.networkDefaultProofOfWorkNonceTrialsPerByte: - logger.error('++++++++++++175++++++++++++') - nonceTrialsPerByte = \ - defaults.networkDefaultProofOfWorkNonceTrialsPerByte + logger.error('createRandomAddress 165') + try: + if nonceTrialsPerByte < \ + defaults.networkDefaultProofOfWorkNonceTrialsPerByte: + logger.error('++++++++++++175++++++++++++') + nonceTrialsPerByte = \ + defaults.networkDefaultProofOfWorkNonceTrialsPerByte + except Exception as e: + logger.error('type(nonceTrialsPerByte) -{}'.format( + type(nonceTrialsPerByte))) + logger.error('type(defaults.networkDefaultProofOfWorkNonceTrialsPerByte) -{}'.format( + type(defaults.networkDefaultProofOfWorkNonceTrialsPerByte))) + logger.error('createRandomAddress except') + logger.error(str(e)) + logger.error('createRandomAddress 171') if payloadLengthExtraBytes == 0: logger.error('++++++++++++179++++++++++++') payloadLengthExtraBytes = BMConfigParser().getint( 'bitmessagesettings', 'defaultpayloadlengthextrabytes') + logger.error('createRandomAddress 176') if payloadLengthExtraBytes < \ defaults.networkDefaultPayloadLengthExtraBytes: logger.error('++++++++++++184++++++++++++') payloadLengthExtraBytes = \ defaults.networkDefaultPayloadLengthExtraBytes + logger.error('createRandomAddress 181') if command == 'createRandomAddress': logger.error('++++++++++++188++++++++++++') queues.UISignalQueue.put(( 'updateStatusBar', "" )) - logger.info('&&&&&&&&&&&&&&&&&&&&&&&') - logger.info('---------144--------------') - logger.info('&&&&&&&&&&&&&&&&&&&&&&&\n') + logger.error('&&&&&&&&&&&&&&&&&&&&&&&') + logger.error('---------144--------------') + logger.error('&&&&&&&&&&&&&&&&&&&&&&&') # This next section is a little bit strange. We're going # to generate keys over and over until we find one # that starts with either \x00 or \x00\x00. Then when # we pack them into a Bitmessage address, we won't store # the \x00 or \x00\x00 bytes thus making the address shorter. + logger.error('createRandomAddress 190') startTime = time.time() numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix = 0 + logger.error('createRandomAddress 193') potentialPrivSigningKey = OpenSSL.rand(32) + logger.error('createRandomAddress 194') potentialPubSigningKey = highlevelcrypto.pointMult( potentialPrivSigningKey) logger.error('&&&&&&&&&&&&&&&&&&&&&&&') diff --git a/src/tests/test_api.py b/src/tests/test_api.py index 446b5cfe..e70331aa 100755 --- a/src/tests/test_api.py +++ b/src/tests/test_api.py @@ -21,22 +21,12 @@ class TestAPIProto(TestProcessProto): @classmethod def setUpClass(cls): - print('@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@') - print('is this TestAPIProto') - print('@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@') - """Setup XMLRPC proxy for pybitmessage API""" # super(TestAPIProto, cls).tearDownClass() try: - print('*****************************') - print('try block is I am successfully called the ') - print('*****************************') super(TestAPIProto, cls).setUpClass() except: - print('(((((((((((((((((((((((') - print('except block because of this condition are getting failed') - print('))))))))))))))))))))))))') - + pass cls.addresses = [] cls.api = xmlrpclib.ServerProxy( "http://username:password@127.0.0.1:8442/") @@ -125,7 +115,6 @@ class TestAPI(TestAPIProto): self.assertEqual(result['streamNumber'], 1) def test_create_deterministic_addresses(self): - #11111111111111111111111111 """API command 'getDeterministicAddress': with various params""" self.assertEqual( self.api.getDeterministicAddress(self._seed, 4, 1), @@ -135,23 +124,22 @@ class TestAPI(TestAPIProto): self.api.getDeterministicAddress(self._seed, 3, 1), 'BM-2DBPTgeSawWYZceFD69AbDT5q4iUWtj1ZN' ) - self.assertRegexpMatches( + self.assertRegex( self.api.getDeterministicAddress(self._seed, 2, 1), r'^API Error 0002:' ) # This is here until the streams will be implemented - self.assertRegexpMatches( + self.assertRegex( self.api.getDeterministicAddress(self._seed, 3, 2), r'API Error 0003:' ) #currently working on this condition def test_create_random_address(self): - #22222222222222222222222222222222 """API command 'createRandomAddress': basic BM-address validation""" addr = self._add_random_address('random_1'.encode()) - self.assertRegexpMatches(addr, r'^BM-') - self.assertRegexpMatches(addr[3:], r'[a-zA-Z1-9]+$') + self.assertRegex(addr, r'^BM-') + self.assertRegex(addr[3:], r'[a-zA-Z1-9]+$') # Whitepaper says "around 36 character" self.assertLessEqual(len(addr[3:]), 40) self.assertEqual(self.api.deleteAddress(addr), 'success') @@ -159,6 +147,7 @@ class TestAPI(TestAPIProto): def test_addressbook(self): """Testing API commands for addressbook manipulations""" # Initially it's empty + # self.assertEqual( json.loads(self.api.listAddressBookEntries()).get('addresses'), [] @@ -188,9 +177,9 @@ class TestAPI(TestAPIProto): """API command 'sendBroadcast': ensure it returns ackData""" addr = self._add_random_address('random_2'.encode()) ack = self.api.sendBroadcast( - addr, base64.encodestring('test_subject'), - base64.encodestring('test message') - ) + addr, base64.encodebytes('test_subject'.encode()), + base64.encodebytes('test message'.encode()) + ).data try: int(ack, 16) except ValueError: @@ -206,19 +195,20 @@ class TestAPI(TestAPIProto): 'BM-2cWzSnwjJ7yRP3nLEWUV5LisTZyREWSzUK' ) # # cleanup - # self.assertEqual( - # self.api.leaveChan('BM-2cWzSnwjJ7yRP3nLEWUV5LisTZyREWSzUK'), - # 'success' - # ) + self.assertEqual( + self.api.leaveChan('BM-2cWzSnwjJ7yRP3nLEWUV5LisTZyREWSzUK'), + 'success' + ) # # Join chan with addresses of version 3 or 4 - # for addr in ( - # 'BM-2cWzSnwjJ7yRP3nLEWUV5LisTZyREWSzUK', - # 'BM-2DBPTgeSawWYZceFD69AbDT5q4iUWtj1ZN' - # ): - # self.assertEqual(self.api.joinChan(self._seed, addr), 'success') - # self.assertEqual(self.api.leaveChan(addr), 'success') + #Today + for addr in ( + 'BM-2cWzSnwjJ7yRP3nLEWUV5LisTZyREWSzUK', + 'BM-2DBPTgeSawWYZceFD69AbDT5q4iUWtj1ZN' + ): + self.assertEqual(self.api.joinChan(self._seed, addr), 'success') + self.assertEqual(self.api.leaveChan(addr), 'success') # # Joining with wrong address should fail - # self.assertRegexpMatches( - # self.api.joinChan(self._seed, 'BM-2cWzSnwjJ7yRP3nLEW'), - # r'^API Error 0008:' - # ) + self.assertRegex( + self.api.joinChan(self._seed, 'BM-2cWzSnwjJ7yRP3nLEW'), + r'^API Error 0008:' + ) diff --git a/src/tests/test_process.py b/src/tests/test_process.py index 9656000d..a73c64cf 100755 --- a/src/tests/test_process.py +++ b/src/tests/test_process.py @@ -74,37 +74,8 @@ class TestProcessProto(unittest.TestCase): @classmethod def _cleanup_files(cls): - print('the printing _cleanup_files -{}'.format(cls._files)) for pfile in cls._files: try: - if pfile == 'debug.log': - print('***************************') - print('72727272727272772727272727') - print('going to open the debug.log file-{}'.format(pfile)) - print(os.path.join(cls.home, pfile)) - print('75757575757575757575757') - try: - with open(os.path.join(cls.home, pfile), 'r') as outfile: - print(outfile.readlines()) - print('with with with with ') - print('is coming inside the open function') - print('with with with with ') - except: - print('!!!!!!!!!!!!!!!!!!!!!!!!!') - print('expectation are occured ') - print('!!!!!!!!!!!!!!!!!!!!!!!!!') - print('***************************') - print('----------------------------') - print(' pfile pfile pfile -{}'.format(pfile)) - try: - with open(os.path.join(cls.home, pfile), 'r') as outfile: - pass - # print(outfile.read()) - print('----------------------------') - except: - print('``````````````````````````````````````') - print('exceptation are occured while working opening th file-{}'.format(pfile)) - print('``````````````````````````````````````') os.remove(os.path.join(cls.home, pfile)) except OSError: pass @@ -112,9 +83,6 @@ class TestProcessProto(unittest.TestCase): @classmethod def tearDownClass(cls): """Ensures that pybitmessage stopped and removes files""" - print('######################################') - print('is this are even called tearDownClass') - print('######################################') try: if not cls._stop_process(): cls.process.kill()