gpt4 book ai didi

python - 进行单元测试时未定义名称 'self'?

转载 作者:太空狗 更新时间:2023-10-29 22:07:06 26 4
gpt4 key购买 nike

编辑

所以我再次尝试,使用一个名为 test2.py 的新文件,它成功了。我打包了repomantest.pysrc文件夹下。在创建并安装了我的 repoman egg 之后,我修改了 test.py。我认为这就是问题所在。但感谢您的帮助。你们认为这是确切的原因吗​​?


import unittest
import requests
from repoman.core import ultraman, supported
from repoman.ext import writefile,locate_repo

class TestWriteFile(unittest.TestCase):

def setUp(self):
self.username = 'dummy'
self.password = 'dummy'
self.remote = 'http://192.168.1.138:6666/scm/hg/NCL'

def test_scm_permission(self):
"""
Test SCM login.
"""
r = requests.get("http://192.168.1.138:6666/scm/", auth=(self.username, self.password))
self.assertTrue(r.ok)

if __name__ == '__main__':
unittest.main()

运行 python test.py 我得到这个错误:

Traceback (most recent call last):
File "test.py", line 7, in <module>
class TestWriteFile(unittest.TestCase):
File "test.py", line 19, in TestWriteFile
self.assertTrue(r.ok)
NameError: name 'self' is not defined

我认为我不需要覆盖 __init__ 函数,对吗?这是什么原因造成的?为什么 self 没有定义?我已经声明了我的父类(super class) unittest.TestCase

谢谢。

基本是从官方的sample:Unittest - Basic Example学来的

最佳答案

我不确定问题出在哪里——无论是复制错误还是执行了错误的 test.py [更新:或一些混合制表符和空格的问题,我永远无法弄清楚这些是什么时候发生的被标记,而当它们不被标记时]——但根本原因几乎可以肯定是缩进错误。

注意错误信息是

NameError: name 'self' is not defined

不是

NameError: global name 'self' is not defined

这是@Rik Poggi 得到的。如果您将 self.assertTrue 向上/向上移动一个级别,就会发生这种情况:

~/coding$ cat test_good_indentation.py
import unittest

class TestWriteFile(unittest.TestCase):
def test(self):
"""
Doc goes here.
"""
self.assertTrue(1)

if __name__ == '__main__':
unittest.main()

~/coding$ python test_good_indentation.py
.
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK

对比

~/coding$ cat test_bad_indentation.py
import unittest

class TestWriteFile(unittest.TestCase):
def test(self):
"""
Doc goes here.
"""
self.assertTrue(1)

if __name__ == '__main__':
unittest.main()

~/coding$ python test_bad_indentation.py
Traceback (most recent call last):
File "test_bad_indentation.py", line 3, in <module>
class TestWriteFile(unittest.TestCase):
File "test_bad_indentation.py", line 8, in TestWriteFile
self.assertTrue(1)
NameError: name 'self' is not defined

关于python - 进行单元测试时未定义名称 'self'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9541397/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com