Python脚本被杀死

时间:2018-03-29 15:15:10

标签: python python-3.x flask flask-sqlalchemy python-unittest

环境 烧瓶0.10.1 SqlAlchemy 1.0.10 Python 3.4.3

使用unittest

我创建了两个单独的测试,其目标是通过700k记录查看数据库并进行一些字符串查找。当一次执行一个测试时,它可以正常工作,但是当整个脚本执行时:

python name_of_script.py

退出" KILLED"在随机的地方。

两个测试的主要代码都是这样的:

def test_redundant_categories_exist(self):
    self.assertTrue(self.get_redundant_categories() > 0, 'There are 0 redundant categories to remove. Cannot test removing them if there are none to remove.')

def get_redundant_categories(self):
        total = 0
        with get_db_session_scope(db.session) as db_session:
            records = db_session.query(Category)
            for row in records:
                if len(row.c) > 1:
                    c = row.c
                    #TODO: threads, each thread handles a bulk of rows
                    redundant_categories = [cat_x.id
                                            for cat_x in c
                                            for cat_y in c
                                            if cat_x != cat_y and re.search(r'(^|/)' + cat_x.path + r'($|/)', cat_y.path)
                                            ]
                    total += len(redundant_categories)
            records = None
            db_session.close()
        return total

另一个测试调用位于manager.py文件中的函数,该函数执行类似操作,但在数据库中添加了批量删除。

    def test_remove_redundant_mappings(self):
        import os
        os.system( "python ../../manager.py remove_redundant_mappings" )
        self.assertEqual(self.get_redundant_categories(), 0, "There are redundant categories left after running manager.py remove_redundant_mappings()")

是否有可能在测试之间将数据保存在内存中?我不太明白如何单独执行测试,但是当背靠背运行时,过程以Killed结束。

有什么想法吗?

编辑(事情我试图无济于事):

  • manager.py导入该功能,并在不使用os.system(..)
  • 的情况下调用该功能
  • import gc并在gc.collect()之后和get_redundant_categories()
  • 之后运行remove_redundant_mappings()

1 个答案:

答案 0 :(得分:0)

在搜索高低时,我偶然发现了StackOverflow question/answer

中的以下评论
  

我认为,正在发生的事情是,人们正在实例化会话而不是关闭会话。然后在不关闭会话的情况下对对象进行垃圾收集。当会话对象超出范围时,为什么sqlalchemy会话不会关闭自己,并且总是超出我的范围。 @ melchoir55

所以我将以下内容添加到正在测试的方法中:

db_session.close()

现在单元测试执行而不会被杀死。

相关问题