Example #1
0
    def test_script_convert_basis(self):
        expected = [(0.91, -0.89, -0.02, 1.78, -1.55, 0.47),
                    (-0.02, 0.91, -0.89, -1.55, -0.47, -1.78),
                    (-0.89, 0.91, -0.02, 1.78, -0.47, 1.55),
                    (0.91, -0.89, -0.02, -1.78, 1.55, 0.47),
                    (-0.89, -0.02, 0.91, -0.47, 1.78, 1.55),
                    (0.91, -0.89, -0.02, 1.78, -1.55, 0.47),
                    (-0.02, -0.89, 0.91, -0.47, -1.55, -1.78),
                    (-0.89, -0.02, 0.91, 0.47, -1.78, 1.55),
                    (-0.89, 0.91, -0.02, 1.78, -0.47, 1.55),
                    (-0.02, -0.89, 0.91, -0.47, -1.55, -1.78),
                    (0.91, -0.89, -0.02, 1.78, -1.55, 0.47),
                    (-0.89, 0.91, -0.02, -1.78, 0.47, 1.55),
                    (0.91, -0.89, -0.02, -1.78, 1.55, 0.47),
                    (-0.02, 0.91, -0.89, 1.55, -0.47, 1.78),
                    (-0.89, 0.91, -0.02, -1.78, -0.47, -1.55),
                    (0.91, -0.89, -0.02, 1.78, -1.55, 0.47)]

        for exp, (insys, outsys) in zip(
                expected, product(['NED', 'USE', 'XYZ', 'NWU'], repeat=2)):

            with CatchOutput() as out:
                obspy_mopad([
                    'convert', '-b', insys, outsys,
                    ','.join(str(x) for x in self.mt)
                ])

            actual = eval(out.stdout)
            self.assertEqual(len(exp), len(actual))
            for i, (e, a) in enumerate(zip(exp, actual)):
                msg = '%d: %f != %f in %s -> %s conversion' % (i, e, a, insys,
                                                               outsys)
                self.assertAlmostEqual(e, a, msg=msg)
Example #2
0
 def test_multipleSamplingrates(self):
     """
     Check for multiple sampling rates
     """
     lines = [
         "TIMESERIES XX_TEST__BHZ_R, 200 samples, 200 sps, "
         "2008-01-15T00:00:00.000000, SLIST, INTEGER, Counts",
         "TIMESERIES XX_TEST__BHZ_R,  50 samples,  50 sps, "
         "2008-01-15T00:00:01.000000, SLIST, INTEGER, Counts",
         "TIMESERIES XX_TEST__BHZ_R, 200 samples, 200 sps, "
         "2008-01-15T00:00:02.000000, SLIST, INTEGER, Counts",
     ]
     reltol = 1
     if MATPLOTLIB_VERSION < [1, 3, 0]:
         reltol = 60
     files = []
     with NamedTemporaryFile() as f1:
         with NamedTemporaryFile() as f2:
             with NamedTemporaryFile() as f3:
                 for i, fp in enumerate([f1, f2, f3]):
                     fp.write(("%s\n" % lines[i]).encode('ascii', 'strict'))
                     fp.flush()
                     fp.seek(0)
                     files.append(fp.name)
                 with ImageComparison(self.path,
                                      'scan_mult_sampl.png',
                                      reltol=reltol) as ic:
                     with CatchOutput():
                         obspy_scan(files + ['--output', ic.name])
Example #3
0
    def test_CatchOutput(self):
        """
        """
        libc = CDLL(find_library("c"))

        with CatchOutput() as out:
            os.system('echo "abc"')
            libc.printf(b"def\n")
            print("ghi")
            print("jkl", file=sys.stdout)
            os.system('echo "123" 1>&2')
            print("456", file=sys.stderr)

        if PY2:
            if platform.system() == "Windows":
                self.assertEqual(out.stdout, b'"abc"\ndef\nghi\njkl\n')
                self.assertEqual(out.stderr, b'"123" \n456\n')
            else:
                self.assertEqual(out.stdout, b"abc\ndef\nghi\njkl\n")
                self.assertEqual(out.stderr, b"123\n456\n")
        else:
            # XXX: cannot catch the printf call to def in Py3k
            # XXX: Introduces special characters on MAC OSX which
            #      avoid test report to be sent (see #743). Therefore
            #      test is skipped
            if platform.system() == "Windows":
                self.assertEqual(out.stdout, b'"abc"\nghi\njkl\n')
                self.assertEqual(out.stderr, b'"123" \n456\n')
            else:
                self.assertEqual(out.stdout, b"abc\nghi\njkl\n")
                self.assertEqual(out.stderr, b"123\n456\n")
