0

There is a part of the code in the file fastq_trimmer.py:

if __name__ == '__main__':
    usage = '''
    Fastq Trimmer CLI.

    Usage:
        fastq_trimmer.py trim <filePath> <trimFactor>

    '''

    args = docopt(usage)

    if args['trim']:
        commenceOperation(args)
    else:
        print(usage)

Im trying to write a unittest :

import fastq_trimmer
from docopt import docopt

doc = fastq_trimmer.commenceOperation(args)

class TestTrimmer(unittest.TestCase):

    def test_exceptions(self):
        args = docopt(doc, ["/home/eliran/Desktop/example.fastq", "5"])
        self.assertEqual(args["<filePath>"], "/home/eliran/Desktop/example.fastq")
        self.assertEqual(args["<trimFactor>"], "5")

basically im trying to control the args variable from the unittest file so I can 'inject' the CLI with the args i specify in the unittest file.

Eliran Turgeman
  • 1,526
  • 2
  • 16
  • 34
  • The easiest way is to separate those concerns, guard the parsing and usage of command line arguments behind `if __name__ == "__main__":` (see https://stackoverflow.com/q/419163/3001761) so you can import the function and call it with whatever you want. – jonrsharpe May 13 '20 at 14:41
  • It raises an error : ```AttributeError: module 'fastq_trimmer' has no attribute 'args' ``` – Eliran Turgeman May 13 '20 at 14:52
  • ... *what* does? The code you've shown? Is `args` actually being assigned at the module level? – jonrsharpe May 13 '20 at 14:53
  • i've changed the code as you suggested in ```fastq_trimmer.py```, will edit the changes in the question – Eliran Turgeman May 13 '20 at 14:54
  • That's right, `args` is no longer defined at the module level when the file is imported. You can now `fastq_trimmer.commenceOperation()`. – jonrsharpe May 13 '20 at 14:56
  • changed to ```doc = fastq_trimmer.commenceOperation(args)```, another error is raised : ```NameError: name 'args' is not defined``` – Eliran Turgeman May 13 '20 at 14:58
  • This may seem like a stupid question, but... *did* you define `args`, before trying to pass it as an argument? – jonrsharpe May 13 '20 at 14:59
  • isn't this line defining args ```args = docopt(usage)``` ? – Eliran Turgeman May 13 '20 at 15:00
  • Yes, it is. But is `doc = fastq_trimmer.commenceOperation(args)` actually being executed in the scope where `args = docopt(usage)` was executed (in fact, was `args = docopt(usage)` being executed at all)? Because if not, it's unclear why you think that would be relevant. – jonrsharpe May 13 '20 at 15:03
  • Well yeah you are right that's not what im trying to do. Im simply trying to create a docopt object from the unittest file so i can send it to ```fastq_trimmer.py``` with ```fastq_trimmer.commenceOperation(docoptObj)``` – Eliran Turgeman May 13 '20 at 15:09
  • 1
    `docopt` just creates a *dictionary*, so you can do `fastq_trimmer.commenceOperation({ ... })` to test your function with different inputs. – jonrsharpe May 13 '20 at 15:16

0 Answers0