在 python unittest 中,保存 Peewee 对象的实例会引发 peewee.IntegrityError: 和 peewee.OperationalError:

维克多·里贝罗

当我在 python unittest 的 setUp 中保存一个实例时,我弹出了 2 个错误:

sqlite3.IntegrityError:NOT NULL 约束失败: registro_c170.reg_c100_id

peewee.OperationalError:连接已经打开。(这是为我的测试类中的每个 test_method 引发的。)

语境:

我对面向对象编程和单元测试很陌生。我正在使用 python 来构建寄存器层次结构的模型。该登记册保存有关税收和问责制的信息。

模型:

from peewee import *

db = SqliteDatabase('pis_cofins.db')

class BaseModel(Model):

    class Meta:
        database = db

class Registro_C100(BaseModel):
    """
    """
    # Atributos
    x = CharField()
    y = CharField()


    @property
    def dados(self):
        # some property

    @dados.setter
    def dados(self, novos_dados):
        #...


    @property
    def formato_linha(self):
        # some method

class Registro_C170(BaseModel):
    """
    """
    # Atributos
    a = CharField()
    b = CharField()

    reg_c100 = ForeignKeyField(Registro_C100, backref='registros_c170')

    @property
    def dados(self):
        # some property

    @dados.setter
    def dados(self, novos_dados):
        # ...

    @property
    def formato_linha(self):
        # some method

模型_测试:

import unittest, os

from peewee import SqliteDatabase

from modelo_pis_cofins import Registro_0140, Registro_C170, Registro_C100

MODELS = [Registro_0140, Registro_C170, Registro_C100]

# use an in-memory SQLite for tests.
test_db = SqliteDatabase(':memory:')

class TestRegistroC170(unittest.TestCase):

    def setUp(self):
        # http://docs.peewee-orm.com/en/latest/peewee/database.html#testing-peewee-applications 
        test_db.bind(MODELS, bind_refs=False, bind_backrefs=False)
        test_db.connect()
        test_db.create_tables(MODELS)

        self.regc170 = Registro_C170()
        self.regc170_1 = Registro_C170(a="a", b="b")
        self.regc170_1.save() # this raises the errors

        self.regc100 = Registro_C100(x="x", y="y")
        self.regc100.save() # this raises the errors

    def tearDown(self):
        test_db.drop_tables(MODELS)
        test_db.close()

    def test_Registro_C170_atributos(self):
        # do some test

    def test_Registro_c170_dados(self): 
        # do some test:

    def test_Registro_C170_formato_linha(self):
        # do some test

    def test_Registro_C170_relacionamentos(self):
        # I will test relationships between "Registro_C170" and "Registro_C100"

        query = Registro_C100.get(Registro_C100.id == 1)
        query.registros_c170

错误:

======================================================================
ERROR: test_Registro_C170_atributos (modelo_pis_cofins_testes.TestRegistroC170)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\vitor.rabelo\virtual_enviroments\processamento_efd\lib\site-packages\peewee.py", line 2640, in execute_sql
    cursor.execute(sql, params or ())
sqlite3.IntegrityError: NOT NULL constraint failed: registro_c170.reg_c100_id

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\vitor.rabelo\Documents\projetos_automatizacao\projeto_efd\processamento_efd\modelo_pis_cofins_testes.py", line 76, in setUp
    self.regc170_1.save()
  File "C:\Users\vitor.rabelo\virtual_enviroments\processamento_efd\lib\site-packages\peewee.py", line 5577, in save
    pk_from_cursor = self.insert(**field_dict).execute()
  File "C:\Users\vitor.rabelo\virtual_enviroments\processamento_efd\lib\site-packages\peewee.py", line 1574, in inner
    return method(self, database, *args, **kwargs)
  File "C:\Users\vitor.rabelo\virtual_enviroments\processamento_efd\lib\site-packages\peewee.py", line 1645, in execute
    return self._execute(database)
  File "C:\Users\vitor.rabelo\virtual_enviroments\processamento_efd\lib\site-packages\peewee.py", line 2288, in _execute
    return super(Insert, self)._execute(database)
  File "C:\Users\vitor.rabelo\virtual_enviroments\processamento_efd\lib\site-packages\peewee.py", line 2063, in _execute
    cursor = database.execute(self)
  File "C:\Users\vitor.rabelo\virtual_enviroments\processamento_efd\lib\site-packages\peewee.py", line 2653, in execute
    return self.execute_sql(sql, params, commit=commit)
  File "C:\Users\vitor.rabelo\virtual_enviroments\processamento_efd\lib\site-packages\peewee.py", line 2647, in execute_sql
    self.commit()
  File "C:\Users\vitor.rabelo\virtual_enviroments\processamento_efd\lib\site-packages\peewee.py", line 2438, in __exit__
    reraise(new_type, new_type(*exc_args), traceback)
  File "C:\Users\vitor.rabelo\virtual_enviroments\processamento_efd\lib\site-packages\peewee.py", line 177, in reraise
    raise value.with_traceback(tb)
  File "C:\Users\vitor.rabelo\virtual_enviroments\processamento_efd\lib\site-packages\peewee.py", line 2640, in execute_sql
    cursor.execute(sql, params or ())
peewee.IntegrityError: NOT NULL constraint failed: registro_c170.reg_c100_id

======================================================================
ERROR: test_Registro_C170_formato_linha (modelo_pis_cofins_testes.TestRegistroC170)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\vitor.rabelo\Documents\projetos_automatizacao\projeto_efd\processamento_efd\modelo_pis_cofins_testes.py", line 68, in setUp
    test_db.connect()
  File "C:\Users\vitor.rabelo\virtual_enviroments\processamento_efd\lib\site-packages\peewee.py", line 2583, in connect
    raise OperationalError('Connection already opened.')
peewee.OperationalError: Connection already opened.

我试过的:

老实说,我知道我唯一可以尝试的是在每个测试方法中创建每个实例,但这正是我想要避免的。

我搜索了“peewee testing”和“peewee unittest”,但没有找到任何有用的东西。Peewee文档只有你展示了如何写的安装和拆卸方法:http://docs.peewee-orm.com/en/latest/peewee/database.html#testing-peewee-applications或如何使用他们的test_utils:HTTP: //docs.peewee-orm.com/en/latest/peewee/playhouse.html#test-utils

ps:这是我的第一个问题,希望它足够清楚:)

维克多·里贝罗

好吧,这很尴尬。我意识到我正在保存一个没有值的实例ForeignKeyField(默认为null=False)。我需要做的就是允许该字段接受null值 ( null=True)。

很抱歉有任何麻烦。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章