Example #4
0
    def test_CatchOutput(self):
        """
        """
        libc = CDLL(find_library("c"))

        with CatchOutput() as out:
            os.system('echo "abc"')
            libc.printf(b"def\n")
            print("ghi")
            print("jkl", file=sys.stdout)
            os.system('echo "123" 1>&2')
            print("456", file=sys.stderr)

        if PY2:
            if platform.system() == "Windows":
                self.assertEqual(out.stdout, '"abc"\ndef\nghi\njkl\n')
                self.assertEqual(out.stderr, '"123" \n456\n')
            else:
                self.assertEqual(out.stdout, "abc\ndef\nghi\njkl\n")
                self.assertEqual(out.stderr, "123\n456\n")
        else:
            # XXX: cannot catch the printf call to def in Py3k
            if platform.system() == "Windows":
                self.assertEqual(out.stdout, '"abc"\nghi\njkl\n')
                self.assertEqual(out.stderr, '"123" \n456\n')
            else:
                self.assertEqual(out.stdout, "abc\nghi\njkl\n")
                self.assertEqual(out.stderr, "123\n456\n")
Example #5
0
    def test_script_convert_type_sdr(self):
        with CatchOutput() as out:
            obspy_mopad([
                'convert', '--fancy', '-t', 'sdr',
                ','.join(str(x) for x in self.mt)
            ])

        expected = '''
Fault plane 1: strike =  77°, dip =  89°, slip-rake = -141°
Fault plane 2: strike = 346°, dip =  51°, slip-rake =   -1°
'''

        result = out.stdout[:-1]
        try:
            if sys.stdout.encoding is not None:
                expected = expected.encode(sys.stdout.encoding)
            else:
                expected = expected.encode()
        except Exception:
            expected = expected.replace('°', ' deg')
            if sys.stdout.encoding is not None:
                expected = expected.encode(sys.stdout.encoding)
            else:
                expected = expected.encode()

        self.assertEqual(expected, result)
Example #6
0
 def test_catch_output_bytes(self):
     with CatchOutput() as out:
         # PY3 does not allow to write directly bytes into text streams
         sys.stdout.buffer.write(b"test_catch_output_bytes #1")
         sys.stderr.buffer.write(b"test_catch_output_bytes #2")
     assert out.stdout == 'test_catch_output_bytes #1'
     assert out.stderr == 'test_catch_output_bytes #2'
Example #7
0
def check_flake8():
    if not HAS_FLAKE8:
        raise Exception('flake8 is required to check code formatting')

    # pyflakes autodetection of PY2 does not work with the future library.
    # Therefore, overwrite the pyflakes autodetection manually
    if PY2:
        import pyflakes.checker  # @UnusedImport
        pyflakes.checker.PY2 = True

    test_dir = os.path.abspath(inspect.getfile(inspect.currentframe()))
    obspy_dir = os.path.dirname(os.path.dirname(os.path.dirname(test_dir)))
    untracked_files = get_untracked_files_from_git() or []
    files = []
    for dirpath, _, filenames in os.walk(obspy_dir):
        filenames = [
            _i for _i in filenames
            if os.path.splitext(_i)[-1] == os.path.extsep + "py"
        ]
        if not filenames:
            continue
        for py_file in filenames:
            py_file = os.path.join(dirpath, py_file)
            # ignore untracked files
            if os.path.abspath(py_file) in untracked_files:
                continue

            # exclude *.py files in obspy/lib
            try:
                tmp_dir, _ = os.path.split(py_file)
                _, tmp_dir = os.path.split(tmp_dir)
                if tmp_dir == "lib":
                    continue
            except:
                pass
            # Check files that do not match any exclusion pattern
            for exclude_pattern in FLAKE8_EXCLUDE_FILES:
                if fnmatch.fnmatch(py_file, exclude_pattern):
                    break
            else:
                files.append(py_file)

    if flake8_version >= LooseVersion('3.0.0'):
        from flake8.api.legacy import get_style_guide
    else:
        from flake8.engine import get_style_guide
    flake8_kwargs = {'parse_argv': False}
    if flake8_version < LooseVersion('2.5.5'):
        import flake8.main
        flake8_kwargs['config_file'] = flake8.main.DEFAULT_CONFIG

    flake8_style = get_style_guide(**flake8_kwargs)
    flake8_style.options.ignore = tuple(
        set(flake8_style.options.ignore).union(set(FLAKE8_IGNORE_CODES)))

    with CatchOutput() as out:
        files = [native_str(f) for f in files]
        report = flake8_style.check_files(files)

    return report, out.stdout
Example #8
0
    def test_segfault_after_error_handling(self):
        """
        Many functions in evalresp call `error_return()` which uses longjmp()
        to jump to some previously set state.

        ObsPy calls some evalresp functions directly so evalresp cannot call
        setjmp(). In that case longjmp() jumps to an undefined location, most
        likely resulting in a segfault.

        This test tests a workaround for this issue.

        As long as it does not segfault the test is doing alright.
        """
        filename = os.path.join(self.data_dir,
                                "TM.SKLT..BHZ_faulty_response.xml")
        inv = read_inventory(filename)

        t_samp = 0.05
        nfft = 256

        with CatchOutput():
            self.assertRaises(ValueError,
                              inv[0][0][0].response.get_evalresp_response,
                              t_samp,
                              nfft,
                              output="DISP")
Example #9
0
    def test_CatchOutput(self):
        """
        Tests for CatchOutput context manager.
        """
        libc = CDLL(find_library("c"))

        with CatchOutput() as out:
            os.system('echo "abc"')
            libc.printf(b"def\n")
            # This flush is necessary for Python 3, which uses different
            # buffering modes. Fortunately, in practice, we do not mix Python
            # and C writes to stdout. This can also be fixed by setting the
            # PYTHONUNBUFFERED environment variable, but this must be done
            # externally, and cannot be done by the script.
            libc.fflush(None)
            print("ghi")
            print("jkl", file=sys.stdout)
            os.system('echo "123" 1>&2')
            print("456", file=sys.stderr)

        if platform.system() == "Windows":
            self.assertEqual(out.stdout, b'"abc"\r\ndef\nghi\r\njkl\r\n')
            self.assertEqual(out.stderr, b'"123" \r\n456\r\n')
        else:
            self.assertEqual(out.stdout, b"abc\ndef\nghi\njkl\n")
            self.assertEqual(out.stderr, b"123\n456\n")
Example #10
0
    def compare_gmt(self, exp_file, *args):
        """
        Helper function that runs GMT and compares results.
        """
        with CatchOutput() as out:
            obspy_mopad(['gmt'] + list(args) +
                        [','.join(str(x) for x in self.mt)])

        expected = os.path.join(self.path, exp_file)

        # Test headers
        with open(expected, 'rt') as expf:
            bio = out.stdout
            # expf.read().splitlines() differs to expf.readlines() ?!?!?!
            for exp_line, out_line in zip_longest(expf.read().splitlines(),
                                                  bio.splitlines(),
                                                  fillvalue=''):
                if exp_line.startswith('>') or out_line.startswith('>'):
                    self.assertEqual(exp_line,
                                     out_line,
                                     msg='Headers do not match!')

        # Test actual data
        exp_data = np.genfromtxt(expected, comments='>')
        with io.BytesIO(out.stdout.encode('utf-8')) as bio:
            out_data = np.genfromtxt(bio, comments='>')
        self.assertEqual(exp_data.shape,
                         out_data.shape,
                         msg='Data does not match!')
        self.assertTrue(np.allclose(exp_data, out_data),
                        msg='Data does not match!')
Example #11
0
 def test_multiple_sampling_rates(self):
     """
     Check for multiple sampling rates
     """
     lines = [
         "TIMESERIES XX_TEST__BHZ_R, 200 samples, 200 sps, "
         "2008-01-15T00:00:00.000000, SLIST, INTEGER, Counts",
         "TIMESERIES XX_TEST__BHZ_R,  50 samples,  50 sps, "
         "2008-01-15T00:00:00.900000, SLIST, INTEGER, Counts",
         "TIMESERIES XX_TEST__BHZ_R, 200 samples, 200 sps, "
         "2008-01-15T00:00:02.000000, SLIST, INTEGER, Counts",
     ]
     files = []
     expected = [
         "XX.TEST..BHZ 2008-01-15T00:00:01.000000Z "
         "2008-01-15T00:00:00.899995Z -0.100",
         "XX.TEST..BHZ 2008-01-15T00:00:01.899999Z "
         "2008-01-15T00:00:02.000000Z 0.100"
     ]
     with NamedTemporaryFile() as f1, NamedTemporaryFile() as f2, \
             NamedTemporaryFile() as f3:
         for i, fp in enumerate([f1, f2, f3]):
             fp.write(("%s\n" % lines[i]).encode('ascii', 'strict'))
             fp.flush()
             fp.seek(0)
             files.append(fp.name)
         with ImageComparison(self.path, 'scan_mult_sampl.png')\
                 as ic:
             with CatchOutput() as out:
                 obspy_scan(files + ['--output', ic.name, '--print-gaps'])
             self.assertEqual(expected, out.stdout.splitlines())
Example #12
0
    def test_script_decompose(self):
        with CatchOutput() as out:
            obspy_mopad(['decompose', '-y', ','.join(str(x) for x in self.mt)])

        expected = '''
Scalar Moment: M0 = 2.61206 Nm (Mw = -5.8)
Moment Tensor: Mnn =  0.091,  Mee = -0.089, Mdd = -0.002,
               Mne =  0.178,  Mnd = -0.155, Med =  0.047    [ x 10 ]


Fault plane 1: strike =  77°, dip =  89°, slip-rake = -141°
Fault plane 2: strike = 346°, dip =  51°, slip-rake =   -1°
'''

        result = out.stdout[:-1]
        try:
            if sys.stdout.encoding is not None:
                expected = expected.encode(sys.stdout.encoding)
            else:
                expected = expected.encode()
        except Exception:
            expected = expected.replace('°', ' deg')
            if sys.stdout.encoding is not None:
                expected = expected.encode(sys.stdout.encoding)
            else:
                expected = expected.encode()

        self.assertEqual(expected, result)
Example #13
0
    def test_script_plot(self):
        # See test_Beachball:
        data = [
            [0.91, -0.89, -0.02, 1.78, -1.55, 0.47],
            [274, 13, 55],
            [130, 79, 98],
            [264.98, 45.00, -159.99],
            [160.55, 76.00, -46.78],
            [1.45, -6.60, 5.14, -2.67, -3.16, 1.36],
            [235, 80, 35],
            [138, 56, 168],
            [1, 1, 1, 0, 0, 0],
            [-1, -1, -1, 0, 0, 0],
            [1, -2, 1, 0, 0, 0],
            [1, -1, 0, 0, 0, 0],
            [1, -1, 0, 0, 0, -1],
            [179, 55, -78],
            [10, 42.5, 90],
            [10, 42.5, 92],
            [150, 87, 1],
            [0.99, -2.00, 1.01, 0.92, 0.48, 0.15],
            [5.24, -6.77, 1.53, 0.81, 1.49, -0.05],
            [16.578, -7.987, -8.592, -5.515, -29.732, 7.517],
            [-2.39, 1.04, 1.35, 0.57, -2.94, -0.94],
        ]
        filenames = [
            'bb_sumatra_mt.png', 'bb_sumatra_np1.png', 'bb_sumatra_np2.png',
            'bb_19950128_np1.png', 'bb_19950128_np2.png', 'bb_20090102_mt.png',
            'bb_20090102_np1.png', 'bb-20090102-np2.png', 'bb_explosion.png',
            'bb_implosion.png', 'bb_clvd.png', 'bb_double_couple.png',
            'bb_lars.png', 'bb_geiyo_np1.png', 'bb_honshu_np1.png',
            'bb_honshu_np2.png', 'bb_tottori_np1.png', 'bb_20040905_1_mt.png',
            'bb_20040905_0_mt.png', 'bb_miyagi_mt.png', 'bb_chile_mt.png',
        ]

        messages = ''
        for mt, filename in zip(data, filenames):
            try:
                with ImageComparison(self.path, filename) as ic:
                    with CatchOutput() as out:
                        obspy_mopad(['plot',
                                     '--output-file', ic.name,
                                     '--input-system', 'USE',
                                     '--tension-color', 'b',
                                     '--pressure-color', 'w',
                                     '--lines', '1', 'k', '1',
                                     '--nodals', '1', 'k', '1',
                                     '--size', '2.54', '--quality', '200',
                                     '--',
                                     ','.join(str(x) for x in mt)])
                    self.assertEqual('', out.stdout)
            except ImageComparisonException as e:
                if ic.keep_output:
                    messages += str(e)
                else:
                    raise

        if messages:
            self.fail(messages)
