Best Python code snippet using locust
clienttests.py
Source:clienttests.py  
...50        data = {"test":"value"}51        self._urlopen_result = json.dumps(data)52        result = self._client.create(self._url, item = data, parameters = {}, decode = False)53        self.assertEqual(data, json.load(result), "Wrong result returned")54    def test_create_failure_urlopen(self):55        # Mock _urlopen56        self._client._urlopen = self._urlopen_failure57        try:58            self._client.create(self._url, item = {})59        except ApiException:60            return61        self.assertFalse(True)62    # Delete tests63    def test_delete_success(self):64        # Mock _urlopen65        self._client._urlopen = self._urlopen_success66        self._client.delete(self._url)67    def test_delete_wrong_url(self):68        # Mock _urlopen69        self._client._urlopen = self._urlopen_success70        try:71            self._client.delete(self._url + "x")72        except:73            return74        self.assertFalse(True)75    def test_delete_failure_urlopen(self):76        # Mock _urlopen77        self._client._urlopen = self._urlopen_failure78        try:79            self._client.delete(self._url)80        except ApiException:81            return82        self.assertFalse(True)83    # Read tests84    def test_read_success(self):85        # Mock _urlopen86        self._client._urlopen = self._urlopen_success87        data = {"test":"value"}88        self._urlopen_result = json.dumps(data)89        result = self._client.read(self._url)90        self.assertEqual(data, result, "Wrong result returned")91    def test_read_wrong_url(self):92        # Mock _urlopen93        self._client._urlopen = self._urlopen_success94        try:95            self._client.read(self._url + "x")96        except:97            return98        self.assertFalse(True)99    def test_read_failure_urlopen(self):100        # Mock _urlopen101        self._client._urlopen = self._urlopen_failure102        try:103            self._client.read(self._url)104        except ApiException:105            return106        self.assertFalse(True)107    # Update tests108    def test_update_success(self):109        # Mock _urlopen110        self._client._urlopen = self._urlopen_success111        data = {"test":"value"}112        self._urlopen_result = json.dumps(data)113        result = self._client.update(self._url, item = data)114        self.assertEqual(data, result, "Wrong result returned")115    def test_update_wrong_url(self):116        # Mock _urlopen117        self._client._urlopen = self._urlopen_success118        data = {"test":"value"}119        self._urlopen_result = json.dumps(data)120        try:121            self._client.update(self._url + "x", item = data)122        except:123            return124        self.assertFalse(True)125    def test_update_success_wo_decode(self):126        # Mock _urlopen127        self._client._urlopen = self._urlopen_success128        data = {"test":"value"}129        self._urlopen_result = json.dumps(data)130        result = self._client.update(self._url, item = data, parameters = {}, decode = False)131        self.assertEqual(data, json.load(result), "Wrong result returned")132    def test_update_failure_urlopen(self):133        # Mock _urlopen134        self._client._urlopen = self._urlopen_failure135        try:136            self._client.update(self._url, item = {})137        except ApiException:138            return139        self.assertFalse(True)140    # Helpers141    def _new_request(self, url, m):142        req = RequestWithMethodMock(url, method = m, headers = self._headers)143        return req144    def _new_request_with_data(self, url, m, d):145        req = RequestWithMethodMock(url, method = m, headers = self._headers, data = d)146        return req...test_unit.py
Source:test_unit.py  
...30class MockClient():31  def __init__(self, status=200):32    self._status = status33    self._body = 'RESPONSE BODY'34  def _urlopen(self, url, data=None, method='GET', headers=None):35    if self._status == 200 and 'Content-Type' in headers and 'multipart/form-data' in headers['Content-Type']:36      self._body = 'MULTIPART FORM DATA BODY'37      return MockResponse(self._status, self._body)38    if 200 <= self._status < 299:39      return MockResponse(self._status, self._body)40    else:41      self._body = 'ERROR RESPONSE BODY'42      raise MockException(self._status, self._body)43class TestClient(unittest.TestCase):44  def setUp(self):45    self.client = Client()46  def test__init__(self):47    url = 'hello'48    headers = {'X-Test': 'test', 'X-Test2': 2}...eansearch.py
Source:eansearch.py  
...9	def __init__(self, token):10		self._apiurl = "https://api.ean-search.org/api?token=" + token + "&format=json"11	def barcodeLookup(self, ean, lang=1):12		"""Lookup the product name for an EAN barcode"""13		contents = self._urlopen(self._apiurl + "&op=barcode-lookup&ean=" + str(ean) + "&language=" + str(lang))14		data = json.loads(contents)15		if "error" in data[0]:16			return None17		else:18			return data[0]["name"]19	def barcodeSearch(self, ean, lang=1):20		"""Lookup the product info for an EAN barcode"""21		contents = self._urlopen(self._apiurl + "&op=barcode-lookup&ean=" + str(ean) + "&language=" + str(lang))22		data = json.loads(contents)23		if "error" in data[0]:24			return None25		else:26			return data[0]27	def verifyChecksum(self, ean):28		"""verify checksum of an EAN barcode"""29		contents = self._urlopen(self._apiurl + "&op=verify-checksum&ean=" + str(ean))30		data = json.loads(contents)31		if "error" in data[0]:32			return None33		else:34			return data[0]["valid"]35	def productSearch(self, name, page=0, lang=99):36		"""search for a product name"""37		contents = self._urlopen(self._apiurl + "&op=product-search&name=" + name + "&page=" + str(page) + "&language=" + str(lang))38		data = json.loads(contents)39		return data["productlist"]40	def categorySearch(self, category, name='', page=0, lang=99):41		"""search for a product name"""42		contents = self._urlopen(self._apiurl + "&op=category-search&category=" + str(category) + "&name=" + name + "&page=" + str(page) + "&language=" + str(lang))43		data = json.loads(contents)44		return data["productlist"]45	def barcodePrefixSearch(self, prefix, page=0, lang=1):46		"""search for a prefix of EAN barcodes"""47		contents = self._urlopen(self._apiurl + "&op=barcode-prefix-search&prefix=" + str(prefix) + "&page=" + str(page) + "&language=" + str(lang))48		data = json.loads(contents)49		return data["productlist"]50	def _urlopen(self, url):51         if (sys.version_info >= (3,)):52             import urllib.request53             return urllib.request.urlopen(url, timeout=180).read().decode("utf-8")54         else:55             import urllib2...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!!
