collinsmarra
collinsmarra

Reputation: 178

marshmallow-sqlachemy returning validationError with pytest

I have the following database table:

import sqlalchemy as sql
class Users(db.Model):
    __tablename__ = "users"

    id = sql.Column(sql.Integer, primary_key=True)
    username = sql.Column(sql.String,index=True, unique=True, nullable=False)
    email = sql.Column(sql.String(120),index=True, unique=True, nullable=False)
    last_seen = sql.Column(sql.DateTime, default=datetime.utcnow())
    password = sql.Column(sql.String(128), nullable=False)

and I have the following schema:

class UserSchema(ma.SQLAlchemySchema):
    class Meta:
        model = Users
        ordered = True

    id = ma.auto_field(dump_only=True)
    username = ma.auto_field(required=True,validate=validate.Length(min=3, max=64))
    email = ma.auto_field(required=True, validate=[validate.Length(max=128),validate.Email()])
    password = ma.auto_field(required=True, load_only=True,validate=validate.Length(min=5))

so I am trying to use pytest with flask to test if I can add a user and I generally get the error: tests/test_users.py::test_create_user {"messages":{"json":{"email":["Missing data for required field."],"password_hash":["Missing data for required field."],"username":["Missing data for required field."]}}}

The function that I am using is:

def test_create_user():
    username = "testing"
    password = "12345678"
    email = "[email protected]"
    flask_app = create_app()
    with flask_app.test_client() as test_client:
        response = test_client.post("/api/users", data=json.dumps({
            'username':username,
            'password':password,
            'email':email
        }))
        print(response.data.decode('utf-8'))
        assert response.status == 201
        assert b'id' in response.data
        assert b'password' not in response.data
        assert b'username' in response.data

I am doing this with postman and I am able to get the correct expected response. So How can I do this with pytest and flask?. I want to be get the expected responses with pytest.

Upvotes: 0

Views: 241

Answers (1)

Menno Hölscher
Menno Hölscher

Reputation: 585

Follow the instruction here.

In short:

  1. Replace data= with json=
  2. Don't create a json-string with json.dumps(), but pass in the dictionary.

The test client will create the json from it and pass it to your Flask code in the desired manner.

Upvotes: 1

Related Questions