Example #14
0
 def test_script_convert_vector(self):
     with CatchOutput() as out:
         obspy_mopad([
             'convert', '-v', 'NED', 'NED',
             ','.join(str(x) for x in self.mt)
         ])
     expected = str(self.mt) + '\n'
     self.assertEqual(expected, out.stdout)
Example #15
0
    def test_print(self):
        with CatchOutput() as out:
            obspy_print(self.all_files)

        expected = '''1 Trace(s) in Stream:
XX.TEST..BHZ | 2008-01-15T00:00:00.025000Z - 2008-01-15T00:00:15.875000Z | 40.0 Hz, 635 samples
'''  # noqa
        self.assertEqual(expected, out.stdout)
Example #16
0
    def test_step_cal_blockette(self):
        """
        Test the step calibration blockette type 300.
        """
        filename = os.path.join(
            os.path.dirname(__file__), 'data',
            'blockette300.mseed')

        with CatchOutput() as out:
            obspy_recordanalyzer([filename])

        expected = '''FILE: %s
Record Number: 0
Record Offset: 0 byte
Header Endianness: Big Endian

FIXED SECTION OF DATA HEADER
    Sequence number: 36680
    Data header/quality indicator: M
    Station identifier code: KIEV
    Location identifier: 00
    Channel identifier: BHZ
    Network code: IU
    Record start time: 2018-02-13T22:43:59.019500Z
    Number of samples: 20
    Sample rate factor: 20
    Sample rate multiplier: 1
    Activity flags: 1
    I/O and clock flags: 32
    Data quality flags: 0
    Number of blockettes that follow: 3
    Time correction: 0
    Beginning of data: 128
    First blockette: 48

BLOCKETTES
    1000:    Encoding Format: 11
        Word Order: 1
        Data Record Length: 9
    1001:    Timing quality: 100
        mu_sec: 38
        Frame count: 6
    300:    Calibration Start Time: 2018-02-13T22:44:00.000000Z
        Number of Step Calibrations: 1
        Step Duration in Seconds: 0
        Interval Duration in Seconds: 900
        Calibration Signal Amplitude: -30.0
        Calibration Monitor Channel: EC0
        Calibration Reference Amplitude: 0.0
        Coupling: resistive
        Rolloff: 3DB@10Hz

CALCULATED VALUES
    Corrected Starttime: 2018-02-13T22:43:59.019538Z

''' % (filename,)  # noqa
        self.assertEqual(expected, out.stdout.replace("\t", "    "))  # noqa
Example #17
0
    def test_print(self):
        with CatchOutput() as out:
            obspy_print(self.all_files)

        self.assertEqual(
            '''1 Trace(s) in Stream:
XX.TEST..BHZ | 2008-01-15T00:00:00.025000Z - 2008-01-15T00:00:15.875000Z | 40.0 Hz, 635 samples
'''.encode('utf-8'),  # noqa
            out.stdout)
