def test_args_optional(self): with captured(out(), err()) as (stdout, stderr): with mock_args([]): TestCommand.main() self.assertIn('opt=None', stdout.getvalue()) with captured(out(), err()) as (stdout, stderr): with mock_args(['--opt', 'OPT']): TestCommand.main() self.assertIn('opt=OPT', stdout.getvalue())
def test_get_version(self): with abduct.captured(abduct.out(), abduct.err()) as (stdout, stderr): with __main__.App(argv=['-v']) as app: with self.assertRaises(SystemExit): app.run() self.assertEqual(stdout.getvalue().strip(), wc_sim.__version__) self.assertEqual(stderr.getvalue(), '') with abduct.captured(abduct.out(), abduct.err()) as (stdout, stderr): with __main__.App(argv=['--version']) as app: with self.assertRaises(SystemExit): app.run() self.assertEqual(stdout.getvalue().strip(), wc_sim.__version__) self.assertEqual(stderr.getvalue(), '')
def test_args_logging_level(self): with captured(out(), err()) as (stdout, stderr): with mock_args([]): TestCommand.main() self.assertIn('logging_level=%s' % logging.WARNING, stdout.getvalue()) with captured(out(), err()) as (stdout, stderr): with mock_args(['--verbose']): TestCommand.main() self.assertIn('logging_level=%s' % logging.INFO, stdout.getvalue()) with captured(out(), err()) as (stdout, stderr): with mock_args(['--debug']): TestCommand.main() self.assertIn('logging_level=%s' % logging.DEBUG, stdout.getvalue())
def test_captured_stderr(stdout, stderr): with captured(err()) as stderr_cap: write() eq_(stderr_cap.getvalue(), 'stderr') eq_(stdout.getvalue(), 'stdout') eq_(stderr.getvalue(), '')
def test_captured_stdout_and_stderr(stdout, stderr): with captured(out(), err()) as (stdout_cap, stderr_cap): write() eq_(stdout_cap.getvalue(), 'stdout') eq_(stderr_cap.getvalue(), 'stderr') eq_(stdout.getvalue(), '') eq_(stderr.getvalue(), '')
def test_args_missing(self): with captured(out(), err()) as (stdout, stderr): with mock_args([]): with self.assertRaises(SystemExit): RequiredArgCommand.main() # Py2 and Py3 argparse have different messages self.assertIn('error: ', stderr.getvalue()) self.assertIn('-r/--req', stderr.getvalue()) self.assertIn('required', stderr.getvalue())
def run_command(additional_args): httpretty_register() args = ['-d', 'DOMAIN', '-n', 'NAME', '-v', 'VERSION', '-i', 'ID'] args += additional_args with captured(out(), err()) as (stdout, stderr): with mock_args(args): Command.main() return stdout, stderr
def run_command(additional_args): httpretty_register() args = ["-d", "DOMAIN"] args += additional_args with captured(out(), err()) as (stdout, stderr): with mock_args(args): Command.main() return stdout, stderr
def test_args_logging_config(self): with InTempDir(): with open('logging.conf', 'w') as fd: fd.write(LOGGING_CONFIG_FILE_DATA) args = ['--logging-config', 'logging.conf'] with captured(out(), err()) as (stdout, stderr): with mock_args(args): TestCommand.main() self.assertIn('EndOfOutput', stdout.getvalue())
def test_raw_cli(self): with mock.patch('sys.argv', ['wc-sim', '--help']): with self.assertRaises(SystemExit) as context: __main__.main() self.assertRegex(context.Exception, 'usage: wc-sim') with mock.patch('sys.argv', ['wc-sim']): with abduct.captured(abduct.out(), abduct.err()) as (stdout, stderr): __main__.main() self.assertRegex(stdout.getvalue().strip(), 'usage: wc-sim') self.assertEqual(stderr.getvalue(), '')
def test_nominal(self): args = ["--name", "DOMAIN", "--retention-days", "10"] headers = {"x-amzn-RequestId": "d68969c7-3f0d-11e1-9b11-7182192d0b57"} httpretty.register_uri( httpretty.POST, "https://swf.us-east-1.amazonaws.com/", content_type="application/json", adding_headers=headers, body="", ) with captured(out(), err()) as (stdout, stderr): with mock_args(args): Command.main() request = httpretty.last_request() self.assertEqual(request.headers.get("x-amz-target"), "SimpleWorkflowService.RegisterDomain") expected = {"name": "DOMAIN", "workflowExecutionRetentionPeriodInDays": "10"} self.assertEqual(json.loads(request.parsed_body), expected) self.assertIn("Success.", stdout.getvalue())
def test_quality_as_word_ok(quality_word, expected_itag): ''' Test that qualities are correctly parsed into their equivalent itags. A unit test for this is not enough, as this involves configuration of the argument parser, and determination of output from the program. This is essentially our "everything is generally ok" end to end test. ''' # expected_raw is a sequence of (itag, url) pairs. Since we're specifically # looking for the itag corresponding to to the quality word, we convert # these tuples to a dict and pull out the URL for the expected itag. expected_raw = _test_utils.read_fixture('files/success_output') expected_url = dict(json.loads(expected_raw))[expected_itag] fake_api_output = _test_utils.read_fixture('files/success_input', 'rb') _test_utils.mock_get_video_info_api_response(fake_api_output) with captured(out(), err()) as (stdout, stderr): yturl.main(['-q', quality_word, _test_utils.FAKE_URL], ) eq(stderr.getvalue(), 'Using itag %d.\n' % expected_itag) eq(stdout.getvalue(), expected_url + '\n')
def assert_scenario(stdout, stderr, scenario): context_out = 'stdout' if scenario.real_output_in_context else '' context_err = 'stderr' if scenario.real_output_in_context else '' except_out = 'stdout' if scenario.real_output_in_except else '' except_err = 'stderr' if scenario.real_output_in_except else '' o = out(release_on_exception=scenario.release, tee=scenario.tee) e = err(release_on_exception=scenario.release, tee=scenario.tee) try: with captured(o, e) as (stdout_cap, stderr_cap): write() eq_(stdout_cap.getvalue(), 'stdout') eq_(stderr_cap.getvalue(), 'stderr') eq_(stdout.getvalue(), context_out) eq_(stderr.getvalue(), context_err) raise MyCustomException() except MyCustomException: eq_(stdout.getvalue(), except_out) eq_(stderr.getvalue(), except_err)
def test_captured_nothing(stdout, stderr): with captured(): write() eq_(stdout.getvalue(), 'stdout') eq_(stderr.getvalue(), 'stderr')
def test_args_help(self): with captured(out(), err()) as (stdout, stderr): with mock_args(['--help']): with self.assertRaises(SystemExit): TestCommand.main() self.assertIn(TestCommand.description, stdout.getvalue())
def test_keyboard_interrupt(self): with captured(out(), err()) as (stdout, stderr): with mock_args([]): with self.assertRaises(SystemExit) as exc: KeyboardInterruptCommand.main() self.assertEqual(str(exc.exception), '1')
def main(): ######################################### ######################################### # a function which computes the volume of a spherical cell with radius 1 :math:`\mu m` import math def volume(radius): return 4 / 3 * math.pi * radius**3 assert volume((3 / 4)**(1 / 3)) == math.pi ######################################### ######################################### # Write a function which uses if statements to return the type of a codon (start, stop, other) def get_codon_type(codon): if codon in 'ATG': return 'start' elif codon in ['TAA', 'TAG', 'TGA']: return 'stop' else: return 'other' assert get_codon_type('ATG') == 'start' assert get_codon_type('TAG') == 'stop' assert get_codon_type('CTT') == 'other' ######################################### ######################################### # a class which represents RNA, with an attribute that stores the sequence # of each transcript and a method which uses a dictionary to compute the # amino acid sequence of the protein coded by the transcript class Rna(object): TRANSLATION_TABLE = { 'TTT': 'F', 'TTC': 'F', 'TTA': 'L', 'TTG': 'L', 'CTT': 'L', 'CTC': 'L', 'CTA': 'L', 'CTG': 'L', 'ATT': 'I', 'ATC': 'I', 'ATA': 'I', 'ATG': 'M', 'GTT': 'V', 'GTC': 'V', 'GTA': 'V', 'GTG': 'V', 'TCT': 'S', 'TCC': 'S', 'TCA': 'S', 'TCG': 'S', 'CCT': 'P', 'CCC': 'P', 'CCA': 'P', 'CCG': 'P', 'ACT': 'T', 'ACC': 'T', 'ACA': 'T', 'ACG': 'T', 'GCT': 'A', 'GCC': 'A', 'GCA': 'A', 'GCG': 'A', 'TAT': 'Y', 'TAC': 'Y', 'TAA': '', 'TAG': '', 'CAT': 'H', 'CAC': 'H', 'CAA': 'Q', 'CAG': 'Q', 'AAT': 'N', 'AAC': 'N', 'AAA': 'K', 'AAG': 'K', 'GAT': 'D', 'GAC': 'D', 'GAA': 'E', 'GAG': 'E', 'TGT': 'C', 'TGC': 'C', 'TGA': '', 'TGG': 'W', 'CGT': 'R', 'CGC': 'R', 'CGA': 'R', 'CGG': 'R', 'AGT': 'S', 'AGC': 'S', 'AGA': 'R', 'AGG': 'R', 'GGT': 'G', 'GGC': 'G', 'GGA': 'G', 'GGG': 'G', } def __init__(self, sequence): self.sequence = sequence def translate(self): aa_sequence = '' for position in range(int(len(self.sequence) / 3)): aa_sequence += self.TRANSLATION_TABLE[ self.sequence[3 * position:3 * (position + 1)]] return aa_sequence assert Rna('ATGGTTACTGAACAT').translate() == 'MVTEH' ######################################### ######################################### # Import the ``csv`` package and use it to read a tab-separated file with # a header row into a list of dictionaries such as the example provided at # `https://en.wikipedia.org/wiki/Tab-separated_values # <https://en.wikipedia.org/wiki/Tab-separated_values>`_ import os filename = os.path.join( os.path.dirname(__file__), '../../../docs/concepts_skills/software_engineering/example.tsv') with open(filename, 'w') as file: file.write( ('Sepal length\tSepal width\tPetal length\tPetal width\tSpecies\n' '5.1\t3.5\t1.4\t0.2\tI. setosa\n' '4.9\t3.0\t1.4\t0.2\tI. setosa\n' '4.7\t3.2\t1.3\t0.2\tI. setosa\n' '4.6\t3.1\t1.5\t0.2\tI. setosa\n' '5.0\t3.6\t1.4\t0.2\tI. setosa\n')) import csv with open(filename, 'r') as file: data = list(csv.DictReader(file, delimiter='\t')) assert len(data) == 5 assert data[0] == { 'Sepal length': '5.1', 'Sepal width': '3.5', 'Petal length': '1.4', 'Petal width': '0.2', 'Species': 'I. setosa' } os.remove(filename) ######################################### ######################################### # Use the ``print`` and ``format`` methods to write `Hello {your name}!` to standard out import abduct with abduct.captured(abduct.out(tee=True)) as stdout: print('Hello {}'.format('reader')) out_text = stdout.getvalue()