Home > Net >  Add variable to URL in Locust test
Add variable to URL in Locust test

Time:05-07

I'm been trying to figure out how to add a variable captured from a prior 'task' on Locust and add a variable to a new tasks GET request URL.

The variable below, portid, is suppose to go on the end of the get request: /portfolios/portid

Example 1:

@task
    def PortPage(self):
      get = self.client.get("/portfolios/"   portid, data=data, headers=header)

Error:

TypeError: can only concatenate str (not "int") to str

Example 2:

I've also tried with a % sign because I read it has worked before but not for my instance..

@task
    def PortPage(self):
      get = self.client.get("/portfolios/" % portid, data=data, headers=header)

Error:

TypeError: not all arguments converted during string formatting

Any assistance obviously appreciated.

CodePudding user response:

You're just looking for normal string formatting!

>>> portid = 100
>>> f"/portfolios/{portid}"
'/portfolios/100'

The issue is simply that Python doesn't guess when you attempt to add a number to a string what should happen!

You can choose from a few options according to your needs, though the f-string variant is probably preferable for your case

>>> "/portfolios/"   portid          # fails with the error
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "int") to str
>>> "/portfolios/"   str(portid)     # effectively simplest
'/portfolios/100'
>>> f"/portfolios/{portid}"          # modern
'/portfolios/100'
>>> "/portfolios/{}".format(portid)  # obvious
'/portfolios/100'
>>> "/portfolios/%i" % portid        # considered old, will do some coercions
'/portfolios/100'
  • Related