Example #18
0
    def test_multiple_sampling_rates(self):
        """
        Check for multiple sampling rates
        """
        lines = [
            "TIMESERIES XX_TEST__BHZ_R, 200 samples, 200 sps, "
            "2008-01-15T00:00:00.000000, SLIST, INTEGER, Counts",
            "TIMESERIES XX_TEST__BHZ_R,  50 samples,  50 sps, "
            "2008-01-15T00:00:00.900000, SLIST, INTEGER, Counts",
            "TIMESERIES XX_TEST__BHZ_R, 200 samples, 200 sps, "
            "2008-01-15T00:00:02.000000, SLIST, INTEGER, Counts",
        ]
        files = []
        expected = [
            "XX.TEST..BHZ 2008-01-15T00:00:01.000000Z "
            "2008-01-15T00:00:00.899995Z -0.100",
            "XX.TEST..BHZ 2008-01-15T00:00:01.899999Z "
            "2008-01-15T00:00:02.000000Z 0.100"
        ]
        with NamedTemporaryFile() as f1, NamedTemporaryFile() as f2, \
                NamedTemporaryFile() as f3:
            for i, fp in enumerate([f1, f2, f3]):
                fp.write(("%s\n" % lines[i]).encode('ascii',
                                                    'strict'))
                fp.flush()
                fp.seek(0)
                files.append(fp.name)

            # make image comparison instance and set manual rms (see #2089)
            image_comp = ImageComparison(self.path, 'scan_mult_sampl.png')
            image_comp.tol = 40

            with image_comp as ic:

                obspy_scan(files + ['--output', ic.name, '--print-gaps'])

                with CatchOutput() as out:
                    obspy_scan(files + ['--output', ic.name, '--print-gaps'])

                # read output and compare with expected
                # only check if datetime objects are close, not exact
                output = out.stdout.splitlines()
                for ex_line, out_line in zip(expected, output):
                    ex_split = ex_line.split(' ')
                    out_split = out_line.split(' ')
                    for ex_str, out_str in zip(ex_split, out_split):
                        try:
                            utc1 = UTCDateTime(ex_str)
                            utc2 = UTCDateTime(out_str)
                        except (ValueError, TypeError):
                            # if str is not a datetime it should be equal
                            self.assertEqual(ex_str, out_str)
                        else:
                            # datetimes just need to be close
                            t1, t2 = utc1.timestamp, utc2.timestamp
                            self.assertTrue(abs(t1 - t2) < .001)
Example #19
0
    def test_print_nomerge(self):
        with CatchOutput() as out:
            obspy_print(['--no-merge'] + self.all_files)

        self.assertEqual(
            '''2 Trace(s) in Stream:
XX.TEST..BHZ | 2008-01-15T00:00:00.025000Z - 2008-01-15T00:00:15.875000Z | 40.0 Hz, 635 samples
XX.TEST..BHZ | 2008-01-15T00:00:00.025000Z - 2008-01-15T00:00:15.875000Z | 40.0 Hz, 635 samples
'''.encode('utf-8'),  # noqa
            out.stdout.replace(b'\r', b''))
Example #20
0
    def test_catch_output(self):
        """
        Tests that CatchOutput catches messages
        """
        with CatchOutput() as out:
            sys.stdout.write("test_catch_output #1")
            sys.stderr.write("test_catch_output #2")
        self.assertEqual(out.stdout, 'test_catch_output #1')
        self.assertEqual(out.stderr, 'test_catch_output #2')

        with CatchOutput() as out:
            print("test_catch_output #3")
        self.assertEqual(out.stdout, 'test_catch_output #3\n')
        self.assertEqual(out.stderr, '')

        with CatchOutput() as out:
            print("test_catch_output #4", file=sys.stdout)
            print("test_catch_output #5", file=sys.stderr)
        self.assertEqual(out.stdout, 'test_catch_output #4\n')
        self.assertEqual(out.stderr, 'test_catch_output #5\n')
Example #21
0
    def test_CatchOutput(self):
        """
        """
        libc = CDLL("libc.so.6")

        with CatchOutput() as out:
            libc.printf("hello world stdout\n")
            os.system('echo "mystderr" 1>&2')

        self.assertEqual(out.stdout, "hello world stdout\n")
        self.assertEqual(out.stderr, "mystderr\n")
Example #22
0
 def test_supress_output(self):
     """
     Tests that CatchOutput suppresses messages
     """
     # this should write nothing to console
     with CatchOutput():
         sys.stdout.write("test_suppress_output #1 failed")
         sys.stderr.write("test_suppress_output #2 failed")
         print("test_suppress_output #3 failed")
         print("test_suppress_output #4 failed", file=sys.stdout)
         print("test_suppress_output #5 failed", file=sys.stderr)
