Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7029087
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 28, 20262026-05-28T00:29:32+00:00 2026-05-28T00:29:32+00:00

I am trying to write a parser in Python for a special text file

  • 0

I am trying to write a parser in Python for a special text file format. To get an idea how to structure the code I looked into the source code of the JSON parser which is part of the Python standard library (Python/Lib/json).

In this json directory there is a tests directory which holds a number of unit tests. I replaced the json tests with my tests but now I do not know how to call them.

Looking into the directory there is a __init__.py file making it a module and inside of this file there is the following code snippet for running the tests:

here = os.path.dirname(__file__)

def test_suite():
    suite = additional_tests()
    loader = unittest.TestLoader()
    for fn in os.listdir(here):
        if fn.startswith("test") and fn.endswith(".py"):
            modname = "json.tests." + fn[:-3]
            __import__(modname)
            module = sys.modules[modname]
            suite.addTests(loader.loadTestsFromModule(module))
    return suite

def additional_tests():
    suite = unittest.TestSuite()
    for mod in (json, json.encoder, json.decoder):
        suite.addTest(doctest.DocTestSuite(mod))
    suite.addTest(TestPyTest('test_pyjson'))
    suite.addTest(TestCTest('test_cjson'))
    return suite

def main():
    suite = test_suite()
    runner = unittest.TextTestRunner()
    runner.run(suite)

if __name__ == '__main__':
    sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
    main()

My problem is now how are these unit tests executed? I am confused because the if __name__ == '__main__': if clause validates to true if this file is called directly and not being imported as a module. However as it is in the __init__.py file of the module it should be executed right after import.

Should an import tests in the python console start all the unit tests?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-28T00:29:32+00:00Added an answer on May 28, 2026 at 12:29 am

    First: the __init__.py file in a directory marks the directory as a package and all other files with the .py ending therein are modules.

    Second: To validate the __name__ == '__main__' conditional you have to execute the file. So a simple import won’t do.

    For further question on package and module structure i would suggest ro read the Official Python Documentation on Packages.

    The unittests are structured into testsuites, which can contain one ore more TestCases which consists of one or more tests.

    The tests are usually methods of a TestCase derived class. You can either run the tests by defining a runTest() method or defining multiple test_* methods, which will be executed autmatically. To execute a Unittest you can either use the convenience function unittest.main() which basicaly tries to construct a testsuite, testresult and testrunner object by using default-rules.

    The execution of your unittest itself is done by the testrunner object. The standard testrunner-class is TextTestRunner, which uses a TextTestResult-class to store the testresults and prints them to stdout. See Official unittest Documentation for unittest.main() for the simplest variant.

    Summary

    1) A unittest is basically a TestSuite containing one ore more TestCases:

    TestSuite      <---executed by--- TestRunner
       + TestCaseA                        |
           +test_a()                      |
           +test_b()             stores test-results 
               ...                      into
           +test_z()                      |
        + TestCaseB                       V
        + TestCaseC                  TestResult
    

    2) The TestCases are subclasses of unittest.TestCase. You can create a TestSuite, by using a loader (e.g.: unittest.defaultTestLoader) which is basically a factory for a testsuite, or you can add the TestCases manually (suite.addTest(test) / suite.addTests(tests) – tests may be TestCases or even other TestSuites) or by combining those two methods.

    3) To execute a testsuite you use a unittest.TestRunner-object which saves the results in a unittest.TestResult object.

    Normaly you would be using unittest.TextTestRunner-object to get a simple output of the testresults to stdout.

    That’s excatly what happens also in your main-routine:

    def main():
        suite = test_suite()                #1 create a TestSuite object
        runner = unittest.TextTestRunner()  #2 create a TextTestRunner object
        runner.run(suite)                   #3 executes the TestSuite with TestSuite
                                            #  build by the function test_suite()
    

    To execute your testsuite you would have then to execute python __init__.py .

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm trying to write a small parser with Irony . Unfortunately I get a
I am trying to write a Python code analyzer, and I am trying to
I am trying to write a program to check that some C source code
I am trying to write a python parser with boost::spirit library. Here is the
I am trying to write a parser class derived from the Python argparse ArgumentParser
I'm trying to write a small Python script to parse the .strings file in
I'm trying to write a parser for the EDI data format, which is just
I'm trying to write a generic XML to Core Data parser using libxml2. Since
Trying to write a couple of functions that will encrypt or decrypt a file
Im trying to write a single byte at a certain location in a file.

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.