Skip to content
Advertisement

How to use flake8 as unittest case?

I want to make flake8 a unittest case for all my source files. The unittest have to fail when the code is not PEP8 conform.

I still do this with pycodestyle that way.

pep = pycodestyle.Checker(filename)
return pep.check_all() == 0

But I don’t know how to do this with flake8 after import flake8.

Advertisement

Answer

As others have pointed out, this is not something you should be doing in unit tests. Unit tests should be used to check behavior and functionality of the code, something like linting and code style enforcement is best left to pre-commit checks or CI. The flake8 documentation has instructions on version control integration where you can see how to integrate it with pre-commit

But if you REALLY want to do it your way for some reason, you can see the documentation for legacy flake8 python api. And you can do something like

from flake8.api import legacy as flake8

style_guide = flake8.get_style_guide(
    ignore=['E24', 'W5'],
    select=['E', 'W', 'F'],
    format     ='pylint',
)

result = style_guide.input_file("filename")
if result.total_errors:
    # do whatever you want here. Raise errors or whatever.
    pass
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement