在python中仅对root用户进行单元测试

arj*_*kok 7 python

python的单元测试库(特别是3.x,我真的不关心2.x)是否只有root用户才能访问装饰器?

我有这个测试功能.

def test_blabla_as_root():
    self.assertEqual(blabla(), 1)
Run Code Online (Sandbox Code Playgroud)

blabla函数只能由root执行.我只想要root用户装饰器,所以普通用户将跳过此测试:

@support.root_only
def test_blabla_as_root():
    self.assertEqual(blabla(), 1)
Run Code Online (Sandbox Code Playgroud)

这样的装饰是否存在?我们有@ support.cpython_only装饰器.

Tho*_*zco 6

如果您正在使用unittest,则可以使用unittest.skipIf和跳过测试或整个测试用例unittest.skipUnless.

在这里,您可以这样做:

import os

@unittest.skipUnless(os.getuid() == 0)  # Root has an uid of 0
def test_bla_as_root(self):
    ...
Run Code Online (Sandbox Code Playgroud)

这可以简化为(不太可读):

@unittest.skipIf(os.getuid())
Run Code Online (Sandbox Code Playgroud)