简体   繁体   English

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

[英]In python unittest, saving an instance of Peewee object raises peewee.IntegrityError: and peewee.OperationalError:

When I save a instance inside the setUp of python unittest I have 2 errors popping up: 当我将实例保存在python unittest的setUp中时,弹出两个错误:

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

and

peewee.OperationalError: Connection already opened. peewee.OperationalError:连接已打开。 (this one is raised for each test_method inside my testing Class.) (针对我的测试类中的每个test_method提出此方法。)

Context: 语境:

I'm very new to object-oriented programming and unittest. 我对面向对象的编程和单元测试非常陌生。 I'm using python to build a model of a hierarchy of registers. 我正在使用python构建寄存器层次结构的模型。 This registers holds information about taxation and accountability. 该注册簿包含有关税收和责任的信息。

Model: 模型:

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

Model_Test: Model_Test:

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

Errors: 错误:

======================================================================
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.

What I tried: 我试过的

Honestly, the only thing I know I could try is to create each instance inside each test method, but it is exactly what I'm trying to avoid. 老实说,我唯一能尝试的就是在每个测试方法中创建每个实例,但这正是我要避免的事情。

I have searched about "peewee testing" and "peewee unittest" and haven't found anython helpful. 我已经搜索过“小矮人测试”和“小矮人单元测试”,但没有发现任何帮助。 Peewee documentation only shows you how to write the setUp and tearDown methods: http://docs.peewee-orm.com/en/latest/peewee/database.html#testing-peewee-applications or how to use their test_utils: http://docs.peewee-orm.com/en/latest/peewee/playhouse.html#test-utils 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: This is my first question, hope it's clear enough :) ps:这是我的第一个问题,希望它足够清楚:)

Ok, this is embarassing. 好的,这很尴尬。 I realized that I was saving an instance with no value to the ForeignKeyField (that defaults to null=False ). 我意识到我将一个没有值的实例保存到ForeignKeyField (默认为null=False )。 All I need to do is to allow the field to accept null values ( null=True ). 我需要做的就是允许该字段接受null值( null=True )。

Sorry for any trouble. 对不起,有什么麻烦。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM