Beispiel #1
0
    def test_handle_url_with_json_and_stream_url(self, console, args):
        stream = Mock()
        streams = dict(worst=Mock(), best=stream)
        plugin = Mock(FakePlugin(),
                      module="fake",
                      arguments=[],
                      streams=Mock(return_value=streams))

        with patch("streamlink_cli.main.streamlink",
                   resolve_url=Mock(return_value=plugin)):
            handle_url()
            self.assertEqual(console.msg.mock_calls, [])
            self.assertEqual(console.msg_json.mock_calls,
                             [call(dict(plugin="fake", streams=streams))])
            self.assertEqual(console.error.mock_calls, [])
            if is_py3:
                console.msg_json.mock_calls.clear()

                console.json = False
                handle_url()
                self.assertEqual(console.msg.mock_calls,
                                 [call("{0}", stream.to_manifest_url())])
                self.assertEqual(console.msg_json.mock_calls, [])
                self.assertEqual(console.error.mock_calls, [])
                console.msg_json.mock_calls.clear()
                """ fails
Beispiel #2
0
 def test_rm_stray_tuned_profiles(self, _check_execute_command):
     profiles = {'p1': self.tspec1, 'p2': self.tspec2, 'p3': self.tspec3}
     # for this test, going to use host "a" and put 4 cephadm generated
     # profiles "p1" "p2", "p3" and "who" only two of which should be there ("p1", "p2")
     # as well as a file not generated by cephadm. Only the "p3" and "who"
     # profiles should be removed from the host. This should total to 4
     # calls to check_execute_command, 1 "ls", 2 "rm", and 1 "sysctl --system"
     _check_execute_command.return_value = '\n'.join([
         'p1-cephadm-tuned-profile.conf', 'p2-cephadm-tuned-profile.conf',
         'p3-cephadm-tuned-profile.conf', 'who-cephadm-tuned-profile.conf',
         'dont-touch-me'
     ])
     mgr = FakeMgr(['a', 'b', 'c'], ['a', 'b', 'c'], [], profiles)
     tp = TunedProfileUtils(mgr)
     tp._remove_stray_tuned_profiles(
         'a', self.profiles_to_calls(tp, [self.tspec1, self.tspec2]))
     calls = [
         mock.call('a', ['ls', SYSCTL_DIR]),
         mock.call(
             'a',
             ['rm', '-f', f'{SYSCTL_DIR}/p3-cephadm-tuned-profile.conf']),
         mock.call(
             'a',
             ['rm', '-f', f'{SYSCTL_DIR}/who-cephadm-tuned-profile.conf']),
         mock.call('a', ['sysctl', '--system'])
     ]
     _check_execute_command.assert_has_calls(calls, any_order=True)
Beispiel #3
0
    def test_hls_low_latency_has_prefetch_disable_ads_has_preroll(
            self, mock_log):
        self.subject([
            Playlist(0,
                     [SegmentAd(0),
                      SegmentAd(1),
                      SegmentAd(2),
                      SegmentAd(3)]),
            Playlist(4, [
                Segment(4),
                Segment(5),
                Segment(6),
                Segment(7),
                SegmentPrefetch(8),
                SegmentPrefetch(9)
            ],
                     end=True)
        ],
                     disable_ads=True,
                     low_latency=True)

        self.await_read(read_all=True)
        self.assertEqual(mock_log.info.mock_calls, [
            call("Will skip ad segments"),
            call("Low latency streaming (HLS live edge: 2)"),
            call("Waiting for pre-roll ads to finish, be patient")
        ])
Beispiel #4
0
    def test_handle_stream_with_json_and_stream_url(self, console, args):
        stream = Mock()
        streams = dict(best=stream)
        plugin = Mock(FakePlugin(),
                      module="fake",
                      arguments=[],
                      streams=Mock(return_value=streams))

        handle_stream(plugin, streams, "best")
        self.assertEqual(console.msg.mock_calls, [])
        self.assertEqual(console.msg_json.mock_calls, [call(stream)])
        self.assertEqual(console.error.mock_calls, [])
        if is_py3:
            console.msg_json.mock_calls.clear()

            console.json = False
            handle_stream(plugin, streams, "best")
            self.assertEqual(console.msg.mock_calls,
                             [call("{0}", stream.to_url())])
            self.assertEqual(console.msg_json.mock_calls, [])
            self.assertEqual(console.error.mock_calls, [])
            console.msg.mock_calls.clear()

            stream.to_url.side_effect = TypeError()
            handle_stream(plugin, streams, "best")
            self.assertEqual(console.msg.mock_calls, [])
            self.assertEqual(console.msg_json.mock_calls, [])
            self.assertEqual(
                console.exit.mock_calls,
                [call("The stream specified cannot be translated to a URL")])
Beispiel #5
0
 def test_can_register_retry_handler(self):
     client = mock.Mock()
     limiter = adaptive.register_retry_handler(client)
     self.assertEqual(client.meta.events.register.call_args_list, [
         mock.call('before-send', limiter.on_sending_request),
         mock.call('needs-retry', limiter.on_receiving_response)
     ])
    def test_filtered_logging(self, mock_log):
        segments = self.get_segments(8)
        thread, reader, writer = self.subject(segments, [
            self.get_playlist(0, [0, 1], filtered=True),
            self.get_playlist(2, [2, 3], filtered=False),
            self.get_playlist(4, [4, 5], filtered=True),
            self.get_playlist(6, [6, 7], filtered=False, end=True)
        ])

        self.assertTrue(reader.filter_event.is_set(), "Doesn't let the reader wait if not filtering")

        for i in range(2):
            thread.await_write()
            thread.await_write()
            self.assertEqual(len(mock_log.info.mock_calls), i * 2 + 1)
            self.assertEqual(mock_log.info.mock_calls[i * 2 + 0], call("Filtering out segments and pausing stream output"))
            self.assertFalse(reader.filter_event.is_set(), "Lets the reader wait if filtering")

            thread.await_write()
            thread.await_write()
            self.assertEqual(len(mock_log.info.mock_calls), i * 2 + 2)
            self.assertEqual(mock_log.info.mock_calls[i * 2 + 1], call("Resuming stream output"))
            self.assertTrue(reader.filter_event.is_set(), "Doesn't let the reader wait if not filtering")

            thread.await_read()

        self.assertEqual(
            b"".join(thread.data),
            b"".join(list(itertools.chain(segments[2:4], segments[6:8]))),
            "Correctly filters out segments"
        )
        for i, _ in enumerate(segments):
            self.assertTrue(self.mocks[self.url_segment.format(i)].called, "Downloads all segments")
Beispiel #7
0
 def test_search_caseness(self):
     (stdout, pkgs) = self.patched_search(['LOTUS'])
     self.assertEqual(stdout.write.mock_calls,
                      [mock.call(u'N/S Matched: LOTUS'), mock.call('\n')])
     pkg_names = map(str, pkgs)
     self.assertIn('lotus-3-16.i686', pkg_names)
     self.assertIn('lotus-3-16.x86_64', pkg_names)
Beispiel #8
0
    def test_tracks_added_callback(self, track_lib_mock, lib_mock):
        callback = mock.Mock()
        sp_playlist = spotify.ffi.cast('sp_playlist *', 42)
        playlist = spotify.Playlist._cached(
            self.session, sp_playlist=sp_playlist
        )
        playlist.on(spotify.PlaylistEvent.TRACKS_ADDED, callback)
        sp_tracks = [
            spotify.ffi.cast('sp_track *', 43),
            spotify.ffi.cast('sp_track *', 44),
            spotify.ffi.cast('sp_track *', 45),
        ]
        index = 7

        _PlaylistCallbacks.tracks_added(
            sp_playlist, sp_tracks, len(sp_tracks), index, spotify.ffi.NULL
        )

        callback.assert_called_once_with(playlist, mock.ANY, index)
        tracks = callback.call_args[0][1]
        self.assertEqual(len(tracks), len(sp_tracks))
        self.assertIsInstance(tracks[0], spotify.Track)
        self.assertEqual(tracks[0]._sp_track, sp_tracks[0])
        track_lib_mock.sp_track_add_ref.assert_has_calls(
            [
                mock.call(sp_tracks[0]),
                mock.call(sp_tracks[1]),
                mock.call(sp_tracks[2]),
            ]
        )
Beispiel #9
0
 def test_setdict_alias(self):
     with mock.patch.object(self.settings, 'set') as mock_set:
         self.settings.setdict({'TEST_1': 'value1', 'TEST_2': 'value2'}, 10)
         self.assertEqual(mock_set.call_count, 2)
         calls = [mock.call('TEST_1', 'value1', 10),
                  mock.call('TEST_2', 'value2', 10)]
         mock_set.assert_has_calls(calls, any_order=True)
Beispiel #10
0
    def test_hls_low_latency_no_prefetch_disable_ads_has_preroll(
            self, mock_log):
        daterange = TagDateRangeAd(duration=4)
        self.subject([
            Playlist(
                0, [daterange,
                    Segment(0),
                    Segment(1),
                    Segment(2),
                    Segment(3)]),
            Playlist(
                4, [Segment(4), Segment(5),
                    Segment(6), Segment(7)], end=True)
        ],
                     disable_ads=True,
                     low_latency=True)

        self.await_write(6)
        self.await_read(read_all=True)
        self.assertEqual(mock_log.info.mock_calls, [
            call("Will skip ad segments"),
            call("Low latency streaming (HLS live edge: 2)"),
            call("Waiting for pre-roll ads to finish, be patient"),
            call("This is not a low latency stream")
        ])
Beispiel #11
0
 def test_name(self, mock_log):
     NamedPipe()
     NamedPipe()
     self.assertEqual(mock_log.info.mock_calls, [
         call("Creating pipe streamlinkpipe-12345-1-67890"),
         call("Creating pipe streamlinkpipe-12345-2-67890")
     ])
Beispiel #12
0
    def test_instantiation(self):
        # Instantiate the class.
        dynamodb_class = type(
            'dynamodb', (DynamoDBHighLevelResource, ServiceResource),
            {'meta': self.meta})
        with mock.patch('boto3.dynamodb.transform.TransformationInjector') \
                as mock_injector:
            dynamodb_class(client=self.client)

        # It should have fired the following events upon instantiation.
        event_call_args = self.events.register.call_args_list
        self.assertEqual(
            event_call_args,
            [mock.call(
                'provide-client-params.dynamodb',
                copy_dynamodb_params,
                unique_id='dynamodb-create-params-copy'),
             mock.call(
                'before-parameter-build.dynamodb',
                mock_injector.return_value.inject_condition_expressions,
                unique_id='dynamodb-condition-expression'),
             mock.call(
                'before-parameter-build.dynamodb',
                mock_injector.return_value.inject_attribute_value_input,
                unique_id='dynamodb-attr-value-input'),
             mock.call(
                'after-call.dynamodb',
                mock_injector.return_value.inject_attribute_value_output,
                unique_id='dynamodb-attr-value-output')]
        )
Beispiel #13
0
 def test_setdict_alias(self):
     with mock.patch.object(self.settings, 'set') as mock_set:
         self.settings.setdict({'TEST_1': 'value1', 'TEST_2': 'value2'}, 10)
         self.assertEqual(mock_set.call_count, 2)
         calls = [mock.call('TEST_1', 'value1', 10),
                  mock.call('TEST_2', 'value2', 10)]
         mock_set.assert_has_calls(calls, any_order=True)
Beispiel #14
0
    def test_ceph_volume_no_filter_for_batch(self, _run_cephadm, cephadm_module: CephadmOrchestrator):
        _run_cephadm.return_value = ('{}', '', 0)

        error_message = """cephadm exited with an error code: 1, stderr:/usr/bin/podman:stderr usage: ceph-volume inventory [-h] [--format {plain,json,json-pretty}] [path]/usr/bin/podman:stderr ceph-volume inventory: error: unrecognized arguments: --filter-for-batch
