Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit test for only root user in python

Tags:

python

Does unit test library for python (especially 3.x, I don't really care about 2.x) has decorator to be accessed only by root user?

I have this testing function.

def test_blabla_as_root():
    self.assertEqual(blabla(), 1)

blabla function can only be executed by root. I want root user only decorator so normal user will skip this test:

@support.root_only
def test_blabla_as_root():
    self.assertEqual(blabla(), 1)

Does such decorator exist? We have @support.cpython_only decorator though.

like image 973
arjunaskykok Avatar asked Aug 07 '13 08:08

arjunaskykok


People also ask

How do I run a unit test in Python?

If you're using the PyCharm IDE, you can run unittest or pytest by following these steps: In the Project tool window, select the tests directory. On the context menu, choose the run command for unittest . For example, choose Run 'Unittests in my Tests…'.

What does Unittest main () do?

Internally, unittest. main() is using a few tricks to figure out the name of the module (source file) that contains the call to main() . It then imports this modules, examines it, gets a list of all classes and functions which could be tests (according the configuration) and then creates a test case for each of them.

Is PyUnit the same as Unittest?

Yes. unittest is a xUnit style frameworkfor Python, it was previously called PyUnit.


1 Answers

If you're using unittest, you can skip tests or entire test cases using unittest.skipIf and unittest.skipUnless.

Here, you could do:

import os

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

Which could be simplified in a (less readable):

@unittest.skipIf(os.getuid())
like image 58
Thomas Orozco Avatar answered Oct 14 '22 20:10

Thomas Orozco