0

Okey, so it's a bit weird problem and I have no idea where to look for solution

class which operates at "/" route

parser = reqparse.RequestParser()
parser.add_argument('task')
parser.add_argument('message')

class SimpleRequest(Resource):
    # definiujemy rodzaj zapytania HTTP
    def get(self):
        return "hello world"

    def post(self):
        args = parser.parse_args()
        return args['message']

as we can see it returns what it get as body of Request

Simple test

    def test_simple_request(self):
        result = requests.get(f'{APP_URL}/')
        self.assertEqual(result.status_code, 200)
        test_text = 'simple_text'
        message = {"message": test_text}
        result = requests.post(f'{APP_URL}/', message)
        self.assertEqual(result.text, test_text)

I am sending 'simple_text', but what I am getting in return is '"simple_text"\n' so my test return assertion failure and it potentially can lead to huge bugs

Did I missed something?

debugger screeen

Misieq
  • 507
  • 2
  • 12
  • you could just strip the whitespace characters from your result.text variable – I break things Jan 20 '21 at 14:50
  • Yea, in this case, but what about more complex application it can lead to hidden bugs which can ruin your application. For example it's mockup server and you send one string, expecting getting another, simple if(x == y) will not run after that because expected string will be diferent from which one that you are getting – Misieq Jan 20 '21 at 14:55

1 Answers1

2

First, what is going on:

Your code is using the default content type, which is application/json. This is ruled by the output_json() method, which creates the response object with JSON encoded body. There you can see the interesting part:

# always end the json dumps with a new line
# see https://github.com/mitsuhiko/flask/pull/1262
dumped = dumps(data, **settings) + "\n"

This is because of this request

And here you can find the reasoning behind it.

So, what to do?

Use the json() method of the response object. It will return just what you expect it to return.

So, your test should end just like this:

self.assertEqual(result.json(), test_text)
wankata
  • 855
  • 4
  • 12