Traceback (most recent call last):
  File "<stdin>", line 6112, in <module>
  File "<stdin>", line 1299, in _infer_fsid
  File "<stdin>", line 1382, in _infer_image
  File "<stdin>", line 3612, in command_ceph_volume
  File "<stdin>", line 1061, in call_throws"""

        with with_host(cephadm_module, 'test'):
            _run_cephadm.reset_mock()
            _run_cephadm.side_effect = OrchestratorError(error_message)

            s = CephadmServe(cephadm_module)._refresh_host_devices('test')
            assert s == 'host test `cephadm ceph-volume` failed: ' + error_message

            assert _run_cephadm.mock_calls == [
                mock.call('test', 'osd', 'ceph-volume',
                          ['--', 'inventory', '--format=json', '--filter-for-batch'], image='',
                          no_fsid=False),
                mock.call('test', 'osd', 'ceph-volume',
                          ['--', 'inventory', '--format=json'], image='',
                          no_fsid=False),
            ]
Beispiel #15
0
    def test_handle_stream_with_json_and_stream_url(self, console, args):
        stream = Mock()
        streams = dict(best=stream)

        plugin = FakePlugin("")
        plugin._streams = streams

        handle_stream(plugin, streams, "best")
        self.assertEqual(console.msg.mock_calls, [])
        self.assertEqual(console.msg_json.mock_calls, [
            call(stream,
                 metadata=dict(id=u"test-id-1234-5678",
                               author=u"Tѥst Āuƭhǿr",
                               category=None,
                               title=u"Test Title"))
        ])
        self.assertEqual(console.error.mock_calls, [])
        console.msg_json.mock_calls *= 0

        console.json = False
        handle_stream(plugin, streams, "best")
        self.assertEqual(console.msg.mock_calls,
                         [call("{0}", stream.to_url())])
        self.assertEqual(console.msg_json.mock_calls, [])
        self.assertEqual(console.error.mock_calls, [])
        console.msg.mock_calls *= 0

        stream.to_url.side_effect = TypeError()
        handle_stream(plugin, streams, "best")
        self.assertEqual(console.msg.mock_calls, [])
        self.assertEqual(console.msg_json.mock_calls, [])
        self.assertEqual(
            console.exit.mock_calls,
            [call("The stream specified cannot be translated to a URL")])
Beispiel #16
0
 def test_short_exception(self, stderr):
     try:
         raise RuntimeError("test exception")
     except RuntimeError:
         print_small_exception("test_short_exception")
         self.assertSequenceEqual(
             [call('RuntimeError: test exception\n'),
              call('\n')], stderr.write.mock_calls)
 def test_register(self):
     event_emitter = mock.Mock(HierarchicalEmitter)
     self.handler.register(event_emitter)
     self.assertEqual(event_emitter.register_last.call_args_list, [
         mock.call('before-parameter-build', self.handler.capture),
         mock.call('request-created', self.handler.capture),
         mock.call('response-received', self.handler.capture),
         mock.call('after-call', self.handler.capture),
         mock.call('after-call-error', self.handler.capture),
     ])
Beispiel #18
0
 def test_hosting_host_single(self, mock_log):
     res, channel, author = self.subject("foo", [(1, "bar", "Bar"), (2, )])
     self.assertFalse(res, "Doesn't stop HLS resolve procedure")
     self.assertEqual(channel, "bar", "Switches channel")
     self.assertEqual(author, "Bar", "Overrides author metadata")
     self.assertEqual(
         mock_log.info.mock_calls,
         [call("foo is hosting bar"),
          call("switching to bar")])
     self.assertEqual(mock_log.error.mock_calls, [],
                      "Doesn't log anything to error")
 def test_send(self):
     client = WebsocketClient(self.session, "wss://localhost:0")
     with patch.object(client, "ws") as mock_ws:
         client.send("foo")
         client.send(b"foo", ABNF.OPCODE_BINARY)
         client.send_json({"foo": "bar", "baz": "qux"})
     self.assertEqual(mock_ws.send.call_args_list, [
         call("foo", ABNF.OPCODE_TEXT),
         call(b"foo", ABNF.OPCODE_BINARY),
         call("{\"foo\":\"bar\",\"baz\":\"qux\"}", ABNF.OPCODE_TEXT),
     ])
Beispiel #20
0
 def test_hosting_host_single_disable(self, mock_log):
     res, channel, channel_id, author = self.subject("foo", [(1, 2, "bar", "Bar")], disable=True)
     self.assertTrue(res, "Stops HLS resolve procedure")
     self.assertEqual(channel, "foo", "Doesn't switch channel")
     self.assertEqual(channel_id, 1, "Doesn't switch channel id")
     self.assertEqual(author, None, "Doesn't override author metadata")
     self.assertEqual(mock_log.info.mock_calls, [
         call("foo is hosting bar"),
         call("hosting was disabled by command line option")
     ])
     self.assertEqual(mock_log.error.mock_calls, [], "Doesn't log anything to error")
Beispiel #21
0
 def test_setup_from_dnf_conf(self, setup_m):
     conf = mock.Mock(debuglevel=2, errorlevel=2, logdir=self.logdir)
     self.logging.setup_from_dnf_conf(conf)
     self.assertEqual(setup_m.call_args, mock.call(dnf.logging.INFO,
                                                   dnf.logging.WARNING,
                                                   self.logdir))
     conf = mock.Mock(debuglevel=6, errorlevel=6, logdir=self.logdir)
     self.logging.setup_from_dnf_conf(conf)
     self.assertEqual(setup_m.call_args, mock.call(dnf.logging.DEBUG,
                                                   dnf.logging.WARNING,
                                                   self.logdir))
Beispiel #22
0
 def test_events_emitted_request_params(self):
     self.request_params.traverse_and_document_shape(
         section=self.doc_structure,
         shape=self.operation_model.input_shape,
         history=[])
     self.assertEqual(self.event_emitter.emit.call_args_list, [
         mock.call('docs.request-params.myservice.SampleOperation.Foo',
                   section=self.doc_structure.get_section('Foo')),
         mock.call(('docs.request-params.myservice.SampleOperation'
                    '.complete-section'),
                   section=self.doc_structure)
     ])
Beispiel #23
0
 def test_register(self):
     event_emitter = mock.Mock(HierarchicalEmitter)
     self.handler.register(event_emitter)
     self.assertEqual(
         event_emitter.register_last.call_args_list,
         [
             mock.call('before-parameter-build', self.handler.capture),
             mock.call('request-created', self.handler.capture),
             mock.call('response-received', self.handler.capture),
             mock.call('after-call', self.handler.capture),
             mock.call('after-call-error', self.handler.capture),
         ]
     )
Beispiel #24
0
    def test_log_current_versions(self, mock_log):
        self.subject(["streamlink", "--loglevel", "info"])
        self.assertEqual(mock_log.debug.mock_calls, [],
                         "Doesn't log anything if not debug logging")

        with patch("sys.platform", "linux"), \
             patch("platform.platform", Mock(return_value="linux")):
            self.subject(["streamlink", "--loglevel", "debug"])
            self.assertEqual(mock_log.debug.mock_calls[:4], [
                call("OS:         linux"),
                call("Python:     python"),
                call("Streamlink: streamlink"),
                call("Requests(requests), Socks(socks), Websocket(websocket)")
            ])
            mock_log.debug.reset_mock()

        with patch("sys.platform", "win32"), \
             patch("platform.system", Mock(return_value="Windows")), \
             patch("platform.release", Mock(return_value="0.0.0")):
            self.subject(["streamlink", "--loglevel", "debug"])
            self.assertEqual(mock_log.debug.mock_calls[:4], [
                call("OS:         Windows 0.0.0"),
                call("Python:     python"),
                call("Streamlink: streamlink"),
                call("Requests(requests), Socks(socks), Websocket(websocket)")
            ])
            mock_log.debug.reset_mock()
Beispiel #25
0
    def test_write_only_strips_until_text_is_found(self):
        self.node.add_child(parser.DataNode('  '))
        tag_child = parser.TagNode('foo')
        tag_child.add_child(parser.DataNode('  '))
        tag_child_2 = parser.TagNode('foo')
        tag_child_2.add_child(parser.DataNode(' foo'))
        tag_child_2.add_child(parser.DataNode(' '))
        tag_child.add_child(tag_child_2)
        self.node.add_child(tag_child)

        self.node.write(self.doc)

        calls = [mock.call('foo'), mock.call(' ')]
        self.doc.handle_data.assert_has_calls(calls)
Beispiel #26
0
    def test_attach_to_logs(self):
        project = mock.create_autospec(Project)
        log_printer = mock.create_autospec(LogPrinter, containers=[])
        service_names = ['web', 'db']
        timeout = 12

        with mock.patch('compose.cli.main.signal', autospec=True) as mock_signal:
            attach_to_logs(project, log_printer, service_names, timeout)

        assert mock_signal.signal.mock_calls == [
            mock.call(mock_signal.SIGINT, mock.ANY),
            mock.call(mock_signal.SIGTERM, mock.ANY),
        ]
        log_printer.run.assert_called_once_with()
Beispiel #27
0
    def test_hls_low_latency_no_prefetch(self, mock_log):
        self.subject([
            Playlist(0, [Segment(0), Segment(1), Segment(2), Segment(3)]),
            Playlist(4, [Segment(4), Segment(5), Segment(6), Segment(7)], end=True)
        ], disable_ads=False, low_latency=True)

        self.assertTrue(self.session.get_plugin_option("twitch", "low-latency"))
        self.assertFalse(self.session.get_plugin_option("twitch", "disable-ads"))

        self.await_write(6)
        self.await_read(read_all=True)
        self.assertEqual(mock_log.info.mock_calls, [
            call("Low latency streaming (HLS live edge: 2)"),
            call("This is not a low latency stream")
        ])
Beispiel #28
0
    def test_attach_to_logs(self):
        project = mock.create_autospec(Project)
        log_printer = mock.create_autospec(LogPrinter, containers=[])
        service_names = ['web', 'db']
        timeout = 12

        with mock.patch('compose.cli.main.signal',
                        autospec=True) as mock_signal:
            attach_to_logs(project, log_printer, service_names, timeout)

        assert mock_signal.signal.mock_calls == [
            mock.call(mock_signal.SIGINT, mock.ANY),
            mock.call(mock_signal.SIGTERM, mock.ANY),
        ]
        log_printer.run.assert_called_once_with()
Beispiel #29
0
 def test_get_streams(self, parse_variant_playlist):
     session = Streamlink()
     Mjunoon.bind(session, "test")
     script_text = """
     <script id="playerScript"  src="playerAssets/js/player.js?v=2.2&streamUrl=https://vod.mjunoon.tv:8181/live/41/41.m3u8&streamUrl=https://vod.mjunoon.tv:8181/live/17/17.m3u8"></script>
     """
     parse_variant_playlist.items.return_value = [("test", Mock())]
     with requests_mock.Mocker() as rmock:
         rmock.get("https://mjunoon.tv/news-live", text=script_text)
         plugin = Mjunoon("https://mjunoon.tv/news-live")
         _ = list(plugin.streams())
         self.assertSequenceEqual(
             [call(ANY, "https://vod.mjunoon.tv:8181/live/41/41.m3u8", params=dict(id=1), verify=False),
              call(ANY, "https://vod.mjunoon.tv:8181/live/17/17.m3u8", params=dict(id=2), verify=False)],
             [parse_variant_playlist.mock_calls[0], parse_variant_playlist.mock_calls[3]])
Beispiel #30
0
    def test_hls_no_low_latency_no_prefetch(self, mock_logging):
        streams = ["[{0}]".format(i).encode("ascii") for i in range(10)]
        playlists = [
            self.getPlaylist(0, [0, 1, 2, 3], []),
            self.getPlaylist(4, [4, 5, 6, 7], []) + "#EXT-X-ENDLIST\n"
        ]
        streamlink, result, mocked = self.get_result(streams, playlists, low_latency=True)

        self.assertTrue(streamlink.get_plugin_option("twitch", "low-latency"))
        self.assertFalse(streamlink.get_plugin_option("twitch", "disable-ads"))

        mock_logging.info.assert_has_calls([
            call("Low latency streaming (HLS live edge: 2)"),
            call("This is not a low latency stream")
        ])
Beispiel #31
0
 def test_events_emitted_response_example(self):
     self.response_example.traverse_and_document_shape(
         section=self.doc_structure,
         shape=self.operation_model.input_shape,
         history=[])
     structure_section = self.doc_structure.get_section('structure-value')
     print(self.event_emitter.emit.call_args_list[0][1]['section'].name)
     self.assertEqual(self.event_emitter.emit.call_args_list, [
         mock.call('docs.response-example.myservice.SampleOperation.Foo',
                   section=structure_section.get_section('Foo').get_section(
                       'member-value')),
         mock.call(('docs.response-example.myservice.SampleOperation'
                    '.complete-section'),
                   section=self.doc_structure)
     ])
Beispiel #32
0
 def test_get_streams(self, parse_variant_playlist):
     session = Streamlink()
     Mjunoon.bind(session, "test")
     script_text = """
     <script id="playerScript"  src="playerAssets/js/player.js?v=2.2&streamUrl=https://vod.mjunoon.tv:8181/live/41/41.m3u8&streamUrl=https://vod.mjunoon.tv:8181/live/17/17.m3u8"></script>
     """  # noqa: E501
     parse_variant_playlist.items.return_value = [("test", Mock())]
     with requests_mock.Mocker() as rmock:
         rmock.get("https://mjunoon.tv/news-live", text=script_text)
         plugin = Mjunoon("https://mjunoon.tv/news-live")
         _ = list(plugin.streams())
         self.assertSequenceEqual(
             [call(ANY, "https://vod.mjunoon.tv:8181/live/41/41.m3u8", params=dict(id=1), verify=False),
              call(ANY, "https://vod.mjunoon.tv:8181/live/17/17.m3u8", params=dict(id=2), verify=False)],
             [parse_variant_playlist.mock_calls[0], parse_variant_playlist.mock_calls[3]])
Beispiel #33
0
    def test_hls_low_latency_has_prefetch_has_preroll(self, mock_log):
        daterange = TagDateRangeAd(duration=4)
        thread, segments = self.subject([
            Playlist(
                0, [daterange,
                    Segment(0),
                    Segment(1),
                    Segment(2),
                    Segment(3)]),
            Playlist(4, [
                Segment(4),
                Segment(5),
                Segment(6),
                Segment(7),
                SegmentPrefetch(8),
                SegmentPrefetch(9)
            ],
                     end=True)
        ],
                                        disable_ads=False,
                                        low_latency=True)

        self.await_write(8)
        self.assertEqual(self.await_read(read_all=True),
                         self.content(segments, cond=lambda s: s.num > 1),
                         "Skips first two segments due to reduced live-edge")
        self.assertFalse(
            any([self.called(s) for s in segments.values() if s.num < 2]),
            "Skips first two preroll segments")
        self.assertTrue(
            all([self.called(s) for s in segments.values() if s.num >= 2]),
            "Downloads all remaining segments")
        self.assertEqual(mock_log.info.mock_calls,
                         [call("Low latency streaming (HLS live edge: 2)")])
Beispiel #34
0
 def test_create_transfer_manager(self):
     client = object()
     config = TransferConfig()
     osutil = OSUtils()
     with mock.patch('ibm_boto3.s3.transfer.TransferManager') as manager:
         create_transfer_manager(client, config, osutil)
         assert manager.call_args == mock.call(client, config, osutil, None)
Beispiel #35
0
    def test_userconfirm(self, input_fnc):
        # with defaultyes==False
        input_fnc.return_value = 'y'
        self.assertTrue(self.output.userconfirm())
        self.assertEqual(input_fnc.call_args, mock.call(u'Is this ok [y/N]: '))

        input_fnc.return_value = 'n'
        self.assertFalse(self.output.userconfirm())

        input_fnc.return_value = ''
        self.assertFalse(self.output.userconfirm())

        input_fnc.side_effect = self._keyboard_interrupt
        input_fnc.return_value = 'y'
        self.assertFalse(self.output.userconfirm())

        input_fnc.side_effect = self._eof_error
        self.assertFalse(self.output.userconfirm())

        # with defaultyes==True
        self.output.conf.defaultyes = True
        input_fnc.side_effect = None
        input_fnc.return_value = ''
        self.assertTrue(self.output.userconfirm())

        input_fnc.side_effect = self._keyboard_interrupt
        input_fnc.return_value = ''
        self.assertFalse(self.output.userconfirm())

        input_fnc.side_effect = self._eof_error
        self.assertTrue(self.output.userconfirm())
    def test_parse_stream_progress(self):
        # Configure Mock response with progress
        test_docker_response_progress = {
            "status": "Pushing",
            "progress_detail": {
                "current": 655337,
                "start": 1413994898,
                "total": 20412416
            },
            "id": "51783549ce98",
            "progress": "[=>                                                 ] 790.1 kB/19.99 MB 30s"
        }
        test_docker_response_encoded = json.dumps(test_docker_response_progress).encode('utf-8')
        test_values_list = [test_docker_response_encoded]

        mock_response_attributes = {"__iter__.return_value": iter(test_values_list)}
        self.mock_object_response.configure_mock(**mock_response_attributes)

        # Configure Normalized keys with return value
        mock_attributes_normalize_keys = {"return_value": test_docker_response_progress}
        self.mock_utils_normalize_keys.configure_mock(**mock_attributes_normalize_keys)

        # Configure Mock for Display Progress
        attributes_display_progress = {"return_value": test_docker_response_progress}
        self.mock_display_progress.configure_mock(**attributes_display_progress)

        parse_stream(self.mock_object_response)

        self.mock_display_progress.assert_has_call(mock.call(test_docker_response_progress))
Beispiel #37
0
class TestTwitchReruns(unittest.TestCase):
    log_call = call("Reruns were disabled by command line option")

    def subject(self, **params):
        with patch(
                "streamlink.plugins.twitch.TwitchAPI.stream_metadata") as mock:
            mock.return_value = None if params.pop("offline", False) else {
                "type": params.pop("stream_type", "live")
            }
            session = Streamlink()
            Twitch.bind(session, "tests.plugins.test_twitch")
            plugin = Twitch("https://www.twitch.tv/foo")
            plugin.options.set("disable-reruns", params.pop("disable", True))

            return plugin._check_for_rerun()

    def test_disable_reruns_live(self, mock_log):
        self.assertFalse(self.subject())
        self.assertNotIn(self.log_call, mock_log.info.call_args_list)

    def test_disable_reruns_not_live(self, mock_log):
        self.assertTrue(self.subject(stream_type="rerun"))
        self.assertIn(self.log_call, mock_log.info.call_args_list)

    def test_disable_reruns_offline(self, mock_log):
        self.assertFalse(self.subject(offline=True))
        self.assertNotIn(self.log_call, mock_log.info.call_args_list)

    def test_enable_reruns(self, mock_log):
        self.assertFalse(self.subject(stream_type="rerun", disable=False))
        self.assertNotIn(self.log_call, mock_log.info.call_args_list)
Beispiel #38
0
    def test_cookie_store_clear_filter(self):
        session = Mock()
        session.http.cookies = requests.cookies.RequestsCookieJar()

        Plugin.bind(session, 'tests.test_plugin')
        Plugin.cache = Mock()
        Plugin.cache.get_all.return_value = {
            "__cookie:test-name:test.se:80:/":
            self._create_cookie_dict("test-name", "test-value", None),
            "__cookie:test-name2:test.se:80:/":
            self._create_cookie_dict("test-name2", "test-value2", None)
        }
        plugin = Plugin("http://test.se")

        # non-empty cookiejar
        self.assertTrue(len(session.http.cookies.get_dict()) > 0)

        plugin.clear_cookies(lambda c: c.name.endswith("2"))
        self.assertSequenceEqual(
            Plugin.cache.set.mock_calls,
            [call("__cookie:test-name2:test.se:80:/", None, 0)])
        self.assertSequenceEqual(
            list(map(self._cookie_to_dict, session.http.cookies)), [
                self._cookie_to_dict(
                    requests.cookies.create_cookie(
                        "test-name", "test-value", domain="test.se"))
            ])
Beispiel #39
0
    def test_parse_stream_status(self):
        # Configure Mock response with status
        test_docker_response_status = {
            "status": "Download complete",
            "progress_detail": {},
            "id": "12340981vas"
        }
        test_docker_response_encoded = json.dumps(
            test_docker_response_status).encode('utf-8')
        test_values_list = [test_docker_response_encoded]

        mock_response_attributes = {
            "__iter__.return_value": iter(test_values_list)
        }
        self.mock_object_response.configure_mock(**mock_response_attributes)

        # Configure Normalized keys with return value
        mock_attributes_normalize_keys = {
            "return_value": test_docker_response_status
        }
        self.mock_utils_normalize_keys.configure_mock(
            **mock_attributes_normalize_keys)

        parse_stream(self.mock_object_response)

        self.mock_display_progress.assert_has_call(
            mock.call(test_docker_response_status))
    def test_parse_stream_json(self):
        # Defined json response for testing
        test_response_json = {"test": "test messsage", "foo": "bar"}
        test_response_json_encoded = json.dumps(test_response_json).encode('utf-8')
        test_values_list = [test_response_json_encoded]

        mock_response_attributes = {"__iter__.return_value": iter(test_values_list)}
        self.mock_object_response.configure_mock(**mock_response_attributes)

        # Configure normalize keys with dict
        mock_attributes_normalize_keys = {"return_value": test_response_json}
        self.mock_utils_normalize_keys.configure_mock(**mock_attributes_normalize_keys)

        parse_stream(self.mock_object_response)

        self.mock_utils_stdout.write.called_once_with(mock.call(test_response_json))
        self.mock_utils_stdout.flush.called_once_with(mock.call())
Beispiel #41
0
    def test_arguments(self):
        from streamlink_cli.main import setup_plugin_args
        session = Streamlink()
        parser = MagicMock()
        plugin_parser = MagicMock()
        parser.add_argument_group = MagicMock(return_value=plugin_parser)

        session.plugins = {
            'tvplayer': TVPlayer
        }

        setup_plugin_args(session, parser)

        self.assertSequenceEqual(plugin_parser.add_argument.mock_calls,
                                 [call('--tvplayer-email', metavar="EMAIL", help=ANY),
                                  call('--tvplayer-password', metavar="PASSWORD", help=ANY)],
                                 )
Beispiel #42
0
    def test_cookie_store_clear(self):
        session = Mock()
        session.http.cookies = requests.cookies.RequestsCookieJar()

        Plugin.bind(session, 'tests.test_plugin')
        Plugin.cache = Mock()
        Plugin.cache.get_all.return_value = {
            "__cookie:test-name:test.se:80:/": self._create_cookie_dict("test-name", "test-value", None),
            "__cookie:test-name2:test.se:80:/": self._create_cookie_dict("test-name2", "test-value2", None)
        }
        plugin = Plugin("http://test.se")

        # non-empty cookiejar
        self.assertTrue(len(session.http.cookies.get_dict()) > 0)


        plugin.clear_cookies()
        self.assertSequenceEqual(
            Plugin.cache.set.mock_calls,
            [call("__cookie:test-name:test.se:80:/", None, 0),
             call("__cookie:test-name2:test.se:80:/", None, 0)])
        self.assertSequenceEqual(session.http.cookies, [])
Beispiel #43
0
    def test_stream_open_video_audio(self, muxer, reader):
        stream = DASHStream(self.session, Mock(), Mock(id=1, mimeType="video/mp4"), Mock(id=2, mimeType="audio/mp3", lang='en'))
        open_reader = reader.return_value = Mock()

        stream.open()

        self.assertSequenceEqual(reader.mock_calls, [call(stream, 1, "video/mp4"),
                                                     call().open(),
                                                     call(stream, 2, "audio/mp3"),
                                                     call().open()])
        self.assertSequenceEqual(muxer.mock_calls, [call(self.session, open_reader, open_reader, copyts=True),
                                                    call().open()])
    def test_parse_stream_stream(self):
        # Configure Mock response with stream
        test_docker_response_stream = {
            "stream": "test stream"
        }
        test_docker_response_encoded = json.dumps(test_docker_response_stream).encode('utf-8')
        test_values_list = [test_docker_response_encoded]

        mock_response_attributes = {"__iter__.return_value": iter(test_values_list)}
        self.mock_object_response.configure_mock(**mock_response_attributes)

        # Configure Normalized keys with return value
        mock_attributes_normalize_keys = {"return_value": test_docker_response_stream}
        self.mock_utils_normalize_keys.configure_mock(**mock_attributes_normalize_keys)

        parse_stream(self.mock_object_response)

        self.mock_display_stream.assert_has_call(mock.call(test_docker_response_stream))
    def test_parse_stream_status(self):
        # Configure Mock response with status
        test_docker_response_status = {
            "status": "Download complete",
            "progress_detail": {},
            "id": "12340981vas"
        }
        test_docker_response_encoded = json.dumps(test_docker_response_status).encode('utf-8')
        test_values_list = [test_docker_response_encoded]

        mock_response_attributes = {"__iter__.return_value": iter(test_values_list)}
        self.mock_object_response.configure_mock(**mock_response_attributes)

        # Configure Normalized keys with return value
        mock_attributes_normalize_keys = {"return_value": test_docker_response_status}
        self.mock_utils_normalize_keys.configure_mock(**mock_attributes_normalize_keys)

        parse_stream(self.mock_object_response)

        self.mock_display_progress.assert_has_call(mock.call(test_docker_response_status))
Beispiel #46
0
    def test_cookie_store_clear_filter(self):
        session = Mock()
        session.http.cookies = requests.cookies.RequestsCookieJar()

        Plugin.bind(session, 'tests.test_plugin')
        Plugin.cache = Mock()
        Plugin.cache.get_all.return_value = {
            "__cookie:test-name:test.se:80:/": self._create_cookie_dict("test-name", "test-value", None),
            "__cookie:test-name2:test.se:80:/": self._create_cookie_dict("test-name2", "test-value2", None)
        }
        plugin = Plugin("http://test.se")

        # non-empty cookiejar
        self.assertTrue(len(session.http.cookies.get_dict()) > 0)


        plugin.clear_cookies(lambda c: c.name.endswith("2"))
        self.assertSequenceEqual(
            Plugin.cache.set.mock_calls,
            [call("__cookie:test-name2:test.se:80:/", None, 0)])
        self.assertSequenceEqual(
            list(map(self._cookie_to_dict, session.http.cookies)),
            [self._cookie_to_dict(requests.cookies.create_cookie("test-name", "test-value", domain="test.se"))]
        )