'how to compare value in python [closed]

I am new to python, here I am getting values (0, 1) from a server response, how to use this in assertTrue in python.

  ret = (0, 1)  // (0, 1) this is response getting from server
  self.assertTrue(ret  == '(0, 1)')  // is this right way to do?


Solution 1:[1]

Assuming the response from the server is a tuple, you could test it with a simple test case as follows:

import unittest

response = (0, 1)
  
class SimpleTest(unittest.TestCase):
    # Returns True or False. 
    def test(self):        
        self.assertTrue((response == (0, 1)), "The response is not (0, 1)")
  
if __name__ == '__main__':
    unittest.main()

If it is not a tuple but a string that you receive, you could change the value in the assertTrue condition from (0, 1) to "(0, 1)".

Please refer to the documentation on unittest for more details.

If you don't want to use unittest, but you do want to make sure that the response is correct, you could also use the assert statement (however, there might be better ways to check this):

response = (0, 1)
assert(response == (0, 1)) # This will do nothing

assert(response == (1, 1)) # This results in an AssertionError

Due to the AssertionError your program will stop. If you don't want this, you could use a try-except block:

response = (0, 1)
  
try:
    assert(response == (0, 1))
except AssertionError:
    print("The response is not correct.")

EDIT:

As the response you are receiving is of type MQTTMessageInfo, you want to compare against this. I didn't find much documentation on this type, but you can see what the class looks like on Github.

Here, you can see the response you are seeing is a string representation of the following:

def __str__(self):
    return str((self.rc, self.mid))

The first value in (0, 1) is the self.rc and the second is self.mid. If you only want to assert that these two values are indeed correct, you can modify the test case above to something like this:

self.assertTrue((response.rc == 0 and response.mid == 1)), "The MQTTMessageInfo is not rc=0, and mid=1")

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1