daydreamer
daydreamer

Reputation: 91969

sqlalchemy test: adding same user twice not throwing exception when unique=True

I am using Flask and my SQLAlchemy model is

class User(UserMixin, db.Model):
    __tablename__ = 'users'
    # noinspection PyShadowingBuiltins
    uuid = Column('uuid', GUID(), default=uuid.uuid4, primary_key=True,
                  unique=True)
    email = Column('email', String, nullable=False, unique=True) # yes unique is True

I write the test and import data like

app = Flask(__name__)
app.config['SECRET_KEY'] = dev.SECRET_KEY
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'
db = SQLAlchemy(app)

My test looks like

class TestUser(TestCase):
    def setUp(self):
        db.create_all()

   def test_add_existing_user(self):
        user = User('test_add_existing_user', 'welcome')
        db.session.add(user)
        db.session.commit()
        self.assertEquals(1, len(User.query.all()))

        db.session.add(user)
        db.session.commit()
        self.assertEquals(2, len(User.query.all())) # just to verify if it saves the same user twice.

    def tearDown(self):
        db.drop_all()
        db.session.remove()

When I run this test, I see

Failure
Traceback (most recent call last):
  File "<project path>/tests/test_user.py", line 28, in test_add_existing_user
    self.assertEquals(2, len(User.query.all()))
AssertionError: 2 != 1

It seems it is not saving the same user twice, but I want the exception to be thrown which I am not receiving, what is that I am not doing right here or missing?

Upvotes: 1

Views: 1237

Answers (1)

daydreamer
daydreamer

Reputation: 91969

Just realized, I was saving the same user twice, rather than creating the new user with sae email.

SQLAlchemy will save the same user as many times as one wants.

Doing the following works

    def test_add_existing_user(self):
        user = User('test_add_existing_user', 'welcome')
        db.session.add(user)
        db.session.commit()
        self.assertEquals(1, len(User.query.all()))

        db.session.add(User(user.email, 'welcome'))
        db.session.commit()

Upvotes: 4

Related Questions