Example #23
0
    def test_catch_output(self):
        """
        Tests that CatchOutput catches messages
        """
        with CatchOutput() as out:
            sys.stdout.write("test_catch_output #1")
            sys.stderr.write("test_catch_output #2")
        assert out.stdout == 'test_catch_output #1'
        assert out.stderr == 'test_catch_output #2'

        with CatchOutput() as out:
            print("test_catch_output #3")
        assert out.stdout == 'test_catch_output #3\n'
        assert out.stderr == ''

        with CatchOutput() as out:
            print("test_catch_output #4", file=sys.stdout)
            print("test_catch_output #5", file=sys.stderr)
        assert out.stdout == 'test_catch_output #4\n'
        assert out.stderr == 'test_catch_output #5\n'
Example #24
0
 def test_catch_output_bytes(self):
     with CatchOutput() as out:
         if PY2:
             sys.stdout.write(b"test_catch_output_bytes #1")
             sys.stderr.write(b"test_catch_output_bytes #2")
         else:
             # PY3 does not allow to write directly bytes into text streams
             sys.stdout.buffer.write(b"test_catch_output_bytes #1")
             sys.stderr.buffer.write(b"test_catch_output_bytes #2")
     self.assertEqual(out.stdout, 'test_catch_output_bytes #1')
     self.assertEqual(out.stderr, 'test_catch_output_bytes #2')
Example #25
0
    def test_script_convert_type_sdr(self):
        with CatchOutput() as out:
            obspy_mopad(['convert', '--fancy', '-t', 'sdr',
                         ','.join(str(x) for x in self.mt)])

        expected = '''
Fault plane 1: strike =  77°, dip =  89°, slip-rake = -141°
Fault plane 2: strike = 346°, dip =  51°, slip-rake =   -1°

'''

        self.assertEqual(expected.encode('utf-8'), out.stdout)
Example #26
0
    def test_script_convert_type_sdr(self):
        with CatchOutput() as out:
            obspy_mopad([
                'convert', '--fancy', '-t', 'sdr',
                ','.join(str(x) for x in self.mt)
            ])
        expected = '''
Fault plane 1: strike =  77°, dip =  89°, slip-rake = -141°
Fault plane 2: strike = 346°, dip =  51°, slip-rake =   -1°
'''
        result = out.stdout[:-1]
        self._normalized_assert_equal(expected, result)
Example #27
0
    def test_script_decompose(self):
        with CatchOutput() as out:
            obspy_mopad(['decompose', '-y', ','.join(str(x) for x in self.mt)])
        expected = '''
Scalar Moment: M0 = 2.61206 Nm (Mw = -5.8)
Moment Tensor: Mnn =  0.091,  Mee = -0.089, Mdd = -0.002,
               Mne =  0.178,  Mnd = -0.155, Med =  0.047    [ x 10 ]


Fault plane 1: strike =  77°, dip =  89°, slip-rake = -141°
Fault plane 2: strike = 346°, dip =  51°, slip-rake =   -1°
'''
        result = out.stdout[:-1]
        self._normalized_assert_equal(expected, result)
Example #28
0
    def test_CatchOutput_IO(self):
        """
        Tests that CatchOutput context manager does not break I/O.
        """
        with CatchOutput():
            fn = tempfile.TemporaryFile(prefix='obspy')

        try:
            fn.write(b'abc')
            fn.seek(0)
            fn.read(3)
            fn.close()
        except OSError as e:
            self.fail('CatchOutput has broken file I/O!\n' + str(e))
Example #29
0
    def test_script(self):
        with open(self.samples_file, 'r') as fh:
            # Testing once is sufficient.
            line = fh.readline()
            longitude, latitude, checked_region = line.strip().split('\t')

            with CatchOutput() as out:
                obspy_flinnengdahl([longitude, latitude])
            region = out.stdout.strip()

            self.assertEqual(region,
                             checked_region,
                             msg='(%s, %s) got %s instead of %s' %
                             (longitude, latitude, region, checked_region))
Example #30
0
    def test_script_convert_type_tensor_large(self):
        with CatchOutput() as out:
            obspy_mopad([
                'convert', '--fancy', '-t', 't',
                ','.join(str(x * 100) for x in self.mt)
            ])
        expected = '''
   Full moment tensor in NED-coordinates:

  /  0.51  1.00 -0.87 \\
  |  1.00 -0.50  0.26  |   x  178.000000
  \ -0.87  0.26 -0.01 /

'''
        self.assertEqual(expected, out.stdout)