instance_id
stringlengths
10
57
patch
stringlengths
261
37.7k
repo
stringlengths
7
53
base_commit
stringlengths
40
40
hints_text
stringclasses
301 values
test_patch
stringlengths
212
2.22M
problem_statement
stringlengths
23
37.7k
version
stringclasses
1 value
environment_setup_commit
stringlengths
40
40
FAIL_TO_PASS
listlengths
1
4.94k
PASS_TO_PASS
listlengths
0
7.82k
meta
dict
created_at
stringlengths
25
25
license
stringclasses
8 values
__index_level_0__
int64
0
6.41k
stfc__fparser-378
diff --git a/CHANGELOG.md b/CHANGELOG.md index 558dbde..410780d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,6 +18,9 @@ Modifications by (in alphabetical order): * P. Vitt, University of Siegen, Germany * A. Voysey, UK Met Office +15/09/2022 PR #378 for #375. Permit source files containing only comments + to be parsed. + 12/09/2022 PR #374 for #373. Removes @staticmethod decorator added to Stmt_Function_Stmt.tostr() in error. diff --git a/src/fparser/two/Fortran2003.py b/src/fparser/two/Fortran2003.py index 8b5b726..d63f7ce 100644 --- a/src/fparser/two/Fortran2003.py +++ b/src/fparser/two/Fortran2003.py @@ -290,6 +290,7 @@ class Program(BlockBase): # R201 """ content = [] add_comments_includes_directives(content, reader) + comments = content != [] try: while True: obj = Program_Unit(reader) @@ -304,7 +305,12 @@ class Program(BlockBase): # R201 # (via Main_Program0) with a program containing no program # statement as this is optional in Fortran. # - return BlockBase.match(Main_Program0, [], None, reader) + result = BlockBase.match(Main_Program0, [], None, reader) + if not result and comments: + # This program only contains comments. + return (content,) + else: + return result except StopIteration: # Reader has no more lines. pass
stfc/fparser
a9c7a7df29b96cf8d4e7c6d6a80f6b39aa946291
diff --git a/src/fparser/two/tests/fortran2003/test_program_r201.py b/src/fparser/two/tests/fortran2003/test_program_r201.py index cb33f6e..aa0f18b 100644 --- a/src/fparser/two/tests/fortran2003/test_program_r201.py +++ b/src/fparser/two/tests/fortran2003/test_program_r201.py @@ -1,4 +1,4 @@ -# Copyright (c) 2018-2019 Science and Technology Facilities Council +# Copyright (c) 2018-2022 Science and Technology Facilities Council # All rights reserved. @@ -58,6 +58,17 @@ def test_empty_input(f2003_create): assert str(ast) == "" +def test_only_comments(f2003_create): + """Test that a file containing only comments can be parsed + successfully + + """ + code = "! comment1\n! comment2" + reader = get_reader(code, ignore_comments=False) + ast = Program(reader) + assert code in str(ast) + + # Test single program units
Parsing of comment-only files Hi, fparser2 is currently unable to parse comment-only files. I appreciate that it's debatable whether it should, however, I have one admittedly very specific use-case where I may end up splitting source-files into pieces before parsing them individually (each of those pieces valid and complete fortran program units -- or only comments). It's easy enough to work around this, of course, but I was wondering if you consider this to be something that should be working in general? ``` from pathlib import Path fcode = """ ! Some file ! that has only comments ! for whatever reason """.strip() Path('/tmp/myfile.F90').write_text(fcode) ``` ``` from fparser.two.parser import ParserFactory from fparser.common.readfortran import FortranFileReader f2008_parser = ParserFactory().create(std="f2008") reader = FortranFileReader("/tmp/myfile.F90", ignore_comments=False) parse_tree = f2008_parser(reader) print(parse_tree) ``` ``` --------------------------------------------------------------------------- NoMatchError Traceback (most recent call last) File ~/loki/nabr-lightweight-sourcefiles/loki_env/lib/python3.8/site-packages/fparser/two/Fortran2003.py:237, in Program.__new__(cls, string) 236 try: --> 237 return Base.__new__(cls, string) 238 except NoMatchError: 239 # At the moment there is no useful information provided by 240 # NoMatchError so we pass on an empty string. File ~/loki/nabr-lightweight-sourcefiles/loki_env/lib/python3.8/site-packages/fparser/two/utils.py:428, in Base.__new__(cls, string, parent_cls) 427 errmsg = f"{cls.__name__}: '{string}'" --> 428 raise NoMatchError(errmsg) NoMatchError: at line 3 >>>! for whatever reason During handling of the above exception, another exception occurred: FortranSyntaxError Traceback (most recent call last) Untitled-1.ipynb Cell 3 in <cell line: 2>() <a href='vscode-notebook-cell:Untitled-1.ipynb?jupyter-notebook#W1sdW50aXRsZWQ%3D?line=0'>1</a> reader = FortranFileReader("/tmp/myfile.F90", ignore_comments=False) ----> <a href='vscode-notebook-cell:Untitled-1.ipynb?jupyter-notebook#W1sdW50aXRsZWQ%3D?line=1'>2</a> parse_tree = f2008_parser(reader) <a href='vscode-notebook-cell:Untitled-1.ipynb?jupyter-notebook#W1sdW50aXRsZWQ%3D?line=2'>3</a> print(parse_tree) File ~/loki/nabr-lightweight-sourcefiles/loki_env/lib/python3.8/site-packages/fparser/two/Fortran2003.py:241, in Program.__new__(cls, string) 237 return Base.__new__(cls, string) 238 except NoMatchError: 239 # At the moment there is no useful information provided by 240 # NoMatchError so we pass on an empty string. --> 241 raise FortranSyntaxError(string, "") 242 except InternalSyntaxError as excinfo: 243 # InternalSyntaxError is used when a syntax error has been 244 # found in a rule that does not have access to the reader 245 # object. This is then re-raised here as a 246 # FortranSyntaxError, adding the reader object (which 247 # provides line number information). 248 raise FortranSyntaxError(string, excinfo) FortranSyntaxError: at line 3 >>>! for whatever reason ``` Just to demonstrate that this parses fine once I add some Fortran afterwards: ``` fcode += """ subroutine main end """.rstrip() Path('/tmp/myotherfile.F90').write_text(fcode) ``` ``` reader = FortranFileReader("/tmp/myotherfile.F90", ignore_comments=False) parse_tree = f2008_parser(reader) print(parse_tree) ! Some file ! that has only comments ! for whatever reason SUBROUTINE main END ``` FWIW: Out of curiosity I had a look at what compilers do with this: gfortran, ifort, ifx parse this without problems, nvfortran is the only one at least printing a warning stating that this file is empty. All generate `.o` files, though.
0.0
a9c7a7df29b96cf8d4e7c6d6a80f6b39aa946291
[ "src/fparser/two/tests/fortran2003/test_program_r201.py::test_only_comments" ]
[ "src/fparser/two/tests/fortran2003/test_program_r201.py::test_empty_input", "src/fparser/two/tests/fortran2003/test_program_r201.py::test_single", "src/fparser/two/tests/fortran2003/test_program_r201.py::test_single_with_end_name", "src/fparser/two/tests/fortran2003/test_program_r201.py::test_single_error1", "src/fparser/two/tests/fortran2003/test_program_r201.py::test_single_error2", "src/fparser/two/tests/fortran2003/test_program_r201.py::test_multiple", "src/fparser/two/tests/fortran2003/test_program_r201.py::test_multiple_error2", "src/fparser/two/tests/fortran2003/test_program_r201.py::test_multiple_error3", "src/fparser/two/tests/fortran2003/test_program_r201.py::test_missing_prog", "src/fparser/two/tests/fortran2003/test_program_r201.py::test_comment0", "src/fparser/two/tests/fortran2003/test_program_r201.py::test_comment1", "src/fparser/two/tests/fortran2003/test_program_r201.py::test_comment2", "src/fparser/two/tests/fortran2003/test_program_r201.py::test_comment3", "src/fparser/two/tests/fortran2003/test_program_r201.py::test_comment4", "src/fparser/two/tests/fortran2003/test_program_r201.py::test_include0", "src/fparser/two/tests/fortran2003/test_program_r201.py::test_include1", "src/fparser/two/tests/fortran2003/test_program_r201.py::test_mix" ]
{ "failed_lite_validators": [ "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2022-09-14 16:20:06+00:00
bsd-3-clause
5,735
stfc__fparser-381
diff --git a/CHANGELOG.md b/CHANGELOG.md index e2a372b..6b6df97 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,6 +18,8 @@ Modifications by (in alphabetical order): * P. Vitt, University of Siegen, Germany * A. Voysey, UK Met Office +13/10/2022 PR #381 for #298. Fix F2008 allocate statement with arguments. + 20/09/2022 PR #376 for #349. Add support for use association to the symbol table. @@ -30,6 +32,8 @@ Modifications by (in alphabetical order): 05/09/2022 PR #372 fix for whitespace being lost when Format_Item_List is contained within parentheses. +02/09/2022 PR #356 - add support for the mold allocate parameter. + 11/08/2022 PR #368 for #367. Add support for visiting tuples in walk() utility. @@ -47,8 +51,6 @@ Modifications by (in alphabetical order): 20/06/2022 PR #345 - add fparser2 performance benchmark in the scripts folder. -02/09/2022 PR #356 - add support for the mold allocate parameter. - ## Release 0.0.16 (16/06/2022) ## 14/06/2022 PR #337 towards #312 (performance improvements). Removes some diff --git a/src/fparser/two/Fortran2003.py b/src/fparser/two/Fortran2003.py index bc7b7f9..4623784 100644 --- a/src/fparser/two/Fortran2003.py +++ b/src/fparser/two/Fortran2003.py @@ -4853,28 +4853,53 @@ class Allocate_Stmt(StmtBase): # R623 subclass_names = [] use_names = ["Type_Spec", "Allocation_List", "Alloc_Opt_List"] - @staticmethod - def match(string): + @classmethod + def match(cls, string): + """ + Attempts to match the supplied string as an Allocate_Stmt. + + :param str string: the string to attempt to match. + + :returns: A 2-tuple giving the Type_Spec and Allocation_List if the \ + match is successful, None otherwise. + :rtype: Optional[ \ + Tuple[Optional[:py:class:`fparser.two.Fortran2003.Type_Spec`], \ + :py:class:`fparser.two.Fortran2003.Allocation_List`]] + """ if string[:8].upper() != "ALLOCATE": - return + return None line = string[8:].lstrip() if not line or line[0] != "(" or line[-1] != ")": - return + return None line, repmap = string_replace_map(line[1:-1].strip()) - i = line.find("::") + idx = line.find("::") spec = None - if i != -1: - spec = Type_Spec(repmap(line[:i].rstrip())) - line = line[i + 2 :].lstrip() - i = line.find("=") + if idx != -1: + spec = Type_Spec(repmap(line[:idx].rstrip())) + line = line[idx + 2 :].lstrip() + idx = line.find("=") opts = None - if i != -1: - j = line[:i].rfind(",") - assert j != -1, repr((i, j, line)) - opts = Alloc_Opt_List(repmap(line[j + 1 :].lstrip())) - line = line[:j].rstrip() + if idx != -1: + jdx = line[:idx].rfind(",") + if jdx == -1: + # There must be at least one positional argument before any + # named arguments. + return None + # Use the class 'alloc_opt_list' property to ensure we use the + # correct class depending on whether 'cls' is associated with + # Fortran2003 or Fortran2008. + opts = cls.alloc_opt_list()(repmap(line[jdx + 1 :].lstrip())) + line = line[:jdx].rstrip() return spec, Allocation_List(repmap(line)), opts + @classmethod + def alloc_opt_list(cls): + """ + :returns: the Fortran2003 flavour of Alloc_Opt_List. + :rtype: type + """ + return Alloc_Opt_List + def tostr(self): spec, lst, opts = self.items if spec is not None: diff --git a/src/fparser/two/Fortran2008.py b/src/fparser/two/Fortran2008.py index 31a9646..6d5f8ea 100644 --- a/src/fparser/two/Fortran2008.py +++ b/src/fparser/two/Fortran2008.py @@ -760,6 +760,14 @@ class Allocate_Stmt(Allocate_Stmt_2003): # R626 subclass_names = [] use_names = ["Type_Spec", "Allocation_List", "Alloc_Opt_List"] + @classmethod + def alloc_opt_list(cls): + """ + :returns: the Fortran2008 flavour of Alloc_Opt_List. + :rtype: type + """ + return Alloc_Opt_List + class If_Stmt(If_Stmt_2003): # R837 """
stfc/fparser
b0bc4b5b9fb39c4a3d6ca69f75fa55aa6a6ca7ea
diff --git a/src/fparser/two/tests/fortran2003/test_allocate_stmt_r623.py b/src/fparser/two/tests/fortran2003/test_allocate_stmt_r623.py index 1290b23..263fe4c 100644 --- a/src/fparser/two/tests/fortran2003/test_allocate_stmt_r623.py +++ b/src/fparser/two/tests/fortran2003/test_allocate_stmt_r623.py @@ -37,13 +37,15 @@ import pytest from fparser.two.utils import NoMatchError -from fparser.two.Fortran2003 import Allocate_Stmt, Alloc_Opt +from fparser.two.Fortran2003 import Allocate_Stmt, Alloc_Opt, Alloc_Opt_List @pytest.mark.usefixtures("f2003_create") def test_allocate_stmt(): """Tests for the allocate statement: R623.""" tcls = Allocate_Stmt + assert tcls.alloc_opt_list() == Alloc_Opt_List + obj = tcls("allocate(a,b)") assert isinstance(obj, tcls), repr(obj) assert str(obj) == "ALLOCATE(a, b)" @@ -55,6 +57,31 @@ def test_allocate_stmt(): assert str(obj) == "ALLOCATE(REAL(KIND = 8)::a, STAT = b, SOURCE = c // d)" [email protected]("f2003_create") +def test_allocate_no_match(): + """Tests that the expected NoMatchError is raised if there are problems.""" + tcls = Allocate_Stmt + # Missing parenthesis. + with pytest.raises(NoMatchError) as err: + tcls("allocate(var(3)") + assert "allocate(var(3)" in str(err.value) + with pytest.raises(NoMatchError) as err: + tcls("allocate var(3))") + assert "allocate var(3))" in str(err.value) + # Misspelt key word. + with pytest.raises(NoMatchError) as err: + tcls("allocte(var(3))") + assert "allocte(var(3))" in str(err.value) + # No arguments. + with pytest.raises(NoMatchError) as err: + tcls("allocate()") + assert "allocate()" in str(err.value) + # Missing positional argument. + with pytest.raises(NoMatchError) as err: + tcls("allocate(stat=ierr)") + assert "allocate(stat=ierr)" in str(err.value) + + @pytest.mark.usefixtures("f2003_create") def test_alloc_opt(): """Tests for the various forms of alloc-opt: R624.""" diff --git a/src/fparser/two/tests/fortran2008/test_alloc_opt_r627.py b/src/fparser/two/tests/fortran2008/test_alloc_opt_r627.py index 914656c..fd8ec2a 100644 --- a/src/fparser/two/tests/fortran2008/test_alloc_opt_r627.py +++ b/src/fparser/two/tests/fortran2008/test_alloc_opt_r627.py @@ -45,7 +45,7 @@ test for. """ import pytest -from fparser.two.Fortran2008 import Allocate_Stmt, Alloc_Opt +from fparser.two.Fortran2008 import Allocate_Stmt, Alloc_Opt, Alloc_Opt_List @pytest.mark.usefixtures("f2008_create") @@ -61,5 +61,9 @@ def test_allocate_stmt(): """Check that the Fortran2008 version of allocate has picked up the version of Alloc_Opt that supports MOLD.""" obj = Allocate_Stmt("allocate(b, mold=c)") + assert obj.alloc_opt_list() == Alloc_Opt_List assert isinstance(obj, Allocate_Stmt), repr(obj) assert str(obj) == "ALLOCATE(b, MOLD = c)" + obj = Allocate_Stmt("allocate(b, mold=c, stat=ierr)") + assert isinstance(obj, Allocate_Stmt), repr(obj) + assert str(obj) == "ALLOCATE(b, MOLD = c, STAT = ierr)"
Allocate with mold= parameter This is valid Fortran, but not accepted by fparser: ``` subroutine a(b1) integer, dimension(:,:), allocatable :: b1 integer, dimension(:,:), allocatable :: a1 allocate(a1, mold=b1) end subroutine a ``` Supporting the `mold` argument makes it easier to create the kernel-extraction driver (since we can then allocate variables without having to analyse the number of dimensions). It's not urgent, since I have a work around.
0.0
b0bc4b5b9fb39c4a3d6ca69f75fa55aa6a6ca7ea
[ "src/fparser/two/tests/fortran2003/test_allocate_stmt_r623.py::test_allocate_stmt", "src/fparser/two/tests/fortran2003/test_allocate_stmt_r623.py::test_allocate_no_match", "src/fparser/two/tests/fortran2008/test_alloc_opt_r627.py::test_allocate_stmt" ]
[ "src/fparser/two/tests/fortran2003/test_allocate_stmt_r623.py::test_alloc_opt", "src/fparser/two/tests/fortran2008/test_alloc_opt_r627.py::test_alloc_opt" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2022-10-11 15:17:40+00:00
bsd-3-clause
5,736
stfc__fparser-387
diff --git a/CHANGELOG.md b/CHANGELOG.md index 613d94f..f6c59c9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,9 @@ Modifications by (in alphabetical order): * A. Voysey, UK Met Office +01/02/2023 PR #387 for #386. Support extension to permit in-line '!' + comments in fixed-format Fortran. + 30/11/2022 PR #382 for #264. Ignore quotation marks in in-line comments. 18/10/2022 PR #380 towards #379. Improve support for operators and symbol diff --git a/doc/fparser.rst b/doc/fparser.rst index ff091cd..f805166 100644 --- a/doc/fparser.rst +++ b/doc/fparser.rst @@ -1,7 +1,7 @@ .. -*- rest -*- .. - Copyright (c) 2017-2018 Science and Technology Facilities Council. + Copyright (c) 2017-2023 Science and Technology Facilities Council. All rights reserved. @@ -100,7 +100,7 @@ As indicated by the above output, the `fparser.api.parse()` function returns a `Statement` tree representation of the parsed source code. This `parse()` function is actually a convenience method that wraps the creation of a reader for Fortran source code (either -FortranStringReader or FortranFileReader) followed by a call to use +`FortranStringReader` or `FortranFileReader`) followed by a call to use that reader to create the tree, e.g.: :: @@ -232,6 +232,14 @@ For example, >>> reader.next() Line('integer i,incx,incy,ix,iy,m,mp1,n',(9, 9),'') +Owing to its origins in the f2py project, the reader contains functionality +to identify the format of the provided source by examining Python-style +encoding information (c.f. `PEP 263`). Since this is not a part of the Fortran +standard, this functionality is disabled by default. It can be enabled by +providing the argument `ignore_encoding=False` to the reader. + +.. _PEP 263: https://peps.python.org/pep-0263/ + Note that the `FortranReaderBase.next()` method may return `Line`, `SyntaxErrorLine`, `Comment`, `MultiLine`, or `SyntaxErrorMultiLine` instances. diff --git a/src/fparser/common/readfortran.py b/src/fparser/common/readfortran.py index 4bb7e97..8efc4c8 100644 --- a/src/fparser/common/readfortran.py +++ b/src/fparser/common/readfortran.py @@ -1,6 +1,6 @@ #!/usr/bin/env python # -*- coding: utf-8 -*- -# Modified work Copyright (c) 2017-2022 Science and Technology +# Modified work Copyright (c) 2017-2023 Science and Technology # Facilities Council. # Original work Copyright (c) 1999-2008 Pearu Peterson @@ -791,22 +791,13 @@ class FortranReaderBase: if self.reader is not None: # inside INCLUDE statement try: - # Manually check to see if something has not - # matched and has been placed in the fifo. We - # can't use _next() as this method is associated - # with the include reader (self.reader._next()), - # not this reader (self._next()). - return self.fifo_item.pop(0) - except IndexError: - # There is nothing in the fifo buffer. - try: - # Return a line from the include. - return self.reader.next(ignore_comments) - except StopIteration: - # There is nothing left in the include - # file. Setting reader to None indicates that - # we should now read from the main reader. - self.reader = None + # Return a line from the include. + return self.reader.next(ignore_comments) + except StopIteration: + # There is nothing left in the include + # file. Setting reader to None indicates that + # we should now read from the main reader. + self.reader = None item = self._next(ignore_comments) if isinstance(item, Line) and _IS_INCLUDE_LINE(item.line): # catch INCLUDE statement and create a new FortranReader @@ -1555,9 +1546,12 @@ class FortranFileReader(FortranReaderBase): :param file_candidate: A filename or file-like object. :param list include_dirs: Directories in which to look for inclusions. - :param list source_only: Fortran source files to search for modules + :param list source_only: Fortran source files to search for modules \ required by "use" statements. :param bool ignore_comments: Whether or not to ignore comments + :param Optional[bool] ignore_encoding: whether or not to ignore Python-style \ + encoding information (e.g. "-*- fortran -*-") when attempting to determine \ + the format of the file. Default is True. For example: @@ -1568,7 +1562,12 @@ class FortranFileReader(FortranReaderBase): """ def __init__( - self, file_candidate, include_dirs=None, source_only=None, ignore_comments=True + self, + file_candidate, + include_dirs=None, + source_only=None, + ignore_comments=True, + ignore_encoding=True, ): # The filename is used as a unique ID. This is then used to cache the # contents of the file. Obviously if the file changes content but not @@ -1592,9 +1591,11 @@ class FortranFileReader(FortranReaderBase): message = "FortranFileReader is used with a filename" message += " or file-like object." raise ValueError(message) - mode = fparser.common.sourceinfo.get_source_info(file_candidate) + mode = fparser.common.sourceinfo.get_source_info( + file_candidate, ignore_encoding + ) - FortranReaderBase.__init__(self, self.file, mode, ignore_comments) + super().__init__(self.file, mode, ignore_comments) if include_dirs is None: self.include_dirs.insert(0, os.path.dirname(self.id)) @@ -1620,6 +1621,9 @@ class FortranStringReader(FortranReaderBase): :param list source_only: Fortran source files to search for modules required by "use" statements. :param bool ignore_comments: Whether or not to ignore comments + :param Optional[bool] ignore_encoding: whether or not to ignore Python-style \ + encoding information (e.g. "-*- fortran -*-") when attempting to determine \ + the format of the source. Default is True. For example: @@ -1635,7 +1639,12 @@ class FortranStringReader(FortranReaderBase): """ def __init__( - self, string, include_dirs=None, source_only=None, ignore_comments=True + self, + string, + include_dirs=None, + source_only=None, + ignore_comments=True, + ignore_encoding=True, ): # The Python ID of the string was used to uniquely identify it for # caching purposes. Unfortunately this ID is only unique for the @@ -1648,8 +1657,10 @@ class FortranStringReader(FortranReaderBase): # self.id = "string-" + str(hash(string)) source = StringIO(string) - mode = fparser.common.sourceinfo.get_source_info_str(string) - FortranReaderBase.__init__(self, source, mode, ignore_comments) + mode = fparser.common.sourceinfo.get_source_info_str( + string, ignore_encoding=ignore_encoding + ) + super().__init__(source, mode, ignore_comments) if include_dirs is not None: self.include_dirs = include_dirs[:] if source_only is not None: diff --git a/src/fparser/common/sourceinfo.py b/src/fparser/common/sourceinfo.py index e8ce5c4..de01d03 100644 --- a/src/fparser/common/sourceinfo.py +++ b/src/fparser/common/sourceinfo.py @@ -1,5 +1,5 @@ -# Modified work Copyright (c) 2017-2022 Science and Technology -# Facilities Council +# Modified work Copyright (c) 2017-2023 Science and Technology +# Facilities Council. # Original work Copyright (c) 1999-2008 Pearu Peterson # All rights reserved. @@ -227,25 +227,35 @@ _HAS_PYF_HEADER = re.compile(r"-[*]-\s*pyf\s*-[*]-", re.I).search _FREE_FORMAT_START = re.compile(r"[^c*!]\s*[^\s\d\t]", re.I).match -def get_source_info_str(source): +def get_source_info_str(source, ignore_encoding=True): """ Determines the format of Fortran source held in a string. - Returns a FortranFormat object. + :param bool ignore_encoding: whether or not to ignore any Python-style \ + encoding information in the first line of the file. + + :returns: a FortranFormat object. + :rtype: :py:class:`fparser.common.sourceinfo.FortranFormat` + """ lines = source.splitlines() if not lines: return FortranFormat(False, False) - firstline = lines[0].lstrip() - if _HAS_F_HEADER(firstline): - return FortranFormat(False, True) - if _HAS_FIX_HEADER(firstline): - return FortranFormat(False, False) - if _HAS_FREE_HEADER(firstline): - return FortranFormat(True, False) - if _HAS_PYF_HEADER(firstline): - return FortranFormat(True, True) + if not ignore_encoding: + # We check to see whether the file contains a comment describing its + # encoding. This has nothing to do with the Fortran standard (see e.g. + # https://peps.python.org/pep-0263/) and hence is not done by default. + firstline = lines[0].lstrip() + if _HAS_F_HEADER(firstline): + # -*- fortran -*- implies Fortran77 so fixed format. + return FortranFormat(False, True) + if _HAS_FIX_HEADER(firstline): + return FortranFormat(False, False) + if _HAS_FREE_HEADER(firstline): + return FortranFormat(True, False) + if _HAS_PYF_HEADER(firstline): + return FortranFormat(True, True) line_tally = 10000 # Check up to this number of non-comment lines is_free = False @@ -263,7 +273,7 @@ def get_source_info_str(source): ############################################################################## -def get_source_info(file_candidate): +def get_source_info(file_candidate, ignore_encoding=True): """ Determines the format of Fortran source held in a file. @@ -303,7 +313,9 @@ def get_source_info(file_candidate): # pointer = file_candidate.tell() file_candidate.seek(0) - source_info = get_source_info_str(file_candidate.read()) + source_info = get_source_info_str( + file_candidate.read(), ignore_encoding=ignore_encoding + ) file_candidate.seek(pointer) return source_info @@ -322,7 +334,9 @@ def get_source_info(file_candidate): with open( file_candidate, "r", encoding="utf-8", errors="fparser-logging" ) as file_object: - string = get_source_info_str(file_object.read()) + string = get_source_info_str( + file_object.read(), ignore_encoding=ignore_encoding + ) return string
stfc/fparser
266caf63ab9a422fa49396469e0853773092834f
diff --git a/.github/workflows/unit-tests.yml b/.github/workflows/unit-tests.yml index bbafd85..229fd1d 100644 --- a/.github/workflows/unit-tests.yml +++ b/.github/workflows/unit-tests.yml @@ -1,7 +1,7 @@ # ----------------------------------------------------------------------------- # BSD 3-Clause License # -# Copyright (c) 2020-2022, Science and Technology Facilities Council. +# Copyright (c) 2020-2023, Science and Technology Facilities Council. # All rights reserved. # # Redistribution and use in source and binary forms, with or without @@ -65,7 +65,7 @@ jobs: runs-on: ubuntu-latest strategy: matrix: - python-version: ['3.6', '3.8', '3.10'] + python-version: ['3.7', '3.8', '3.11'] steps: - uses: actions/checkout@v2 with: diff --git a/src/fparser/common/tests/test_readfortran.py b/src/fparser/common/tests/test_readfortran.py index 36f64d3..a3b7f5a 100644 --- a/src/fparser/common/tests/test_readfortran.py +++ b/src/fparser/common/tests/test_readfortran.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- ############################################################################## -# Copyright (c) 2017-2022 Science and Technology Facilities Council +# Copyright (c) 2017-2023 Science and Technology Facilities Council. # # All rights reserved. # @@ -104,11 +104,10 @@ def test_line_map(): assert line.get_line(apply_map=True) == "write(*,*) 'var = ', var" -def test_111fortranreaderbase(log, monkeypatch): +def test_fortranreaderbase_logging(log, monkeypatch): """ - Tests the FortranReaderBase class. + Tests the logging functionality of the FortranReaderBase class. - Currently only tests logging functionality. """ class FailFile: @@ -534,7 +533,7 @@ def test_include6(tmpdir, ignore_comments): fortran_code = ( "program test\n" " ! prog comment 1\n" - " include '{0}'\n" + " include '{0}' ! this is an include\n" " ! prog comment 2\n" "end program".format(include_filename) ) @@ -549,6 +548,7 @@ def test_include6(tmpdir, ignore_comments): "! include comment 1\n" "print *, 'Hello'\n" "! include comment 2\n" + "! this is an include\n" "! prog comment 2\n" "end program" ) @@ -858,7 +858,31 @@ def test_string_reader(): assert unit_under_test.get_single_line(ignore_empty=True) == expected -############################################################################## [email protected]("reader_cls", [FortranStringReader, FortranFileReader]) +def test_reader_ignore_encoding(reader_cls, tmp_path): + """ + Tests that the Fortran{String,File}Reader can be configured to take notice of + Python-style encoding information. + """ + source = "! -*- f77 -*-\n" + FULL_FREE_SOURCE + if reader_cls is FortranFileReader: + sfile = tmp_path / "my_test.f90" + sfile.write_text(source) + # File location with full path. + rinput = str(sfile.absolute()) + else: + rinput = source + reader = reader_cls(rinput) + # By default the encoding information is ignored so the format should be + # free format, not strict. + assert reader.format == FortranFormat(True, False) + # Check that explicitly setting ignore_encoding=True gives the same behaviour. + reader1 = reader_cls(rinput, ignore_encoding=True) + assert reader1.format == FortranFormat(True, False) + # Now test when the reader takes notice of the encoding information. + reader2 = reader_cls(rinput, ignore_encoding=False) + # Should be fixed format, strict. + assert reader2.format == FortranFormat(False, True) def test_inherited_f77(): @@ -887,7 +911,9 @@ a 'g ] # Reading from buffer - reader = FortranStringReader(string_f77, ignore_comments=False) + reader = FortranStringReader( + string_f77, ignore_comments=False, ignore_encoding=False + ) assert reader.format.mode == "f77", repr(reader.format.mode) stack = expected[:] for item in reader: @@ -899,7 +925,7 @@ a 'g with open(filename, "w") as fortran_file: print(string_f77, file=fortran_file) - reader = FortranFileReader(filename, ignore_comments=False) + reader = FortranFileReader(filename, ignore_comments=False, ignore_encoding=False) stack = expected[:] for item in reader: assert str(item) == stack.pop(0) @@ -971,7 +997,9 @@ end python module foo "Comment('! end of file',(26, 26))", ] - reader = FortranStringReader(string_pyf, ignore_comments=False) + reader = FortranStringReader( + string_pyf, ignore_comments=False, ignore_encoding=False + ) assert reader.format.mode == "pyf", repr(reader.format.mode) for item in reader: assert str(item) == expected.pop(0) @@ -1018,7 +1046,9 @@ cComment "Comment('',(15, 15))", "line #17'end'", ] - reader = FortranStringReader(string_fix90, ignore_comments=False) + reader = FortranStringReader( + string_fix90, ignore_comments=False, ignore_encoding=False + ) assert reader.format.mode == "fix", repr(reader.format.mode) for item in reader: assert str(item) == expected.pop(0) diff --git a/src/fparser/common/tests/test_sourceinfo.py b/src/fparser/common/tests/test_sourceinfo.py index aa3df87..098de10 100644 --- a/src/fparser/common/tests/test_sourceinfo.py +++ b/src/fparser/common/tests/test_sourceinfo.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- ############################################################################## -# Copyright (c) 2017-2022 Science and Technology Facilities Council. +# Copyright (c) 2017-2023 Science and Technology Facilities Council. # # All rights reserved. # @@ -206,8 +206,9 @@ def test_format_from_mode_bad(): ("! -*- fix -*-", FortranFormat(False, False)), ("! -*- pyf -*-", FortranFormat(True, True)), ], + name="header", ) -def header(request): +def header_fixture(request): """ Returns parameters for header tests. """ @@ -283,7 +284,7 @@ def test_get_source_info_str(header, content): if content[0] is not None: full_source += content[0] - source_info = get_source_info_str(full_source) + source_info = get_source_info_str(full_source, ignore_encoding=False) if header[0]: assert source_info == header[1] else: # No header @@ -331,7 +332,7 @@ def test_get_source_info_filename(extension, header, content): print(full_source, file=source_file) try: - source_info = get_source_info(filename) + source_info = get_source_info(filename, ignore_encoding=False) if extension[1] is not None: assert source_info == extension[1] elif header[0] is not None: @@ -361,7 +362,7 @@ def test_get_source_info_file(extension, header, content): print(full_source, file=source_file) source_file.seek(0) - source_info = get_source_info(source_file) + source_info = get_source_info(source_file, ignore_encoding=False) if header[0] is not None: assert source_info == header[1] else: # No header
Support extension to permit in-line '!' comments in fixed-format Fortran The OpenMPI Fortran include files are fixed format (they have the `-*- fortran -*-` header and non-comment lines begin with 6 spaces). However, they also have some 'inline' style comments, e.g.: ! MPI F08 conformance ! logical MPI_SUBARRAYS_SUPPORTED logical MPI_ASYNC_PROTECTS_NONBLOCKING ! Hard-coded for .false. for now parameter (MPI_SUBARRAYS_SUPPORTED= .false.) and fparser does not accept such comments giving rise to a syntax error. Given that this is in OpenMPI code this must mean that the vast majority of compilers have no problem, despite it being non-standards compliant F77. I'm therefore inclined to say that fparser should just silently permit such comments too.
0.0
266caf63ab9a422fa49396469e0853773092834f
[ "src/fparser/common/tests/test_readfortran.py::test_include6[True]", "src/fparser/common/tests/test_readfortran.py::test_include6[False]", "src/fparser/common/tests/test_readfortran.py::test_reader_ignore_encoding[FortranStringReader]", "src/fparser/common/tests/test_readfortran.py::test_reader_ignore_encoding[FortranFileReader]", "src/fparser/common/tests/test_readfortran.py::test_inherited_f77", "src/fparser/common/tests/test_readfortran.py::test_pyf", "src/fparser/common/tests/test_readfortran.py::test_fix90", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header0-content0]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header0-content0]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header0-content0]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header0-content1]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header0-content1]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header1-content1]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header1-content1]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header1-content1]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header1-content1]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header1-content1]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header1-content0]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header1-content0]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header1-content2]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header1-content2]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header0-content2]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header0-content2]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header2-content2]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header2-content2]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header2-content2]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header2-content2]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header2-content2]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header2-content2]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header2-content2]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header2-content1]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header2-content1]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header2-content0]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header2-content0]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header2-content3]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header2-content3]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header1-content3]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header1-content3]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header0-content3]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header0-content3]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header3-content3]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header3-content3]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header3-content3]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header3-content3]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header3-content3]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header3-content3]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header3-content3]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header3-content3]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header3-content3]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header3-content2]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header3-content2]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header3-content1]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header3-content1]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header3-content0]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header3-content0]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header3-content4]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header3-content4]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header2-content4]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header2-content4]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header1-content4]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header1-content4]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header0-content4]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header0-content4]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header4-content4]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header4-content4]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header4-content4]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header4-content4]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header4-content4]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header4-content4]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header4-content4]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header4-content4]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header4-content4]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header4-content3]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header4-content3]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header4-content2]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header4-content2]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header4-content1]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header4-content1]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header4-content0]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header4-content0]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header4-content5]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header4-content5]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header4-content5]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header4-content5]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header4-content5]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header4-content5]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header4-content5]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header4-content5]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header4-content5]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header3-content5]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header3-content5]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header2-content5]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header2-content5]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header1-content5]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header1-content5]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header0-content5]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header0-content5]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header5-content5]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header5-content5]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header5-content5]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header5-content5]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header5-content5]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header5-content5]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header5-content5]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header5-content5]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header5-content5]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header5-content4]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header5-content4]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header5-content4]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header5-content4]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header5-content4]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header5-content4]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header5-content4]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header5-content4]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header5-content4]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header5-content3]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header5-content3]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header5-content2]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header5-content2]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header5-content1]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header5-content1]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header5-content0]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header5-content0]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header5-content6]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header5-content6]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header5-content6]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header5-content6]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header5-content6]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header5-content6]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header5-content6]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header5-content6]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header5-content6]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header4-content6]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header4-content6]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header4-content6]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header4-content6]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header4-content6]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header4-content6]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header4-content6]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header4-content6]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header4-content6]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header3-content6]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header3-content6]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header2-content6]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header2-content6]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header1-content6]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header1-content6]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header0-content6]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header0-content6]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header6-content6]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header6-content6]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header6-content6]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header6-content6]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header6-content6]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header6-content6]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header6-content6]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header6-content6]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header6-content6]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header6-content5]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header6-content5]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header6-content5]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header6-content5]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header6-content5]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header6-content5]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header6-content5]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header6-content5]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header6-content5]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header6-content4]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header6-content4]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header6-content4]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header6-content4]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header6-content4]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header6-content4]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header6-content4]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header6-content4]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header6-content4]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header6-content3]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header6-content3]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header6-content2]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header6-content2]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header6-content1]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header6-content1]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header6-content0]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header6-content0]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header6-content3]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header6-content3]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header6-content3]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header6-content3]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header6-content3]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header6-content3]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header6-content3]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header6-content2]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header6-content2]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header6-content1]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header6-content1]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header6-content0]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header6-content0]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header6-content2]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header6-content2]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header6-content2]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header6-content2]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header6-content2]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header6-content1]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header6-content1]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header6-content0]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header6-content0]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header6-content1]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header6-content1]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header6-content1]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header6-content0]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header6-content0]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header6-content0]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header7-content6]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header7-content6]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header7-content6]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header7-content6]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header7-content6]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header7-content6]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header7-content6]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header7-content6]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header7-content6]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header7-content5]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header7-content5]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header7-content5]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header7-content5]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header7-content5]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header7-content5]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header7-content5]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header7-content5]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header7-content5]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header7-content4]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header7-content4]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header7-content4]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header7-content4]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header7-content4]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header7-content4]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header7-content4]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header7-content4]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header7-content4]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header7-content3]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header7-content3]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header7-content2]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header7-content2]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header7-content1]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header7-content1]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header7-content0]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header7-content0]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header7-content3]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header7-content3]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header7-content3]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header7-content3]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header7-content3]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header7-content3]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header7-content3]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header7-content2]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header7-content2]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header7-content1]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header7-content1]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header7-content0]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header7-content0]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header7-content2]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header7-content2]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header7-content2]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header7-content2]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header7-content2]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header7-content1]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header7-content1]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header7-content0]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header7-content0]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header7-content1]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header7-content1]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header7-content1]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header7-content0]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header7-content0]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header7-content0]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header3-content6]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header3-content6]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header3-content6]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header3-content6]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header3-content6]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header3-content6]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header3-content6]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header2-content6]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header2-content6]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header1-content6]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header1-content6]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header0-content6]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header0-content6]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header2-content6]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header2-content6]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header2-content6]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header2-content6]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header2-content6]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header1-content6]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header1-content6]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header0-content6]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header0-content6]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header1-content6]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header1-content6]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header1-content6]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header0-content6]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header0-content6]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header0-content6]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header5-content3]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header5-content3]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header5-content3]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header5-content3]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header5-content3]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header5-content3]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header5-content3]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header5-content2]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header5-content2]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header5-content1]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header5-content1]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header5-content0]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header5-content0]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header5-content2]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header5-content2]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header5-content2]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header5-content2]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header5-content2]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header5-content1]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header5-content1]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header5-content0]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header5-content0]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header5-content1]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header5-content1]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header5-content1]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header5-content0]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header5-content0]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header5-content0]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header3-content5]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header3-content5]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header3-content5]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header3-content5]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header3-content5]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header3-content5]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header3-content5]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header2-content5]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header2-content5]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header1-content5]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header1-content5]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header0-content5]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header0-content5]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header2-content5]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header2-content5]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header2-content5]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header2-content5]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header2-content5]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header1-content5]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header1-content5]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header0-content5]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header0-content5]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header1-content5]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header1-content5]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header1-content5]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header0-content5]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header0-content5]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header0-content5]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header4-content3]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header4-content3]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header4-content3]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header4-content3]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header4-content3]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header4-content3]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header4-content3]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header4-content2]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header4-content2]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header4-content1]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header4-content1]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header4-content0]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header4-content0]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header4-content2]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header4-content2]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header4-content2]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header4-content2]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header4-content2]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header4-content1]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header4-content1]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header4-content0]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header4-content0]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header4-content1]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header4-content1]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header4-content1]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header4-content0]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header4-content0]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header4-content0]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header3-content4]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header3-content4]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header3-content4]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header3-content4]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header3-content4]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header3-content4]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header3-content4]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header2-content4]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header2-content4]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header1-content4]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header1-content4]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header0-content4]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header0-content4]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header2-content4]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header2-content4]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header2-content4]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header2-content4]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header2-content4]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header1-content4]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header1-content4]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header0-content4]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header0-content4]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header1-content4]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header1-content4]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header1-content4]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header0-content4]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header0-content4]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header0-content4]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header2-content3]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header2-content3]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header1-content3]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header1-content3]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header0-content3]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header0-content3]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header2-content2]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header2-content2]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header2-content1]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header2-content1]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header2-content0]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header2-content0]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header1-content2]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header1-content2]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header0-content2]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header0-content2]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header1-content1]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header1-content1]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header1-content0]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header1-content0]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header0-content1]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header0-content1]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension3-header0-content0]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension3-header0-content0]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header3-content2]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header3-content2]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header3-content1]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header3-content1]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header3-content0]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header3-content0]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header3-content2]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header3-content2]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header3-content2]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header3-content2]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header3-content2]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header3-content1]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header3-content1]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header3-content0]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header3-content0]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header3-content1]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header3-content1]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header3-content1]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header3-content0]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header3-content0]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header3-content0]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header2-content3]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header2-content3]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header2-content3]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header2-content3]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header2-content3]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header1-content3]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header1-content3]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header0-content3]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header0-content3]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header1-content3]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header1-content3]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header1-content3]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header0-content3]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header0-content3]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header0-content3]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header1-content2]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header1-content2]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header0-content2]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header0-content2]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header1-content1]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header1-content1]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header1-content0]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header1-content0]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header0-content1]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header0-content1]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension2-header0-content0]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension2-header0-content0]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header2-content1]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header2-content1]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header2-content0]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header2-content0]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header2-content1]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header2-content1]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header2-content1]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header2-content0]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header2-content0]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header2-content0]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header1-content2]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header1-content2]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header1-content2]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header0-content2]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header0-content2]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header0-content2]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header0-content1]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header0-content1]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension1-header0-content0]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension1-header0-content0]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_filename[extension0-header1-content0]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_file[extension0-header1-content0]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header1-content0]", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_str[header0-content1]" ]
[ "src/fparser/common/tests/test_readfortran.py::test_empty_line_err", "src/fparser/common/tests/test_readfortran.py::test_line_map", "src/fparser/common/tests/test_readfortran.py::test_fortranreaderbase_logging", "src/fparser/common/tests/test_readfortran.py::test_include_not_found", "src/fparser/common/tests/test_readfortran.py::test_base_next_good_include", "src/fparser/common/tests/test_readfortran.py::test_fortranreaderbase_info", "src/fparser/common/tests/test_readfortran.py::test_fortranreaderbase_error", "src/fparser/common/tests/test_readfortran.py::test_fortranreaderbase_warning", "src/fparser/common/tests/test_readfortran.py::test_base_handle_multilines", "src/fparser/common/tests/test_readfortran.py::test_base_fixed_nonlabel", "src/fparser/common/tests/test_readfortran.py::test_base_fixed_continuation", "src/fparser/common/tests/test_readfortran.py::test_base_free_continuation", "src/fparser/common/tests/test_readfortran.py::test_include1", "src/fparser/common/tests/test_readfortran.py::test_include2", "src/fparser/common/tests/test_readfortran.py::test_include3", "src/fparser/common/tests/test_readfortran.py::test_include4", "src/fparser/common/tests/test_readfortran.py::test_include5", "src/fparser/common/tests/test_readfortran.py::test_get_item[True]", "src/fparser/common/tests/test_readfortran.py::test_put_item[True]", "src/fparser/common/tests/test_readfortran.py::test_put_item_include[True]", "src/fparser/common/tests/test_readfortran.py::test_multi_put_item[True]", "src/fparser/common/tests/test_readfortran.py::test_get_item[False]", "src/fparser/common/tests/test_readfortran.py::test_put_item[False]", "src/fparser/common/tests/test_readfortran.py::test_put_item_include[False]", "src/fparser/common/tests/test_readfortran.py::test_multi_put_item[False]", "src/fparser/common/tests/test_readfortran.py::test_multi_stmt_line1", "src/fparser/common/tests/test_readfortran.py::test_multi_stmt_line2", "src/fparser/common/tests/test_readfortran.py::test_multi_stmt_line3", "src/fparser/common/tests/test_readfortran.py::test_filename_reader", "src/fparser/common/tests/test_readfortran.py::test_file_reader", "src/fparser/common/tests/test_readfortran.py::test_none_in_fifo", "src/fparser/common/tests/test_readfortran.py::test_bad_file_reader", "src/fparser/common/tests/test_readfortran.py::test_string_reader", "src/fparser/common/tests/test_readfortran.py::test_f2py_directive_fixf90[True]", "src/fparser/common/tests/test_readfortran.py::test_f2py_freef90[True]", "src/fparser/common/tests/test_readfortran.py::test_f2py_directive_fixf90[False]", "src/fparser/common/tests/test_readfortran.py::test_f2py_freef90[False]", "src/fparser/common/tests/test_readfortran.py::test_utf_char_in_code", "src/fparser/common/tests/test_readfortran.py::test_extract_label", "src/fparser/common/tests/test_readfortran.py::test_extract_construct_name", "src/fparser/common/tests/test_readfortran.py::test_handle_cpp_directive[#include", "src/fparser/common/tests/test_readfortran.py::test_handle_cpp_directive[", "src/fparser/common/tests/test_readfortran.py::test_handle_cpp_directive[#define", "src/fparser/common/tests/test_readfortran.py::test_handle_cpp_directive[#ifdef", "src/fparser/common/tests/test_readfortran.py::test_handle_cpp_directive[#if", "src/fparser/common/tests/test_readfortran.py::test_handle_cpp_directive[abc", "src/fparser/common/tests/test_readfortran.py::test_handle_cpp_directive[\"#\"-False]", "src/fparser/common/tests/test_readfortran.py::test_handle_cpp_directive[!", "src/fparser/common/tests/test_readfortran.py::test_reader_cpp_directives", "src/fparser/common/tests/test_readfortran.py::test_multiline_cpp_directives", "src/fparser/common/tests/test_readfortran.py::test_single_comment", "src/fparser/common/tests/test_readfortran.py::test_many_comments", "src/fparser/common/tests/test_readfortran.py::test_quotes_in_inline_comments[", "src/fparser/common/tests/test_readfortran.py::test_comments_within_continuation", "src/fparser/common/tests/test_readfortran.py::test_single_blank_line[\\n]", "src/fparser/common/tests/test_readfortran.py::test_single_blank_line[", "src/fparser/common/tests/test_readfortran.py::test_multiple_blank_lines", "src/fparser/common/tests/test_readfortran.py::test_blank_lines_within_continuation", "src/fparser/common/tests/test_sourceinfo.py::test_format_constructor_faults", "src/fparser/common/tests/test_sourceinfo.py::test_fortranformat_constructor[pretty0]", "src/fparser/common/tests/test_sourceinfo.py::test_fortranformat_equality[pretty0-permutations0]", "src/fparser/common/tests/test_sourceinfo.py::test_fortranformat_equality[pretty0-permutations1]", "src/fparser/common/tests/test_sourceinfo.py::test_fortranformat_equality[pretty0-permutations2]", "src/fparser/common/tests/test_sourceinfo.py::test_fortranformat_equality[pretty0-permutations3]", "src/fparser/common/tests/test_sourceinfo.py::test_fortranformat_constructor[pretty1]", "src/fparser/common/tests/test_sourceinfo.py::test_fortranformat_equality[pretty1-permutations0]", "src/fparser/common/tests/test_sourceinfo.py::test_fortranformat_equality[pretty1-permutations1]", "src/fparser/common/tests/test_sourceinfo.py::test_fortranformat_equality[pretty1-permutations2]", "src/fparser/common/tests/test_sourceinfo.py::test_fortranformat_equality[pretty1-permutations3]", "src/fparser/common/tests/test_sourceinfo.py::test_fortranformat_constructor[pretty2]", "src/fparser/common/tests/test_sourceinfo.py::test_fortranformat_equality[pretty2-permutations0]", "src/fparser/common/tests/test_sourceinfo.py::test_fortranformat_equality[pretty2-permutations1]", "src/fparser/common/tests/test_sourceinfo.py::test_fortranformat_equality[pretty2-permutations2]", "src/fparser/common/tests/test_sourceinfo.py::test_fortranformat_equality[pretty2-permutations3]", "src/fparser/common/tests/test_sourceinfo.py::test_fortranformat_constructor[pretty3]", "src/fparser/common/tests/test_sourceinfo.py::test_fortranformat_equality[pretty3-permutations0]", "src/fparser/common/tests/test_sourceinfo.py::test_fortranformat_equality[pretty3-permutations1]", "src/fparser/common/tests/test_sourceinfo.py::test_fortranformat_equality[pretty3-permutations2]", "src/fparser/common/tests/test_sourceinfo.py::test_fortranformat_equality[pretty3-permutations3]", "src/fparser/common/tests/test_sourceinfo.py::test_fortranformat_invalid", "src/fparser/common/tests/test_sourceinfo.py::test_fortranformat_from_mode[mode0]", "src/fparser/common/tests/test_sourceinfo.py::test_fortranformat_from_mode[mode1]", "src/fparser/common/tests/test_sourceinfo.py::test_fortranformat_from_mode[mode2]", "src/fparser/common/tests/test_sourceinfo.py::test_fortranformat_from_mode[mode3]", "src/fparser/common/tests/test_sourceinfo.py::test_format_from_mode_bad", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_utf8", "src/fparser/common/tests/test_sourceinfo.py::test_get_source_info_wrong" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2023-01-27 11:31:05+00:00
bsd-3-clause
5,737
stfc__fparser-408
diff --git a/CHANGELOG.md b/CHANGELOG.md index 202a531..37b8b35 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,6 +18,8 @@ Modifications by (in alphabetical order): * P. Vitt, University of Siegen, Germany * A. Voysey, UK Met Office +15/05/2023 PR #408 for #403. Add support for the F2008 DO CONCURRENT. + 26/04/2023 PR #406 for #405. Add support for F2008 optional "::" in PROCEDURE statement. diff --git a/doc/source/fparser2.rst b/doc/source/fparser2.rst index 66d55f7..c7a1722 100644 --- a/doc/source/fparser2.rst +++ b/doc/source/fparser2.rst @@ -45,7 +45,8 @@ the Fortran2008.py `file`__ which extends the Fortran2003 rules appropriately. At this time fparser2 supports the following Fortran2008 features: submodules, co-arrays, the 'mold' argument to allocate, the 'contiguous' keyword, the 'BLOCK' construct, the -'CRITICAL' construct and the optional '::' for a procedure statement. +'CRITICAL' construct, the optional '::' for a procedure statement and +the 'do concurrent' construct. __ https://github.com/stfc/fparser/blob/master/src/fparser/two/Fortran2003.py __ https://github.com/stfc/fparser/blob/master/src/fparser/two/Fortran2008.py diff --git a/src/fparser/two/Fortran2003.py b/src/fparser/two/Fortran2003.py index d314d1e..d303d69 100644 --- a/src/fparser/two/Fortran2003.py +++ b/src/fparser/two/Fortran2003.py @@ -1,6 +1,6 @@ #!/usr/bin/env python -# Modified work Copyright (c) 2017-2022 Science and Technology +# Modified work Copyright (c) 2017-2023 Science and Technology # Facilities Council. # Original work Copyright (c) 1999-2008 Pearu Peterson @@ -5249,7 +5249,7 @@ class Allocate_Stmt(StmtBase): # R623 allocate-stmt is ALLOCATE ( [ type-spec :: ] allocation-list [, alloc-opt-list ] ) - Subject to the following constraints\: + Subject to the following constraints: C622 (R629) Each allocate-object shall be a nonprocedure pointer or an allocatable variable. @@ -7949,14 +7949,24 @@ class Nonlabel_Do_Stmt(StmtBase, WORDClsBase): # pylint: disable=invalid-name return self.item.name -class Loop_Control(Base): # pylint: disable=invalid-name +# pylint: disable=invalid-name +class Loop_Control(Base): # R830 """ - R830:: + Fortran 2003 rule R830 - <loop-control> = [ , ] <do-variable> = scalar-int-expr, - scalar-int-expr - [ , <scalar-int-expr> ] - | [ , ] WHILE ( <scalar-logical-expr> ) + loop-control is [ , ] do-variable = scalar-int-expr , scalar-int-expr + [ , scalar-int-expr ] + or [ , ] WHILE ( scalar-logical-expr ) + + This class would be better and more extensible if it called 2 + classes, one for each of the above expressions. Something like the + suggestion below. However, this would result in a different + fparser tree, see issue #416. + + F2003: While_Loop_Cntl: scalar-logical-expression, delim + F2003: Counter_Loop_Cntl: var, lower, upper, [step], delim + F2008: Concurrent_Loop_Cntl: conc_expr, delim + F2018: Concurrent_Loop_Cntl: conc_expr, local_x, delim """ @@ -7965,66 +7975,73 @@ class Loop_Control(Base): # pylint: disable=invalid-name @staticmethod def match(string): - """ - :param str string: Fortran code to check for a match - :return: 3-tuple containing strings and instances of the classes - determining loop control (optional comma delimiter, - optional scalar logical expression describing "WHILE" - condition or optional counter expression containing loop - counter and scalar integer expression) - :rtype: 3-tuple of objects or nothing for an "infinite loop" - """ - # pylint: disable=unbalanced-tuple-unpacking + """Attempts to match the supplied text with this rule. + + :param str string: Fortran code to check for a match. + + :returns: None if there is no match, a 3-tuple with the first \ + entry providing the result of matching the 'WHILE' part of \ + the rule if there is a match, the second entry providing \ + the result of matching the 'COUNTER' part of the rule if \ + there is a match and the third entry indicating whether \ + there is an optional preceding ','. + :rtype: Optional[Tuple[ \ + Optional[ \ + :py:class:`fparser.two.Fortran2003.Scalar_Logical_Expr`], \ + Optional[Tuple[ \ + :py:class:`fparser.two.Fortran2003.Do_Variable`, List[str]]], \ + Optional[str]]] + + """ + line = string.lstrip().rstrip() + # Try to match optional delimiter optional_delim = None - # Match optional delimiter - if string.startswith(","): - line, repmap = string_replace_map(string[1:].lstrip()) - optional_delim = ", " - else: - line, repmap = string_replace_map(string) - # Match "WHILE" scalar logical expression + if line.startswith(","): + line = line[1:].lstrip() + optional_delim = "," + line, repmap = string_replace_map(line) + # Try to match with WHILE if line[:5].upper() == "WHILE" and line[5:].lstrip().startswith("("): - lbrak = line[5:].lstrip() - i = lbrak.find(")") - if i != -1 and i == len(lbrak) - 1: - scalar_logical_expr = Scalar_Logical_Expr(repmap(lbrak[1:i].strip())) - return scalar_logical_expr, None, optional_delim - # Match counter expression - # More than one '=' in counter expression + brackets = line[5:].lstrip() + rbrack_index = brackets.find(")") + if rbrack_index != -1 and rbrack_index == len(brackets) - 1: + scalar_logical_expr = Scalar_Logical_Expr( + repmap(brackets[1:rbrack_index].strip()) + ) + return (scalar_logical_expr, None, optional_delim) + # Try to match counter expression + # More than one '=' in counter expression is not valid if line.count("=") != 1: - return + return None var, rhs = line.split("=") - rhs = [s.strip() for s in rhs.lstrip().split(",")] + rhs = [entry.strip() for entry in rhs.lstrip().split(",")] # Incorrect number of elements in counter expression if not 2 <= len(rhs) <= 3: - return + return None counter_expr = ( - Variable(repmap(var.rstrip())), + Do_Variable(repmap(var.rstrip())), list(map(Scalar_Int_Expr, list(map(repmap, rhs)))), ) - return None, counter_expr, optional_delim + return (None, counter_expr, optional_delim) def tostr(self): """ - :return: parsed representation of loop control construct - :rtype: string + :returns: the Fortran representation of this object. + :rtype: str """ - # pylint: disable=unbalanced-tuple-unpacking - scalar_logical_expr, counter_expr, optional_delim = self.items - # Return loop control construct containing "WHILE" condition and - # its <scalar-logical-expr> - if scalar_logical_expr is not None: - loopctrl = "WHILE (%s)" % scalar_logical_expr - # Return loop control construct containing counter expression: - # <do-variable> as LHS and <scalar-int-expr> list as RHS - elif counter_expr[0] is not None and counter_expr[1] is not None: - loopctrl = "%s = %s" % ( - counter_expr[0], - ", ".join(map(str, counter_expr[1])), + if self.items[0]: + # Return loop control construct containing "WHILE" condition and + # its <scalar-logical-expr> + loopctrl = f"WHILE ({self.items[0]})" + else: # counter expression + # Return loop control construct containing counter expression: + # <do-variable> as LHS and <scalar-int-expr> list as RHS + loopctrl = ( + f"{self.items[1][0]} = " f"{', '.join(map(str, self.items[1][1]))}" ) # Add optional delimiter to loop control construct if present - if optional_delim is not None: - loopctrl = optional_delim + loopctrl + if self.items[2]: + loopctrl = f"{self.items[2]} {loopctrl}" return loopctrl diff --git a/src/fparser/two/Fortran2008.py b/src/fparser/two/Fortran2008.py index 9a46e26..134fcb4 100644 --- a/src/fparser/two/Fortran2008.py +++ b/src/fparser/two/Fortran2008.py @@ -93,6 +93,9 @@ from fparser.two.utils import ( WORDClsBase, ) +# These pylint errors are due to the auto-generation of classes in the +# Fortran2003 file. +# pylint: disable=no-name-in-module from fparser.two.Fortran2003 import ( Base, BlockBase, @@ -105,6 +108,7 @@ from fparser.two.Fortran2003 import ( Execution_Part_Construct, File_Name_Expr, File_Unit_Number, + Forall_Header, Implicit_Part, Implicit_Part_Stmt, Import_Stmt, @@ -120,6 +124,8 @@ from fparser.two.Fortran2003 import ( Use_Stmt, ) +# pylint: enable=no-name-in-module + # Import of F2003 classes that are updated in this standard. from fparser.two.Fortran2003 import ( Action_Stmt as Action_Stmt_2003, @@ -136,6 +142,7 @@ from fparser.two.Fortran2003 import ( Executable_Construct as Executable_Construct_2003, Executable_Construct_C201 as Executable_Construct_C201_2003, If_Stmt as If_Stmt_2003, + Loop_Control as Loop_Control_2003, Open_Stmt as Open_Stmt_2003, Procedure_Stmt as Procedure_Stmt_2003, Program_Unit as Program_Unit_2003, @@ -817,6 +824,90 @@ class Allocate_Stmt(Allocate_Stmt_2003): # R626 return Alloc_Opt_List +class Loop_Control(Loop_Control_2003): # R818 + """Fortran 2008 rule R818 + + loop-control is [ , ] do-variable = scalar-int-expr , scalar-int-expr + [ , scalar-int-expr ] + or [ , ] WHILE ( scalar-logical-expr ) + or [ , ] CONCURRENT forall-header + + Extends the Fortran2003 rule R830 with the additional CONCURRENT clause. + + The F2003 Loop_Control class would be better and more extensible + if it called 2 classes, one for each of the above + expressions. This would then affect the implementation of this + class. Something like the suggestion below. However, this would + result in a different fparser tree, see issue #416. + + F2003: While_Loop_Cntl: scalar-logical-expression, delim + F2003: Counter_Loop_Cntl: var, lower, upper, [step], delim + F2008: Concurrent_Loop_Cntl: conc_expr, delim + F2018: Concurrent_Loop_Cntl: conc_expr, local_x, delim + + """ + + subclass_names = [] + # This class' match method makes use of the Fortran2003 match + # method so 'use_names' should include any classes used within + # there as well as any used here. + use_names = Loop_Control_2003.use_names[:] + use_names.append("Forall_Header") + + @staticmethod + def match(string): + """Attempts to match the supplied text with this rule. + + :param str string: Fortran code to check for a match. + + :returns: None if there is no match, a tuple with the first \ + entry providing the result of matching the 'WHILE' part of \ + the rule if there is a match, the second entry providing \ + the result of matching the 'COUNTER' part of the rule if \ + there is a match, the third entry indicating whether \ + there is an optional preceding ',' and the fourth entry \ + providing the result of matching the 'CONCURRENT' part of \ + the rule if there is a match. + + :rtype: Optional[Tuple[ \ + Optional[ \ + :py:class:`fparser.two.Fortran2003.Scalar_Logical_Expr`], \ + Optional[Tuple[ \ + :py:class:`fparser.two.Fortran2003.Do_Variable`, List[str]]], \ + Optional[str], \ + Optional[:py:class:`fparser.two.Fortran2003.Forall_Header`]]] + + """ + # Fortran2003 matches all but CONCURRENT so try this first + result = Loop_Control_2003.match(string) + if result: + return result + (None,) + # Try to match with CONCURRENT + line = string.lstrip() + optional_delim = None + if line.startswith(","): + line = line[1:].lstrip() + optional_delim = "," + if line[:10].upper() != "CONCURRENT": + return None + return (None, None, optional_delim, Forall_Header(line[10:].lstrip().rstrip())) + + def tostr(self): + """ + :returns: the Fortran representation of this object. + :rtype: str + """ + if self.items[0] or self.items[1]: + # Use the F2003 tostr() implementation + return Loop_Control_2003.tostr(self) + # Return loop control construct containing "CONCURRENT" clause + loopctrl = f"CONCURRENT {self.items[3]}" + # Add optional delimiter to loop control construct if present + if self.items[2]: + loopctrl = f"{self.items[2]} {loopctrl}" + return loopctrl + + class If_Stmt(If_Stmt_2003): # R837 """ Fortran 2008 rule R837
stfc/fparser
be09a2385d5066caaf57e97b654c920974805048
diff --git a/src/fparser/two/tests/fortran2003/test_loop_control_r830.py b/src/fparser/two/tests/fortran2003/test_loop_control_r830.py new file mode 100644 index 0000000..a758342 --- /dev/null +++ b/src/fparser/two/tests/fortran2003/test_loop_control_r830.py @@ -0,0 +1,120 @@ +# Copyright (c) 2023 Science and Technology Facilities Council + +# All rights reserved. + +# Modifications made as part of the fparser project are distributed +# under the following license: + +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: + +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. + +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. + +# 3. Neither the name of the copyright holder nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. + +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""Test Fortran 2003 rule R830 : This file tests the support for the +loop-control rule. + +""" +import pytest +from fparser.two.Fortran2003 import Loop_Control +from fparser.two.utils import NoMatchError + + +def test_start_end_space_while(): + """Test that there is a match if the string contains white space at + the start and end and that the tostr() output is as expected. Also + test matching to the while form of this rule. + + """ + result = Loop_Control(" while (.true.) ") + assert isinstance(result, Loop_Control) + assert str(result) == "WHILE (.TRUE.)" + + +def test_delim(): + """Test that there is a match if the string contains an optional + delimiter at the start and that the tostr() output is as expected. + + """ + result = Loop_Control(" , while (.true.) ") + assert isinstance(result, Loop_Control) + assert str(result) == ", WHILE (.TRUE.)" + + +def test_repmap(): + """Test matching when the while logical expresssion contains + brackets. This tests the use of the string_replace_map() function. + + """ + result = Loop_Control(" , while (((a .or. b) .and. (c .or. d))) ") + assert isinstance(result, Loop_Control) + assert str(result) == ", WHILE (((a .OR. b) .AND. (c .OR. d)))" + + +def test_counter(): + """Test matching to the counter form of this rule and that the tostr() + output is as expected. + + """ + # Lower-bound and upper-bound only + result = Loop_Control("idx = start,stop") + assert isinstance(result, Loop_Control) + assert str(result) == "idx = start, stop" + # Lower-bound, upper-bound and step + result = Loop_Control("idx = start,stop,step") + assert isinstance(result, Loop_Control) + assert str(result) == "idx = start, stop, step" + # Bounds are integer expressions + result = Loop_Control("idx = ((s+2)-q),(p*m)/4,a+b+c") + assert isinstance(result, Loop_Control) + assert str(result) == "idx = ((s + 2) - q), (p * m) / 4, a + b + c" + + [email protected]( + "string", + [ + "", + " ", + ": while(.true.)", + "whil (.true.)", + "while .true.", + "while ()", + "while( )", + "while (.true ", + "while ())", + "while('text')", + " == ", + " = ", + "idx=", + "=1,2", + "idx=1", + "idx=1,2,3,4", + "1=1,2", + "idx=1,.false.", + ], +) +def test_invalid(string): + """Test that there is no match for various invalid input strings.""" + with pytest.raises(NoMatchError): + _ = Loop_Control(string) diff --git a/src/fparser/two/tests/fortran2008/test_loop_control_r818.py b/src/fparser/two/tests/fortran2008/test_loop_control_r818.py new file mode 100644 index 0000000..934800d --- /dev/null +++ b/src/fparser/two/tests/fortran2008/test_loop_control_r818.py @@ -0,0 +1,93 @@ +# Copyright (c) 2023 Science and Technology Facilities Council + +# All rights reserved. + +# Modifications made as part of the fparser project are distributed +# under the following license: + +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: + +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. + +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. + +# 3. Neither the name of the copyright holder nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. + +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""Test Fortran 2008 rule R818 + + loop-control is [ , ] do-variable = scalar-int-expr , scalar-int-expr + [ , scalar-int-expr ] + or [ , ] WHILE ( scalar-logical-expr ) + or [ , ] CONCURRENT forall-header + + Extends the Fortran2003 rule R830 with the additional CONCURRENT clause. + +""" +import pytest +from fparser.two.Fortran2008 import Loop_Control +from fparser.two.utils import NoMatchError + + +def test_f2003_match(): + """Test that there is a match if the string contains a F2003 form of + the rule and that the F2003 tostr() is as expected. + + """ + result = Loop_Control("while (.true.)") + assert isinstance(result, Loop_Control) + assert str(result) == "WHILE (.TRUE.)" + + +def test_start_space(): + """Test that there is a match if the string contains white space at + the start and end and that the tostr() output is as expected. + + """ + result = Loop_Control(" concurrent (i=1:10) ") + assert isinstance(result, Loop_Control) + assert str(result) == "CONCURRENT (i = 1 : 10)" + + +def test_delim(): + """Test that there is a match if the string contains an options + delimiter at the start and that the tostr() output is as expected. + + """ + result = Loop_Control(" , concurrent (i=1:10)") + assert isinstance(result, Loop_Control) + assert str(result) == ", CONCURRENT (i = 1 : 10)" + + [email protected]( + "string", + [ + "", + ": concurrent (i=1:10)", + "concurren (i=1:10)", + "concurrent", + "concurrent invalid", + ], +) +def test_invalid(string): + """Test that there is no match for various invalid input strings.""" + with pytest.raises(NoMatchError): + _ = Loop_Control(string) diff --git a/src/fparser/two/tests/test_fortran2003.py b/src/fparser/two/tests/test_fortran2003.py index f49a2ad..fc75b86 100644 --- a/src/fparser/two/tests/test_fortran2003.py +++ b/src/fparser/two/tests/test_fortran2003.py @@ -2113,26 +2113,6 @@ def test_label_do_stmt(): assert repr(obj) == "Label_Do_Stmt(None, Label('12'), None)" -def test_loop_control(): - """Tests incorrect loop control constructs (R829). Correct loop - control constructs are tested in test_block_label_do_construct() - and test_nonblock_label_do_construct().""" - tcls = Loop_Control - - # More than one '=' in counter expression - with pytest.raises(NoMatchError) as excinfo: - _ = tcls("j = 1 = 10") - assert "Loop_Control: 'j = 1 = 10'" in str(excinfo.value) - - # Incorrect number of elements in counter expression - with pytest.raises(NoMatchError) as excinfo: - _ = tcls("k = 10, -10, -2, -1") - assert "Loop_Control: 'k = 10, -10, -2, -1'" in str(excinfo.value) - with pytest.raises(NoMatchError) as excinfo: - _ = tcls("l = 5") - assert "Loop_Control: 'l = 5'" in str(excinfo.value) - - def test_continue_stmt(): # R848 tcls = Continue_Stmt obj = tcls("continue")
No Support for DO CONCURRENT It seems like fparser does not support F08 `DO CONCURRENT`: ``` C:\PycharmProjects\fortran> python main.py Traceback (most recent call last): File "C:\Users\micha\anaconda3\envs\fortran\lib\site-packages\fparser\two\Fortran2003.py", line 266, in __new__ return Base.__new__(cls, string) File "C:\Users\micha\anaconda3\envs\fortran\lib\site-packages\fparser\two\utils.py", line 487, in __new__ raise NoMatchError(errmsg) fparser.two.utils.NoMatchError: at line 14 >>> do concurrent (i=1:n) local_init(a) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\micha\PycharmProjects\fortran\main.py", line 7, in <module> parse_tree = f08_parser(reader) File "C:\Users\micha\anaconda3\envs\fortran\lib\site-packages\fparser\two\Fortran2003.py", line 270, in __new__ raise FortranSyntaxError(string, "") fparser.two.utils.FortranSyntaxError: at line 14 >>> do concurrent (i=1:n) local_init(a) ``` Failing code is: ```Fortran module saxpy_impl implicit none contains subroutine saxpy(a, x, y, n) use iso_fortran_env implicit none integer :: n real(kind=real32) :: a real(kind=real32), dimension(n) :: x real(kind=real32), dimension(n) :: y integer :: i do concurrent (i=1:n) local_init(a) y(i) = a * x(i) + y(i) end do end subroutine saxpy end module saxpy_impl ```
0.0
be09a2385d5066caaf57e97b654c920974805048
[ "src/fparser/two/tests/fortran2003/test_loop_control_r830.py::test_start_end_space_while", "src/fparser/two/tests/fortran2003/test_loop_control_r830.py::test_delim", "src/fparser/two/tests/fortran2003/test_loop_control_r830.py::test_repmap", "src/fparser/two/tests/fortran2003/test_loop_control_r830.py::test_counter", "src/fparser/two/tests/fortran2003/test_loop_control_r830.py::test_invalid[]", "src/fparser/two/tests/fortran2003/test_loop_control_r830.py::test_invalid[", "src/fparser/two/tests/fortran2003/test_loop_control_r830.py::test_invalid[:", "src/fparser/two/tests/fortran2003/test_loop_control_r830.py::test_invalid[whil", "src/fparser/two/tests/fortran2003/test_loop_control_r830.py::test_invalid[while", "src/fparser/two/tests/fortran2003/test_loop_control_r830.py::test_invalid[while(", "src/fparser/two/tests/fortran2003/test_loop_control_r830.py::test_invalid[while('text')]", "src/fparser/two/tests/fortran2003/test_loop_control_r830.py::test_invalid[idx=]", "src/fparser/two/tests/fortran2003/test_loop_control_r830.py::test_invalid[=1,2]", "src/fparser/two/tests/fortran2003/test_loop_control_r830.py::test_invalid[idx=1]", "src/fparser/two/tests/fortran2003/test_loop_control_r830.py::test_invalid[idx=1,2,3,4]", "src/fparser/two/tests/fortran2003/test_loop_control_r830.py::test_invalid[1=1,2]", "src/fparser/two/tests/fortran2003/test_loop_control_r830.py::test_invalid[idx=1,.false.]", "src/fparser/two/tests/fortran2008/test_loop_control_r818.py::test_f2003_match", "src/fparser/two/tests/fortran2008/test_loop_control_r818.py::test_start_space", "src/fparser/two/tests/fortran2008/test_loop_control_r818.py::test_delim", "src/fparser/two/tests/fortran2008/test_loop_control_r818.py::test_invalid[]", "src/fparser/two/tests/fortran2008/test_loop_control_r818.py::test_invalid[:", "src/fparser/two/tests/fortran2008/test_loop_control_r818.py::test_invalid[concurren", "src/fparser/two/tests/fortran2008/test_loop_control_r818.py::test_invalid[concurrent]", "src/fparser/two/tests/fortran2008/test_loop_control_r818.py::test_invalid[concurrent", "src/fparser/two/tests/test_fortran2003.py::test_specification_part", "src/fparser/two/tests/test_fortran2003.py::test_constant", "src/fparser/two/tests/test_fortran2003.py::test_literal_constant", "src/fparser/two/tests/test_fortran2003.py::test_type_param_value", "src/fparser/two/tests/test_fortran2003.py::test_intrinsic_type_spec", "src/fparser/two/tests/test_fortran2003.py::test_signed_int_literal_constant", "src/fparser/two/tests/test_fortran2003.py::test_int_literal_constant", "src/fparser/two/tests/test_fortran2003.py::test_binary_constant", "src/fparser/two/tests/test_fortran2003.py::test_octal_constant", "src/fparser/two/tests/test_fortran2003.py::test_hex_constant", "src/fparser/two/tests/test_fortran2003.py::test_signed_real_literal_constant", "src/fparser/two/tests/test_fortran2003.py::test_real_literal_constant", "src/fparser/two/tests/test_fortran2003.py::test_char_selector", "src/fparser/two/tests/test_fortran2003.py::test_complex_literal_constant", "src/fparser/two/tests/test_fortran2003.py::test_type_name", "src/fparser/two/tests/test_fortran2003.py::test_length_selector", "src/fparser/two/tests/test_fortran2003.py::test_char_length", "src/fparser/two/tests/test_fortran2003.py::test_logical_literal_constant", "src/fparser/two/tests/test_fortran2003.py::test_type_attr_spec", "src/fparser/two/tests/test_fortran2003.py::test_end_type_stmt", "src/fparser/two/tests/test_fortran2003.py::test_sequence_stmt", "src/fparser/two/tests/test_fortran2003.py::test_type_param_def_stmt", "src/fparser/two/tests/test_fortran2003.py::test_type_param_decl", "src/fparser/two/tests/test_fortran2003.py::test_type_param_attr_spec", "src/fparser/two/tests/test_fortran2003.py::test_component_attr_spec", "src/fparser/two/tests/test_fortran2003.py::test_component_decl", "src/fparser/two/tests/test_fortran2003.py::test_proc_component_def_stmt", "src/fparser/two/tests/test_fortran2003.py::test_private_components_stmt", "src/fparser/two/tests/test_fortran2003.py::test_type_bound_procedure_part", "src/fparser/two/tests/test_fortran2003.py::test_proc_binding_stmt", "src/fparser/two/tests/test_fortran2003.py::test_generic_binding", "src/fparser/two/tests/test_fortran2003.py::test_final_binding", "src/fparser/two/tests/test_fortran2003.py::test_derived_type_spec", "src/fparser/two/tests/test_fortran2003.py::test_type_param_spec", "src/fparser/two/tests/test_fortran2003.py::test_type_param_spec_list", "src/fparser/two/tests/test_fortran2003.py::test_structure_constructor", "src/fparser/two/tests/test_fortran2003.py::test_component_spec", "src/fparser/two/tests/test_fortran2003.py::test_component_spec_list", "src/fparser/two/tests/test_fortran2003.py::test_enum_def", "src/fparser/two/tests/test_fortran2003.py::test_enum_def_stmt", "src/fparser/two/tests/test_fortran2003.py::test_array_constructor", "src/fparser/two/tests/test_fortran2003.py::test_ac_spec", "src/fparser/two/tests/test_fortran2003.py::test_ac_value_list", "src/fparser/two/tests/test_fortran2003.py::test_ac_implied_do", "src/fparser/two/tests/test_fortran2003.py::test_ac_implied_do_control", "src/fparser/two/tests/test_fortran2003.py::test_declaration_type_spec", "src/fparser/two/tests/test_fortran2003.py::test_attr_spec", "src/fparser/two/tests/test_fortran2003.py::test_dimension_attr_spec", "src/fparser/two/tests/test_fortran2003.py::test_intent_attr_spec", "src/fparser/two/tests/test_fortran2003.py::test_target_entity_decl", "src/fparser/two/tests/test_fortran2003.py::test_access_spec", "src/fparser/two/tests/test_fortran2003.py::test_language_binding_spec", "src/fparser/two/tests/test_fortran2003.py::test_explicit_shape_spec", "src/fparser/two/tests/test_fortran2003.py::test_upper_bound", "src/fparser/two/tests/test_fortran2003.py::test_assumed_shape_spec", "src/fparser/two/tests/test_fortran2003.py::test_deferred_shape_spec", "src/fparser/two/tests/test_fortran2003.py::test_assumed_size_spec", "src/fparser/two/tests/test_fortran2003.py::test_access_stmt", "src/fparser/two/tests/test_fortran2003.py::test_data_stmt", "src/fparser/two/tests/test_fortran2003.py::test_data_stmt_set", "src/fparser/two/tests/test_fortran2003.py::test_data_implied_do", "src/fparser/two/tests/test_fortran2003.py::test_dimension_stmt", "src/fparser/two/tests/test_fortran2003.py::test_intent_stmt", "src/fparser/two/tests/test_fortran2003.py::test_optional_stmt", "src/fparser/two/tests/test_fortran2003.py::test_parameter_stmt", "src/fparser/two/tests/test_fortran2003.py::test_named_constant_def", "src/fparser/two/tests/test_fortran2003.py::test_pointer_stmt", "src/fparser/two/tests/test_fortran2003.py::test_pointer_decl", "src/fparser/two/tests/test_fortran2003.py::test_protected_stmt", "src/fparser/two/tests/test_fortran2003.py::test_save_stmt", "src/fparser/two/tests/test_fortran2003.py::test_saved_entity", "src/fparser/two/tests/test_fortran2003.py::test_target_stmt", "src/fparser/two/tests/test_fortran2003.py::test_value_stmt", "src/fparser/two/tests/test_fortran2003.py::test_volatile_stmt", "src/fparser/two/tests/test_fortran2003.py::test_implicit_stmt", "src/fparser/two/tests/test_fortran2003.py::test_implicit_spec", "src/fparser/two/tests/test_fortran2003.py::test_letter_spec", "src/fparser/two/tests/test_fortran2003.py::test_namelist_stmt", "src/fparser/two/tests/test_fortran2003.py::test_equivalence_stmt", "src/fparser/two/tests/test_fortran2003.py::test_common_stmt", "src/fparser/two/tests/test_fortran2003.py::test_common_block_object", "src/fparser/two/tests/test_fortran2003.py::test_substring", "src/fparser/two/tests/test_fortran2003.py::test_substring_range", "src/fparser/two/tests/test_fortran2003.py::test_part_ref", "src/fparser/two/tests/test_fortran2003.py::test_type_param_inquiry", "src/fparser/two/tests/test_fortran2003.py::test_array_section", "src/fparser/two/tests/test_fortran2003.py::test_section_subscript", "src/fparser/two/tests/test_fortran2003.py::test_section_subscript_list", "src/fparser/two/tests/test_fortran2003.py::test_subscript_triplet", "src/fparser/two/tests/test_fortran2003.py::test_allocate_stmt", "src/fparser/two/tests/test_fortran2003.py::test_alloc_opt", "src/fparser/two/tests/test_fortran2003.py::test_nullify_stmt", "src/fparser/two/tests/test_fortran2003.py::test_deallocate_stmt", "src/fparser/two/tests/test_fortran2003.py::test_level_1_expr", "src/fparser/two/tests/test_fortran2003.py::test_mult_operand", "src/fparser/two/tests/test_fortran2003.py::test_level_2_expr", "src/fparser/two/tests/test_fortran2003.py::test_level_2_unary_expr", "src/fparser/two/tests/test_fortran2003.py::test_level_3_expr", "src/fparser/two/tests/test_fortran2003.py::test_level_4_expr", "src/fparser/two/tests/test_fortran2003.py::test_and_operand", "src/fparser/two/tests/test_fortran2003.py::test_or_operand", "src/fparser/two/tests/test_fortran2003.py::test_equiv_operand", "src/fparser/two/tests/test_fortran2003.py::test_level_5_expr", "src/fparser/two/tests/test_fortran2003.py::test_expr", "src/fparser/two/tests/test_fortran2003.py::test_logical_initialization_expr", "src/fparser/two/tests/test_fortran2003.py::test_assignment_stmt", "src/fparser/two/tests/test_fortran2003.py::test_pointer_assignment_stmt", "src/fparser/two/tests/test_fortran2003.py::test_proc_component_ref", "src/fparser/two/tests/test_fortran2003.py::test_where_stmt", "src/fparser/two/tests/test_fortran2003.py::test_where_construct_stmt", "src/fparser/two/tests/test_fortran2003.py::test_forall_construct", "src/fparser/two/tests/test_fortran2003.py::test_forall_triplet_spec", "src/fparser/two/tests/test_fortran2003.py::test_if_nonblock_do", "src/fparser/two/tests/test_fortran2003.py::test_case_selector", "src/fparser/two/tests/test_fortran2003.py::test_select_type_stmt", "src/fparser/two/tests/test_fortran2003.py::test_type_guard_stmt", "src/fparser/two/tests/test_fortran2003.py::test_label_do_stmt", "src/fparser/two/tests/test_fortran2003.py::test_continue_stmt", "src/fparser/two/tests/test_fortran2003.py::test_stop_stmt", "src/fparser/two/tests/test_fortran2003.py::test_io_unit", "src/fparser/two/tests/test_fortran2003.py::test_read_stmt", "src/fparser/two/tests/test_fortran2003.py::test_print_stmt", "src/fparser/two/tests/test_fortran2003.py::test_format", "src/fparser/two/tests/test_fortran2003.py::test_io_implied_do", "src/fparser/two/tests/test_fortran2003.py::test_io_implied_do_control", "src/fparser/two/tests/test_fortran2003.py::test_wait_stmt", "src/fparser/two/tests/test_fortran2003.py::test_wait_spec", "src/fparser/two/tests/test_fortran2003.py::test_backspace_stmt", "src/fparser/two/tests/test_fortran2003.py::test_endfile_stmt", "src/fparser/two/tests/test_fortran2003.py::test_rewind_stmt", "src/fparser/two/tests/test_fortran2003.py::test_position_spec", "src/fparser/two/tests/test_fortran2003.py::test_flush_stmt", "src/fparser/two/tests/test_fortran2003.py::test_flush_spec", "src/fparser/two/tests/test_fortran2003.py::test_inquire_stmt", "src/fparser/two/tests/test_fortran2003.py::test_inquire_spec", "src/fparser/two/tests/test_fortran2003.py::test_inquire_spec_list", "src/fparser/two/tests/test_fortran2003.py::test_open_stmt", "src/fparser/two/tests/test_fortran2003.py::test_connect_spec", "src/fparser/two/tests/test_fortran2003.py::test_connect_spec_list", "src/fparser/two/tests/test_fortran2003.py::test_format_stmt", "src/fparser/two/tests/test_fortran2003.py::test_format_specification", "src/fparser/two/tests/test_fortran2003.py::test_format_item", "src/fparser/two/tests/test_fortran2003.py::test_data_edit_desc", "src/fparser/two/tests/test_fortran2003.py::test_format_item_list", "src/fparser/two/tests/test_fortran2003.py::test_main_program0", "src/fparser/two/tests/test_fortran2003.py::test_invalid_main_program0", "src/fparser/two/tests/test_fortran2003.py::test_module", "src/fparser/two/tests/test_fortran2003.py::test_module_subprogram_part", "src/fparser/two/tests/test_fortran2003.py::test_module_nature", "src/fparser/two/tests/test_fortran2003.py::test_interface_block", "src/fparser/two/tests/test_fortran2003.py::test_interface_specification", "src/fparser/two/tests/test_fortran2003.py::test_interface_stmt", "src/fparser/two/tests/test_fortran2003.py::test_end_interface_stmt", "src/fparser/two/tests/test_fortran2003.py::test_interface_body", "src/fparser/two/tests/test_fortran2003.py::test_subroutine_body", "src/fparser/two/tests/test_fortran2003.py::test_function_body", "src/fparser/two/tests/test_fortran2003.py::test_procedure_stmt", "src/fparser/two/tests/test_fortran2003.py::test_generic_spec", "src/fparser/two/tests/test_fortran2003.py::test_dtio_generic_spec", "src/fparser/two/tests/test_fortran2003.py::test_import_stmt", "src/fparser/two/tests/test_fortran2003.py::test_external_stmt", "src/fparser/two/tests/test_fortran2003.py::test_procedure_declaration_stmt", "src/fparser/two/tests/test_fortran2003.py::test_proc_attr_spec[private-Access_Spec-PRIVATE]", "src/fparser/two/tests/test_fortran2003.py::test_proc_attr_spec[public-Access_Spec-PUBLIC]", "src/fparser/two/tests/test_fortran2003.py::test_proc_attr_spec[bind(c)-Language_Binding_Spec-BIND(C)]", "src/fparser/two/tests/test_fortran2003.py::test_proc_attr_spec[bind(c,", "src/fparser/two/tests/test_fortran2003.py::test_proc_attr_spec[intent(in)-Proc_Attr_Spec-INTENT(IN)]", "src/fparser/two/tests/test_fortran2003.py::test_proc_attr_spec[intent(out)-Proc_Attr_Spec-INTENT(OUT)]", "src/fparser/two/tests/test_fortran2003.py::test_proc_attr_spec[intent(inout)-Proc_Attr_Spec-INTENT(INOUT)]", "src/fparser/two/tests/test_fortran2003.py::test_proc_attr_spec[optional-Proc_Attr_Spec-OPTIONAL]", "src/fparser/two/tests/test_fortran2003.py::test_proc_attr_spec[pointer-Proc_Attr_Spec-POINTER]", "src/fparser/two/tests/test_fortran2003.py::test_proc_attr_spec[protected-Proc_Attr_Spec-PROTECTED]", "src/fparser/two/tests/test_fortran2003.py::test_proc_attr_spec[save-Proc_Attr_Spec-SAVE]", "src/fparser/two/tests/test_fortran2003.py::test_proc_decl", "src/fparser/two/tests/test_fortran2003.py::test_intrinsic_stmt", "src/fparser/two/tests/test_fortran2003.py::test_function_reference", "src/fparser/two/tests/test_fortran2003.py::test_call_stmt", "src/fparser/two/tests/test_fortran2003.py::test_procedure_designator", "src/fparser/two/tests/test_fortran2003.py::test_actual_arg_spec", "src/fparser/two/tests/test_fortran2003.py::test_actual_arg_spec_list", "src/fparser/two/tests/test_fortran2003.py::test_alt_return_spec", "src/fparser/two/tests/test_fortran2003.py::test_function_subprogram", "src/fparser/two/tests/test_fortran2003.py::test_function_stmt", "src/fparser/two/tests/test_fortran2003.py::test_dummy_arg_name", "src/fparser/two/tests/test_fortran2003.py::test_prefix_spec[integer-Intrinsic_Type_Spec-INTEGER]", "src/fparser/two/tests/test_fortran2003.py::test_prefix_spec[integer", "src/fparser/two/tests/test_fortran2003.py::test_prefix_spec[real-Intrinsic_Type_Spec-REAL]", "src/fparser/two/tests/test_fortran2003.py::test_prefix_spec[double", "src/fparser/two/tests/test_fortran2003.py::test_prefix_spec[complex-Intrinsic_Type_Spec-COMPLEX]", "src/fparser/two/tests/test_fortran2003.py::test_prefix_spec[character-Intrinsic_Type_Spec-CHARACTER]", "src/fparser/two/tests/test_fortran2003.py::test_prefix_spec[logical-Intrinsic_Type_Spec-LOGICAL]", "src/fparser/two/tests/test_fortran2003.py::test_prefix_spec[type(foo)-Declaration_Type_Spec-TYPE(foo)]", "src/fparser/two/tests/test_fortran2003.py::test_prefix_spec[class(bar)-Declaration_Type_Spec-CLASS(bar)]", "src/fparser/two/tests/test_fortran2003.py::test_prefix_spec[class(*)-Declaration_Type_Spec-CLASS(*)]", "src/fparser/two/tests/test_fortran2003.py::test_prefix_spec[elemental-Prefix_Spec-ELEMENTAL]", "src/fparser/two/tests/test_fortran2003.py::test_prefix_spec[impure-Prefix_Spec-IMPURE]", "src/fparser/two/tests/test_fortran2003.py::test_prefix_spec[module-Prefix_Spec-MODULE]", "src/fparser/two/tests/test_fortran2003.py::test_prefix_spec[pure-Prefix_Spec-PURE]", "src/fparser/two/tests/test_fortran2003.py::test_prefix_spec[recursive-Prefix_Spec-RECURSIVE]", "src/fparser/two/tests/test_fortran2003.py::test_suffix", "src/fparser/two/tests/test_fortran2003.py::test_end_function_stmt", "src/fparser/two/tests/test_fortran2003.py::test_subroutine_subprogram", "src/fparser/two/tests/test_fortran2003.py::test_subroutine_stmt", "src/fparser/two/tests/test_fortran2003.py::test_dummy_arg", "src/fparser/two/tests/test_fortran2003.py::test_end_subroutine_stmt", "src/fparser/two/tests/test_fortran2003.py::test_entry_stmt", "src/fparser/two/tests/test_fortran2003.py::test_return_stmt", "src/fparser/two/tests/test_fortran2003.py::test_contains" ]
[]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2023-04-29 01:33:38+00:00
bsd-3-clause
5,738
stfc__fparser-414
diff --git a/CHANGELOG.md b/CHANGELOG.md index 4b7f83b..151f365 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,8 +18,11 @@ Modifications by (in alphabetical order): * P. Vitt, University of Siegen, Germany * A. Voysey, UK Met Office -15/05/2023 PR #415 for #165. Bug fix for spurious matching of 'NAMELIST' in - certain contexts. +16/05/2023 PR #414 for #412. Bug fix for disappearing line when parsing + include files. + +15/05/2023 PR #415 for #165. Bug fix for code aborting when trying to match + 'NAMELIST' in certain contexts. 15/05/2023 PR #408 for #403. Add support for the F2008 DO CONCURRENT. diff --git a/src/fparser/common/readfortran.py b/src/fparser/common/readfortran.py index 16480fd..a5f886d 100644 --- a/src/fparser/common/readfortran.py +++ b/src/fparser/common/readfortran.py @@ -745,8 +745,19 @@ class FortranReaderBase: return item def put_item(self, item): - """Insert item to FIFO item buffer.""" - self.fifo_item.insert(0, item) + """Insert item into FIFO buffer of 'innermost' reader object. + + :param item: the item to insert into the FIFO. + :type item: :py:class:`fparser.common.readfortran.Line` | \ + :py:class:`fparser.common.readfortran.MultiLine` | \ + :py:class:`fparser.common.readfortran.Comment` + """ + if self.reader: + # We are reading an INCLUDE file so put this item in the FIFO + # of the corresponding reader. + self.reader.put_item(item) + else: + self.fifo_item.insert(0, item) # Iterator methods: @@ -767,7 +778,7 @@ class FortranReaderBase: value. :returns: the next line item. This can be from a local fifo \ - buffer, from an include reader or from this reader. + buffer, from an include reader or from this reader. :rtype: py:class:`fparser.common.readfortran.Line` :raises StopIteration: if no more lines are found. @@ -780,7 +791,6 @@ class FortranReaderBase: if self.reader is not None: # inside INCLUDE statement try: - # Return a line from the include. return self.reader.next(ignore_comments) except StopIteration: # There is nothing left in the include
stfc/fparser
0d802aa2bc12e97da06bc97be40bd1e927467460
diff --git a/src/fparser/common/tests/test_readfortran.py b/src/fparser/common/tests/test_readfortran.py index a3b7f5a..05d48bb 100644 --- a/src/fparser/common/tests/test_readfortran.py +++ b/src/fparser/common/tests/test_readfortran.py @@ -680,20 +680,46 @@ def test_put_item(ignore_comments): assert fifo_line == orig_line -def test_put_item_include(ignore_comments): +def test_put_item_include(ignore_comments, tmpdir): """Check that when a line that has been included via an include statement is consumed it can be pushed back so it can be consumed again. Test with and without ignoring comments. """ - reader = FortranStringReader(FORTRAN_CODE, ignore_comments=ignore_comments) + _ = tmpdir.chdir() + cwd = str(tmpdir) + include_code = """ + var1 = 1 + var2 = 2 + var3 = 3 +""" + with open(os.path.join(cwd, "my_include.h"), "w") as cfile: + cfile.write(include_code) + code = """ +program my_prog + integer :: var1, var2, var3 + include 'my_include.h' +end program my_prog +""" + reader = FortranStringReader(code, ignore_comments=ignore_comments) + lines = [] while True: - orig_line = reader.get_item() - if not orig_line: + lines.append(reader.get_item()) + # Try immediately putting the line back and then requesting it again. + # This checks that the correct FIFO buffer is being used. + reader.put_item(lines[-1]) + assert reader.get_item().line == lines[-1].line + if "var3 =" in lines[-1].line: + # Stop reading while we're still in the INCLUDE file so that we + # have a stack of readers when calling `put_item` below. break - reader.put_item(orig_line) - fifo_line = reader.get_item() - assert fifo_line == orig_line + # Put all the lines back in the same order that we saw them. + for line in reversed(lines): + reader.put_item(line) + # Check that the reader returns all those lines in the same order that + # we saw them originally. + for line in lines: + assert reader.get_item().line == line.line def test_multi_put_item(ignore_comments):
Syntax error when parsing source which INCLUDEs an INTERFACE block. Parsing the following code: PROGRAM test_include INCLUDE 'mpif.h' WRITE(*,*) MPI_COMM_WORLD END with the include path set to find the NVIDIA mpi header files gives: File: 'fixed_form.f' Syntax error: at line 2 >>> INCLUDE 'mpif.h' irrespective of whether the reader is set to free or fixed format.
0.0
0d802aa2bc12e97da06bc97be40bd1e927467460
[ "src/fparser/common/tests/test_readfortran.py::test_put_item_include[True]", "src/fparser/common/tests/test_readfortran.py::test_put_item_include[False]" ]
[ "src/fparser/common/tests/test_readfortran.py::test_empty_line_err", "src/fparser/common/tests/test_readfortran.py::test_line_map", "src/fparser/common/tests/test_readfortran.py::test_fortranreaderbase_logging", "src/fparser/common/tests/test_readfortran.py::test_include_not_found", "src/fparser/common/tests/test_readfortran.py::test_base_next_good_include", "src/fparser/common/tests/test_readfortran.py::test_fortranreaderbase_info", "src/fparser/common/tests/test_readfortran.py::test_fortranreaderbase_error", "src/fparser/common/tests/test_readfortran.py::test_fortranreaderbase_warning", "src/fparser/common/tests/test_readfortran.py::test_base_handle_multilines", "src/fparser/common/tests/test_readfortran.py::test_base_fixed_nonlabel", "src/fparser/common/tests/test_readfortran.py::test_base_fixed_continuation", "src/fparser/common/tests/test_readfortran.py::test_base_free_continuation", "src/fparser/common/tests/test_readfortran.py::test_include1", "src/fparser/common/tests/test_readfortran.py::test_include2", "src/fparser/common/tests/test_readfortran.py::test_include3", "src/fparser/common/tests/test_readfortran.py::test_include4", "src/fparser/common/tests/test_readfortran.py::test_include5", "src/fparser/common/tests/test_readfortran.py::test_include6[True]", "src/fparser/common/tests/test_readfortran.py::test_get_item[True]", "src/fparser/common/tests/test_readfortran.py::test_put_item[True]", "src/fparser/common/tests/test_readfortran.py::test_multi_put_item[True]", "src/fparser/common/tests/test_readfortran.py::test_include6[False]", "src/fparser/common/tests/test_readfortran.py::test_get_item[False]", "src/fparser/common/tests/test_readfortran.py::test_put_item[False]", "src/fparser/common/tests/test_readfortran.py::test_multi_put_item[False]", "src/fparser/common/tests/test_readfortran.py::test_multi_stmt_line1", "src/fparser/common/tests/test_readfortran.py::test_multi_stmt_line2", "src/fparser/common/tests/test_readfortran.py::test_multi_stmt_line3", "src/fparser/common/tests/test_readfortran.py::test_filename_reader", "src/fparser/common/tests/test_readfortran.py::test_file_reader", "src/fparser/common/tests/test_readfortran.py::test_none_in_fifo", "src/fparser/common/tests/test_readfortran.py::test_bad_file_reader", "src/fparser/common/tests/test_readfortran.py::test_string_reader", "src/fparser/common/tests/test_readfortran.py::test_reader_ignore_encoding[FortranStringReader]", "src/fparser/common/tests/test_readfortran.py::test_reader_ignore_encoding[FortranFileReader]", "src/fparser/common/tests/test_readfortran.py::test_inherited_f77", "src/fparser/common/tests/test_readfortran.py::test_pyf", "src/fparser/common/tests/test_readfortran.py::test_fix90", "src/fparser/common/tests/test_readfortran.py::test_f2py_directive_fixf90[True]", "src/fparser/common/tests/test_readfortran.py::test_f2py_freef90[True]", "src/fparser/common/tests/test_readfortran.py::test_f2py_directive_fixf90[False]", "src/fparser/common/tests/test_readfortran.py::test_f2py_freef90[False]", "src/fparser/common/tests/test_readfortran.py::test_utf_char_in_code", "src/fparser/common/tests/test_readfortran.py::test_extract_label", "src/fparser/common/tests/test_readfortran.py::test_extract_construct_name", "src/fparser/common/tests/test_readfortran.py::test_handle_cpp_directive[#include", "src/fparser/common/tests/test_readfortran.py::test_handle_cpp_directive[", "src/fparser/common/tests/test_readfortran.py::test_handle_cpp_directive[#define", "src/fparser/common/tests/test_readfortran.py::test_handle_cpp_directive[#ifdef", "src/fparser/common/tests/test_readfortran.py::test_handle_cpp_directive[#if", "src/fparser/common/tests/test_readfortran.py::test_handle_cpp_directive[abc", "src/fparser/common/tests/test_readfortran.py::test_handle_cpp_directive[\"#\"-False]", "src/fparser/common/tests/test_readfortran.py::test_handle_cpp_directive[!", "src/fparser/common/tests/test_readfortran.py::test_reader_cpp_directives", "src/fparser/common/tests/test_readfortran.py::test_multiline_cpp_directives", "src/fparser/common/tests/test_readfortran.py::test_single_comment", "src/fparser/common/tests/test_readfortran.py::test_many_comments", "src/fparser/common/tests/test_readfortran.py::test_quotes_in_inline_comments[", "src/fparser/common/tests/test_readfortran.py::test_comments_within_continuation", "src/fparser/common/tests/test_readfortran.py::test_single_blank_line[\\n]", "src/fparser/common/tests/test_readfortran.py::test_single_blank_line[", "src/fparser/common/tests/test_readfortran.py::test_multiple_blank_lines", "src/fparser/common/tests/test_readfortran.py::test_blank_lines_within_continuation" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2023-05-11 15:45:55+00:00
bsd-3-clause
5,739
stfc__fparser-415
diff --git a/CHANGELOG.md b/CHANGELOG.md index 37b8b35..4b7f83b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,6 +18,9 @@ Modifications by (in alphabetical order): * P. Vitt, University of Siegen, Germany * A. Voysey, UK Met Office +15/05/2023 PR #415 for #165. Bug fix for spurious matching of 'NAMELIST' in + certain contexts. + 15/05/2023 PR #408 for #403. Add support for the F2008 DO CONCURRENT. 26/04/2023 PR #406 for #405. Add support for F2008 optional "::" in PROCEDURE diff --git a/src/fparser/two/Fortran2003.py b/src/fparser/two/Fortran2003.py index d303d69..3f93fd2 100644 --- a/src/fparser/two/Fortran2003.py +++ b/src/fparser/two/Fortran2003.py @@ -4651,15 +4651,12 @@ class Letter_Spec(Base): # R551 class Namelist_Stmt(StmtBase): # R552 """ - :: - - <namelist-stmt> = NAMELIST / <namelist-group-name> / - <namelist-group-object-list> [ [ , ] / <namelist-group-name> / - <namelist-group-object-list> ]... + Fortran 2003 rule R552:: - Attributes:: - - items : (Namelist_Group_Name, Namelist_Group_Object_List)-tuple + namelist-stmt is NAMELIST + / namelist-group-name / namelist-group-object-list + [ [,] / namelist-group-name / + namelist-group-object-list ] ... """ @@ -4668,28 +4665,46 @@ class Namelist_Stmt(StmtBase): # R552 @staticmethod def match(string): - if string[:8].upper() != "NAMELIST": - return - line = string[8:].lstrip() + """Implements the matching for a Namelist_Stmt. + + :param str string: a string containing the code to match. + + :returns: `None` if there is no match, otherwise a `tuple` \ + containing 2-tuples with a namelist name and a namelist object \ + list. + :rtype: Optional[Tuple[Tuple[ \ + fparser.two.Fortran2003.Namelist_Group_Name, \ + fparser.two.Fortran2003.Namelist_Group_Object_List]]] + + """ + line = string.lstrip() + if line[:8].upper() != "NAMELIST": + return None + line = line[8:].lstrip() + if not line: + return None parts = line.split("/") + text_before_slash = parts.pop(0) + if text_before_slash: + return None items = [] - fst = parts.pop(0) - assert not fst, repr((fst, parts)) while len(parts) >= 2: - name, lst = parts[:2] - del parts[:2] - name = name.strip() - lst = lst.strip() + name = parts.pop(0).strip() + lst = parts.pop(0).strip() if lst.endswith(","): lst = lst[:-1].rstrip() items.append((Namelist_Group_Name(name), Namelist_Group_Object_List(lst))) - assert not parts, repr(parts) + if parts: + # There is a missing second '/' + return None return tuple(items) def tostr(self): - return "NAMELIST " + ", ".join( - "/%s/ %s" % (name_lst) for name_lst in self.items - ) + """ + :returns: this Namelist_Stmt as a string. + :rtype: str + """ + return "NAMELIST " + ", ".join(f"/{name}/ {lst}" for name, lst in self.items) class Namelist_Group_Object(Base): # R553
stfc/fparser
fbcc2c67e3257402b602c756da997f42af20a27e
diff --git a/src/fparser/two/tests/fortran2003/test_namelist_stmt_r552.py b/src/fparser/two/tests/fortran2003/test_namelist_stmt_r552.py new file mode 100644 index 0000000..bdedf82 --- /dev/null +++ b/src/fparser/two/tests/fortran2003/test_namelist_stmt_r552.py @@ -0,0 +1,88 @@ +# Copyright (c) 2023 Science and Technology Facilities Council. + +# All rights reserved. + +# Modifications made as part of the fparser project are distributed +# under the following license: + +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: + +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. + +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. + +# 3. Neither the name of the copyright holder nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. + +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""Test Fortran 2003 rule R552 : This file tests the support for the +NAMELIST statement. + +""" +import pytest + +from fparser.two.Fortran2003 import Namelist_Stmt +from fparser.two.utils import NoMatchError + + [email protected]( + "code", + [ + "", + "namelost", + "namelist", + "namelist x", + "namelist x/", + "namelist /x", + "namelist /x/ y /", + ], +) +def test_match_errors(code): + """Test that the match method returns None when the supplied code is + invalid. Also check that this results in a NoMatchError for an + instance of the class. + + """ + assert not Namelist_Stmt.match(code) + with pytest.raises(NoMatchError): + _ = Namelist_Stmt(code) + + +def test_simple(): + """Test that a namelist with a single name and list is matched and + that the tostr() method outputs the resultant code as + expected. Also check that the namelist keyword matching is case + insensitive and that leading and trailing spaces are supported. + + """ + result = Namelist_Stmt(" NamelisT /x/ a ") + assert isinstance(result, Namelist_Stmt) + assert result.tostr() == "NAMELIST /x/ a" + + +def test_multi(): + """Test that multiple names and lists are matched, with and without a + comma separator and that the tostr() method outputs the resultant + code as expected. + + """ + result = Namelist_Stmt("namelist /x/ a, /y/ b,c /z/ d") + assert isinstance(result, Namelist_Stmt) + assert result.tostr() == "NAMELIST /x/ a, /y/ b, c, /z/ d" diff --git a/src/fparser/two/tests/test_fortran2003.py b/src/fparser/two/tests/test_fortran2003.py index fc75b86..0ee3529 100644 --- a/src/fparser/two/tests/test_fortran2003.py +++ b/src/fparser/two/tests/test_fortran2003.py @@ -1394,16 +1394,6 @@ def test_letter_spec(): # R551 assert str(obj) == "D" -def test_namelist_stmt(): # R552 - tcls = Namelist_Stmt - obj = tcls("namelist / nlist / a") - assert isinstance(obj, tcls), repr(obj) - assert str(obj) == "NAMELIST /nlist/ a" - - obj = tcls("namelist / nlist / a, /mlist/ b,c /klist/ d,e") - assert str(obj) == "NAMELIST /nlist/ a, /mlist/ b, c, /klist/ d, e" - - def test_equivalence_stmt(): # R554 tcls = Equivalence_Stmt obj = tcls("equivalence (a, b ,z)")
namelist false match error The f2003 namelist match rule r552 produces an assertion error when a variable starting with the name `namelist' is initialised ... ``` program test NamelistFile = "dummy file" end program ```
0.0
fbcc2c67e3257402b602c756da997f42af20a27e
[ "src/fparser/two/tests/fortran2003/test_namelist_stmt_r552.py::test_match_errors[namelist]", "src/fparser/two/tests/fortran2003/test_namelist_stmt_r552.py::test_match_errors[namelist", "src/fparser/two/tests/fortran2003/test_namelist_stmt_r552.py::test_simple" ]
[ "src/fparser/two/tests/fortran2003/test_namelist_stmt_r552.py::test_match_errors[]", "src/fparser/two/tests/fortran2003/test_namelist_stmt_r552.py::test_match_errors[namelost]", "src/fparser/two/tests/fortran2003/test_namelist_stmt_r552.py::test_multi", "src/fparser/two/tests/test_fortran2003.py::test_specification_part", "src/fparser/two/tests/test_fortran2003.py::test_constant", "src/fparser/two/tests/test_fortran2003.py::test_literal_constant", "src/fparser/two/tests/test_fortran2003.py::test_type_param_value", "src/fparser/two/tests/test_fortran2003.py::test_intrinsic_type_spec", "src/fparser/two/tests/test_fortran2003.py::test_signed_int_literal_constant", "src/fparser/two/tests/test_fortran2003.py::test_int_literal_constant", "src/fparser/two/tests/test_fortran2003.py::test_binary_constant", "src/fparser/two/tests/test_fortran2003.py::test_octal_constant", "src/fparser/two/tests/test_fortran2003.py::test_hex_constant", "src/fparser/two/tests/test_fortran2003.py::test_signed_real_literal_constant", "src/fparser/two/tests/test_fortran2003.py::test_real_literal_constant", "src/fparser/two/tests/test_fortran2003.py::test_char_selector", "src/fparser/two/tests/test_fortran2003.py::test_complex_literal_constant", "src/fparser/two/tests/test_fortran2003.py::test_type_name", "src/fparser/two/tests/test_fortran2003.py::test_length_selector", "src/fparser/two/tests/test_fortran2003.py::test_char_length", "src/fparser/two/tests/test_fortran2003.py::test_logical_literal_constant", "src/fparser/two/tests/test_fortran2003.py::test_type_attr_spec", "src/fparser/two/tests/test_fortran2003.py::test_end_type_stmt", "src/fparser/two/tests/test_fortran2003.py::test_sequence_stmt", "src/fparser/two/tests/test_fortran2003.py::test_type_param_def_stmt", "src/fparser/two/tests/test_fortran2003.py::test_type_param_decl", "src/fparser/two/tests/test_fortran2003.py::test_type_param_attr_spec", "src/fparser/two/tests/test_fortran2003.py::test_component_attr_spec", "src/fparser/two/tests/test_fortran2003.py::test_component_decl", "src/fparser/two/tests/test_fortran2003.py::test_proc_component_def_stmt", "src/fparser/two/tests/test_fortran2003.py::test_private_components_stmt", "src/fparser/two/tests/test_fortran2003.py::test_type_bound_procedure_part", "src/fparser/two/tests/test_fortran2003.py::test_proc_binding_stmt", "src/fparser/two/tests/test_fortran2003.py::test_generic_binding", "src/fparser/two/tests/test_fortran2003.py::test_final_binding", "src/fparser/two/tests/test_fortran2003.py::test_derived_type_spec", "src/fparser/two/tests/test_fortran2003.py::test_type_param_spec", "src/fparser/two/tests/test_fortran2003.py::test_type_param_spec_list", "src/fparser/two/tests/test_fortran2003.py::test_structure_constructor", "src/fparser/two/tests/test_fortran2003.py::test_component_spec", "src/fparser/two/tests/test_fortran2003.py::test_component_spec_list", "src/fparser/two/tests/test_fortran2003.py::test_enum_def", "src/fparser/two/tests/test_fortran2003.py::test_enum_def_stmt", "src/fparser/two/tests/test_fortran2003.py::test_array_constructor", "src/fparser/two/tests/test_fortran2003.py::test_ac_spec", "src/fparser/two/tests/test_fortran2003.py::test_ac_value_list", "src/fparser/two/tests/test_fortran2003.py::test_ac_implied_do", "src/fparser/two/tests/test_fortran2003.py::test_ac_implied_do_control", "src/fparser/two/tests/test_fortran2003.py::test_declaration_type_spec", "src/fparser/two/tests/test_fortran2003.py::test_attr_spec", "src/fparser/two/tests/test_fortran2003.py::test_dimension_attr_spec", "src/fparser/two/tests/test_fortran2003.py::test_intent_attr_spec", "src/fparser/two/tests/test_fortran2003.py::test_target_entity_decl", "src/fparser/two/tests/test_fortran2003.py::test_access_spec", "src/fparser/two/tests/test_fortran2003.py::test_language_binding_spec", "src/fparser/two/tests/test_fortran2003.py::test_explicit_shape_spec", "src/fparser/two/tests/test_fortran2003.py::test_upper_bound", "src/fparser/two/tests/test_fortran2003.py::test_assumed_shape_spec", "src/fparser/two/tests/test_fortran2003.py::test_deferred_shape_spec", "src/fparser/two/tests/test_fortran2003.py::test_assumed_size_spec", "src/fparser/two/tests/test_fortran2003.py::test_access_stmt", "src/fparser/two/tests/test_fortran2003.py::test_data_stmt", "src/fparser/two/tests/test_fortran2003.py::test_data_stmt_set", "src/fparser/two/tests/test_fortran2003.py::test_data_implied_do", "src/fparser/two/tests/test_fortran2003.py::test_dimension_stmt", "src/fparser/two/tests/test_fortran2003.py::test_intent_stmt", "src/fparser/two/tests/test_fortran2003.py::test_optional_stmt", "src/fparser/two/tests/test_fortran2003.py::test_parameter_stmt", "src/fparser/two/tests/test_fortran2003.py::test_named_constant_def", "src/fparser/two/tests/test_fortran2003.py::test_pointer_stmt", "src/fparser/two/tests/test_fortran2003.py::test_pointer_decl", "src/fparser/two/tests/test_fortran2003.py::test_protected_stmt", "src/fparser/two/tests/test_fortran2003.py::test_save_stmt", "src/fparser/two/tests/test_fortran2003.py::test_saved_entity", "src/fparser/two/tests/test_fortran2003.py::test_target_stmt", "src/fparser/two/tests/test_fortran2003.py::test_value_stmt", "src/fparser/two/tests/test_fortran2003.py::test_volatile_stmt", "src/fparser/two/tests/test_fortran2003.py::test_implicit_stmt", "src/fparser/two/tests/test_fortran2003.py::test_implicit_spec", "src/fparser/two/tests/test_fortran2003.py::test_letter_spec", "src/fparser/two/tests/test_fortran2003.py::test_equivalence_stmt", "src/fparser/two/tests/test_fortran2003.py::test_common_stmt", "src/fparser/two/tests/test_fortran2003.py::test_common_block_object", "src/fparser/two/tests/test_fortran2003.py::test_substring", "src/fparser/two/tests/test_fortran2003.py::test_substring_range", "src/fparser/two/tests/test_fortran2003.py::test_part_ref", "src/fparser/two/tests/test_fortran2003.py::test_type_param_inquiry", "src/fparser/two/tests/test_fortran2003.py::test_array_section", "src/fparser/two/tests/test_fortran2003.py::test_section_subscript", "src/fparser/two/tests/test_fortran2003.py::test_section_subscript_list", "src/fparser/two/tests/test_fortran2003.py::test_subscript_triplet", "src/fparser/two/tests/test_fortran2003.py::test_allocate_stmt", "src/fparser/two/tests/test_fortran2003.py::test_alloc_opt", "src/fparser/two/tests/test_fortran2003.py::test_nullify_stmt", "src/fparser/two/tests/test_fortran2003.py::test_deallocate_stmt", "src/fparser/two/tests/test_fortran2003.py::test_level_1_expr", "src/fparser/two/tests/test_fortran2003.py::test_mult_operand", "src/fparser/two/tests/test_fortran2003.py::test_level_2_expr", "src/fparser/two/tests/test_fortran2003.py::test_level_2_unary_expr", "src/fparser/two/tests/test_fortran2003.py::test_level_3_expr", "src/fparser/two/tests/test_fortran2003.py::test_level_4_expr", "src/fparser/two/tests/test_fortran2003.py::test_and_operand", "src/fparser/two/tests/test_fortran2003.py::test_or_operand", "src/fparser/two/tests/test_fortran2003.py::test_equiv_operand", "src/fparser/two/tests/test_fortran2003.py::test_level_5_expr", "src/fparser/two/tests/test_fortran2003.py::test_expr", "src/fparser/two/tests/test_fortran2003.py::test_logical_initialization_expr", "src/fparser/two/tests/test_fortran2003.py::test_assignment_stmt", "src/fparser/two/tests/test_fortran2003.py::test_pointer_assignment_stmt", "src/fparser/two/tests/test_fortran2003.py::test_proc_component_ref", "src/fparser/two/tests/test_fortran2003.py::test_where_stmt", "src/fparser/two/tests/test_fortran2003.py::test_where_construct_stmt", "src/fparser/two/tests/test_fortran2003.py::test_forall_construct", "src/fparser/two/tests/test_fortran2003.py::test_forall_triplet_spec", "src/fparser/two/tests/test_fortran2003.py::test_if_nonblock_do", "src/fparser/two/tests/test_fortran2003.py::test_case_selector", "src/fparser/two/tests/test_fortran2003.py::test_select_type_stmt", "src/fparser/two/tests/test_fortran2003.py::test_type_guard_stmt", "src/fparser/two/tests/test_fortran2003.py::test_label_do_stmt", "src/fparser/two/tests/test_fortran2003.py::test_continue_stmt", "src/fparser/two/tests/test_fortran2003.py::test_stop_stmt", "src/fparser/two/tests/test_fortran2003.py::test_io_unit", "src/fparser/two/tests/test_fortran2003.py::test_read_stmt", "src/fparser/two/tests/test_fortran2003.py::test_print_stmt", "src/fparser/two/tests/test_fortran2003.py::test_format", "src/fparser/two/tests/test_fortran2003.py::test_io_implied_do", "src/fparser/two/tests/test_fortran2003.py::test_io_implied_do_control", "src/fparser/two/tests/test_fortran2003.py::test_wait_stmt", "src/fparser/two/tests/test_fortran2003.py::test_wait_spec", "src/fparser/two/tests/test_fortran2003.py::test_backspace_stmt", "src/fparser/two/tests/test_fortran2003.py::test_endfile_stmt", "src/fparser/two/tests/test_fortran2003.py::test_rewind_stmt", "src/fparser/two/tests/test_fortran2003.py::test_position_spec", "src/fparser/two/tests/test_fortran2003.py::test_flush_stmt", "src/fparser/two/tests/test_fortran2003.py::test_flush_spec", "src/fparser/two/tests/test_fortran2003.py::test_inquire_stmt", "src/fparser/two/tests/test_fortran2003.py::test_inquire_spec", "src/fparser/two/tests/test_fortran2003.py::test_inquire_spec_list", "src/fparser/two/tests/test_fortran2003.py::test_open_stmt", "src/fparser/two/tests/test_fortran2003.py::test_connect_spec", "src/fparser/two/tests/test_fortran2003.py::test_connect_spec_list", "src/fparser/two/tests/test_fortran2003.py::test_format_stmt", "src/fparser/two/tests/test_fortran2003.py::test_format_specification", "src/fparser/two/tests/test_fortran2003.py::test_format_item", "src/fparser/two/tests/test_fortran2003.py::test_data_edit_desc", "src/fparser/two/tests/test_fortran2003.py::test_format_item_list", "src/fparser/two/tests/test_fortran2003.py::test_main_program0", "src/fparser/two/tests/test_fortran2003.py::test_invalid_main_program0", "src/fparser/two/tests/test_fortran2003.py::test_module", "src/fparser/two/tests/test_fortran2003.py::test_module_subprogram_part", "src/fparser/two/tests/test_fortran2003.py::test_module_nature", "src/fparser/two/tests/test_fortran2003.py::test_interface_block", "src/fparser/two/tests/test_fortran2003.py::test_interface_specification", "src/fparser/two/tests/test_fortran2003.py::test_interface_stmt", "src/fparser/two/tests/test_fortran2003.py::test_end_interface_stmt", "src/fparser/two/tests/test_fortran2003.py::test_interface_body", "src/fparser/two/tests/test_fortran2003.py::test_subroutine_body", "src/fparser/two/tests/test_fortran2003.py::test_function_body", "src/fparser/two/tests/test_fortran2003.py::test_procedure_stmt", "src/fparser/two/tests/test_fortran2003.py::test_generic_spec", "src/fparser/two/tests/test_fortran2003.py::test_dtio_generic_spec", "src/fparser/two/tests/test_fortran2003.py::test_import_stmt", "src/fparser/two/tests/test_fortran2003.py::test_external_stmt", "src/fparser/two/tests/test_fortran2003.py::test_procedure_declaration_stmt", "src/fparser/two/tests/test_fortran2003.py::test_proc_attr_spec[private-Access_Spec-PRIVATE]", "src/fparser/two/tests/test_fortran2003.py::test_proc_attr_spec[public-Access_Spec-PUBLIC]", "src/fparser/two/tests/test_fortran2003.py::test_proc_attr_spec[bind(c)-Language_Binding_Spec-BIND(C)]", "src/fparser/two/tests/test_fortran2003.py::test_proc_attr_spec[bind(c,", "src/fparser/two/tests/test_fortran2003.py::test_proc_attr_spec[intent(in)-Proc_Attr_Spec-INTENT(IN)]", "src/fparser/two/tests/test_fortran2003.py::test_proc_attr_spec[intent(out)-Proc_Attr_Spec-INTENT(OUT)]", "src/fparser/two/tests/test_fortran2003.py::test_proc_attr_spec[intent(inout)-Proc_Attr_Spec-INTENT(INOUT)]", "src/fparser/two/tests/test_fortran2003.py::test_proc_attr_spec[optional-Proc_Attr_Spec-OPTIONAL]", "src/fparser/two/tests/test_fortran2003.py::test_proc_attr_spec[pointer-Proc_Attr_Spec-POINTER]", "src/fparser/two/tests/test_fortran2003.py::test_proc_attr_spec[protected-Proc_Attr_Spec-PROTECTED]", "src/fparser/two/tests/test_fortran2003.py::test_proc_attr_spec[save-Proc_Attr_Spec-SAVE]", "src/fparser/two/tests/test_fortran2003.py::test_proc_decl", "src/fparser/two/tests/test_fortran2003.py::test_intrinsic_stmt", "src/fparser/two/tests/test_fortran2003.py::test_function_reference", "src/fparser/two/tests/test_fortran2003.py::test_call_stmt", "src/fparser/two/tests/test_fortran2003.py::test_procedure_designator", "src/fparser/two/tests/test_fortran2003.py::test_actual_arg_spec", "src/fparser/two/tests/test_fortran2003.py::test_actual_arg_spec_list", "src/fparser/two/tests/test_fortran2003.py::test_alt_return_spec", "src/fparser/two/tests/test_fortran2003.py::test_function_subprogram", "src/fparser/two/tests/test_fortran2003.py::test_function_stmt", "src/fparser/two/tests/test_fortran2003.py::test_dummy_arg_name", "src/fparser/two/tests/test_fortran2003.py::test_prefix_spec[integer-Intrinsic_Type_Spec-INTEGER]", "src/fparser/two/tests/test_fortran2003.py::test_prefix_spec[integer", "src/fparser/two/tests/test_fortran2003.py::test_prefix_spec[real-Intrinsic_Type_Spec-REAL]", "src/fparser/two/tests/test_fortran2003.py::test_prefix_spec[double", "src/fparser/two/tests/test_fortran2003.py::test_prefix_spec[complex-Intrinsic_Type_Spec-COMPLEX]", "src/fparser/two/tests/test_fortran2003.py::test_prefix_spec[character-Intrinsic_Type_Spec-CHARACTER]", "src/fparser/two/tests/test_fortran2003.py::test_prefix_spec[logical-Intrinsic_Type_Spec-LOGICAL]", "src/fparser/two/tests/test_fortran2003.py::test_prefix_spec[type(foo)-Declaration_Type_Spec-TYPE(foo)]", "src/fparser/two/tests/test_fortran2003.py::test_prefix_spec[class(bar)-Declaration_Type_Spec-CLASS(bar)]", "src/fparser/two/tests/test_fortran2003.py::test_prefix_spec[class(*)-Declaration_Type_Spec-CLASS(*)]", "src/fparser/two/tests/test_fortran2003.py::test_prefix_spec[elemental-Prefix_Spec-ELEMENTAL]", "src/fparser/two/tests/test_fortran2003.py::test_prefix_spec[impure-Prefix_Spec-IMPURE]", "src/fparser/two/tests/test_fortran2003.py::test_prefix_spec[module-Prefix_Spec-MODULE]", "src/fparser/two/tests/test_fortran2003.py::test_prefix_spec[pure-Prefix_Spec-PURE]", "src/fparser/two/tests/test_fortran2003.py::test_prefix_spec[recursive-Prefix_Spec-RECURSIVE]", "src/fparser/two/tests/test_fortran2003.py::test_suffix", "src/fparser/two/tests/test_fortran2003.py::test_end_function_stmt", "src/fparser/two/tests/test_fortran2003.py::test_subroutine_subprogram", "src/fparser/two/tests/test_fortran2003.py::test_subroutine_stmt", "src/fparser/two/tests/test_fortran2003.py::test_dummy_arg", "src/fparser/two/tests/test_fortran2003.py::test_end_subroutine_stmt", "src/fparser/two/tests/test_fortran2003.py::test_entry_stmt", "src/fparser/two/tests/test_fortran2003.py::test_return_stmt", "src/fparser/two/tests/test_fortran2003.py::test_contains" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2023-05-12 15:09:53+00:00
bsd-3-clause
5,740
stfc__fparser-431
diff --git a/CHANGELOG.md b/CHANGELOG.md index 9563415..210c960 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,6 +18,8 @@ Modifications by (in alphabetical order): * P. Vitt, University of Siegen, Germany * A. Voysey, UK Met Office +03/10/2023 PR #431 for #430. Fixes bug in WHERE handling in fparser1. + 14/09/2023 PR #425 for #411. Splits the monolithic Fortran2008.py file into separate classes. diff --git a/src/fparser/one/block_statements.py b/src/fparser/one/block_statements.py index 125073b..4fa946b 100644 --- a/src/fparser/one/block_statements.py +++ b/src/fparser/one/block_statements.py @@ -1089,7 +1089,7 @@ class Where(BeginStatement): name = "" def tostr(self): - return "WHERE ( %s )" % (self.expr) + return f"WHERE ( {self.item.apply_map(self.expr)} )" def process_item(self): self.expr = self.item.get_line()[5:].lstrip()[1:-1].strip()
stfc/fparser
5018a64e765187b444a3e3540eb2c0dd10262f24
diff --git a/src/fparser/one/tests/test_where_construct_stmt_r745.py b/src/fparser/one/tests/test_where_construct_stmt_r745.py new file mode 100644 index 0000000..c4baad4 --- /dev/null +++ b/src/fparser/one/tests/test_where_construct_stmt_r745.py @@ -0,0 +1,74 @@ +# ----------------------------------------------------------------------------- +# BSD 3-Clause License +# +# Copyright (c) 2023, Science and Technology Facilities Council. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this +# list of conditions and the following disclaimer. +# +# * Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# +# * Neither the name of the copyright holder nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN +# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +# POSSIBILITY OF SUCH DAMAGE. +# ----------------------------------------------------------------------------- + +""" + Module containing tests for Fortran2003 where_construct_stmt rule R745. + + R745 where-construct-stmt is [where-construct-name:] WHERE ( mask-expr ) + +""" +import pytest + +from fparser.common.sourceinfo import FortranFormat +from fparser.one.parsefortran import FortranParser +from fparser.common.readfortran import FortranStringReader + + [email protected]("name", ["", "name"]) +def test_where_construct_stmt(name): + """Test that the Fortran2003 where_construct_stmt rule R745 works + correctly. Test with and without the optional + where-construct-name. + + R745 where-construct-stmt is [where-construct-name:] WHERE ( mask-expr ) + + """ + space = "" + colon = "" + if name: + colon = ":" + space = " " + code = ( + f" SUBROUTINE columnwise_code()\n" + f" {name}{colon}{space}WHERE ( col_mat(:,:,cell) /= 0.0_r_solve )\n" + f" col_mat(:,:,cell) = 1.0_r_solver/col_mat(:,:,cell)\n" + f" END WHERE{space}{name}\n" + f" END SUBROUTINE columnwise_code" + ) + reader = FortranStringReader(code) + reader.set_format(FortranFormat(True, False)) + parser = FortranParser(reader) + parser.parse() + mod = parser.block.content[0] + assert str(mod) == code
where statement bug in fparser1 There is a bug in the processing of fparser1 for where statements. We get the internal expression on output instead of the value of the external expression. For example, the following input code ... ``` subroutine columnwise_op_asm_m2v_lumped_inv_kernel_code() where (columnwise_matrix(:,:,cell) /= 0.0_r_solver) columnwise_matrix(:,:,cell) = 1.0_r_solver/columnwise_matrix(:,:,cell) end where end subroutine columnwise_op_asm_m2v_lumped_inv_kernel_code ``` gives ``` !BEGINSOURCE SUBROUTINE columnwise_op_asm_m2v_lumped_inv_kernel_code() WHERE ( F2PY_EXPR_TUPLE_1 ) columnwise_matrix(:,:,cell) = 1.0_r_solver/columnwise_matrix(:,:,cell) END WHERE END SUBROUTINE columnwise_op_asm_m2v_lumped_inv_kernel_code ``` We are not actively supporting fparser1 anymore, however, PSyclone still uses it for parsing LFRic and this fixes that bug without having to wait for the new fparser2/psyir parsing of LFRic which will take some time to complete.
0.0
5018a64e765187b444a3e3540eb2c0dd10262f24
[ "src/fparser/one/tests/test_where_construct_stmt_r745.py::test_where_construct_stmt[]", "src/fparser/one/tests/test_where_construct_stmt_r745.py::test_where_construct_stmt[name]" ]
[]
{ "failed_lite_validators": [ "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2023-10-02 15:00:26+00:00
bsd-3-clause
5,741
stfc__fparser-47
diff --git a/src/fparser/Fortran2003.py b/src/fparser/Fortran2003.py index 429ca80..20f3dca 100644 --- a/src/fparser/Fortran2003.py +++ b/src/fparser/Fortran2003.py @@ -161,8 +161,16 @@ class Base(ComparableMixin): subclasses = {} @show_result - def __new__(cls, string, parent_cls = None): + def __new__(cls, string, parent_cls=None): """ + Create a new instance of this object. + + :param cls: the class of object to create + :type cls: :py:type:`type` + :param string: (source of) Fortran string to parse + :type string: str or :py:class:`FortranReaderBase` + :param parent_cls: the parent class of this object + :type parent_cls: :py:type:`type` """ if parent_cls is None: parent_cls = [cls] @@ -218,12 +226,9 @@ class Base(ComparableMixin): obj = None if obj is not None: return obj - else: raise AssertionError(repr(result)) errmsg = '%s: %r' % (cls.__name__, string) - #if isinstance(string, FortranReaderBase) and string.fifo_item: - # errmsg += ' while reaching %s' % (string.fifo_item[-1]) raise NoMatchError(errmsg) ## def restore_reader(self): @@ -5379,6 +5384,7 @@ class Internal_File_Variable(Base): # R903 """ subclass_names = ['Char_Variable'] + class Open_Stmt(StmtBase, CALLBase): # R904 """ <open-stmt> = OPEN ( <connect-spec-list> ) @@ -5387,10 +5393,15 @@ class Open_Stmt(StmtBase, CALLBase): # R904 use_names = ['Connect_Spec_List'] @staticmethod def match(string): - return CALLBase.match('OPEN', Connect_Spec_List, string, require_rhs=True) + # The Connect_Spec_List class is generated automatically + # by code at the end of this module + return CALLBase.match('OPEN', Connect_Spec_List, string, + require_rhs=True) -class Connect_Spec(KeywordValueBase): # R905 + +class Connect_Spec(KeywordValueBase): """ + R905 <connect-spec> = [ UNIT = ] <file-unit-number> | ACCESS = <scalar-default-char-expr> | ACTION = <scalar-default-char-expr> @@ -5412,26 +5423,40 @@ class Connect_Spec(KeywordValueBase): # R905 | STATUS = <scalar-default-char-expr> """ subclass_names = [] - use_names = ['File_Unit_Number', 'Scalar_Default_Char_Expr', 'Label', 'File_Name_Expr', 'Iomsg_Variable', + use_names = ['File_Unit_Number', 'Scalar_Default_Char_Expr', 'Label', + 'File_Name_Expr', 'Iomsg_Variable', 'Scalar_Int_Expr', 'Scalar_Int_Variable'] + + @staticmethod def match(string): - for (k,v) in [\ - (['ACCESS','ACTION','ASYNCHRONOUS','BLANK','DECIMAL','DELIM','ENCODING', - 'FORM','PAD','POSITION','ROUND','SIGN','STATUS'], Scalar_Default_Char_Expr), - ('ERR', Label), - ('FILE',File_Name_Expr), - ('IOSTAT', Scalar_Int_Variable), - ('IOMSG', Iomsg_Variable), - ('RECL', Scalar_Int_Expr), - ('UNIT', File_Unit_Number), - ]: + ''' + :param str string: Fortran code to check for a match + :return: 2-tuple containing the keyword and value or None if the + supplied string is not a match + :rtype: 2-tuple containing keyword (e.g. "UNIT") and associated value + ''' + if "=" not in string: + # The only argument which need not be named is the unit number + return 'UNIT', File_Unit_Number(string) + # We have a keyword-value pair. Check whether it is valid... + for (keyword, value) in [ + (['ACCESS', 'ACTION', 'ASYNCHRONOUS', 'BLANK', 'DECIMAL', + 'DELIM', 'ENCODING', 'FORM', 'PAD', 'POSITION', 'ROUND', + 'SIGN', 'STATUS'], Scalar_Default_Char_Expr), + ('ERR', Label), + ('FILE', File_Name_Expr), + ('IOSTAT', Scalar_Int_Variable), + ('IOMSG', Iomsg_Variable), + ('RECL', Scalar_Int_Expr), + ('UNIT', File_Unit_Number)]: try: - obj = KeywordValueBase.match(k, v, string, upper_lhs = True) + obj = KeywordValueBase.match(keyword, value, string, + upper_lhs=True) except NoMatchError: obj = None - if obj is not None: return obj - return 'UNIT', File_Unit_Number - match = staticmethod(match) + if obj is not None: + return obj + return None class File_Name_Expr(Base): # R906 @@ -6027,7 +6052,7 @@ items : (Inquire_Spec_List, Scalar_Int_Variable, Output_Item_List) class Inquire_Spec(KeywordValueBase): # R930 """ -:F03R:`930`:: + :F03R:`930`:: <inquire-spec> = [ UNIT = ] <file-unit-number> | FILE = <file-name-expr> | ACCESS = <scalar-default-char-variable> @@ -6065,9 +6090,9 @@ class Inquire_Spec(KeywordValueBase): # R930 | UNFORMATTED = <scalar-default-char-variable> | WRITE = <scalar-default-char-variable> -Attributes ----------- -items : (str, instance) + Attributes + ---------- + items : (str, instance) """ subclass_names = [] use_names = ['File_Unit_Number', 'File_Name_Expr', @@ -6077,6 +6102,18 @@ items : (str, instance) @staticmethod def match(string): + ''' + :param str string: The string to check for conformance with an + Inquire_Spec + :return: 2-tuple of name (e.g. "UNIT") and value or None if + string is not a valid Inquire_Spec + :rtype: 2-tuple where first object represents the name and the + second the value. + ''' + if "=" not in string: + # The only argument which need not be named is the unit number + return 'UNIT', File_Unit_Number(string) + # We have a keyword-value pair. Check whether it is valid... for (keyword, value) in [ (['ACCESS', 'ACTION', 'ASYNCHRONOUS', 'BLANK', 'DECIMAL', 'DELIM', 'DIRECT', 'ENCODING', 'FORM', 'NAME', 'PAD', @@ -6092,11 +6129,14 @@ items : (str, instance) ('IOMSG', Iomsg_Variable), ('FILE', File_Name_Expr), ('UNIT', File_Unit_Number)]: - obj = KeywordValueBase.match(keyword, value, string, - upper_lhs=True) + try: + obj = KeywordValueBase.match(keyword, value, string, + upper_lhs=True) + except NoMatchError: + obj = None if obj is not None: return obj - return 'UNIT', File_Unit_Number(string) + return None ############################################################################### ############################### SECTION 10 #################################### @@ -7561,14 +7601,16 @@ ClassType = type(Base) _names = dir() for clsname in _names: cls = eval(clsname) - if not (isinstance(cls, ClassType) and issubclass(cls, Base) and not cls.__name__.endswith('Base')): continue + if not (isinstance(cls, ClassType) and issubclass(cls, Base) and + not cls.__name__.endswith('Base')): + continue names = getattr(cls, 'subclass_names', []) + getattr(cls, 'use_names', []) for n in names: if n in _names: continue if n.endswith('_List'): _names.append(n) n = n[:-5] - #print 'Generating %s_List' % (n) + # Generate 'list' class exec('''\ class %s_List(SequenceBase): subclass_names = [\'%s\']
stfc/fparser
108c0f201abbabbde3ceb9fcc3ff7ffa4b0c3dbd
diff --git a/src/fparser/tests/fparser2/test_Fortran2003.py b/src/fparser/tests/fparser2/test_Fortran2003.py index 9b33289..e373b81 100644 --- a/src/fparser/tests/fparser2/test_Fortran2003.py +++ b/src/fparser/tests/fparser2/test_Fortran2003.py @@ -2811,7 +2811,7 @@ def test_Inquire_Stmt(): # R929 def test_Inquire_Spec(): # R930 ''' Test that we recognise the various possible forms of - inquire list ''' + entries in an inquire list ''' cls = Inquire_Spec obj = cls('1') assert isinstance(obj, cls), repr(obj) @@ -2837,6 +2837,128 @@ def test_Inquire_Spec(): # R930 assert_equal(str(obj), 'DIRECT = a') +def test_Inquire_Spec_List(): # pylint: disable=invalid-name + ''' Test that we recognise the various possible forms of + inquire list - R930 + ''' + # Inquire_Spec_List is generated at runtime in Fortran2003.py + cls = Inquire_Spec_List + + obj = cls('unit=23, file="a_file.dat"') + assert isinstance(obj, cls) + assert str(obj) == 'UNIT = 23, FILE = "a_file.dat"' + + # Invalid list (afile= instead of file=) + with pytest.raises(NoMatchError) as excinfo: + _ = cls('unit=23, afile="a_file.dat"') + assert "NoMatchError: Inquire_Spec_List: 'unit=23, afile=" in str(excinfo) + + +def test_Open_Stmt(): + ''' Check that we correctly parse and re-generate the various forms + of OPEN statement (R904)''' + cls = Open_Stmt + obj = cls("open(23, file='some_file.txt')") + assert isinstance(obj, cls) + assert str(obj) == "OPEN(UNIT = 23, FILE = 'some_file.txt')" + obj = cls("open(unit=23, file='some_file.txt')") + assert isinstance(obj, cls) + assert str(obj) == "OPEN(UNIT = 23, FILE = 'some_file.txt')" + + +def test_Connect_Spec(): + ''' Tests for individual elements of Connect_Spec (R905) ''' + cls = Connect_Spec + # Incorrect name for a member of the list + with pytest.raises(NoMatchError) as excinfo: + _ = cls("afile='a_file.dat'") + assert 'NoMatchError: Connect_Spec: "afile=' in str(excinfo) + + +def test_Connect_Spec_List(): # pylint: disable=invalid-name + ''' + Check that we correctly parse the various valid forms of + connect specification (R905) + ''' + cls = Connect_Spec_List + obj = cls("22, access='direct'") + assert isinstance(obj, cls) + assert str(obj) == "UNIT = 22, ACCESS = 'direct'" + + obj = cls("22, action='read'") + assert isinstance(obj, cls) + assert str(obj) == "UNIT = 22, ACTION = 'read'" + + obj = cls("22, asynchronous='YES'") + assert isinstance(obj, cls) + assert str(obj) == "UNIT = 22, ASYNCHRONOUS = 'YES'" + + obj = cls("22, blank='NULL'") + assert isinstance(obj, cls) + assert str(obj) == "UNIT = 22, BLANK = 'NULL'" + + obj = cls("22, decimal='COMMA'") + assert isinstance(obj, cls) + assert str(obj) == "UNIT = 22, DECIMAL = 'COMMA'" + + obj = cls("22, delim='APOSTROPHE'") + assert isinstance(obj, cls) + assert str(obj) == "UNIT = 22, DELIM = 'APOSTROPHE'" + + obj = cls("22, err=109") + assert isinstance(obj, cls) + assert str(obj) == "UNIT = 22, ERR = 109" + + obj = cls("22, encoding='DEFAULT'") + assert isinstance(obj, cls) + assert str(obj) == "UNIT = 22, ENCODING = 'DEFAULT'" + + obj = cls("22, file='a_file.dat'") + assert isinstance(obj, cls) + assert str(obj) == "UNIT = 22, FILE = 'a_file.dat'" + + obj = cls("22, file='a_file.dat', form='FORMATTED'") + assert isinstance(obj, cls) + assert str(obj) == "UNIT = 22, FILE = 'a_file.dat', FORM = 'FORMATTED'" + + obj = cls("22, file='a_file.dat', iomsg=my_string") + assert isinstance(obj, cls) + assert str(obj) == "UNIT = 22, FILE = 'a_file.dat', IOMSG = my_string" + + obj = cls("22, file='a_file.dat', iostat=ierr") + assert isinstance(obj, cls) + assert str(obj) == "UNIT = 22, FILE = 'a_file.dat', IOSTAT = ierr" + + obj = cls("22, file='a_file.dat', pad='YES'") + assert isinstance(obj, cls) + assert str(obj) == "UNIT = 22, FILE = 'a_file.dat', PAD = 'YES'" + + obj = cls("22, file='a_file.dat', position='APPEND'") + assert isinstance(obj, cls) + assert str(obj) == "UNIT = 22, FILE = 'a_file.dat', POSITION = 'APPEND'" + + obj = cls("22, file='a_file.dat', recl=100") + assert isinstance(obj, cls) + assert str(obj) == "UNIT = 22, FILE = 'a_file.dat', RECL = 100" + + obj = cls("22, file='a_file.dat', round='UP'") + assert isinstance(obj, cls) + assert str(obj) == "UNIT = 22, FILE = 'a_file.dat', ROUND = 'UP'" + + obj = cls("22, file='a_file.dat', sign='PLUS'") + assert isinstance(obj, cls) + assert str(obj) == "UNIT = 22, FILE = 'a_file.dat', SIGN = 'PLUS'" + + obj = cls("22, file='a_file.dat', sign='PLUS', status='OLD'") + assert isinstance(obj, cls) + assert str(obj) == ("UNIT = 22, FILE = 'a_file.dat', SIGN = 'PLUS', " + "STATUS = 'OLD'") + + # Incorrect name for a member of the list + with pytest.raises(NoMatchError) as excinfo: + _ = cls("unit=22, afile='a_file.dat', sign='PLUS', status='OLD'") + assert 'NoMatchError: Connect_Spec_List: "unit=22, afile=' in str(excinfo) + ############################################################################### ############################### SECTION 10 #################################### @@ -3664,42 +3786,43 @@ def test_Contains(): # R1237 if 0: - nof_needed_tests = 0 - nof_needed_match = 0 - total_needs = 0 - total_classes = 0 - for name in dir(): - obj = eval(name) - if not isinstance(obj, ClassType): continue - if not issubclass(obj, Base): continue - clsname = obj.__name__ - if clsname.endswith('Base'): continue - total_classes += 1 - subclass_names = obj.__dict__.get('subclass_names',None) - use_names = obj.__dict__.get('use_names',None) - if not use_names: continue - match = obj.__dict__.get('match',None) + NOF_NEEDED_TESTS = 0 + NOF_NEEDED_MATCH = 0 + TOTAL_NEEDS = 0 + TOTAL_CLASSES = 0 + for NAME in dir(): + OBJ = eval(NAME) + if not isinstance(OBJ, ClassType): continue + if not issubclass(OBJ, Base): continue + CLSNAME = OBJ.__name__ + if CLSNAME.endswith('Base'): continue + TOTAL_CLASSES += 1 + SUBCLASS_NAMES = OBJ.__dict__.get('subclass_names', None) + USE_NAMES = OBJ.__dict__.get('use_names', None) + if not USE_NAMES: continue + MATCH = OBJ.__dict__.get('match', None) try: - test_cls = eval('test_%s' % (clsname)) + TEST_CLS = eval('test_{0}'.format(CLSNAME)) except NameError: - test_cls = None - total_needs += 1 - if match is None: - if test_cls is None: - print('Needs tests:', clsname) - print('Needs match implementation:', clsname) - nof_needed_tests += 1 - nof_needed_match += 1 + TEST_CLS = None + TOTAL_NEEDS += 1 + if MATCH is None: + if TEST_CLS is None: + print('Needs tests:', CLSNAME) + print('Needs match implementation:', CLSNAME) + NOF_NEEDED_TESTS += 1 + NOF_NEEDED_MATCH += 1 else: - print('Needs match implementation:', clsname) - nof_needed_match += 1 + print('Needs match implementation:', CLSNAME) + NOF_NEEDED_MATCH += 1 else: - if test_cls is None: - print('Needs tests:', clsname) - nof_needed_tests += 1 + if TEST_CLS is None: + print('Needs tests:', CLSNAME) + NOF_NEEDED_TESTS += 1 continue print('-----') - print('Nof match implementation needs:',nof_needed_match,'out of',total_needs) - print('Nof tests needs:',nof_needed_tests,'out of',total_needs) - print('Total number of classes:',total_classes) + print('Nof match implementation needs:', NOF_NEEDED_MATCH, + 'out of', TOTAL_NEEDS) + print('Nof tests needs:', NOF_NEEDED_TESTS, 'out of', TOTAL_NEEDS) + print('Total number of classes:', TOTAL_CLASSES) print('-----')
fparser2: generate correct OPEN call when unit number argument is not named When parsing the following OPEN call: OPEN( idrst, FILE = TRIM(cdname), FORM = 'unformatted', ACCESS = 'direct' & & , RECL = 8, STATUS = 'old', ACTION = 'read', IOSTAT = ios, ERR = 987 ) fparser2 generates: OPEN(UNIT = <class 'fparser.Fortran2003.File_Unit_Number'>, FILE = TRIM(cdname), FORM = 'unformatted', ACCESS = 'direct', RECL = 8, STATUS = 'old', ACTION = 'read', IOSTAT = ios, ERR = 987) i.e. the fact that the unit number argument isn't named in the original call appears to cause problems.
0.0
108c0f201abbabbde3ceb9fcc3ff7ffa4b0c3dbd
[ "src/fparser/tests/fparser2/test_Fortran2003.py::test_Open_Stmt" ]
[ "src/fparser/tests/fparser2/test_Fortran2003.py::test_Program", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Specification_Part", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Name", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Literal_Constant", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Type_Param_Value", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Intrinsic_Type_Spec", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Kind_Selector", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Signed_Int_Literal_Constant", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Int_Literal_Constant", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Binary_Constant", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Octal_Constant", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Hex_Constant", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Signed_Real_Literal_Constant", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Real_Literal_Constant", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Char_Selector", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Complex_Literal_Constant", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Type_Name", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Length_Selector", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Char_Length", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Char_Literal_Constant", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Logical_Literal_Constant", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Derived_Type_Stmt", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Type_Attr_Spec", "src/fparser/tests/fparser2/test_Fortran2003.py::test_End_Type_Stmt", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Sequence_Stmt", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Type_Param_Def_Stmt", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Type_Param_Decl", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Type_Param_Attr_Spec", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Component_Attr_Spec", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Component_Decl", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Proc_Component_Def_Stmt", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Type_Bound_Procedure_Part", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Proc_Binding_Stmt", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Specific_Binding", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Generic_Binding", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Final_Binding", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Derived_Type_Spec", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Type_Param_Spec", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Type_Param_Spec_List", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Structure_Constructor_2", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Structure_Constructor", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Component_Spec", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Component_Spec_List", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Enum_Def", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Enum_Def_Stmt", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Array_Constructor", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Ac_Spec", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Ac_Value_List", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Ac_Implied_Do", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Ac_Implied_Do_Control", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Type_Declaration_Stmt", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Declaration_Type_Spec", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Attr_Spec", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Dimension_Attr_Spec", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Intent_Attr_Spec", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Entity_Decl", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Target_Entity_Decl", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Access_Spec", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Language_Binding_Spec", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Explicit_Shape_Spec", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Upper_Bound", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Assumed_Shape_Spec", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Deferred_Shape_Spec", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Assumed_Size_Spec", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Access_Stmt", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Data_Stmt", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Data_Stmt_Set", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Data_Implied_Do", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Dimension_Stmt", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Intent_Stmt", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Optional_Stmt", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Parameter_Stmt", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Named_Constant_Def", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Pointer_Stmt", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Pointer_Decl", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Protected_Stmt", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Save_Stmt", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Saved_Entity", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Target_Stmt", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Value_Stmt", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Volatile_Stmt", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Implicit_Stmt", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Implicit_Spec", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Letter_Spec", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Namelist_Stmt", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Equivalence_Stmt", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Common_Stmt", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Common_Block_Object", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Substring", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Substring_Range", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Data_Ref", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Part_Ref", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Type_Param_Inquiry", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Array_Section", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Section_Subscript", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Section_Subscript_List", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Subscript_Triplet", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Allocate_Stmt", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Alloc_Opt", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Nullify_Stmt", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Deallocate_Stmt", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Primary", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Parenthesis", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Level_1_Expr", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Mult_Operand", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Add_Operand", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Level_2_Expr", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Level_2_Unary_Expr", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Level_3_Expr", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Level_4_Expr", "src/fparser/tests/fparser2/test_Fortran2003.py::test_And_Operand", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Or_Operand", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Equiv_Operand", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Level_5_Expr", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Expr", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Logical_Expr", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Logical_Initialization_Expr", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Assignment_Stmt", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Pointer_Assignment_Stmt", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Proc_Component_Ref", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Where_Stmt", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Where_Construct", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Where_Construct_Stmt", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Forall_Construct", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Forall_Header", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Forall_Triplet_Spec", "src/fparser/tests/fparser2/test_Fortran2003.py::test_If_Construct", "src/fparser/tests/fparser2/test_Fortran2003.py::test_if_nonblock_do", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Case_Construct", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Case_Selector", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Associate_Construct", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Select_Type_Construct", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Select_Type_Stmt", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Type_Guard_Stmt", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Block_Label_Do_Construct", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Block_Nonlabel_Do_Construct", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Label_Do_Stmt", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Nonblock_Do_Construct", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Continue_Stmt", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Stop_Stmt", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Io_Unit", "src/fparser/tests/fparser2/test_Fortran2003.py::test_read_stmt", "src/fparser/tests/fparser2/test_Fortran2003.py::test_write_stmt", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Print_Stmt", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Io_Control_Spec", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Io_Control_Spec_List", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Format", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Io_Implied_Do", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Io_Implied_Do_Control", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Wait_Stmt", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Wait_Spec", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Backspace_Stmt", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Endfile_Stmt", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Rewind_Stmt", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Position_Spec", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Flush_Stmt", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Flush_Spec", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Inquire_Stmt", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Inquire_Spec", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Format_Stmt", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Format_Specification", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Format_Item", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Format_Item_List", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Main_Program", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Module", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Module_Subprogram_Part", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Use_Stmt", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Module_Nature", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Rename", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Block_Data", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Interface_Block", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Interface_Specification", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Interface_Stmt", "src/fparser/tests/fparser2/test_Fortran2003.py::test_End_Interface_Stmt", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Interface_Body", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Subroutine_Body", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Function_Body", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Procedure_Stmt", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Generic_Spec", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Dtio_Generic_Spec", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Import_Stmt", "src/fparser/tests/fparser2/test_Fortran2003.py::test_External_Stmt", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Procedure_Declaration_Stmt", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Proc_Attr_Spec", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Proc_Decl", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Intrinsic_Stmt", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Function_Reference", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Call_Stmt", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Procedure_Designator", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Actual_Arg_Spec", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Actual_Arg_Spec_List", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Alt_Return_Spec", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Function_Subprogram", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Function_Stmt", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Dummy_Arg_Name", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Prefix", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Prefix_Spec", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Suffix", "src/fparser/tests/fparser2/test_Fortran2003.py::test_End_Function_Stmt", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Subroutine_Subprogram", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Subroutine_Stmt", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Dummy_Arg", "src/fparser/tests/fparser2/test_Fortran2003.py::test_End_Subroutine_Stmt", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Entry_Stmt", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Return_Stmt", "src/fparser/tests/fparser2/test_Fortran2003.py::test_Contains" ]
{ "failed_lite_validators": [ "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2017-10-18 12:31:33+00:00
bsd-3-clause
5,742
stigok__ruterstop-65
diff --git a/ruterstop/__init__.py b/ruterstop/__init__.py index 7e4028a..b44d6be 100644 --- a/ruterstop/__init__.py +++ b/ruterstop/__init__.py @@ -18,7 +18,7 @@ from datetime import datetime, timedelta import requests import bottle -from ruterstop.utils import norwegian_ascii, timed_cache +from ruterstop.utils import delta, human_delta, norwegian_ascii, timed_cache __version__ = "0.3.1" @@ -82,32 +82,6 @@ def default_error_handler(res): webapp.default_error_handler = default_error_handler -def human_delta(until=None, *, since=None): - """ - Return a 6 char long string describing minutes left 'until' date occurs. - Example output: - naa (if delta < 60 seconds) - 1 min - 7 min - 10 min - 99 min - """ - now_str = "{:>6}".format("naa") - if not since: - since = datetime.now() - - if since > until: - return now_str - - secs = (until - since).seconds - mins = int(secs / 60) # floor - mins = max(0, min(mins, 99)) # between 0 and 99 - - if mins < 1: - return now_str - - return "{:2} min".format(mins) - class Departure(namedtuple("Departure", ["line", "name", "eta", "direction", "realtime"])): """Represents a transport departure""" @@ -117,6 +91,13 @@ class Departure(namedtuple("Departure", ["line", "name", "eta", "direction", "re name += " " + self.name return "{:14}{:>7}".format(name[:14], human_delta(until=self.eta)) + def ts_str(self): + name = str(self.line) + if self.name: + name += " " + self.name + return "{:16}{:%H:%M}".format(name[:14], self.eta) + + # Python < 3.7 equivalent of `defaults` kwarg of `namedtuple` Departure.__new__.__defaults__ = (False,) @@ -223,7 +204,7 @@ def get_departures(*, stop_id=None): return parse_departures(raw_stop) -def format_departure_list(departures, *, min_eta=0, directions=None, grouped=False): +def format_departure_list(departures, *, min_eta=0, long_eta=-1, directions=None, grouped=False): """ Filters, formats and groups departures based on arguments passed. """ @@ -268,7 +249,10 @@ def format_departure_list(departures, *, min_eta=0, directions=None, grouped=Fal # Create pretty output s = "" for dep in deps: - s += str(dep) + '\n' + if long_eta >= 0 and delta(dep.eta) > long_eta: + s += dep.ts_str() + '\n' + else: + s += str(dep) + '\n' return s @@ -285,6 +269,9 @@ def main(argv=sys.argv, *, stdout=sys.stdout): help="filter direction of departures") par.add_argument('--min-eta', type=int, default=0, metavar="<minutes>", help="minimum ETA of departures to return") + par.add_argument('--long-eta', type=int, default=-1, metavar="<minutes>", + help="show departure time when ETA is later than this limit" + + "(disable with -1)") par.add_argument('--grouped', action="store_true", help="group departures with same ETA together " + "when --direction is also specified.") @@ -332,7 +319,9 @@ def main(argv=sys.argv, *, stdout=sys.stdout): # Just print stop information deps = get_departures(stop_id=args.stop_id) - formatted = format_departure_list(deps, min_eta=args.min_eta, + formatted = format_departure_list(deps, + min_eta=args.min_eta, + long_eta=args.long_eta, directions=directions, grouped=args.grouped) diff --git a/ruterstop/utils.py b/ruterstop/utils.py index 77f762f..4852322 100644 --- a/ruterstop/utils.py +++ b/ruterstop/utils.py @@ -38,3 +38,40 @@ def timed_cache(*, expires_sec=60, now=datetime.now): return wrapper return decorator + + +def delta(until=None, *, since=None): + """ + Return amount of whole minutes until `until` date occurs, since `since`. + Returns -1 if since is later than until. + """ + if not since: + since = datetime.now() + + if since > until: + return -1 + + secs = (until - since).seconds + mins = max(0, secs / 60) + return int(mins) + + +def human_delta(until=None, *, since=None): + """ + Return a 6 char long string describing minutes left 'until' date occurs. + Example output: + naa (if delta < 60 seconds) + 1 min + 7 min + 10 min + 99 min + """ + now_str = "{:>6}".format("naa") + + since = since if since else datetime.now() + mins = min(delta(until, since=since), 99) + + if mins < 1: + return now_str + + return "{:2} min".format(mins)
stigok/ruterstop
78eca8f2fb8204199b41e87a84271dd12d7cfd5b
diff --git a/ruterstop/tests/test_ruterstop.py b/ruterstop/tests/test_ruterstop.py index b261318..976b579 100644 --- a/ruterstop/tests/test_ruterstop.py +++ b/ruterstop/tests/test_ruterstop.py @@ -6,12 +6,14 @@ from io import StringIO from unittest import TestCase from unittest.mock import Mock, MagicMock, patch +from freezegun import freeze_time + import ruterstop class DepartureClassTestCase(TestCase): def test_str_representation(self): - with patch('ruterstop.datetime') as mock_date: + with patch('ruterstop.utils.datetime') as mock_date: ref = datetime.min mock_date.now.return_value = ref in_7_mins = ref + timedelta(minutes=7) @@ -141,3 +143,29 @@ class RuterstopTestCase(TestCase): self.assertEqual(lines[1], "20, 21 2 min") self.assertEqual(lines[2], "21 Thre 3 min") self.assertEqual(lines[3], "21 Four 4 min") + + @patch("ruterstop.get_realtime_stop", return_value=None) + def test_shows_timestamp_for_long_etas(self, _): + seed = datetime(2020, 1, 1, 10, 0, 0) + with freeze_time(seed): + def futr(minutes): + return seed + timedelta(minutes=minutes) + + d = ruterstop.Departure + deps = [ + # Shouldn't matter if a departure is realtime or not + d("01", "a", futr(60), "inbound", realtime=True), + d("02", "b", futr(120), "inbound", realtime=True), + d("03", "c", futr(150), "inbound", realtime=False), + ] + + args = " --stop-id=2121 --direction=inbound --long-eta=59".split(' ') + + # Use the fake departure list in this patch + with patch("ruterstop.parse_departures", return_value=deps) as mock: + with StringIO() as output: + ruterstop.main(args, stdout=output) + lines = output.getvalue().split('\n') + self.assertEqual(lines[0], "01 a 11:00") + self.assertEqual(lines[1], "02 b 12:00") + self.assertEqual(lines[2], "03 c 12:30") diff --git a/ruterstop/tests/test_utils.py b/ruterstop/tests/test_utils.py index 98b2420..53a5786 100644 --- a/ruterstop/tests/test_utils.py +++ b/ruterstop/tests/test_utils.py @@ -24,7 +24,7 @@ class HumanDeltaTestCase(TestCase): self.assertEqual(res, expected, "test case #%d" % (i + 1)) def test_default_kwarg_value(self): - with patch('ruterstop.datetime') as mock_date: + with patch('ruterstop.utils.datetime') as mock_date: mock_date.now.return_value = datetime.min ruterstop.human_delta(until=datetime.min + timedelta(seconds=120)) self.assertEqual(mock_date.now.call_count, 1)
Mulighet for å vise klokkeslett Det hadde vært kult man kunne vist klokkeslett hvis det var over en viss tid igjen. Slik ofte skilt pleier å være.
0.0
78eca8f2fb8204199b41e87a84271dd12d7cfd5b
[ "ruterstop/tests/test_ruterstop.py::DepartureClassTestCase::test_str_representation", "ruterstop/tests/test_ruterstop.py::RuterstopTestCase::test_shows_timestamp_for_long_etas", "ruterstop/tests/test_utils.py::HumanDeltaTestCase::test_default_kwarg_value" ]
[ "ruterstop/tests/test_ruterstop.py::StopPlaceTestCase::test_get_stop_search_result", "ruterstop/tests/test_ruterstop.py::StopPlaceTestCase::test_parse_stop", "ruterstop/tests/test_ruterstop.py::RuterstopTestCase::test_does_not_hide_realtime_departures_after_eta", "ruterstop/tests/test_ruterstop.py::RuterstopTestCase::test_get_realtime_stop", "ruterstop/tests/test_ruterstop.py::RuterstopTestCase::test_groups_output_when_grouped_enabled", "ruterstop/tests/test_ruterstop.py::RuterstopTestCase::test_parse_departures", "ruterstop/tests/test_utils.py::HumanDeltaTestCase::test_output", "ruterstop/tests/test_utils.py::NorwegianAsciiTestCase::test_norwegian_ascii", "ruterstop/tests/test_utils.py::TimedCacheTestCase::test_timed_cache" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2020-06-16 16:22:40+00:00
mit
5,743
stitchfix__nodebook-18
diff --git a/nodebook/pickledict.py b/nodebook/pickledict.py index 01740f4..33a32e3 100644 --- a/nodebook/pickledict.py +++ b/nodebook/pickledict.py @@ -66,7 +66,6 @@ class PickleDict(DictMixin): persist_path: if provided, perform serialization to/from disk to this path """ self.persist_path = persist_path - self.encodings = {} self.dump = partial(msgpack.dump, default=msgpack_serialize) self.load = partial(msgpack.load, ext_hook=msgpack_deserialize) self.dict = {} @@ -96,25 +95,21 @@ class PickleDict(DictMixin): if self.persist_path is not None: path = self.dict[key] with open(path, 'rb') as f: - value = self.load(f, encoding=self.encodings[key]) + value = self.load(f, raw=False) else: f = StringIO(self.dict[key]) - value = self.load(f, encoding=self.encodings[key]) + value = self.load(f, raw=False) return value def __setitem__(self, key, value): - encoding = None - if isinstance(value, six.string_types): - encoding = 'utf-8' - self.encodings[key] = encoding if self.persist_path is not None: path = os.path.join(self.persist_path, '%s.pak' % key) with open(path, 'wb') as f: - self.dump(value, f, encoding=encoding) + self.dump(value, f, strict_types=True, use_bin_type=True) self.dict[key] = path else: f = StringIO() - self.dump(value, f, encoding=encoding) + self.dump(value, f, strict_types=True, use_bin_type=True) serialized = f.getvalue() self.dict[key] = serialized diff --git a/setup.py b/setup.py index d54a7f5..eb22642 100644 --- a/setup.py +++ b/setup.py @@ -5,7 +5,7 @@ import sys setup( name='nodebook', - version='0.3.0', + version='0.3.1', author='Kevin Zielnicki', author_email='[email protected]', license='Stitch Fix 2018',
stitchfix/nodebook
6ddc1a7f5e47a80060365bfb1b9012b928f68970
diff --git a/tests/test_pickledict.py b/tests/test_pickledict.py index 30ac34b..de2cc45 100644 --- a/tests/test_pickledict.py +++ b/tests/test_pickledict.py @@ -25,10 +25,33 @@ class TestPickleDict(object): mydict['test_string'] = 'foo' assert mydict['test_string'] == 'foo' + d = {'foo':'bar'} + mydict['test_string_dict'] = d + assert mydict['test_string_dict'] == d + def test_bytes(self, mydict): mydict['test_bytes'] = b'foo' assert mydict['test_bytes'] == b'foo' + d = {b'foo':b'bar'} + mydict['test_bytes_dict'] = d + assert mydict['test_bytes_dict'] == d + + def test_list(self, mydict): + l = [1,2,3] + mydict['test_list'] = l + assert mydict['test_list'] == l + + def test_tuple(self, mydict): + t = (1,2,3) + mydict['test_tuple'] = t + assert mydict['test_tuple'] == t + + def test_set(self, mydict): + s = {1,2,3} + mydict['test_set'] = s + assert mydict['test_set'] == s + def test_df(self, mydict): df = pd.DataFrame({'a': [0, 1, 2], 'b': ['foo', 'bar', 'baz']}) mydict['test_df'] = df
In python3, strings in dictionaries are de-serialized as bytes Eg, `foo = {'key':42}` is deserialized as `{b'key':42}`
0.0
6ddc1a7f5e47a80060365bfb1b9012b928f68970
[ "tests/test_pickledict.py::TestPickleDict::test_string[mode_memory]", "tests/test_pickledict.py::TestPickleDict::test_string[mode_disk]", "tests/test_pickledict.py::TestPickleDict::test_tuple[mode_memory]", "tests/test_pickledict.py::TestPickleDict::test_tuple[mode_disk]" ]
[ "tests/test_pickledict.py::TestPickleDict::test_int[mode_memory]", "tests/test_pickledict.py::TestPickleDict::test_int[mode_disk]", "tests/test_pickledict.py::TestPickleDict::test_bytes[mode_memory]", "tests/test_pickledict.py::TestPickleDict::test_bytes[mode_disk]", "tests/test_pickledict.py::TestPickleDict::test_list[mode_memory]", "tests/test_pickledict.py::TestPickleDict::test_list[mode_disk]", "tests/test_pickledict.py::TestPickleDict::test_set[mode_memory]", "tests/test_pickledict.py::TestPickleDict::test_set[mode_disk]", "tests/test_pickledict.py::TestPickleDict::test_df[mode_memory]", "tests/test_pickledict.py::TestPickleDict::test_df[mode_disk]", "tests/test_pickledict.py::TestPickleDict::test_func[mode_memory]", "tests/test_pickledict.py::TestPickleDict::test_func[mode_disk]", "tests/test_pickledict.py::TestPickleDict::test_closure[mode_memory]", "tests/test_pickledict.py::TestPickleDict::test_closure[mode_disk]", "tests/test_pickledict.py::TestPickleDict::test_immutability[mode_memory]", "tests/test_pickledict.py::TestPickleDict::test_immutability[mode_disk]" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2018-08-14 18:14:32+00:00
apache-2.0
5,744
stitchfix__nodebook-8
diff --git a/nodebook/nodebookcore.py b/nodebook/nodebookcore.py index 98b5cdc..ddae374 100644 --- a/nodebook/nodebookcore.py +++ b/nodebook/nodebookcore.py @@ -46,6 +46,9 @@ class ReferenceFinder(ast.NodeVisitor): self.locals.add(node.name) self.generic_visit(node) + def visit_arg(self, node): + self.locals.add(node.arg) + def visit_AugAssign(self, node): target = node.target while (type(target) is ast.Subscript): diff --git a/setup.py b/setup.py index 11d6a77..adc7229 100644 --- a/setup.py +++ b/setup.py @@ -5,7 +5,7 @@ import sys setup( name='nodebook', - version='0.2.0', + version='0.2.1', author='Kevin Zielnicki', author_email='[email protected]', license='Stitch Fix 2017',
stitchfix/nodebook
b6e1ec614fd39acb740b04e99ee7e97d99122420
diff --git a/tests/test_nodebookcore.py b/tests/test_nodebookcore.py index cfd9646..470121c 100644 --- a/tests/test_nodebookcore.py +++ b/tests/test_nodebookcore.py @@ -42,6 +42,16 @@ class TestReferenceFinder(object): assert rf.locals == {'pd', 'y'} assert rf.imports == {'pandas'} + def test_function(self, rf): + code_tree = ast.parse( + "def add(x,y):\n" + " return x+y\n" + ) + rf.visit(code_tree) + assert rf.inputs == set() + assert rf.locals == {'add', 'x', 'y'} + assert rf.imports == set() + class TestNodebook(object): @pytest.fixture() diff --git a/tests/test_pickledict.py b/tests/test_pickledict.py index ef35fdd..90b7088 100644 --- a/tests/test_pickledict.py +++ b/tests/test_pickledict.py @@ -33,6 +33,12 @@ class TestPickleDict(object): df = pd.DataFrame({'a': [0, 1, 2], 'b': ['foo', 'bar', 'baz']}) mydict['test_df'] = df assert mydict['test_df'].equals(df) + + def test_func(self, mydict): + def add(a, b): + return a + b + mydict['test_func'] = add + assert mydict['test_func'](3,5) == 8 def test_immutability(self, mydict): l = [1, 2, 3]
Functions don't work in nodebook in py3 Because of changes to the ast in Python 3, functions no longer are parsed correctly. Eg, from @hacktuarial: ``` def add(a, b): return a + b ``` nodebook throws an error: ``` KeyError: "name 'a' is not defined" ```
0.0
b6e1ec614fd39acb740b04e99ee7e97d99122420
[ "tests/test_nodebookcore.py::TestReferenceFinder::test_function" ]
[ "tests/test_nodebookcore.py::TestReferenceFinder::test_assign", "tests/test_nodebookcore.py::TestReferenceFinder::test_augassign", "tests/test_nodebookcore.py::TestReferenceFinder::test_import", "tests/test_nodebookcore.py::TestReferenceFinder::test_multiline", "tests/test_nodebookcore.py::TestNodebook::test_single_node", "tests/test_nodebookcore.py::TestNodebook::test_node_chain", "tests/test_pickledict.py::TestPickleDict::test_int[mode_memory]", "tests/test_pickledict.py::TestPickleDict::test_int[mode_disk]", "tests/test_pickledict.py::TestPickleDict::test_string[mode_memory]", "tests/test_pickledict.py::TestPickleDict::test_string[mode_disk]", "tests/test_pickledict.py::TestPickleDict::test_bytes[mode_memory]", "tests/test_pickledict.py::TestPickleDict::test_bytes[mode_disk]", "tests/test_pickledict.py::TestPickleDict::test_df[mode_memory]", "tests/test_pickledict.py::TestPickleDict::test_df[mode_disk]", "tests/test_pickledict.py::TestPickleDict::test_func[mode_memory]", "tests/test_pickledict.py::TestPickleDict::test_func[mode_disk]", "tests/test_pickledict.py::TestPickleDict::test_immutability[mode_memory]", "tests/test_pickledict.py::TestPickleDict::test_immutability[mode_disk]" ]
{ "failed_lite_validators": [ "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2017-10-21 23:04:18+00:00
apache-2.0
5,745
stopthatcow__zazu-184
diff --git a/zazu/plugins/github_scm_host.py b/zazu/plugins/github_scm_host.py index 27b0d13..e7b6126 100644 --- a/zazu/plugins/github_scm_host.py +++ b/zazu/plugins/github_scm_host.py @@ -23,7 +23,6 @@ class ScmHost(zazu.scm_host.ScmHost): """ self._github_handle = None - self._user = user self._url = url def connect(self): @@ -38,7 +37,7 @@ class ScmHost(zazu.scm_host.ScmHost): def repos(self): """List repos available to this user.""" try: - for r in self._github().get_user(self._user).get_repos(): + for r in self._github().get_user().get_repos(): yield GitHubScmRepoAdaptor(r) except github.GithubException as e: raise zazu.scm_host.ScmHostError(str(e))
stopthatcow/zazu
c2694b4b0527decc0877f47efc688886c90411c3
diff --git a/tests/test_github_scm_host.py b/tests/test_github_scm_host.py index 5c91ee3..dd005e0 100644 --- a/tests/test_github_scm_host.py +++ b/tests/test_github_scm_host.py @@ -32,7 +32,7 @@ def test_github_scm_host_get_repos(mocker, scm_host_mock): mocker.patch('zazu.github_helper.make_gh', return_value=github_mock) scm_host_mock.connect() repos = list(scm_host_mock.repos()) - github_mock.get_user.assert_called_once_with('stopthatcow') + github_mock.get_user.assert_called_once_with() user_mock.get_repos.assert_called_once() assert len(repos) == 1 assert repos[0].name == 'zazu' @@ -54,7 +54,6 @@ def test_from_config(git_repo): with zazu.util.cd(git_repo.working_tree_dir): uut = zazu.plugins.github_scm_host.ScmHost.from_config({'user': 'stopthatcow', 'type': 'github'}) - assert uut._user == 'stopthatcow' assert uut.type() == 'github'
Fix github SCM to list private repos Right now github SCM class returns only public repos for the logged-in user. This should also return private repos.
0.0
c2694b4b0527decc0877f47efc688886c90411c3
[ "tests/test_github_scm_host.py::test_github_scm_host_get_repos" ]
[ "tests/test_github_scm_host.py::test_github_scm_host_get_repos_error", "tests/test_github_scm_host.py::test_from_config", "tests/test_github_scm_host.py::test_github_scm_host_repo_adaptor" ]
{ "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false }
2020-06-06 17:08:59+00:00
mit
5,746
stratasan__stratatilities-9
diff --git a/.gitignore b/.gitignore index 71e6852..7f9f422 100644 --- a/.gitignore +++ b/.gitignore @@ -8,7 +8,6 @@ __pycache__/ # Distribution / packaging .Python -env/ build/ develop-eggs/ dist/ @@ -20,9 +19,11 @@ lib64/ parts/ sdist/ var/ +wheels/ *.egg-info/ .installed.cfg *.egg +MANIFEST # PyInstaller # Usually these files are written by a python script from a template @@ -37,13 +38,15 @@ pip-delete-this-directory.txt # Unit test / coverage reports htmlcov/ .tox/ +.nox/ .coverage .coverage.* .cache nosetests.xml coverage.xml -*,cover +*.cover .hypothesis/ +.pytest_cache/ # Translations *.mo @@ -51,6 +54,15 @@ coverage.xml # Django stuff: *.log +local_settings.py +db.sqlite3 + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy # Sphinx documentation docs/_build/ @@ -58,5 +70,45 @@ docs/_build/ # PyBuilder target/ -# pyenv python configuration file +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv .python-version + +# celery beat schedule file +celerybeat-schedule + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ \ No newline at end of file diff --git a/.travis.yml b/.travis.yml index 3fa014f..f7024d9 100644 --- a/.travis.yml +++ b/.travis.yml @@ -5,7 +5,6 @@ language: python python: - 3.6 - 3.5 - - 2.7 # command to install dependencies, e.g. pip install -r requirements.txt --use-mirrors install: diff --git a/stratatilities/auth.py b/stratatilities/auth.py index 4e83835..bd0b4da 100644 --- a/stratatilities/auth.py +++ b/stratatilities/auth.py @@ -1,4 +1,5 @@ import base64 +from getpass import getpass import json import logging import os @@ -86,6 +87,27 @@ def get_vault_client(vault_addr=os.environ.get('VAULT_ADDR')): return hvac.Client(url=vault_addr, verify=False, token=vault_token) +def get_vault_client_via_ldap( + username, mount_point='ldap', + vault_addr=os.environ.get('VAULT_ADDR')): + """ Return an authenticated vault client via LDAP. + + Password will be acquired via `getpass.getpass`. Services should + use `get_vault_client` with IAM privileges. + + InvalidRequest is raised from an incorrect password being entered + """ + client = hvac.Client(url=vault_addr) + # with an incorrect password, an InvalidRequest is raised + client.auth.ldap.login( + username=username, + password=getpass('LDAP Password:'), + mount_point=mount_point + ) + assert client.is_authenticated(), 'Client is not authenticated!' + return client + + def return_token(vault_addr=os.environ.get('VAULT_ADDR')): vault_token = os.environ.get('VAULT_TOKEN', None) if not vault_token:
stratasan/stratatilities
9e723ba0c6ae7aacbbc8c3304f54b36398ae92dc
diff --git a/tests/test_auth.py b/tests/test_auth.py index 4bd63f6..37cf3ca 100644 --- a/tests/test_auth.py +++ b/tests/test_auth.py @@ -3,7 +3,9 @@ try: except ImportError: from unittest.mock import Mock, patch -from stratatilities.auth import read_vault_secret, get_vault_client +from stratatilities.auth import ( + read_vault_secret, get_vault_client, get_vault_client_via_ldap +) def test_get_vault_client(): @@ -22,7 +24,7 @@ def test_get_vault_client(): ) -def test_read_vault_client(): +def test_read_vault_secret(): client = Mock() path = 'path/to/sekret' @@ -49,3 +51,24 @@ def test_read_vault_client(): # return 'data' and not do a further key access answer = read_vault_secret(client, path, vault_value_key=None) assert answer == complex_value + + +def test_get_vault_client_via_ldap(): + with patch('stratatilities.auth.hvac') as hvac,\ + patch('stratatilities.auth.getpass') as getpass: + username, vault_addr = 'username', 'https://vault.example.com' + + hvac.Client.return_value.is_authenticated.return_value = True + + client = get_vault_client_via_ldap( + username, + vault_addr=vault_addr + ) + hvac.Client.assert_called_with(url=vault_addr) + assert hvac.Client.return_value == client + # the password will come from getpass when not supplied in the call + client.auth.ldap.login.assert_called_with( + username=username, + password=getpass.return_value, + mount_point='ldap' + )
Add method to get vault client w/ LDAP auth Will be helpful in notebook.stratasan.com. Ideally password is accessed w/ `getpass.getpass`.
0.0
9e723ba0c6ae7aacbbc8c3304f54b36398ae92dc
[ "tests/test_auth.py::test_get_vault_client", "tests/test_auth.py::test_read_vault_secret", "tests/test_auth.py::test_get_vault_client_via_ldap" ]
[]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2018-11-05 17:59:10+00:00
mit
5,747
stravalib__stravalib-309
diff --git a/changelog.md b/changelog.md index 9350dcf..1871743 100644 --- a/changelog.md +++ b/changelog.md @@ -1,6 +1,7 @@ # Change Log ## Unreleased +* Add: Support uploading `activity_file` object with type `bytes` (@gitexel, #308) ## v1.1.0 diff --git a/stravalib/client.py b/stravalib/client.py index e2ac772..fa23a81 100644 --- a/stravalib/client.py +++ b/stravalib/client.py @@ -694,7 +694,7 @@ class Client(object): https://developers.strava.com/docs/reference/#api-Uploads-createUpload :param activity_file: The file object to upload or file contents. - :type activity_file: file or str + :type activity_file: TextIOWrapper, str or bytes :param data_type: File format for upload. Possible values: fit, fit.gz, tcx, tcx.gz, gpx, gpx.gz :type data_type: str @@ -734,7 +734,7 @@ class Client(object): if not hasattr(activity_file, 'read'): if isinstance(activity_file, str): activity_file = BytesIO(activity_file.encode('utf-8')) - elif isinstance(activity_file, str): + elif isinstance(activity_file, bytes): activity_file = BytesIO(activity_file) else: raise TypeError("Invalid type specified for activity_file: {0}".format(type(activity_file)))
stravalib/stravalib
19e051ed0d7f52b7f3fc17522eeb0c1b0f3a991f
diff --git a/stravalib/tests/integration/test_client.py b/stravalib/tests/integration/test_client.py index 30d1812..10aa27d 100644 --- a/stravalib/tests/integration/test_client.py +++ b/stravalib/tests/integration/test_client.py @@ -83,6 +83,7 @@ def test_update_activity( ( ('file', 'tcx', {}, {'data_type': 'tcx'}, None, None), ('str', 'tcx', {}, {'data_type': 'tcx'}, None, None), + ('bytes', 'tcx', {}, {'data_type': 'tcx'}, None, None), ('not_supported', 'tcx', {}, {}, None, TypeError), ('file', 'invalid', {}, {}, None, ValueError), ('file', 'tcx', {'name': 'name'}, {'data_type': 'tcx', 'name': 'name'}, None, None), @@ -135,6 +136,8 @@ def test_upload_activity( _call_upload(f) elif activity_file_type == 'str': _call_upload(f.read()) + elif activity_file_type == 'bytes': + _call_upload(f.read().encode('utf-8')) else: _call_upload({}) diff --git a/stravalib/tests/unit/test_client_utils.py b/stravalib/tests/unit/test_client_utils.py index 88a8a8a..e3e6cd4 100644 --- a/stravalib/tests/unit/test_client_utils.py +++ b/stravalib/tests/unit/test_client_utils.py @@ -1,5 +1,8 @@ +import os +from unittest import mock + from stravalib.client import Client -from stravalib.tests import TestBase +from stravalib.tests import TestBase, RESOURCES_DIR import datetime import pytz from urllib import parse as urlparse @@ -54,3 +57,32 @@ class ClientAuthorizationUrlTest(TestBase): self.assertEqual(self.get_url_param(url, "client_id"), "1") self.assertEqual(self.get_url_param(url, "redirect_uri"), "www.example.com") self.assertEqual(self.get_url_param(url, "approval_prompt"), "auto") + + +class TestClientUploadActivity(TestBase): + client = Client() + + def test_upload_activity_file_with_different_types(self): + """ + Test uploading an activity with different activity_file object types. + + """ + + with mock.patch("stravalib.protocol.ApiV3.post", return_value={}), open( + os.path.join(RESOURCES_DIR, "sample.tcx") + ) as fp: + # test activity_file with type TextIOWrapper + uploader = self.client.upload_activity(fp, data_type="tcx") + self.assertTrue(uploader.is_processing) + + # test activity_file with type str + uploader = self.client.upload_activity( + fp.read(), data_type="tcx", activity_type="ride" + ) + self.assertTrue(uploader.is_processing) + + # test activity_file with type bytes + uploader = self.client.upload_activity( + fp.read().encode("utf-8"), data_type="tcx", activity_type="ride" + ) + self.assertTrue(uploader.is_processing)
unable to upload_activity if its bytes type When calling `client.upload_activity` and `activity_file` type is `bytes`, I get this error `Invalid type specified for activity_file: bytes`
0.0
19e051ed0d7f52b7f3fc17522eeb0c1b0f3a991f
[ "stravalib/tests/integration/test_client.py::test_upload_activity[bytes-tcx-upload_kwargs2-expected_params2-None-None]", "stravalib/tests/unit/test_client_utils.py::TestClientUploadActivity::test_upload_activity_file_with_different_types" ]
[ "stravalib/tests/integration/test_client.py::test_get_athlete", "stravalib/tests/integration/test_client.py::test_get_activity[None-/activities/42?include_all_efforts=False]", "stravalib/tests/integration/test_client.py::test_get_activity[False-/activities/42?include_all_efforts=False]", "stravalib/tests/integration/test_client.py::test_get_activity[True-/activities/42?include_all_efforts=True]", "stravalib/tests/integration/test_client.py::test_update_activity[update_kwargs0-expected_params0-None-None]", "stravalib/tests/integration/test_client.py::test_update_activity[update_kwargs1-expected_params1-None-None]", "stravalib/tests/integration/test_client.py::test_update_activity[update_kwargs2-expected_params2-None-ValueError]", "stravalib/tests/integration/test_client.py::test_update_activity[update_kwargs3-expected_params3-None-None]", "stravalib/tests/integration/test_client.py::test_update_activity[update_kwargs4-expected_params4-None-None]", "stravalib/tests/integration/test_client.py::test_update_activity[update_kwargs5-expected_params5-None-None]", "stravalib/tests/integration/test_client.py::test_update_activity[update_kwargs6-expected_params6-DeprecationWarning-None]", "stravalib/tests/integration/test_client.py::test_update_activity[update_kwargs7-expected_params7-None-None]", "stravalib/tests/integration/test_client.py::test_update_activity[update_kwargs8-expected_params8-None-None]", "stravalib/tests/integration/test_client.py::test_update_activity[update_kwargs9-expected_params9-None-None]", "stravalib/tests/integration/test_client.py::test_update_activity[update_kwargs10-expected_params10-None-None]", "stravalib/tests/integration/test_client.py::test_update_activity[update_kwargs11-expected_params11-DeprecationWarning-None]", "stravalib/tests/integration/test_client.py::test_update_activity[update_kwargs12-expected_params12-None-None]", "stravalib/tests/integration/test_client.py::test_upload_activity[file-tcx-upload_kwargs0-expected_params0-None-None]", "stravalib/tests/integration/test_client.py::test_upload_activity[str-tcx-upload_kwargs1-expected_params1-None-None]", "stravalib/tests/integration/test_client.py::test_upload_activity[not_supported-tcx-upload_kwargs3-expected_params3-None-TypeError]", "stravalib/tests/integration/test_client.py::test_upload_activity[file-invalid-upload_kwargs4-expected_params4-None-ValueError]", "stravalib/tests/integration/test_client.py::test_upload_activity[file-tcx-upload_kwargs5-expected_params5-None-None]", "stravalib/tests/integration/test_client.py::test_upload_activity[file-tcx-upload_kwargs6-expected_params6-None-None]", "stravalib/tests/integration/test_client.py::test_upload_activity[file-tcx-upload_kwargs7-expected_params7-FutureWarning-None]", "stravalib/tests/integration/test_client.py::test_upload_activity[file-tcx-upload_kwargs8-expected_params8-FutureWarning-None]", "stravalib/tests/integration/test_client.py::test_upload_activity[file-tcx-upload_kwargs9-None-None-ValueError]", "stravalib/tests/integration/test_client.py::test_upload_activity[file-tcx-upload_kwargs10-expected_params10-DeprecationWarning-None]", "stravalib/tests/integration/test_client.py::test_upload_activity[file-tcx-upload_kwargs11-expected_params11-None-None]", "stravalib/tests/integration/test_client.py::test_upload_activity[file-tcx-upload_kwargs12-expected_params12-None-None]", "stravalib/tests/integration/test_client.py::test_upload_activity[file-tcx-upload_kwargs13-expected_params13-None-None]", "stravalib/tests/integration/test_client.py::test_update_athlete[update_kwargs0-expected_params0-None-None]", "stravalib/tests/integration/test_client.py::test_update_athlete[update_kwargs1-expected_params1-DeprecationWarning-None]", "stravalib/tests/integration/test_client.py::test_update_athlete[update_kwargs2-expected_params2-DeprecationWarning-None]", "stravalib/tests/integration/test_client.py::test_update_athlete[update_kwargs3-expected_params3-DeprecationWarning-None]", "stravalib/tests/integration/test_client.py::test_update_athlete[update_kwargs4-expected_params4-DeprecationWarning-None]", "stravalib/tests/integration/test_client.py::test_update_athlete[update_kwargs5-expected_params5-None-ValueError]", "stravalib/tests/integration/test_client.py::test_update_athlete[update_kwargs6-expected_params6-None-None]", "stravalib/tests/integration/test_client.py::test_update_athlete[update_kwargs7-expected_params7-None-None]", "stravalib/tests/integration/test_client.py::test_update_athlete[update_kwargs8-expected_params8-None-None]", "stravalib/tests/integration/test_client.py::test_create_activity[extra_create_kwargs0-extra_expected_params0-None]", "stravalib/tests/integration/test_client.py::test_create_activity[extra_create_kwargs1-extra_expected_params1-None]", "stravalib/tests/integration/test_client.py::test_create_activity[extra_create_kwargs2-extra_expected_params2-None]", "stravalib/tests/integration/test_client.py::test_create_activity[extra_create_kwargs3-extra_expected_params3-ValueError]", "stravalib/tests/integration/test_client.py::test_create_activity[extra_create_kwargs4-extra_expected_params4-None]", "stravalib/tests/integration/test_client.py::test_create_activity[extra_create_kwargs5-extra_expected_params5-None]", "stravalib/tests/integration/test_client.py::test_create_activity[extra_create_kwargs6-extra_expected_params6-None]", "stravalib/tests/integration/test_client.py::test_create_activity[extra_create_kwargs7-extra_expected_params7-None]", "stravalib/tests/integration/test_client.py::test_create_activity[extra_create_kwargs8-extra_expected_params8-None]", "stravalib/tests/integration/test_client.py::test_activity_uploader", "stravalib/tests/integration/test_client.py::test_get_route", "stravalib/tests/integration/test_client.py::test_get_starred_segments[None-0-0]", "stravalib/tests/integration/test_client.py::test_get_starred_segments[None-10-10]", "stravalib/tests/integration/test_client.py::test_get_starred_segments[10-10-10]", "stravalib/tests/integration/test_client.py::test_get_starred_segments[10-20-10]", "stravalib/tests/integration/test_client.py::test_get_starred_segments[10-1-1]", "stravalib/tests/integration/test_client.py::test_get_starred_segments[10-0-0]", "stravalib/tests/integration/test_client.py::test_get_activities[None-10-10]", "stravalib/tests/integration/test_client.py::test_get_activities[None-0-0]", "stravalib/tests/integration/test_client.py::test_get_activities[10-10-10]", "stravalib/tests/integration/test_client.py::test_get_activities[10-20-10]", "stravalib/tests/integration/test_client.py::test_get_activities[10-1-1]", "stravalib/tests/integration/test_client.py::test_get_activities[10-0-0]", "stravalib/tests/integration/test_client.py::test_get_activities_paged", "stravalib/tests/unit/test_client_utils.py::ClientUtilsTest::test_utc_datetime_to_epoch_utc_datetime_given_correct_epoch_returned", "stravalib/tests/unit/test_client_utils.py::ClientAuthorizationUrlTest::test_correct_scope", "stravalib/tests/unit/test_client_utils.py::ClientAuthorizationUrlTest::test_incorrect_approval_prompt_raises", "stravalib/tests/unit/test_client_utils.py::ClientAuthorizationUrlTest::test_incorrect_scope_raises", "stravalib/tests/unit/test_client_utils.py::ClientAuthorizationUrlTest::test_params", "stravalib/tests/unit/test_client_utils.py::ClientAuthorizationUrlTest::test_scope_may_be_list", "stravalib/tests/unit/test_client_utils.py::ClientAuthorizationUrlTest::test_state_param" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2023-01-06 14:04:09+00:00
apache-2.0
5,748
stravalib__stravalib-454
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index c1e950f..26e03a2 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -25,7 +25,7 @@ default_stages: [commit] repos: # Misc commit checks - repo: https://github.com/pre-commit/pre-commit-hooks - rev: v4.4.0 + rev: v4.5.0 # ref: https://github.com/pre-commit/pre-commit-hooks#hooks-available hooks: # Autoformat: Makes sure files end in a newline and only a newline. @@ -37,14 +37,14 @@ repos: # Linting code using ruff - repo: https://github.com/astral-sh/ruff-pre-commit - rev: v0.0.292 + rev: v0.1.9 hooks: - id: ruff args: [--fix, --exit-non-zero-on-fix] # Black for auto code formatting - repo: https://github.com/psf/black - rev: 23.9.1 + rev: 23.12.1 hooks: - id: black entry: bash -c 'black "$@"; git add -u' -- diff --git a/changelog.md b/changelog.md index d127d7c..8cfcf9e 100644 --- a/changelog.md +++ b/changelog.md @@ -2,12 +2,13 @@ ## Unreleased -- Fix: forgot to update model CI build to follow new src layout (@lwasser, #438) +- Fix: Forgot to update model CI build to follow new src layout (@lwasser, #438) - Fix: Type annotation on field that are of type timedelta are now correct (@enadeau, #440) - Fix: Correct type for ActivityPhoto sizes attribute (@jsamoocha, #444) - Fix: codespell config - ignore resources dir in tests (@lwasser, #445) - Add: Support for Strava's new read rate limits (@jsamoocha, #446) -- Fix: ignore documentation autogenerated api stubs (@lwasser, #447) +- Fix: Ignore documentation autogenerated api stubs (@lwasser, #447) +- Add: Improved handling of unexpected activity types (@jsamoocha, #454) ### Breaking Changes diff --git a/src/stravalib/model.py b/src/stravalib/model.py index 49d9e09..5879ae1 100644 --- a/src/stravalib/model.py +++ b/src/stravalib/model.py @@ -348,6 +348,30 @@ class BoundClientEntity(BaseModel): bound_client: Optional[Any] = Field(None, exclude=True) +class RelaxedActivityType(ActivityType): + @root_validator(pre=True) + def check_activity_type(cls, values: dict[str, Any]) -> dict[str, Any]: + v = values["__root__"] + if v not in get_args(ActivityType.__fields__["__root__"].type_): + LOGGER.warning( + f'Unexpected activity type. Given={v}, replacing by "Workout"' + ) + values["__root__"] = "Workout" + return values + + +class RelaxedSportType(SportType): + @root_validator(pre=True) + def check_sport_type(cls, values: dict[str, Any]) -> dict[str, Any]: + v = values["__root__"] + if v not in get_args(SportType.__fields__["__root__"].type_): + LOGGER.warning( + f'Unexpected sport type. Given={v}, replacing by "Workout"' + ) + values["__root__"] = "Workout" + return values + + class LatLon(LatLng, BackwardCompatibilityMixin, DeprecatedSerializableMixin): """ Enables backward compatibility for legacy namedtuple @@ -935,7 +959,7 @@ class Segment( map: Optional[Map] = None athlete_segment_stats: Optional[AthleteSegmentStats] = None athlete_pr_effort: Optional[AthletePrEffort] = None - activity_type: Optional[ActivityType] = None # type: ignore[assignment] + activity_type: Optional[RelaxedActivityType] = None # type: ignore[assignment] # Undocumented attributes: start_latitude: Optional[float] = None @@ -952,6 +976,7 @@ class Segment( "elevation_high": uh.meters, "elevation_low": uh.meters, "total_elevation_gain": uh.meters, + "activity_type": enum_value, } _latlng_check = validator( @@ -1040,6 +1065,8 @@ class Activity( end_latlng: Optional[LatLon] = None map: Optional[Map] = None gear: Optional[Gear] = None + type: Optional[RelaxedActivityType] = None + sport_type: Optional[RelaxedSportType] = None # Ignoring types here given there are overrides best_efforts: Optional[list[BestEffort]] = None # type: ignore[assignment] segment_efforts: Optional[list[SegmentEffort]] = None # type: ignore[assignment]
stravalib/stravalib
c6f8ad52994bc3e9f202a669087b82f560b5ed5a
diff --git a/src/stravalib/tests/unit/test_model.py b/src/stravalib/tests/unit/test_model.py index b9c6074..ec01344 100644 --- a/src/stravalib/tests/unit/test_model.py +++ b/src/stravalib/tests/unit/test_model.py @@ -225,6 +225,23 @@ def test_backward_compatible_attribute_lookup( assert not hasattr(lookup_expression, "bound_client") [email protected]( + "klass,attr,given_type,expected_type", + ( + (Activity, "type", "Run", "Run"), + (Activity, "sport_type", "Run", "Run"), + (Activity, "type", "FooBar", "Workout"), + (Activity, "sport_type", "FooBar", "Workout"), + (Segment, "activity_type", "Run", "Run"), + (Segment, "activity_type", "FooBar", "Workout"), + ), +) +def test_relaxed_activity_type_validation( + klass, attr, given_type, expected_type +): + assert getattr(klass(**{attr: given_type}), attr) == expected_type + + class ModelTest(TestBase): def setUp(self): super(ModelTest, self).setUp()
ENH: Graceful handling of Pydantic validation errors (for unexpected sports type / activity type) ### Feature Type - [ ] Adding new functionality to stravalib - [X] Changing existing functionality in stravalib - [ ] Removing existing functionality in stravalib ### Problem Description For unexpected activity/sport types, parsing `Activity` objects crashes with a Pydantic `ValidationError`. On (rare) occasions, these unexpected (and undocumented) types pop up in responses from Strava. ### Feature Description We can add custom types and validators for (at least) the mentioned fields `activity_type` and `sports_type`. For unexpected types, we can then parse them and log a warning instead of crashing. ### Alternative Solutions Unfeasible: requesting Strava to always keep the documentation 100% up-to-date. ### Additional Context _No response_ ### Code of Conduct - [X] I agree to follow this project's Code of Conduct
0.0
c6f8ad52994bc3e9f202a669087b82f560b5ed5a
[ "src/stravalib/tests/unit/test_model.py::test_relaxed_activity_type_validation[Activity-type-FooBar-Workout]", "src/stravalib/tests/unit/test_model.py::test_relaxed_activity_type_validation[Activity-sport_type-FooBar-Workout]", "src/stravalib/tests/unit/test_model.py::test_relaxed_activity_type_validation[Segment-activity_type-Run-Run]", "src/stravalib/tests/unit/test_model.py::test_relaxed_activity_type_validation[Segment-activity_type-FooBar-Workout]" ]
[ "src/stravalib/tests/unit/test_model.py::TestLegacyModelSerialization::test_legacy_deserialize[Club-name-foo]", "src/stravalib/tests/unit/test_model.py::TestLegacyModelSerialization::test_legacy_from_dict[Club-name-foo]", "src/stravalib/tests/unit/test_model.py::TestLegacyModelSerialization::test_legacy_to_dict[Club-name-foo]", "src/stravalib/tests/unit/test_model.py::test_backward_compatibility_mixin_field_conversions[Club-raw0-foo]", "src/stravalib/tests/unit/test_model.py::test_backward_compatibility_mixin_field_conversions[ActivityTotals-raw1-expected_value1]", "src/stravalib/tests/unit/test_model.py::test_backward_compatibility_mixin_field_conversions[ActivityTotals-raw2-expected_value2]", "src/stravalib/tests/unit/test_model.py::test_backward_compatibility_mixin_field_conversions[Activity-raw3-expected_value3]", "src/stravalib/tests/unit/test_model.py::test_backward_compatibility_mixin_field_conversions[Club-raw4-expected_value4]", "src/stravalib/tests/unit/test_model.py::test_backward_compatibility_mixin_field_conversions[Activity-raw5-Run]", "src/stravalib/tests/unit/test_model.py::test_deserialization_edge_cases[Activity-raw0-expected_value0]", "src/stravalib/tests/unit/test_model.py::test_deserialization_edge_cases[Activity-raw1-None]", "src/stravalib/tests/unit/test_model.py::test_deserialization_edge_cases[Segment-raw2-None]", "src/stravalib/tests/unit/test_model.py::test_deserialization_edge_cases[SegmentExplorerResult-raw3-None]", "src/stravalib/tests/unit/test_model.py::test_deserialization_edge_cases[ActivityPhoto-raw4-None]", "src/stravalib/tests/unit/test_model.py::test_deserialization_edge_cases[Activity-raw5-None]", "src/stravalib/tests/unit/test_model.py::test_deserialization_edge_cases[Activity-raw6-expected_value6]", "src/stravalib/tests/unit/test_model.py::test_deserialization_edge_cases[BaseEffort-raw7-expected_value7]", "src/stravalib/tests/unit/test_model.py::test_deserialization_edge_cases[ActivityLap-raw8-expected_value8]", "src/stravalib/tests/unit/test_model.py::test_subscription_callback_field_names", "src/stravalib/tests/unit/test_model.py::test_backward_compatible_attribute_lookup[None-None-False0]", "src/stravalib/tests/unit/test_model.py::test_backward_compatible_attribute_lookup[None-None-False1]", "src/stravalib/tests/unit/test_model.py::test_backward_compatible_attribute_lookup[1-1-False0]", "src/stravalib/tests/unit/test_model.py::test_backward_compatible_attribute_lookup[lookup_expression3-expected_result3-False]", "src/stravalib/tests/unit/test_model.py::test_backward_compatible_attribute_lookup[lookup_expression4-expected_result4-False]", "src/stravalib/tests/unit/test_model.py::test_backward_compatible_attribute_lookup[lookup_expression5-expected_result5-False]", "src/stravalib/tests/unit/test_model.py::test_backward_compatible_attribute_lookup[1-1-False1]", "src/stravalib/tests/unit/test_model.py::test_backward_compatible_attribute_lookup[lookup_expression7-expected_result7-None]", "src/stravalib/tests/unit/test_model.py::test_backward_compatible_attribute_lookup[lookup_expression8-expected_result8-True]", "src/stravalib/tests/unit/test_model.py::test_backward_compatible_attribute_lookup[lookup_expression9-expected_result9-False]", "src/stravalib/tests/unit/test_model.py::test_backward_compatible_attribute_lookup[lookup_expression10-expected_result10-False]", "src/stravalib/tests/unit/test_model.py::test_backward_compatible_attribute_lookup[lookup_expression11-expected_result11-None]", "src/stravalib/tests/unit/test_model.py::test_backward_compatible_attribute_lookup[lookup_expression12-expected_result12-True]", "src/stravalib/tests/unit/test_model.py::test_backward_compatible_attribute_lookup[lookup_expression13-expected_result13-None]", "src/stravalib/tests/unit/test_model.py::test_backward_compatible_attribute_lookup[lookup_expression14-expected_result14-True]", "src/stravalib/tests/unit/test_model.py::test_backward_compatible_attribute_lookup[lookup_expression15-expected_result15-False]", "src/stravalib/tests/unit/test_model.py::test_backward_compatible_attribute_lookup[lookup_expression16-expected_result16-False]", "src/stravalib/tests/unit/test_model.py::test_backward_compatible_attribute_lookup[lookup_expression17-expected_result17-None]", "src/stravalib/tests/unit/test_model.py::test_backward_compatible_attribute_lookup[lookup_expression18-expected_result18-True]", "src/stravalib/tests/unit/test_model.py::test_relaxed_activity_type_validation[Activity-type-Run-Run]", "src/stravalib/tests/unit/test_model.py::test_relaxed_activity_type_validation[Activity-sport_type-Run-Run]", "src/stravalib/tests/unit/test_model.py::ModelTest::test_distance_units", "src/stravalib/tests/unit/test_model.py::ModelTest::test_entity_collections", "src/stravalib/tests/unit/test_model.py::ModelTest::test_speed_units", "src/stravalib/tests/unit/test_model.py::ModelTest::test_subscription_deser", "src/stravalib/tests/unit/test_model.py::ModelTest::test_subscription_update_deser", "src/stravalib/tests/unit/test_model.py::ModelTest::test_time_intervals", "src/stravalib/tests/unit/test_model.py::ModelTest::test_weight_units" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2024-01-16 17:00:24+00:00
apache-2.0
5,749
streamlink__streamlink-1070
diff --git a/src/streamlink/plugins/tvplayer.py b/src/streamlink/plugins/tvplayer.py index 249e85fa..f79474e6 100644 --- a/src/streamlink/plugins/tvplayer.py +++ b/src/streamlink/plugins/tvplayer.py @@ -15,7 +15,7 @@ class TVPlayer(Plugin): dummy_postcode = "SE1 9LT" # location of ITV HQ in London url_re = re.compile(r"https?://(?:www.)?tvplayer.com/(:?watch/?|watch/(.+)?)") - stream_attrs_re = re.compile(r'data-(resource|token)\s*=\s*"(.*?)"', re.S) + stream_attrs_re = re.compile(r'data-(resource|token|channel-id)\s*=\s*"(.*?)"', re.S) login_token_re = re.compile(r'input.*?name="token".*?value="(\w+)"') stream_schema = validate.Schema({ "tvplayer": validate.Schema({ @@ -58,20 +58,22 @@ class TVPlayer(Plugin): # there is a 302 redirect on a successful login return res2.status_code == 302 - def _get_stream_data(self, resource, token, service=1): + def _get_stream_data(self, resource, channel_id, token, service=1): # Get the context info (validation token and platform) self.logger.debug("Getting stream information for resource={0}".format(resource)) context_res = http.get(self.context_url, params={"resource": resource, "gen": token}) context_data = http.json(context_res, schema=self.context_schema) + self.logger.debug("Context data: {0}", str(context_data)) # get the stream urls res = http.post(self.api_url, data=dict( service=service, - id=resource, + id=channel_id, validate=context_data["validate"], token=context_data.get("token"), - platform=context_data["platform"]["key"])) + platform=context_data["platform"]["key"]), + raise_for_status=False) return http.json(res, schema=self.stream_schema) @@ -91,7 +93,8 @@ class TVPlayer(Plugin): data=dict(postcode=self.dummy_postcode), params=dict(return_url=self.url)) - stream_attrs = dict((k, v.strip('"')) for k, v in self.stream_attrs_re.findall(res.text)) + stream_attrs = dict((k.replace("-", "_"), v.strip('"')) for k, v in self.stream_attrs_re.findall(res.text)) + self.logger.debug("Got stream attrs: {0}", str(stream_attrs)) if "resource" in stream_attrs and "token" in stream_attrs: stream_data = self._get_stream_data(**stream_attrs)
streamlink/streamlink
4761570f479ba51ffeb099a4e8a2ed3fea6df72d
diff --git a/tests/test_plugin_tvplayer.py b/tests/test_plugin_tvplayer.py index 52f27dc0..f9f13367 100644 --- a/tests/test_plugin_tvplayer.py +++ b/tests/test_plugin_tvplayer.py @@ -41,7 +41,7 @@ class TestPluginTVPlayer(unittest.TestCase): page_resp = Mock() page_resp.text = u""" <div class="video-js theoplayer-skin theo-seekbar-above-controls content-box vjs-fluid" - data-resource= "89" + data-resource= "bbcone" data-token = "1324567894561268987948596154656418448489159" data-content-type="live" data-environment="live" @@ -54,6 +54,7 @@ class TestPluginTVPlayer(unittest.TestCase): mock_http.get.return_value = page_resp hlsstream.parse_variant_playlist.return_value = {"test": HLSStream(self.session, "http://test.se/stream1")} + TVPlayer.bind(self.session, "test.plugin.tvplayer") plugin = TVPlayer("http://tvplayer.com/watch/dave") streams = plugin.get_streams() @@ -63,7 +64,7 @@ class TestPluginTVPlayer(unittest.TestCase): # test the url is used correctly mock_http.get.assert_called_with("http://tvplayer.com/watch/dave") # test that the correct API call is made - mock_get_stream_data.assert_called_with(resource="89", token="1324567894561268987948596154656418448489159") + mock_get_stream_data.assert_called_with(resource="bbcone", channel_id="89", token="1324567894561268987948596154656418448489159") # test that the correct URL is used for the HLSStream hlsstream.parse_variant_playlist.assert_called_with(ANY, "http://test.se/stream1") @@ -76,6 +77,7 @@ class TestPluginTVPlayer(unittest.TestCase): """ mock_http.get.return_value = page_resp + TVPlayer.bind(self.session, "test.plugin.tvplayer") plugin = TVPlayer("http://tvplayer.com/watch/dave") streams = plugin.get_streams()
tvplayer plugin broken https://tvplayer.com/watch/bbcone Unable to open URL: http://api.tvplayer.com/api/v2/stream/live (400 Client Error: Bad Request for url: http://api.tvplayer.com/api/v2/stream/live)
0.0
4761570f479ba51ffeb099a4e8a2ed3fea6df72d
[ "tests/test_plugin_tvplayer.py::TestPluginTVPlayer::test_get_streams" ]
[ "tests/test_plugin_tvplayer.py::TestPluginTVPlayer::test_can_handle_url", "tests/test_plugin_tvplayer.py::TestPluginTVPlayer::test_get_invalid_page" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2017-07-06 16:07:35+00:00
bsd-2-clause
5,750
streamlink__streamlink-1092
diff --git a/docs/_applications.rst b/docs/_applications.rst new file mode 100644 index 00000000..767a79b8 --- /dev/null +++ b/docs/_applications.rst @@ -0,0 +1,24 @@ +.. _applications: + +:orphan: + + +.. raw:: html + + <style> + .rst-content table.field-list td { + padding-top: 8px; + } + </style> + +.. |Windows| raw:: html + + <i class="fa fa-fw fa-windows"></i> + +.. |MacOS| raw:: html + + <i class="fa fa-fw fa-apple"></i> + +.. |Linux| raw:: html + + <i class="fa fa-fw fa-linux"></i> diff --git a/docs/applications.rst b/docs/applications.rst new file mode 100644 index 00000000..598d7197 --- /dev/null +++ b/docs/applications.rst @@ -0,0 +1,22 @@ +.. include:: _applications.rst + + +Streamlink Applications +======================= + + +Streamlink Twitch GUI +--------------------- + +.. image:: https://user-images.githubusercontent.com/467294/28097570-3415020e-66b1-11e7-928d-4b9da35daf13.jpg + :alt: Streamlink Twitch GUI + +:Description: A multi platform Twitch.tv browser for Streamlink +:Type: Graphical User Interface +:OS: |Windows| |MacOS| |Linux| +:Author: `Sebastian Meyer <https://github.com/bastimeyer>`_ +:Website: https://streamlink.github.io/streamlink-twitch-gui +:Source code: https://github.com/streamlink/streamlink-twitch-gui +:Info: A NW.js based desktop web application, formerly known as *Livestreamer Twitch GUI*. Browse Twitch.tv and watch + multiple streams at once. Filter streams by language, receive desktop notifications when followed channels start + streaming and access the Twitch chat by using customizable chat applications. diff --git a/docs/conf.py b/docs/conf.py index 5591eb25..a8b13451 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -58,7 +58,7 @@ release = streamlink_version # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. -exclude_patterns = ['_build'] +exclude_patterns = ['_build', '_applications.rst'] # The reST default role (used for this markup: `text`) to use for all documents. #default_role = None diff --git a/docs/index.rst b/docs/index.rst index 64870690..1deedaae 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -66,3 +66,5 @@ See their respective sections for more information on how to use them. api changelog donate + applications + thirdparty diff --git a/docs/thirdparty.rst b/docs/thirdparty.rst new file mode 100644 index 00000000..5e3ead84 --- /dev/null +++ b/docs/thirdparty.rst @@ -0,0 +1,46 @@ +.. + !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + + If you're a developer and want to add your project/application to this list, please + + 1. adhere to the same structure and format of the entries of the applications.rst file and this one + 2. add your new entry to the bottom of the list + 3. at least provide the required fields (in the same order) + - "Description" (a brief text describing your application) + - "Type" (eg. Graphical User Interface, CLI wrapper, etc.) + - "OS" (please use the available substitutions) + - "Author" (if possible, include a link to the creator's Github/Gitlab profile, etc. or a contact email address) + - "Website" + 4. use an image + - in the jpeg or png format + - with a static and reliable !!!https!!! URL (use Github or an image hoster like Imgur, etc.) + - with a reasonable size and aspect ratio + - with a decent compression quality + - that is not too large (at most 1 MiB allowed, the smaller the better) + - that is neutral and only shows your application + 5. optionally add more fields like a URL to the source code repository, a larger info or features text, etc. + + Please be aware that the Streamlink team may edit and remove your entry at any time. + + Thank you! :) + + !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + + +.. include:: _applications.rst + + +Third Party Applications +======================== + + +.. content list start + + +.. replace this line with the first entry + + +.. content list end + + +Help us extend this list by sending us a pull request on Github. Thanks! diff --git a/src/streamlink/plugins/arconai.py b/src/streamlink/plugins/arconai.py index bd6cff20..7a0ee04b 100644 --- a/src/streamlink/plugins/arconai.py +++ b/src/streamlink/plugins/arconai.py @@ -1,14 +1,13 @@ import re from streamlink.plugin import Plugin -from streamlink.plugin.api import http, validate -from streamlink.plugin.api.utils import parse_json +from streamlink.plugin.api import http +from streamlink.plugin.api import useragents from streamlink.stream import HLSStream -_url_re = re.compile(r"https://www.arconaitv.me/([^/]+)/") +_url_re = re.compile(r'''https?://(www\.)?arconaitv\.me/stream\.php\?id=\d+''') +_playlist_re = re.compile(r'''source\ssrc=["'](?P<url>[^"']+)["']''') -SOURCES_RE = re.compile(r" data-item='([^']+)' ") -USER_AGENT = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36" class ArconaiTv(Plugin): @classmethod @@ -16,19 +15,21 @@ class ArconaiTv(Plugin): return _url_re.match(url) def _get_streams(self): - page = http.get(self.url) - match = SOURCES_RE.search(page.text) - if match is None: - return + headers = { + 'User-Agent': useragents.CHROME, + 'Referer': self.url + } - sources = parse_json(match.group(1)) - if "sources" not in sources or not isinstance(sources["sources"], list): + res = http.get(self.url, headers=headers) + + match = _playlist_re.search(res.text) + if match is None: return - for source in sources["sources"]: - if "src" not in source or not source["src"].endswith(".m3u8"): - continue + url = match.group('url') - yield "live", HLSStream(self.session, source["src"], headers={"User-Agent": USER_AGENT}) + if url: + self.logger.debug('HLS URL: {0}'.format(url)) + yield 'live', HLSStream(self.session, url, headers=headers) __plugin__ = ArconaiTv diff --git a/src/streamlink/plugins/douyutv.py b/src/streamlink/plugins/douyutv.py index b05f4ed0..43ad9daa 100644 --- a/src/streamlink/plugins/douyutv.py +++ b/src/streamlink/plugins/douyutv.py @@ -1,4 +1,3 @@ -import hashlib import re import time import uuid @@ -13,10 +12,9 @@ from streamlink.stream import HTTPStream, HLSStream, RTMPStream #python version by debugzxcv at https://gist.github.com/debugzxcv/85bb2750d8a5e29803f2686c47dc236b from streamlink.plugins.douyutv_blackbox import stupidMD5 -WAPI_URL = "https://www.douyu.com/swf_api/room/{0}?cdn=&nofan=yes&_t={1}&sign={2}" +OAPI_URL = "http://open.douyucdn.cn/api/RoomApi/room/{0}" LAPI_URL = "https://www.douyu.com/lapi/live/getPlay/{0}" VAPI_URL = "https://vmobile.douyu.com/video/getInfo?vid={0}" -WAPI_SECRET = "bLFlashflowlad92" LAPI_SECRET = "a2053899224e8a92974c729dceed1cc99b3d8282" SHOW_STATUS_ONLINE = 1 SHOW_STATUS_OFFLINE = 2 @@ -71,7 +69,7 @@ _room_id_alt_schema = validate.Schema( _room_schema = validate.Schema( { "data": validate.any(None, { - "show_status": validate.all( + "room_status": validate.all( validate.text, validate.transform(int) ) @@ -113,7 +111,7 @@ class Douyutv(Plugin): def _get_room_json(self, channel, rate, ts, did, sign): data = { - "ver": "2017070301", + "ver": "2017071231", "cdn": "ws", #cdns: ["ws", "tct", "ws2", "dl"] "rate": rate, "tt": ts, @@ -144,7 +142,7 @@ class Douyutv(Plugin): #Thanks to @ximellon for providing method. channel = match.group("channel") - http.headers.update({'User-Agent': useragents.CHROME}) + http.headers.update({'User-Agent': useragents.CHROME, 'Referer': self.url}) try: channel = int(channel) except ValueError: @@ -152,19 +150,17 @@ class Douyutv(Plugin): if channel is None: channel = http.get(self.url, schema=_room_id_alt_schema) - ts = int(time.time() / 60) - sign = hashlib.md5(("{0}{1}{2}".format(channel, WAPI_SECRET, ts)).encode("utf-8")).hexdigest() - - res = http.get(WAPI_URL.format(channel, ts, sign)) + res = http.get(OAPI_URL.format(channel)) room = http.json(res, schema=_room_schema) if not room: self.logger.info("Not a valid room url.") return - if room["show_status"] != SHOW_STATUS_ONLINE: + if room["room_status"] != SHOW_STATUS_ONLINE: self.logger.info("Stream currently unavailable.") return + ts = int(time.time() / 60) did = uuid.uuid4().hex.upper() sign = stupidMD5(("{0}{1}{2}{3}".format(channel, did, LAPI_SECRET, ts)))
streamlink/streamlink
3e2cb6dd5b0e8b5de7a44446745c74560960f5dc
diff --git a/tests/test_plugin_arconai.py b/tests/test_plugin_arconai.py new file mode 100644 index 00000000..d1a462f7 --- /dev/null +++ b/tests/test_plugin_arconai.py @@ -0,0 +1,14 @@ +import unittest + +from streamlink.plugins.arconai import ArconaiTv + + +class TestPluginArconaiTv(unittest.TestCase): + def test_can_handle_url(self): + # should match + self.assertTrue(ArconaiTv.can_handle_url('http://arconaitv.me/stream.php?id=1')) + self.assertTrue(ArconaiTv.can_handle_url('http://arconaitv.me/stream.php?id=23')) + self.assertTrue(ArconaiTv.can_handle_url('http://arconaitv.me/stream.php?id=440')) + + # shouldn't match + self.assertFalse(ArconaiTv.can_handle_url('http://arconaitv.me/'))
Where does one go to share a GUI/frontend? ### Checklist - [ ] This is a bug report. - [ ] This is a plugin request. - [ ] This is a feature request. - [x] I used the search function to find already opened/closed issues or pull requests. ### Description I looked around but I couldn't find any place where they can be submitted. Can someone help me out?
0.0
3e2cb6dd5b0e8b5de7a44446745c74560960f5dc
[ "tests/test_plugin_arconai.py::TestPluginArconaiTv::test_can_handle_url" ]
[]
{ "failed_lite_validators": [ "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2017-07-13 02:47:13+00:00
bsd-2-clause
5,751
streamlink__streamlink-122
diff --git a/.travis.yml b/.travis.yml index 57c30c83..c678e2da 100644 --- a/.travis.yml +++ b/.travis.yml @@ -11,7 +11,7 @@ matrix: env: BUILD_DOCS=yes before_install: - - pip install pytest pytest-cov codecov coverage + - pip install pytest pytest-cov codecov coverage mock install: - python setup.py install diff --git a/src/streamlink/plugin/api/http_session.py b/src/streamlink/plugin/api/http_session.py index f5b6879c..0b1caa7a 100644 --- a/src/streamlink/plugin/api/http_session.py +++ b/src/streamlink/plugin/api/http_session.py @@ -66,9 +66,34 @@ class HTTPSession(Session): self.mount("http://", HTTPAdapterWithReadTimeout()) self.mount("https://", HTTPAdapterWithReadTimeout()) + @classmethod + def determine_json_encoding(cls, sample): + """ + Determine which Unicode encoding the JSON text sample is encoded with + + RFC4627 (http://www.ietf.org/rfc/rfc4627.txt) suggests that the encoding of JSON text can be determined + by checking the pattern of NULL bytes in first 4 octets of the text. + :param sample: a sample of at least 4 bytes of the JSON text + :return: the most likely encoding of the JSON text + """ + nulls_at = [i for i, j in enumerate(bytearray(sample[:4])) if j == 0] + if nulls_at == [0, 1, 2]: + return "UTF-32BE" + elif nulls_at == [0, 2]: + return "UTF-16BE" + elif nulls_at == [1, 2, 3]: + return "UTF-32LE" + elif nulls_at == [1, 3]: + return "UTF-16LE" + else: + return "UTF-8" + @classmethod def json(cls, res, *args, **kwargs): """Parses JSON from a response.""" + # if an encoding is already set then use the provided encoding + if res.encoding is None: + res.encoding = cls.determine_json_encoding(res.content[:4]) return parse_json(res.text, *args, **kwargs) @classmethod diff --git a/src/streamlink/plugins/livecodingtv.py b/src/streamlink/plugins/livecodingtv.py index b5ad3a08..74522af7 100644 --- a/src/streamlink/plugins/livecodingtv.py +++ b/src/streamlink/plugins/livecodingtv.py @@ -1,12 +1,20 @@ import re from streamlink.plugin import Plugin +from streamlink.stream import HLSStream from streamlink.stream import RTMPStream, HTTPStream from streamlink.plugin.api import http -_vod_re = re.compile('\"(http(s)?://.*\.mp4\?t=.*)\"') -_rtmp_re = re.compile('rtmp://[^"]+/(?P<channel>\w+)+[^/"]+') -_url_re = re.compile('http(s)?://(?:\w+.)?\livecoding\.tv') +_streams_re = re.compile(r""" + src:\s+"( + rtmp://.*?\?t=.*?| # RTMP stream + https?://.*?playlist.m3u8.*?\?t=.*?| # HLS stream + https?://.*?manifest.mpd.*?\?t=.*?| # DASH stream + https?://.*?.mp4\?t=.*? # HTTP stream + )".*? + type:\s+"(.*?)" # which stream type it is + """, re.M | re.DOTALL | re.VERBOSE) +_url_re = re.compile(r"http(s)?://(?:\w+\.)?livecoding\.tv") class LivecodingTV(Plugin): @@ -16,18 +24,19 @@ class LivecodingTV(Plugin): def _get_streams(self): res = http.get(self.url) - match = _rtmp_re.search(res.content.decode('utf-8')) - if match: - params = { - "rtmp": match.group(0), - "pageUrl": self.url, - "live": True, - } - yield 'live', RTMPStream(self.session, params) - return - - match = _vod_re.search(res.content.decode('utf-8')) - if match: - yield 'vod', HTTPStream(self.session, match.group(1)) + match = _streams_re.findall(res.content.decode('utf-8')) + for url, stream_type in match: + if stream_type == "rtmp/mp4" and RTMPStream.is_usable(self.session): + params = { + "rtmp": url, + "pageUrl": self.url, + "live": True, + } + yield 'live', RTMPStream(self.session, params) + elif stream_type == "application/x-mpegURL": + for s in HLSStream.parse_variant_playlist(self.session, url).items(): + yield s + elif stream_type == "video/mp4": + yield 'vod', HTTPStream(self.session, url) __plugin__ = LivecodingTV diff --git a/src/streamlink/plugins/tvplayer.py b/src/streamlink/plugins/tvplayer.py index ffe8f191..a16d6d34 100644 --- a/src/streamlink/plugins/tvplayer.py +++ b/src/streamlink/plugins/tvplayer.py @@ -11,7 +11,7 @@ class TVPlayer(Plugin): "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) " "Chrome/43.0.2357.65 Safari/537.36") API_URL = "http://api.tvplayer.com/api/v2/stream/live" - _url_re = re.compile(r"http://(?:www.)?tvplayer.com/watch/(.+)") + _url_re = re.compile(r"https?://(?:www.)?tvplayer.com/(:?watch/?|watch/(.+)?)") _stream_attrs_ = re.compile(r'var\s+(validate|platform|resourceId)\s+=\s*(.*?);', re.S) _stream_schema = validate.Schema({ "tvplayer": validate.Schema({ @@ -25,11 +25,12 @@ class TVPlayer(Plugin): @classmethod def can_handle_url(cls, url): match = TVPlayer._url_re.match(url) - return match + return match is not None def _get_streams(self): # find the list of channels from the html in the page - res = http.get(self.url) + self.url = self.url.replace("https", "http") # https redirects to http + res = http.get(self.url, headers={"User-Agent": TVPlayer._user_agent}) stream_attrs = dict((k, v.strip('"')) for k, v in TVPlayer._stream_attrs_.findall(res.text)) # get the stream urls
streamlink/streamlink
d20d1a62b53fc49aab6c9df3bc52020ee77ae607
diff --git a/tests/test_plugin_api_http_session.py b/tests/test_plugin_api_http_session.py index 163a8ee8..bf3296aa 100644 --- a/tests/test_plugin_api_http_session.py +++ b/tests/test_plugin_api_http_session.py @@ -1,5 +1,13 @@ +# coding=utf-8 import unittest +import requests + +try: + from unittest.mock import patch, PropertyMock +except ImportError: + from mock import patch, PropertyMock + from streamlink.exceptions import PluginError from streamlink.plugin.api.http_session import HTTPSession @@ -16,5 +24,26 @@ class TestPluginAPIHTTPSession(unittest.TestCase): self.assertRaises(PluginError, stream_data) + def test_json_encoding(self): + json_str = u"{\"test\": \"Α and Ω\"}" + + # encode the json string with each encoding and assert that the correct one is detected + for encoding in ["UTF-32BE", "UTF-32LE", "UTF-16BE", "UTF-16LE", "UTF-8"]: + with patch('requests.Response.content', new_callable=PropertyMock) as mock_content: + mock_content.return_value = json_str.encode(encoding) + res = requests.Response() + + self.assertEqual(HTTPSession.json(res), {u"test": u"\u0391 and \u03a9"}) + + def test_json_encoding_override(self): + json_text = u"{\"test\": \"Α and Ω\"}".encode("cp949") + + with patch('requests.Response.content', new_callable=PropertyMock) as mock_content: + mock_content.return_value = json_text + res = requests.Response() + res.encoding = "cp949" + + self.assertEqual(HTTPSession.json(res), {u"test": u"\u0391 and \u03a9"}) + if __name__ == "__main__": unittest.main() diff --git a/tests/test_plugin_tvplayer.py b/tests/test_plugin_tvplayer.py new file mode 100644 index 00000000..b3f1a6a3 --- /dev/null +++ b/tests/test_plugin_tvplayer.py @@ -0,0 +1,21 @@ +import unittest + +from streamlink.plugins.tvplayer import TVPlayer + + +class TestPluginTVPlayer(unittest.TestCase): + def test_can_handle_url(self): + # should match + self.assertTrue(TVPlayer.can_handle_url("http://tvplayer.com/watch/")) + self.assertTrue(TVPlayer.can_handle_url("http://www.tvplayer.com/watch/")) + self.assertTrue(TVPlayer.can_handle_url("http://tvplayer.com/watch")) + self.assertTrue(TVPlayer.can_handle_url("http://www.tvplayer.com/watch")) + self.assertTrue(TVPlayer.can_handle_url("http://tvplayer.com/watch/dave")) + self.assertTrue(TVPlayer.can_handle_url("http://www.tvplayer.com/watch/itv")) + self.assertTrue(TVPlayer.can_handle_url("https://www.tvplayer.com/watch/itv")) + self.assertTrue(TVPlayer.can_handle_url("https://tvplayer.com/watch/itv")) + + # shouldn't match + self.assertFalse(TVPlayer.can_handle_url("http://www.tvplayer.com/")) + self.assertFalse(TVPlayer.can_handle_url("http://www.tvcatchup.com/")) + self.assertFalse(TVPlayer.can_handle_url("http://www.youtube.com/"))
Non unicode escaped API breaks the plugin I have a problem on Streamlink 0.0.2 with Twitch plugin. Luckily I figured out what's going on and fixed my own copy of code. So I would like to share my fix though I am not sure with my decision. My question is: > Is it safe to assume that JSON APIs other than Twitch, use particular text encoding? Here is some error log. ``` > streamlink.exe --player <some my player> --twitch-oauth-token <redacted> https://twitch.tv/<readacted> source [cli][info] Found matching plugin twitch for URL https://twitch.tv/<readacted> [plugin.twitch][info] Attempting to authenticate using OAuth token error: 'cp949' codec can't encode character '\u011b' in position 48: illegal multibyte sequence ``` Little backgrounds. 1. Twitch API does not escape 'non-ascii' characters. 2. Twitch API does not state `charset` in the `Content-type` header. Only states MIME type `application/json`. 3. I am running Korean version of Windows 10, and the plugin tries to decode response body with OS default encoding(presumably) which is CP949 in my case. Let me follow the code flow. 1. Twitch plugin tries to authenticate with my OAuth token, in https://github.com/streamlink/streamlink/blob/0.0.2/src/streamlink/plugins/twitch.py#L264 2. ...which is `user` method in helper class, in https://github.com/streamlink/streamlink/blob/0.0.2/src/streamlink/plugins/twitch.py#L208 3. ...which requests API with GET method, in https://github.com/streamlink/streamlink/blob/0.0.2/src/streamlink/plugins/twitch.py#L167 4. I know Twitch API returns in JSON format, so going https://github.com/streamlink/streamlink/blob/0.0.2/src/streamlink/plugins/twitch.py#L182 5. ...which tries to parse response body text in JSON, implicitly tries to decode response body from bytes to str, in https://github.com/streamlink/streamlink/blob/0.0.2/src/streamlink/plugin/api/http_session.py#L70 I could simply edit `http_session.py` and fix it by stating 'known' charset before accessing `text` property, something like: ``` + if res.encoding is None: + res.encoding = 'utf8' return parse_json(res.text, *args, **kwargs) ```
0.0
d20d1a62b53fc49aab6c9df3bc52020ee77ae607
[ "tests/test_plugin_tvplayer.py::TestPluginTVPlayer::test_can_handle_url" ]
[ "tests/test_plugin_api_http_session.py::TestPluginAPIHTTPSession::test_json_encoding", "tests/test_plugin_api_http_session.py::TestPluginAPIHTTPSession::test_json_encoding_override", "tests/test_plugin_api_http_session.py::TestPluginAPIHTTPSession::test_read_timeout" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2016-11-03 13:26:49+00:00
bsd-2-clause
5,752
streamlink__streamlink-135
diff --git a/docs/plugin_matrix.rst b/docs/plugin_matrix.rst index d90da1ff..4cd211c0 100644 --- a/docs/plugin_matrix.rst +++ b/docs/plugin_matrix.rst @@ -12,6 +12,7 @@ is limited. =================== ==================== ===== ===== =========================== Name URL(s) Live VOD Notes =================== ==================== ===== ===== =========================== +adultswim adultswim.com Yes No Streams may be geo-restricted, VOD streams are encrypted afreeca afreecatv.com Yes No afreecatv afreeca.tv Yes No aftonbladet aftonbladet.se Yes Yes diff --git a/src/streamlink/plugins/adultswim.py b/src/streamlink/plugins/adultswim.py new file mode 100644 index 00000000..abe15b82 --- /dev/null +++ b/src/streamlink/plugins/adultswim.py @@ -0,0 +1,74 @@ +#!/usr/bin/env python +import re +from pprint import pprint + +from streamlink.plugin import Plugin +from streamlink.plugin.api import http, validate +from streamlink.stream import HLSStream +from streamlink.utils import parse_json + + +class AdultSwim(Plugin): + _user_agent = ( + "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) " + "Chrome/43.0.2357.65 Safari/537.36") + API_URL = "http://www.adultswim.com/videos/api/v2/videos/{id}?fields=stream" + + _url_re = re.compile(r"http://www\.adultswim\.com/videos/streams/(.*)") + _stream_data_re = re.compile(r".*AS_INITIAL_DATA = (\{.*?});.*", re.M | re.DOTALL) + + _page_data_schema = validate.Schema({ + u"streams": { + validate.text: { + u"stream": validate.text + } + } + }) + + _api_schema = validate.Schema({ + u'status': u'ok', + u'data': { + u'stream': { + u'assets': [ + { + u'url': validate.url() + } + ] + } + } + }) + + @classmethod + def can_handle_url(cls, url): + match = AdultSwim._url_re.match(url) + return match is not None + + def _get_streams(self): + # get the page + res = http.get(self.url, headers={"User-Agent": self._user_agent}) + # find the big blob of stream info in the page + stream_data = self._stream_data_re.match(res.text) + stream_name = AdultSwim._url_re.match(self.url).group(1) or "live-stream" + + if stream_data: + # parse the stream info as json + stream_info = parse_json(stream_data.group(1), schema=self._page_data_schema) + # get the stream ID + stream_id = stream_info[u"streams"][stream_name][u"stream"] + + if stream_id: + api_url = self.API_URL.format(id=stream_id) + + res = http.get(api_url, headers={"User-Agent": self._user_agent}) + stream_data = http.json(res, schema=self._api_schema) + + for asset in stream_data[u'data'][u'stream'][u'assets']: + for n, s in HLSStream.parse_variant_playlist(self.session, asset[u"url"]).items(): + yield n, s + + else: + self.logger.error("Couldn't find the stream ID for this stream: {}".format(stream_name)) + else: + self.logger.error("Couldn't find the stream data for this stream: {}".format(stream_name)) + +__plugin__ = AdultSwim diff --git a/src/streamlink/plugins/goodgame.py b/src/streamlink/plugins/goodgame.py index 75979026..14557b77 100644 --- a/src/streamlink/plugins/goodgame.py +++ b/src/streamlink/plugins/goodgame.py @@ -14,6 +14,7 @@ QUALITIES = { _url_re = re.compile("https://(?:www\.)?goodgame.ru/channel/(?P<user>\w+)") _stream_re = re.compile(r'var src = "([^"]+)";') +_ddos_re = re.compile(r'document.cookie="(__DDOS_[^;]+)') class GoodGame(Plugin): @classmethod @@ -31,6 +32,11 @@ class GoodGame(Plugin): } res = http.get(self.url, headers=headers) + match = _ddos_re.search(res.text) + if match: + headers["Cookie"] = match.group(1) + res = http.get(self.url, headers=headers) + match = _stream_re.search(res.text) if not match: return diff --git a/src/streamlink/plugins/younow.py b/src/streamlink/plugins/younow.py index a3d8149b..320b37b0 100644 --- a/src/streamlink/plugins/younow.py +++ b/src/streamlink/plugins/younow.py @@ -6,7 +6,7 @@ from streamlink.plugin import Plugin, PluginError from streamlink.plugin.api import http from streamlink.stream import RTMPStream -jsonapi= "http://www.younow.com/php/api/broadcast/info/curId=0/user=" +jsonapi= "https://api.younow.com/php/api/broadcast/info/curId=0/user=" # http://younow.com/channel/ _url_re = re.compile("http(s)?://(\w+.)?younow.com/(?P<channel>[^/&?]+)")
streamlink/streamlink
ec64ee2a142535054d2256e26d35655c911559ed
diff --git a/tests/test_plugin_adultswim.py b/tests/test_plugin_adultswim.py new file mode 100644 index 00000000..2fba0fa2 --- /dev/null +++ b/tests/test_plugin_adultswim.py @@ -0,0 +1,16 @@ +import unittest + +from streamlink.plugins.adultswim import AdultSwim + + +class TestPluginAdultSwim(unittest.TestCase): + def test_can_handle_url(self): + # should match + self.assertTrue(AdultSwim.can_handle_url("http://www.adultswim.com/videos/streams/toonami")) + self.assertTrue(AdultSwim.can_handle_url("http://www.adultswim.com/videos/streams/")) + self.assertTrue(AdultSwim.can_handle_url("http://www.adultswim.com/videos/streams/last-stream-on-the-left")) + + # shouldn't match + self.assertFalse(AdultSwim.can_handle_url("http://www.adultswim.com/videos/specials/the-adult-swim-golf-classic-extended/")) + self.assertFalse(AdultSwim.can_handle_url("http://www.tvcatchup.com/")) + self.assertFalse(AdultSwim.can_handle_url("http://www.youtube.com/"))
younow.com is broken They have changed the API url to this one: `https://api.younow.com/php/api/broadcast/info/curId=0/user=` in: https://github.com/streamlink/streamlink/blob/master/src/streamlink/plugins/younow.py#L9 It still needs rtmpdump.exe, so it will give you the following error, related to #56 `[cli][error] Could not open stream: Unable to find rtmpdump.exe command` #81 fixes it, and the plugin works fine.
0.0
ec64ee2a142535054d2256e26d35655c911559ed
[ "tests/test_plugin_adultswim.py::TestPluginAdultSwim::test_can_handle_url" ]
[]
{ "failed_lite_validators": [ "has_hyperlinks", "has_issue_reference", "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2016-11-07 09:07:24+00:00
bsd-2-clause
5,753
streamlink__streamlink-1351
diff --git a/docs/issues.rst b/docs/issues.rst index 5117b5c6..1a88df73 100644 --- a/docs/issues.rst +++ b/docs/issues.rst @@ -20,7 +20,6 @@ Player Parameter Note ============= ======================== ====================================== MPC-HC -- Currently no way of configuring the cache MPlayer ``-cache <kbytes>`` Between 1024 and 8192 is recommended -MPlayer2 ``-cache <kbytes>`` Between 1024 and 8192 is recommended mpv ``--cache <kbytes>`` Between 1024 and 8192 is recommended VLC ``--file-caching <ms> Between 1000 and 10000 is recommended --network-caching <ms>`` diff --git a/docs/players.rst b/docs/players.rst index 00183d07..e8e94525 100644 --- a/docs/players.rst +++ b/docs/players.rst @@ -32,7 +32,6 @@ Name Stdin Pipe Named Pipe HTTP `Daum Pot Player <http://potplayer.daum.net>`_ No No Yes [1]_ `MPC-HC <http://mpc-hc.org/>`_ Yes [2]_ No Yes [1]_ `MPlayer <http://mplayerhq.hu>`_ Yes Yes Yes -`MPlayer2 <http://mplayer2.org>`_ Yes Yes Yes `mpv <http://mpv.io>`_ Yes Yes Yes `QuickTime <http://apple.com/quicktime>`_ No No No `VLC media player <http://videolan.org>`_ Yes [3]_ Yes Yes diff --git a/docs/plugin_matrix.rst b/docs/plugin_matrix.rst index db98da77..8aab1490 100644 --- a/docs/plugin_matrix.rst +++ b/docs/plugin_matrix.rst @@ -30,7 +30,6 @@ artetv arte.tv Yes Yes atresplayer atresplayer.com Yes No Streams are geo-restricted to Spain. bambuser bambuser.com Yes Yes bbciplayer bbc.co.uk/iplayer Yes Yes Streams may be geo-restricted to the United Kingdom. -beam beam.pro Yes Yes beattv be-at.tv Yes Yes Playlist not implemented yet. bfmtv bfmtv.com Yes Yes 01net.com @@ -131,6 +130,7 @@ media_ccc_de - media.ccc.de Yes Yes Only mp4 and HLS are suppor mediaklikk mediaklikk.hu Yes No Streams may be geo-restricted to Hungary. mips mips.tv Yes -- Requires rtmpdump with K-S-V patches. mitele mitele.es Yes No Streams may be geo-restricted to Spain. +mixer mixer.com Yes Yes mlgtv mlg.tv Yes -- nbc nbc.com No Yes Streams are geo-restricted to USA. Authentication is not supported. nbcsports nbcsports.com No Yes Streams maybe be geo-restricted to USA. Authentication is not supported. diff --git a/src/streamlink/plugins/beam.py b/src/streamlink/plugins/beam.py deleted file mode 100644 index 4a71faba..00000000 --- a/src/streamlink/plugins/beam.py +++ /dev/null @@ -1,109 +0,0 @@ -import re - -from streamlink.compat import urlparse, parse_qsl, urljoin -from streamlink.plugin import Plugin -from streamlink.plugin.api import http, validate -from streamlink.stream import HLSStream -from streamlink.stream import HTTPStream -from streamlink.stream import RTMPStream - -_url_re = re.compile(r"http(s)?://(\w+.)?beam.pro/(?P<channel>[^/?]+)") - - -class Beam(Plugin): - api_url = "https://beam.pro/api/v1/{type}/{id}" - channel_manifest = "https://beam.pro/api/v1/channels/{id}/manifest.{type}" - - _vod_schema = validate.Schema({ - "state": "AVAILABLE", - "vods": [{ - "baseUrl": validate.url(), - "data": validate.any(None, { - "Height": int - }), - "format": validate.text - }] - }, - validate.get("vods"), - validate.filter(lambda x: x["format"] in ("raw", "hls")), - [validate.union({ - "url": validate.get("baseUrl"), - "format": validate.get("format"), - "height": validate.all(validate.get("data"), validate.get("Height")) - })]) - _assets_schema = validate.Schema( - validate.union({ - "base": validate.all( - validate.xml_find("./head/meta"), - validate.get("base"), - validate.url(scheme="rtmp") - ), - "videos": validate.all( - validate.xml_findall(".//video"), - [ - validate.union({ - "src": validate.all( - validate.get("src"), - validate.text - ), - "height": validate.all( - validate.get("height"), - validate.text, - validate.transform(int) - ) - }) - ] - ) - }) - ) - - @classmethod - def can_handle_url(cls, url): - return _url_re.match(url) - - def _get_vod_stream(self, vod_id): - res = http.get(self.api_url.format(type="recordings", id=vod_id)) - for sdata in http.json(res, schema=self._vod_schema): - if sdata["format"] == "hls": - hls_url = urljoin(sdata["url"], "manifest.m3u8") - yield "{0}p".format(sdata["height"]), HLSStream(self.session, hls_url) - elif sdata["format"] == "raw": - raw_url = urljoin(sdata["url"], "source.mp4") - yield "{0}p".format(sdata["height"]), HTTPStream(self.session, raw_url) - - def _get_live_stream(self, channel): - res = http.get(self.api_url.format(type="channels", id=channel)) - channel_info = http.json(res) - - if not channel_info["online"]: - return - - res = http.get(self.channel_manifest.format(id=channel_info["id"], type="smil")) - assets = http.xml(res, schema=self._assets_schema) - - for video in assets["videos"]: - name = "{0}p".format(video["height"]) - stream = RTMPStream(self.session, { - "rtmp": "{0}/{1}".format(assets["base"], video["src"]) - }) - yield name, stream - - for s in HLSStream.parse_variant_playlist(self.session, - self.channel_manifest.format(id=channel_info["id"], type="m3u8")).items(): - yield s - - def _get_streams(self): - params = dict(parse_qsl(urlparse(self.url).query)) - vod_id = params.get("vod") - match = _url_re.match(self.url) - channel = match.group("channel") - - if vod_id: - self.logger.debug("Looking for VOD {0} from channel: {1}", vod_id, channel) - return self._get_vod_stream(vod_id) - else: - self.logger.debug("Looking for channel: {0}", channel) - return self._get_live_stream(channel) - - -__plugin__ = Beam diff --git a/src/streamlink/plugins/kanal7.py b/src/streamlink/plugins/kanal7.py index d6677a74..2f9cc2d9 100644 --- a/src/streamlink/plugins/kanal7.py +++ b/src/streamlink/plugins/kanal7.py @@ -11,7 +11,7 @@ from streamlink.stream import HLSStream class Kanal7(Plugin): url_re = re.compile(r"https?://(?:www.)?kanal7.com/canli-izle") iframe_re = re.compile(r'iframe .*?src="(http://[^"]*?)"') - stream_re = re.compile(r'src="(http[^"]*?)"') + stream_re = re.compile(r'''tp_file\s+=\s+['"](http[^"]*?)['"]''') @classmethod def can_handle_url(cls, url): diff --git a/src/streamlink/plugins/mixer.py b/src/streamlink/plugins/mixer.py new file mode 100644 index 00000000..34b0ead8 --- /dev/null +++ b/src/streamlink/plugins/mixer.py @@ -0,0 +1,87 @@ +""" + Mixer API 1.0 documentation + https://dev.mixer.com/rest.html +""" +import re + +from streamlink import NoStreamsError +from streamlink.compat import urlparse, parse_qsl, urljoin +from streamlink.plugin import Plugin +from streamlink.plugin.api import http, validate +from streamlink.stream import HLSStream + +_url_re = re.compile(r"http(s)?://(\w+.)?mixer\.com/(?P<channel>[^/?]+)") + + +class Mixer(Plugin): + api_url = "https://mixer.com/api/v1/{type}/{id}" + + _vod_schema = validate.Schema( + { + "state": "AVAILABLE", + "vods": [{ + "baseUrl": validate.url(), + "data": validate.any(None, { + "Height": int + }), + "format": validate.text + }] + }, + validate.get("vods"), + validate.filter(lambda x: x["format"] in ("raw", "hls")), + [validate.union({ + "url": validate.get("baseUrl"), + "format": validate.get("format"), + "height": validate.all(validate.get("data"), validate.get("Height")) + })]) + + @classmethod + def can_handle_url(cls, url): + return _url_re.match(url) + + def _get_api_res(self, api_type, api_id): + try: + res = http.get(self.api_url.format(type=api_type, id=api_id)) + return res + except Exception as e: + if "404" in str(e): + self.logger.error("invalid {0} - {1}".format(api_type, api_id)) + elif "429" in str(e): + self.logger.error("Too Many Requests, API rate limit exceeded.") + raise NoStreamsError(self.url) + + def _get_vod_stream(self, vod_id): + res = self._get_api_res("recordings", vod_id) + + for sdata in http.json(res, schema=self._vod_schema): + if sdata["format"] == "hls": + hls_url = urljoin(sdata["url"], "manifest.m3u8") + yield "{0}p".format(sdata["height"]), HLSStream(self.session, hls_url) + + def _get_live_stream(self, channel): + res = self._get_api_res("channels", channel) + + channel_info = http.json(res) + if not channel_info["online"]: + return + + user_id = channel_info["id"] + hls_url = self.api_url.format(type="channels", id="{0}/manifest.m3u8".format(user_id)) + for s in HLSStream.parse_variant_playlist(self.session, hls_url).items(): + yield s + + def _get_streams(self): + params = dict(parse_qsl(urlparse(self.url).query)) + vod_id = params.get("vod") + match = _url_re.match(self.url) + channel = match.group("channel") + + if vod_id: + self.logger.debug("Looking for VOD {0} from channel: {1}", vod_id, channel) + return self._get_vod_stream(vod_id) + else: + self.logger.debug("Looking for channel: {0}", channel) + return self._get_live_stream(channel) + + +__plugin__ = Mixer diff --git a/win32/streamlinkrc b/win32/streamlinkrc index 39016668..a6d4fd96 100644 --- a/win32/streamlinkrc +++ b/win32/streamlinkrc @@ -22,9 +22,6 @@ #player="C:\Program Files (x86)\MPC-HC\mpc-hc.exe" #player="C:\Program Files\MPC-HC\mpc-hc64.exe" -# MPlayer2 -#player=C:\mplayer2\mplayer2.exe -cache 4096 - # Use this if you want to transport the stream to the player via a named pipe. #player-fifo
streamlink/streamlink
6d1f9ded3bb293c8f9ad21a2d76301f64513b8d1
diff --git a/tests/test_plugin_mixer.py b/tests/test_plugin_mixer.py new file mode 100644 index 00000000..9c437dda --- /dev/null +++ b/tests/test_plugin_mixer.py @@ -0,0 +1,15 @@ +import unittest + +from streamlink.plugins.mixer import Mixer + + +class TestPluginMixer(unittest.TestCase): + def test_can_handle_url(self): + # should match + self.assertTrue(Mixer.can_handle_url('https://mixer.com/Minecraft?vod=11250002')) + self.assertTrue(Mixer.can_handle_url('https://mixer.com/Minecraft')) + self.assertTrue(Mixer.can_handle_url('https://mixer.com/Monstercat?vod=11030270')) + self.assertTrue(Mixer.can_handle_url('https://mixer.com/Monstercat')) + + # shouldn't match + self.assertFalse(Mixer.can_handle_url('https://mixer.com'))
Kanal7 Defective again Only 2 months later they have changed the design. Not opening with latest 0.9.0 Release: [cli][info] Found matching plugin kanal7 for URL http://www.kanal7.com/canli-izle error: No playable streams found on this URL: http://www.kanal7.com/canli-izle
0.0
6d1f9ded3bb293c8f9ad21a2d76301f64513b8d1
[ "tests/test_plugin_mixer.py::TestPluginMixer::test_can_handle_url" ]
[]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_hyperlinks", "has_added_files", "has_removed_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2017-12-01 10:41:35+00:00
bsd-2-clause
5,754
streamlink__streamlink-1486
diff --git a/src/streamlink/plugins/ruv.py b/src/streamlink/plugins/ruv.py index 09db4860..5873d330 100644 --- a/src/streamlink/plugins/ruv.py +++ b/src/streamlink/plugins/ruv.py @@ -3,40 +3,34 @@ import re from streamlink.plugin import Plugin -from streamlink.stream import RTMPStream, HLSStream +from streamlink.stream import HLSStream from streamlink.plugin.api import http +from streamlink.plugin.api import validate -RTMP_LIVE_URL = "rtmp://ruv{0}livefs.fplive.net/ruv{0}live-live/stream{1}" -RTMP_SARPURINN_URL = "rtmp://sipvodfs.fplive.net/sipvod/{0}/{1}{2}.{3}" - -HLS_RUV_LIVE_URL = "http://ruvruv-live.hls.adaptive.level3.net/ruv/ruv/index/stream{0}.m3u8" -HLS_RADIO_LIVE_URL = "http://sip-live.hds.adaptive.level3.net/hls-live/ruv-{0}/_definst_/live/stream1.m3u8" -HLS_SARPURINN_URL = "http://sip-ruv-vod.dcp.adaptive.level3.net/{0}/{1}{2}.{3}.m3u8" +# URL to the RUV LIVE API +RUV_LIVE_API = """http://www.ruv.is/sites/all/themes/at_ruv/scripts/\ +ruv-stream.php?channel={0}&format=json""" _live_url_re = re.compile(r"""^(?:https?://)?(?:www\.)?ruv\.is/ - (?P<channel_path> - ruv| - ras1| - ras-1| - ras2| - ras-2| - rondo + (?P<stream_id> + ruv/?$| + ruv2/?$| + ruv-2/?$| + ras1/?$| + ras2/?$| + rondo/?$ ) /? """, re.VERBOSE) -_sarpurinn_url_re = re.compile(r"""^(?:https?://)?(?:www\.)?ruv\.is/sarpurinn/ - (?: +_sarpurinn_url_re = re.compile(r"""^(?:https?://)?(?:www\.)?ruv\.is/spila/ + (?P<stream_id> ruv| ruv2| ruv-2| ruv-aukaras| - ras1| - ras-1| - ras2| - ras-2 ) / [a-zA-Z0-9_-]+ @@ -45,37 +39,26 @@ _sarpurinn_url_re = re.compile(r"""^(?:https?://)?(?:www\.)?ruv\.is/sarpurinn/ /? """, re.VERBOSE) -_rtmp_url_re = re.compile(r"""rtmp://sipvodfs\.fplive.net/sipvod/ - (?P<status> - lokad| - opid - ) - / - (?P<date>[0-9]+/[0-9][0-9]/[0-9][0-9]/)? - (?P<id>[A-Z0-9\$_]+) - \. - (?P<ext> - mp4| - mp3 - )""", re.VERBOSE) - -_id_map = { - "ruv": "ruv", - "ras1": "ras1", - "ras-1": "ras1", - "ras2": "ras2", - "ras-2": "ras2", - "rondo": "ras3" -} +_single_re = re.compile(r"""(?P<url>http://[0-9a-zA-Z\-\.]*/ + (lokad|opid) + / + ([0-9]+/[0-9][0-9]/[0-9][0-9]/)? + ([A-Z0-9\$_]+\.mp4\.m3u8) + ) + """, re.VERBOSE) + +_multi_re = re.compile(r"""(?P<base_url>http://[0-9a-zA-Z\-\.]*/ + (lokad|opid) + /) + manifest.m3u8\?tlm=hls&streams= + (?P<streams>[0-9a-zA-Z\/\.\,:]+) + """, re.VERBOSE) class Ruv(Plugin): @classmethod def can_handle_url(cls, url): - if _live_url_re.match(url): - return _live_url_re.match(url) - else: - return _sarpurinn_url_re.match(url) + return _live_url_re.match(url) or _sarpurinn_url_re.match(url) def __init__(self, url): Plugin.__init__(self, url) @@ -83,75 +66,77 @@ class Ruv(Plugin): if live_match: self.live = True - self.channel_path = live_match.group("channel_path") + self.stream_id = live_match.group("stream_id") + + # Remove slashes + self.stream_id.replace("/", "") + + # Remove dashes + self.stream_id.replace("-", "") + + # Rondo is identified as ras3 + if self.stream_id == "rondo": + self.stream_id = "ras3" else: self.live = False def _get_live_streams(self): - stream_id = _id_map[self.channel_path] + # Get JSON API + res = http.get(RUV_LIVE_API.format(self.stream_id)) - if stream_id == "ruv": - qualities_rtmp = ["720p", "480p", "360p", "240p"] - - for i, quality in enumerate(qualities_rtmp): - yield quality, RTMPStream( - self.session, - { - "rtmp": RTMP_LIVE_URL.format(stream_id, i + 1), - "pageUrl": self.url, - "live": True - } - ) + # Parse the JSON API + json_res = http.json(res) - qualities_hls = ["240p", "360p", "480p", "720p"] - for i, quality_hls in enumerate(qualities_hls): - yield quality_hls, HLSStream( - self.session, - HLS_RUV_LIVE_URL.format(i + 1) - ) + for url in json_res["result"]: + if url.startswith("rtmp:"): + continue - else: - yield "audio", RTMPStream(self.session, { - "rtmp": RTMP_LIVE_URL.format(stream_id, 1), - "pageUrl": self.url, - "live": True - }) + # Get available streams + streams = HLSStream.parse_variant_playlist(self.session, url) - yield "audio", HLSStream( - self.session, - HLS_RADIO_LIVE_URL.format(stream_id) - ) + for quality, hls in streams.items(): + yield quality, hls def _get_sarpurinn_streams(self): - res = http.get(self.url) - match = _rtmp_url_re.search(res.text) - - if not match: - yield - - token = match.group("id") - status = match.group("status") - extension = match.group("ext") - date = match.group("date") - if not date: - date = "" + # Get HTML page + res = http.get(self.url).text + lines = "\n".join([l for l in res.split("\n") if "video.src" in l]) + multi_stream_match = _multi_re.search(lines) + + if multi_stream_match and multi_stream_match.group("streams"): + base_url = multi_stream_match.group("base_url") + streams = multi_stream_match.group("streams").split(",") + + for stream in streams: + if stream.count(":") != 1: + continue + + [token, quality] = stream.split(":") + quality = int(quality) + key = "" + + if quality <= 500: + key = "240p" + elif quality <= 800: + key = "360p" + elif quality <= 1200: + key = "480p" + elif quality <= 2400: + key = "720p" + else: + key = "1080p" + + yield key, HLSStream( + self.session, + base_url + token + ) - if extension == "mp3": - key = "audio" else: - key = "576p" - - # HLS on Sarpurinn is currently only available on videos - yield key, HLSStream( - self.session, - HLS_SARPURINN_URL.format(status, date, token, extension) - ) - - yield key, RTMPStream(self.session, { - "rtmp": RTMP_SARPURINN_URL.format(status, date, token, extension), - "pageUrl": self.url, - "live": True - }) + single_stream_match = _single_re.search(lines) + + if single_stream_match: + url = single_stream_match.group("url") + yield "576p", HLSStream(self.session, url) def _get_streams(self): if self.live:
streamlink/streamlink
db9f6640df5bf2cdb8d2acdf2960fe1fc96acfec
diff --git a/tests/test_plugin_ruv.py b/tests/test_plugin_ruv.py new file mode 100644 index 00000000..fc7d5194 --- /dev/null +++ b/tests/test_plugin_ruv.py @@ -0,0 +1,28 @@ +import unittest + +from streamlink.plugins.ruv import Ruv + + +class TestPluginRuv(unittest.TestCase): + def test_can_handle_url(self): + # should match + self.assertTrue(Ruv.can_handle_url("ruv.is/ruv")) + self.assertTrue(Ruv.can_handle_url("http://ruv.is/ruv")) + self.assertTrue(Ruv.can_handle_url("http://ruv.is/ruv/")) + self.assertTrue(Ruv.can_handle_url("https://ruv.is/ruv/")) + self.assertTrue(Ruv.can_handle_url("http://www.ruv.is/ruv")) + self.assertTrue(Ruv.can_handle_url("http://www.ruv.is/ruv/")) + self.assertTrue(Ruv.can_handle_url("ruv.is/ruv2")) + self.assertTrue(Ruv.can_handle_url("ruv.is/ras1")) + self.assertTrue(Ruv.can_handle_url("ruv.is/ras2")) + self.assertTrue(Ruv.can_handle_url("ruv.is/rondo")) + self.assertTrue(Ruv.can_handle_url("http://www.ruv.is/spila/ruv/ol-2018-ishokki-karla/20180217")) + self.assertTrue(Ruv.can_handle_url("http://www.ruv.is/spila/ruv/frettir/20180217")) + + # shouldn't match + self.assertFalse(Ruv.can_handle_url("rruv.is/ruv")) + self.assertFalse(Ruv.can_handle_url("ruv.is/ruvnew")) + self.assertFalse(Ruv.can_handle_url("https://www.bloomberg.com/live/")) + self.assertFalse(Ruv.can_handle_url("https://www.bloomberg.com/politics/articles/2017-04-17/french-race-up-for-grabs-days-before-voters-cast-first-ballots")) + self.assertFalse(Ruv.can_handle_url("http://www.tvcatchup.com/")) + self.assertFalse(Ruv.can_handle_url("http://www.youtube.com/"))
RUV Iceland : plugin partially outdated ### Checklist - [x] This is a bug report. - [ ] This is a plugin request. - [ ] This is a feature request. - [ ] I used the search function to find already opened/closed issues or pull requests. ### Description RUV is Icelandic broadcasting corporation consisting of 3 radio and TV channels : 1. Radio channels ------------------ - RAS 1 : `http://ruv.is/nolayout/popup/ras1` - RAS 2 : `http://ruv.is/nolayout/popup/ras2` - Rondo : `http://ruv.is/nolayout/popup/rondo` 2. TV ----- - RUV : `http://ruv.is/ruv` - RUV 2 : `http://ruv.is/ruv-2` - Krakkaruv : `http://krakkaruv.is/hlusta/spila` ### Expected / Actual behavior Channels use HLS for broacasting. In the past they used rtmp too, not sure if it's still the case. ### Reproduction steps / Stream URLs to test Radio ------ `streamlink -l debug "http://ruv.is/nolayout/popup/ras1" error: No plugin can handle URL: http://ruv.is/nolayout/popup/ras1` TV --- ``` streamlink -l debug --http-proxy "82.221.48.137:8080" "http://ruv.is/ruv" best [cli][info] Found matching plugin ruv for URL http://ruv.is/ruv [cli][info] Available streams: 720p_hls, 480p_hls, 240p_hls, 360p_hls, 240p (wor st), 360p, 480p, 720p (best) [cli][info] Opening stream: 720p (rtmp) [stream.rtmp][debug] Spawning command: C:\Users\Ddr\Downloads\streamlink\\rtmpdu mp\rtmpdump.exe --flv - --live --pageUrl http://ruv.is/ruv --rtmp rtmp://ruvruvl ivefs.fplive.net/ruvruvlive-live/stream1 [cli][error] Could not open stream: Error while executing subprocess ``` ### Environment details (operating system, python version, etc.) W7 PRO/streamlink portable ### Comments, logs, screenshots, etc. TV channels are geolocked unlike radio.
0.0
db9f6640df5bf2cdb8d2acdf2960fe1fc96acfec
[ "tests/test_plugin_ruv.py::TestPluginRuv::test_can_handle_url" ]
[]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2018-02-17 02:09:27+00:00
bsd-2-clause
5,755
streamlink__streamlink-1550
diff --git a/docs/plugin_matrix.rst b/docs/plugin_matrix.rst index b3f1584e..8ba5f492 100644 --- a/docs/plugin_matrix.rst +++ b/docs/plugin_matrix.rst @@ -141,6 +141,7 @@ ovvatv ovva.tv Yes No pandatv panda.tv Yes ? periscope periscope.tv Yes Yes Replay/VOD is supported. picarto picarto.tv Yes Yes +pixiv sketch.pixiv.net Yes -- playtv playtv.fr Yes -- Streams may be geo-restricted to France. pluzz - france.tv Yes Yes Streams may be geo-restricted to France, Andorra and Monaco. - ludo.fr diff --git a/src/streamlink/plugins/pixiv.py b/src/streamlink/plugins/pixiv.py new file mode 100644 index 00000000..5010f563 --- /dev/null +++ b/src/streamlink/plugins/pixiv.py @@ -0,0 +1,134 @@ +# -*- coding: utf-8 -*- +import re + +from streamlink import PluginError +from streamlink.compat import urljoin +from streamlink.exceptions import NoStreamsError +from streamlink.plugin import Plugin +from streamlink.plugin import PluginOptions +from streamlink.plugin.api import http +from streamlink.plugin.api import useragents +from streamlink.plugin.api import validate +from streamlink.stream import HLSStream +from streamlink.utils import parse_json + + +class Pixiv(Plugin): + """Plugin for https://sketch.pixiv.net/lives""" + + _url_re = re.compile(r"https?://sketch\.pixiv\.net/[^/]+(?P<videopage>/lives/\d+)?") + + _videopage_re = re.compile(r"""["']live-button["']><a\shref=["'](?P<path>[^"']+)["']""") + _data_re = re.compile(r"""<script\sid=["']state["']>[^><{]+(?P<data>{[^><]+})</script>""") + _post_key_re = re.compile(r"""name=["']post_key["']\svalue=["'](?P<data>[^"']+)["']""") + + _data_schema = validate.Schema( + validate.all( + validate.transform(_data_re.search), + validate.any( + None, + validate.all( + validate.get("data"), + validate.transform(parse_json), + validate.get("context"), + validate.get("dispatcher"), + validate.get("stores"), + ) + ) + ) + ) + + login_url_get = "https://accounts.pixiv.net/login" + login_url_post = "https://accounts.pixiv.net/api/login" + + options = PluginOptions({ + "username": None, + "password": None + }) + + @classmethod + def can_handle_url(cls, url): + return cls._url_re.match(url) is not None + + def find_videopage(self): + self.logger.debug("Not a videopage") + res = http.get(self.url) + + m = self._videopage_re.search(res.text) + if not m: + self.logger.debug("No stream path, stream might be offline or invalid url.") + raise NoStreamsError(self.url) + + path = m.group("path") + self.logger.debug("Found new path: {0}".format(path)) + return urljoin(self.url, path) + + def _login(self, username, password): + res = http.get(self.login_url_get) + m = self._post_key_re.search(res.text) + if not m: + raise PluginError("Missing post_key, no login posible.") + + post_key = m.group("data") + data = { + "lang": "en", + "source": "sketch", + "post_key": post_key, + "pixiv_id": username, + "password": password, + } + + res = http.post(self.login_url_post, data=data) + res = http.json(res) + + if res["body"].get("success"): + return True + else: + return False + + def _get_streams(self): + http.headers = {"User-Agent": useragents.FIREFOX} + + login_username = self.get_option("username") + login_password = self.get_option("password") + if login_username and login_password: + self.logger.debug("Attempting login as {0}".format(login_username)) + if self._login(login_username, login_password): + self.logger.info("Successfully logged in as {0}".format(login_username)) + else: + self.logger.info("Failed to login as {0}".format(login_username)) + + videopage = self._url_re.match(self.url).group("videopage") + if not videopage: + self.url = self.find_videopage() + + data = http.get(self.url, schema=self._data_schema) + + if not data.get("LiveStore"): + self.logger.debug("No video url found, stream might be offline.") + return + + data = data["LiveStore"]["lives"] + + # get the unknown user-id + for _key in data.keys(): + video_data = data.get(_key) + + owner = video_data["owner"] + self.logger.info("Owner ID: {0}".format(owner["user_id"])) + self.logger.debug("HLS URL: {0}".format(owner["hls_movie"])) + for n, s in HLSStream.parse_variant_playlist(self.session, owner["hls_movie"]).items(): + yield n, s + + performers = video_data.get("performers") + if performers: + for p in performers: + self.logger.info("CO-HOST ID: {0}".format(p["user_id"])) + hls_url = p["hls_movie"] + self.logger.debug("HLS URL: {0}".format(hls_url)) + for n, s in HLSStream.parse_variant_playlist(self.session, hls_url).items(): + _n = "{0}_{1}".format(n, p["user_id"]) + yield _n, s + + +__plugin__ = Pixiv diff --git a/src/streamlink/plugins/youtube.py b/src/streamlink/plugins/youtube.py index 2046634b..b828036c 100644 --- a/src/streamlink/plugins/youtube.py +++ b/src/streamlink/plugins/youtube.py @@ -78,6 +78,8 @@ _config_schema = validate.Schema( validate.optional("hlsvp"): validate.text, validate.optional("live_playback"): validate.transform(bool), validate.optional("reason"): validate.text, + validate.optional("livestream"): validate.text, + validate.optional("live_playback"): validate.text, "status": validate.text } ) @@ -137,7 +139,7 @@ class YouTube(Plugin): } @classmethod - def can_handle_url(self, url): + def can_handle_url(cls, url): return _url_re.match(url) @classmethod @@ -157,13 +159,58 @@ class YouTube(Plugin): return weight, group + def _create_adaptive_streams(self, info, streams, protected): + adaptive_streams = {} + best_audio_itag = None + + # Extract audio streams from the DASH format list + for stream_info in info.get("adaptive_fmts", []): + if stream_info.get("s"): + protected = True + continue + + stream_params = dict(parse_qsl(stream_info["url"])) + if "itag" not in stream_params: + continue + itag = int(stream_params["itag"]) + # extract any high quality streams only available in adaptive formats + adaptive_streams[itag] = stream_info["url"] + + stream_type, stream_format = stream_info["type"] + if stream_type == "audio": + stream = HTTPStream(self.session, stream_info["url"]) + name = "audio_{0}".format(stream_format) + streams[name] = stream + + # find the best quality audio stream m4a, opus or vorbis + if best_audio_itag is None or self.adp_audio[itag] > self.adp_audio[best_audio_itag]: + best_audio_itag = itag + + if best_audio_itag and adaptive_streams and MuxedStream.is_usable(self.session): + aurl = adaptive_streams[best_audio_itag] + for itag, name in self.adp_video.items(): + if itag in adaptive_streams: + vurl = adaptive_streams[itag] + self.logger.debug("MuxedStream: v {video} a {audio} = {name}".format( + audio=best_audio_itag, + name=name, + video=itag, + )) + streams[name] = MuxedStream(self.session, + HTTPStream(self.session, vurl), + HTTPStream(self.session, aurl)) + + return streams, protected + def _find_channel_video(self): res = http.get(self.url) match = _channelid_re.search(res.text) if not match: return - return self._get_channel_video(match.group(1)) + channel_id = match.group(1) + self.logger.debug("Found channel_id: {0}".format(channel_id)) + return self._get_channel_video(channel_id) def _get_channel_video(self, channel_id): query = { @@ -178,6 +225,7 @@ class YouTube(Plugin): for video in videos: video_id = video["id"]["videoId"] + self.logger.debug("Found video_id: {0}".format(video_id)) return video_id def _find_canonical_stream_info(self): @@ -233,10 +281,16 @@ class YouTube(Plugin): return info_parsed def _get_streams(self): + is_live = False + info = self._get_stream_info(self.url) if not info: return + if info.get("livestream") == '1' or info.get("live_playback") == '1': + self.logger.debug("This video is live.") + is_live = True + formats = info.get("fmt_list") streams = {} protected = False @@ -253,40 +307,8 @@ class YouTube(Plugin): streams[name] = stream - adaptive_streams = {} - best_audio_itag = None - - # Extract audio streams from the DASH format list - for stream_info in info.get("adaptive_fmts", []): - if stream_info.get("s"): - protected = True - continue - - stream_params = dict(parse_qsl(stream_info["url"])) - if "itag" not in stream_params: - continue - itag = int(stream_params["itag"]) - # extract any high quality streams only available in adaptive formats - adaptive_streams[itag] = stream_info["url"] - - stream_type, stream_format = stream_info["type"] - if stream_type == "audio": - stream = HTTPStream(self.session, stream_info["url"]) - name = "audio_{0}".format(stream_format) - streams[name] = stream - - # find the best quality audio stream m4a, opus or vorbis - if best_audio_itag is None or self.adp_audio[itag] > self.adp_audio[best_audio_itag]: - best_audio_itag = itag - - if best_audio_itag and adaptive_streams and MuxedStream.is_usable(self.session): - aurl = adaptive_streams[best_audio_itag] - for itag, name in self.adp_video.items(): - if itag in adaptive_streams: - vurl = adaptive_streams[itag] - streams[name] = MuxedStream(self.session, - HTTPStream(self.session, vurl), - HTTPStream(self.session, aurl)) + if is_live is False: + streams, protected = self._create_adaptive_streams(info, streams, protected) hls_playlist = info.get("hlsvp") if hls_playlist: diff --git a/src/streamlink_cli/argparser.py b/src/streamlink_cli/argparser.py index 46e4ab2a..31cdbbe1 100644 --- a/src/streamlink_cli/argparser.py +++ b/src/streamlink_cli/argparser.py @@ -1363,6 +1363,20 @@ plugin.add_argument( A afreecatv.com account password to use with --afreeca-username. """ ) +plugin.add_argument( + "--pixiv-username", + metavar="USERNAME", + help=""" + The email/username used to register with pixiv.net + """ +) +plugin.add_argument( + "--pixiv-password", + metavar="PASSWORD", + help=""" + A pixiv.net account password to use with --pixiv-username + """ +) # Deprecated options stream.add_argument( diff --git a/src/streamlink_cli/main.py b/src/streamlink_cli/main.py index dbb1d527..315a84a9 100644 --- a/src/streamlink_cli/main.py +++ b/src/streamlink_cli/main.py @@ -964,6 +964,17 @@ def setup_plugin_options(): if afreeca_password: streamlink.set_plugin_option("afreeca", "password", afreeca_password) + if args.pixiv_username: + streamlink.set_plugin_option("pixiv", "username", args.pixiv_username) + + if args.pixiv_username and not args.pixiv_password: + pixiv_password = console.askpass("Enter pixiv account password: ") + else: + pixiv_password = args.pixiv_password + + if pixiv_password: + streamlink.set_plugin_option("pixiv", "password", pixiv_password) + def check_root(): if hasattr(os, "getuid"):
streamlink/streamlink
f25bf2157758b9cb5cb3df23c1c3c086ef459f78
diff --git a/tests/test_plugin_pixiv.py b/tests/test_plugin_pixiv.py new file mode 100644 index 00000000..8d547d3d --- /dev/null +++ b/tests/test_plugin_pixiv.py @@ -0,0 +1,19 @@ +import unittest + +from streamlink.plugins.pixiv import Pixiv + + +class TestPluginPixiv(unittest.TestCase): + def test_can_handle_url(self): + should_match = [ + 'https://sketch.pixiv.net/@exampleuser', + 'https://sketch.pixiv.net/@exampleuser/lives/000000000000000000', + ] + for url in should_match: + self.assertTrue(Pixiv.can_handle_url(url)) + + should_not_match = [ + 'https://sketch.pixiv.net', + ] + for url in should_not_match: + self.assertFalse(Pixiv.can_handle_url(url)) diff --git a/tests/test_plugin_youtube.py b/tests/test_plugin_youtube.py new file mode 100644 index 00000000..4b1934d0 --- /dev/null +++ b/tests/test_plugin_youtube.py @@ -0,0 +1,23 @@ +import unittest + +from streamlink.plugins.youtube import YouTube + + +class TestPluginYouTube(unittest.TestCase): + def test_can_handle_url(self): + should_match = [ + "https://www.youtube.com/c/EXAMPLE/live", + "https://www.youtube.com/channel/EXAMPLE", + "https://www.youtube.com/v/aqz-KE-bpKQ", + "https://www.youtube.com/embed/aqz-KE-bpKQ", + "https://www.youtube.com/user/EXAMPLE/", + "https://www.youtube.com/watch?v=aqz-KE-bpKQ", + ] + for url in should_match: + self.assertTrue(YouTube.can_handle_url(url)) + + should_not_match = [ + "https://www.youtube.com", + ] + for url in should_not_match: + self.assertFalse(YouTube.can_handle_url(url))
[Plugin Request] pixiv Sketch - [ ] This is a bug report. - [x] This is a feature request. - [ ] This is a plugin (improvement) request. - [x] I have read the contribution guidelines. I'm requesting a plugin for pixiv sketch its streamed via HLS it serves a generated .m3u8(for 30ish seconds) along with its 3ish second chunk every second or so | xhr | https://hls4.pixivsketch.net/2018022718/15197228728388594847a96103176027c0811ead7c5788b1297/4000000_1920x1080/506579247.ts | xhr | https://hls4.pixivsketch.net/2018022718/15197228728388594847a96103176027c0811ead7c5788b1297/4000000_1920x1080/index.m3u8 hls4.pixivsketch.net: fixed gen'd server* 2018022718: stream start time (YYYYMMDDHH) 1519...1297: fixed UID* 4000000_1920x1080: video quality (low = 365000_480x270) *Until the api regens (The streamers internet drops) a look at the .m3u8 ``` #EXTM3U #EXT-X-VERSION:6 #EXT-X-MEDIA-SEQUENCE:506579247 #EXT-X-TARGETDURATION:6 #EXT-X-START:TIME-OFFSET=-3.00,PRECISE=NO #EXT-X-PROGRAM-DATE-TIME:2018-02-27T22:22:21.000741924+09:00 #EXTINF:3.000000, 506579247.ts #EXT-X-PROGRAM-DATE-TIME:2018-02-27T22:22:24.000744924+09:00 #EXTINF:3.000000, 506579248.ts #EXT-X-PROGRAM-DATE-TIME:2018-02-27T22:22:27.000747924+09:00 #EXTINF:3.000000, 506579249.ts #EXT-X-PROGRAM-DATE-TIME:2018-02-27T22:22:30.000750924+09:00 #EXTINF:3.000000, 506579250.ts #EXT-X-PROGRAM-DATE-TIME:2018-02-27T22:22:33.000753924+09:00 #EXTINF:3.000000, 506579251.ts #EXT-X-PROGRAM-DATE-TIME:2018-02-27T22:22:36.000756924+09:00 #EXTINF:3.000000, 506579252.ts #EXT-X-PROGRAM-DATE-TIME:2018-02-27T22:22:39.000759924+09:00 #EXTINF:3.000000, 506579253.ts #EXT-X-PROGRAM-DATE-TIME:2018-02-27T22:22:42.000762924+09:00 #EXTINF:3.000000, 506579254.ts #EXT-X-PROGRAM-DATE-TIME:2018-02-27T22:22:45.000765924+09:00 #EXTINF:3.000000, 506579255.ts #EXT-X-PROGRAM-DATE-TIME:2018-02-27T22:22:48.000768924+09:00 #EXTINF:3.000000, 506579256.ts ``` **Update** found hlsvariant://... and it works but a proper plugin is appreciated
0.0
f25bf2157758b9cb5cb3df23c1c3c086ef459f78
[ "tests/test_plugin_pixiv.py::TestPluginPixiv::test_can_handle_url", "tests/test_plugin_youtube.py::TestPluginYouTube::test_can_handle_url" ]
[]
{ "failed_lite_validators": [ "has_hyperlinks", "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2018-03-12 20:17:11+00:00
bsd-2-clause
5,756
streamlink__streamlink-1578
diff --git a/src/streamlink/plugins/rtve.py b/src/streamlink/plugins/rtve.py index 21df390a..4870585f 100644 --- a/src/streamlink/plugins/rtve.py +++ b/src/streamlink/plugins/rtve.py @@ -1,5 +1,6 @@ import base64 import re +from functools import partial from Crypto.Cipher import Blowfish @@ -59,7 +60,7 @@ class Rtve(Plugin): https?://(?:www\.)?rtve\.es/(?:directo|noticias|television|deportes|alacarta|drmn)/.*?/? """, re.VERBOSE) cdn_schema = validate.Schema( - validate.transform(parse_xml), + validate.transform(partial(parse_xml, invalid_char_entities=True)), validate.xml_findall(".//preset"), [ validate.union({ diff --git a/src/streamlink/utils/__init__.py b/src/streamlink/utils/__init__.py index 59cecaee..1e531647 100644 --- a/src/streamlink/utils/__init__.py +++ b/src/streamlink/utils/__init__.py @@ -7,7 +7,7 @@ try: except ImportError: # pragma: no cover import xml.etree.ElementTree as ET -from streamlink.compat import urljoin, urlparse, parse_qsl, is_py2, urlunparse +from streamlink.compat import urljoin, urlparse, parse_qsl, is_py2, urlunparse, is_py3 from streamlink.exceptions import PluginError from streamlink.utils.named_pipe import NamedPipe @@ -67,7 +67,7 @@ def parse_json(data, name="JSON", exception=PluginError, schema=None): return json_data -def parse_xml(data, name="XML", ignore_ns=False, exception=PluginError, schema=None): +def parse_xml(data, name="XML", ignore_ns=False, exception=PluginError, schema=None, invalid_char_entities=False): """Wrapper around ElementTree.fromstring with some extras. Provides these extra features: @@ -77,9 +77,14 @@ def parse_xml(data, name="XML", ignore_ns=False, exception=PluginError, schema=N """ if is_py2 and isinstance(data, unicode): data = data.encode("utf8") + elif is_py3: + data = bytearray(data, "utf8") if ignore_ns: - data = re.sub(" xmlns=\"(.+?)\"", "", data) + data = re.sub(br" xmlns=\"(.+?)\"", b"", data) + + if invalid_char_entities: + data = re.sub(br'&(?!(?:#(?:[0-9]+|[Xx][0-9A-Fa-f]+)|[A-Za-z0-9]+);)', b'&amp;', data) try: tree = ET.fromstring(data)
streamlink/streamlink
c2368bea030c50beb794821b01b92bad5e21c5fb
diff --git a/tests/test_utils.py b/tests/test_utils.py index 42419165..3fbefd4f 100644 --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -76,6 +76,20 @@ class TestUtil(unittest.TestCase): self.assertEqual(expected.tag, actual.tag) self.assertEqual(expected.attrib, actual.attrib) + def test_parse_xml_entities_fail(self): + self.assertRaises(PluginError, + parse_xml, u"""<test foo="bar &"/>""") + + + def test_parse_xml_entities(self): + expected = ET.Element("test", {"foo": "bar &"}) + actual = parse_xml(u"""<test foo="bar &"/>""", + schema=validate.Schema(xml_element(tag="test", attrib={"foo": text})), + invalid_char_entities=True) + self.assertEqual(expected.tag, actual.tag) + self.assertEqual(expected.attrib, actual.attrib) + + def test_parse_qsd(self): self.assertEqual( {"test": "1", "foo": "bar"},
Plugin: Rtve.es: Unable to parse XML: not well-formed (invalid token) ### Checklist - [x] This is a bug report. ### Description Rtve plugin always gives XML parsing error for all video urls. ### Reproduction steps / Explicit stream URLs to test 1. http://www.rtve.es/alacarta/videos/telediario/telediario-15-horas-26-03-18/4540424/ 2. http://www.rtve.es/alacarta/videos/aguila-roja/aguila-roja-t9-capitulo-116/3771566/ 3. http://www.rtve.es/directo/la-1 ### Logs ``` [plugin.rtve][debug] Found content with id: 4540424 Plugin error: Unable to parse XML: not well-formed (invalid token): line 1, column 762 (b"<?xml version='1.0'?><quality><pr ...) Process finished with exit code 1 ``` ### Comments, screenshots, etc. xml contains `&` characters, replacing with `&amp;` gets it working. Resolved by modifying streamlink\utils\__init__.py and adding `data = re.sub("&", "&amp;", data.decode('utf8'))` ``` [plugin.rtve][debug] Found content with id: 4540424 OrderedDict([('540p_http', <HTTPStream('http://mvod.lvlt.rtve.es/resources/TE_NGVA/mp4/3/8/1522075587483.mp4')>), ('360p_http', <HTTPStream('http://mvod.lvlt.rtve.es/resources/TE_NGVA/mp4/1/1/1522075683411.mp4')>), ('270p_http', <HTTPStream('http://mvod.lvlt.rtve.es/resources/TE_NGVA/mp4/3/0/1522075727303.mp4')>), ('270p_alt', <HLSStream('http://hlsvod.lvlt.rtve.es/resources/TE_NGVA/mp4/3/0/1522075727303.mp4/1522075727303-audio=48001-video=620000.m3u8?hls_minimum_fragment_length=6&hls_client_manifest_version=3')>), ('270p', <HLSStream('http://hlsvod2017b.akamaized.net/resources/TE_NGVA/mp4/3/0/1522075727303.mp4/1522075727303-audio=48001-video=620000.m3u8?hls_minimum_fragment_length=6&hls_client_manifest_version=3')>), ('360p_alt', <HLSStream('http://hlsvod.lvlt.rtve.es/resources/TE_NGVA/mp4/1/1/1522075683411.mp4/1522075683411-audio=64001-video=720000.m3u8?hls_minimum_fragment_length=6&hls_client_manifest_version=3')>), ('360p', <HLSStream('http://hlsvod2017b.akamaized.net/resources/TE_NGVA/mp4/1/1/1522075683411.mp4/1522075683411-audio=64001-video=720000.m3u8?hls_minimum_fragment_length=6&hls_client_manifest_version=3')>), ('540p_alt', <HLSStream('http://hlsvod.lvlt.rtve.es/resources/TE_NGVA/mp4/3/8/1522075587483.mp4/1522075587483-audio=64001-video=1400000.m3u8?hls_minimum_fragment_length=6&hls_client_manifest_version=3')>), ('540p', <HLSStream('http://hlsvod2017b.akamaized.net/resources/TE_NGVA/mp4/3/8/1522075587483.mp4/1522075587483-audio=64001-video=1400000.m3u8?hls_minimum_fragment_length=6&hls_client_manifest_version=3')>), ('worst', <HLSStream('http://hlsvod.lvlt.rtve.es/resources/TE_NGVA/mp4/3/0/1522075727303.mp4/1522075727303-audio=48001-video=620000.m3u8?hls_minimum_fragment_length=6&hls_client_manifest_version=3')>), ('best', <HLSStream('http://hlsvod2017b.akamaized.net/resources/TE_NGVA/mp4/3/8/1522075587483.mp4/1522075587483-audio=64001-video=1400000.m3u8?hls_minimum_fragment_length=6&hls_client_manifest_version=3')>)]) Process finished with exit code 0 ``` **Don't know if this breaks other plugins as I only use this one.** ``` def parse_xml(data, name="XML", ignore_ns=False, exception=PluginError, schema=None): """Wrapper around ElementTree.fromstring with some extras Provides these extra features: - Handles incorrectly encoded XML - Allows stripping namespace information - Wraps errors in custom exception with a snippet of the data in the message """ if is_py2 and isinstance(data, unicode): data = data.encode("utf8") if ignore_ns: data = re.sub(" xmlns=\"(.+?)\"", "", data) data = re.sub("&", "&amp;", data.decode('utf8')) try: tree = ET.fromstring(data) except Exception as err: snippet = repr(data) if len(snippet) > 35: snippet = snippet[:35] + " ..." raise exception("Unable to parse {0}: {1} ({2})".format(name, err, snippet)) if schema: tree = schema.validate(tree, name=name, exception=exception) return tree ```
0.0
c2368bea030c50beb794821b01b92bad5e21c5fb
[ "tests/test_utils.py::TestUtil::test_parse_xml_entities" ]
[ "tests/test_utils.py::TestUtil::test_absolute_url", "tests/test_utils.py::TestUtil::test_parse_json", "tests/test_utils.py::TestUtil::test_parse_qsd", "tests/test_utils.py::TestUtil::test_parse_xml", "tests/test_utils.py::TestUtil::test_parse_xml_entities_fail", "tests/test_utils.py::TestUtil::test_parse_xml_fail", "tests/test_utils.py::TestUtil::test_parse_xml_ns", "tests/test_utils.py::TestUtil::test_parse_xml_ns_ignore", "tests/test_utils.py::TestUtil::test_parse_xml_validate", "tests/test_utils.py::TestUtil::test_prepend_www", "tests/test_utils.py::TestUtil::test_update_scheme", "tests/test_utils.py::TestUtil::test_verifyjson" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_media", "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2018-03-27 10:04:14+00:00
bsd-2-clause
5,757
streamlink__streamlink-1655
diff --git a/docs/cli.rst b/docs/cli.rst index 90a91512..e96b1c8b 100644 --- a/docs/cli.rst +++ b/docs/cli.rst @@ -337,14 +337,19 @@ change the proxy server that Streamlink will use for HTTP and HTTPS requests res As HTTP and HTTPS requests can be handled by separate proxies, you may need to specify both options if the plugin you use makes HTTP and HTTPS requests. -Both HTTP and SOCKS5 proxies are supported, authentication is supported for both types. +Both HTTP and SOCKS proxies are supported, authentication is supported for both types. + +.. note:: + When using a SOCKS proxy the ``socks4`` and ``socks5`` schemes mean that DNS lookups are done + locally, rather than on the proxy server. To have the proxy server perform the DNS lookups, the + ``socks4a`` and ``socks5h`` schemes should be used instead. For example: .. code-block:: console $ streamlink --http-proxy "http://user:[email protected]:3128/" --https-proxy "socks5://10.10.1.10:1242" - + $ streamlink --http-proxy "socks4a://10.10.1.10:1235" --https-proxy "socks5h://10.10.1.10:1234" Command-line usage ------------------ diff --git a/src/streamlink/plugins/tf1.py b/src/streamlink/plugins/tf1.py index 189f124c..88b5e585 100644 --- a/src/streamlink/plugins/tf1.py +++ b/src/streamlink/plugins/tf1.py @@ -9,13 +9,20 @@ from streamlink.stream import HLSStream class TF1(Plugin): - url_re = re.compile(r"https?://(?:www\.)?(?:tf1\.fr/(tf1|tmc|tfx|tf1-series-films)/direct|(lci).fr/direct)/?") + url_re = re.compile(r"https?://(?:www\.)?(?:tf1\.fr/([\w-]+)/direct|(lci).fr/direct)/?") embed_url = "http://www.wat.tv/embedframe/live{0}" embed_re = re.compile(r"urlLive.*?:.*?\"(http.*?)\"", re.MULTILINE) api_url = "http://www.wat.tv/get/{0}/591997" swf_url = "http://www.wat.tv/images/v70/PlayerLite.swf" - hds_channel_remap = {"tf1": "androidliveconnect", "lci": "androidlivelci", "tfx" : "nt1live", "tf1-series-films" : "hd1live" } - hls_channel_remap = {"lci": "LCI", "tf1": "V4", "tfx" : "nt1", "tf1-series-films" : "hd1" } + hds_channel_remap = {"tf1": "androidliveconnect", + "lci": "androidlivelci", + "tfx": "nt1live", + "hd1": "hd1live", # renamed to tfx + "tf1-series-films": "hd1live"} + hls_channel_remap = {"lci": "LCI", + "tf1": "V4", + "tfx": "nt1", + "tf1-series-films": "hd1"} @classmethod def can_handle_url(cls, url): @@ -23,6 +30,7 @@ class TF1(Plugin): def _get_hds_streams(self, channel): channel = self.hds_channel_remap.get(channel, "{0}live".format(channel)) + self.logger.debug("Using HDS channel name: {0}".format(channel)) manifest_url = http.get(self.api_url.format(channel), params={"getURL": 1}, headers={"User-Agent": useragents.FIREFOX}).text
streamlink/streamlink
e2a55461decc6856912325e8103cefb359027811
diff --git a/tests/test_plugin_tf1.py b/tests/test_plugin_tf1.py index 77afd8d8..f8e48790 100644 --- a/tests/test_plugin_tf1.py +++ b/tests/test_plugin_tf1.py @@ -12,11 +12,11 @@ class TestPluginTF1(unittest.TestCase): self.assertTrue(TF1.can_handle_url("http://lci.fr/direct")) self.assertTrue(TF1.can_handle_url("http://www.lci.fr/direct")) self.assertTrue(TF1.can_handle_url("http://tf1.fr/tmc/direct")) + self.assertTrue(TF1.can_handle_url("http://tf1.fr/lci/direct")) + def test_can_handle_url_negative(self): # shouldn't match self.assertFalse(TF1.can_handle_url("http://tf1.fr/direct")) -# self.assertFalse(TF1.can_handle_url("http://tf1.fr/nt1/direct")) NOTE : TF1 redirect old channel names to new ones (for now). -# self.assertFalse(TF1.can_handle_url("http://tf1.fr/hd1/direct")) self.assertFalse(TF1.can_handle_url("http://www.tf1.fr/direct")) self.assertFalse(TF1.can_handle_url("http://www.tvcatchup.com/")) self.assertFalse(TF1.can_handle_url("http://www.youtube.com/"))
Need a option for DNS through proxy ### Checklist - [ ] This is a bug report. - [x] This is a feature request. - [ ] This is a plugin (improvement) request. - [ ] I have read the contribution guidelines. ### Description Steamlink can't resolve hostnames through the proxy server. If you receive a incorrect ip of the host via DNS spoofing, the option --http-proxy and --https-proxy may not work correctly. ### Expected / Actual behavior Expected: Steamkink connect to youtube server through proxy and work fine. Actual: Read timed out. ### Reproduction steps / Explicit stream URLs to test 1. Run a socks5 proxy server on port 1080 2. streamlink --hls-live-restart --http-proxy "socks5://127.0.0.1:1080" --https-proxy "socks5://127.0.0.1:1080" https://www.youtube.com/watch?v=fO8x9MZ8m9g ### Logs [cli][debug] OS: Windows 10 [cli][debug] Python: 3.6.5 [cli][debug] Streamlink: 0.12.1 [cli][debug] Requests(2.18.4), Socks(1.6.7), Websocket(0.47.0) [cli][info] Found matching plugin youtube for URL https://www.youtube.com/watch?v=fO8x9MZ8m9g error: Unable to open URL: https://youtube.com/get_video_info (SOCKSHTTPSConnectionPool(host='youtube.com', port=443): Read timed out. (read timeout=20.0)) ### Comments, screenshots, etc. This is the log of my socks5 proxy when I run the step 2: [2018-05-15 21:26:52] connect to 8.7.198.45:443 And this is the log when I visit https://youtube.com on firefox(Use the same socks5 proxy and it works fine) [2018-05-15 21:28:51] connect to youtube.com:443 And this is the ping log to youtube.com on my pc Pinging youtube.com [8.7.198.45] with 32 bytes of data: Request timed out. Request timed out. Stramlink resolve the hostname 'youtube.com' direct and receive the incorrect ip '8.7.198.45' via DNS spoofing. Firefox works fine because it send the DNS request through the proxy.
0.0
e2a55461decc6856912325e8103cefb359027811
[ "tests/test_plugin_tf1.py::TestPluginTF1::test_can_handle_url" ]
[ "tests/test_plugin_tf1.py::TestPluginTF1::test_can_handle_url_negative" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2018-05-15 16:20:20+00:00
bsd-2-clause
5,758
streamlink__streamlink-1660
diff --git a/src/streamlink/plugins/tf1.py b/src/streamlink/plugins/tf1.py index 189f124c..88b5e585 100644 --- a/src/streamlink/plugins/tf1.py +++ b/src/streamlink/plugins/tf1.py @@ -9,13 +9,20 @@ from streamlink.stream import HLSStream class TF1(Plugin): - url_re = re.compile(r"https?://(?:www\.)?(?:tf1\.fr/(tf1|tmc|tfx|tf1-series-films)/direct|(lci).fr/direct)/?") + url_re = re.compile(r"https?://(?:www\.)?(?:tf1\.fr/([\w-]+)/direct|(lci).fr/direct)/?") embed_url = "http://www.wat.tv/embedframe/live{0}" embed_re = re.compile(r"urlLive.*?:.*?\"(http.*?)\"", re.MULTILINE) api_url = "http://www.wat.tv/get/{0}/591997" swf_url = "http://www.wat.tv/images/v70/PlayerLite.swf" - hds_channel_remap = {"tf1": "androidliveconnect", "lci": "androidlivelci", "tfx" : "nt1live", "tf1-series-films" : "hd1live" } - hls_channel_remap = {"lci": "LCI", "tf1": "V4", "tfx" : "nt1", "tf1-series-films" : "hd1" } + hds_channel_remap = {"tf1": "androidliveconnect", + "lci": "androidlivelci", + "tfx": "nt1live", + "hd1": "hd1live", # renamed to tfx + "tf1-series-films": "hd1live"} + hls_channel_remap = {"lci": "LCI", + "tf1": "V4", + "tfx": "nt1", + "tf1-series-films": "hd1"} @classmethod def can_handle_url(cls, url): @@ -23,6 +30,7 @@ class TF1(Plugin): def _get_hds_streams(self, channel): channel = self.hds_channel_remap.get(channel, "{0}live".format(channel)) + self.logger.debug("Using HDS channel name: {0}".format(channel)) manifest_url = http.get(self.api_url.format(channel), params={"getURL": 1}, headers={"User-Agent": useragents.FIREFOX}).text
streamlink/streamlink
e2a55461decc6856912325e8103cefb359027811
diff --git a/tests/test_plugin_tf1.py b/tests/test_plugin_tf1.py index 77afd8d8..f8e48790 100644 --- a/tests/test_plugin_tf1.py +++ b/tests/test_plugin_tf1.py @@ -12,11 +12,11 @@ class TestPluginTF1(unittest.TestCase): self.assertTrue(TF1.can_handle_url("http://lci.fr/direct")) self.assertTrue(TF1.can_handle_url("http://www.lci.fr/direct")) self.assertTrue(TF1.can_handle_url("http://tf1.fr/tmc/direct")) + self.assertTrue(TF1.can_handle_url("http://tf1.fr/lci/direct")) + def test_can_handle_url_negative(self): # shouldn't match self.assertFalse(TF1.can_handle_url("http://tf1.fr/direct")) -# self.assertFalse(TF1.can_handle_url("http://tf1.fr/nt1/direct")) NOTE : TF1 redirect old channel names to new ones (for now). -# self.assertFalse(TF1.can_handle_url("http://tf1.fr/hd1/direct")) self.assertFalse(TF1.can_handle_url("http://www.tf1.fr/direct")) self.assertFalse(TF1.can_handle_url("http://www.tvcatchup.com/")) self.assertFalse(TF1.can_handle_url("http://www.youtube.com/"))
LCI not covered by TF1 home page anymore ### Checklist - [ ] This is a bug report. - [ ] This is a feature request. - [x] This is a plugin (improvement) request. - [ ] I have read the contribution guidelines. ### Description I pointed out since a while that tf1 plugin doesn't cover anymore LCI from tf1.fr home website. It did before. ### Expected / Actual behavior Here I point out result with older tf1 plugin : ``` streamlink "https://www.tf1.fr/lci/direct" [cli][info] Found matching plugin tf1 for URL https://www.tf1.fr/lci/direct error: Unable to open URL: http://lcilivhlshdslive-lh.akamaihd.net/z/lci_1@30158 5/manifest.f4m?hdnea=st=1526479986~exp=1526481786~acl=/*~hmac=207f41547435bb3422 e9f51af166cae855bdbb387ac875524827deb528999d9e (403 Client Error: Forbidden for url: http://lcilivhlshdslive-lh.akamaihd.net/z/lci_1@301585/manifest.f4m?hdnea=s t=1526479986~exp=1526481786~acl=/*~hmac=207f41547435bb3422e9f51af166cae855bdbb38 7ac875524827deb528999d9e&g=DSCLJVQYJHGR&hdcore=3.1.0) ``` The latest tf1 plugin gives such result : ``` streamlink "https://www.tf1.fr/lci/direct" [cli][info] Found matching plugin resolve for URL https://www.tf1.fr/lci/direct [plugin.resolve][info] Found iframes: Traceback (most recent call last): File "C:\Program Files\Python27\Scripts\streamlink-script.py", line 11, in <mo dule> load_entry_point('streamlink==0.12.1+8.ge2a5546', 'console_scripts', 'stream link')() File "c:\program files\python27\lib\site-packages\streamlink_cli\main.py", lin e 1113, in main handle_url() File "c:\program files\python27\lib\site-packages\streamlink_cli\main.py", lin e 505, in handle_url streams = fetch_streams(plugin) File "c:\program files\python27\lib\site-packages\streamlink_cli\main.py", lin e 402, in fetch_streams sorting_excludes=args.stream_sorting_excludes) File "c:\program files\python27\lib\site-packages\streamlink\plugin\plugin.py" , line 385, in get_streams return self.streams(*args, **kwargs) File "c:\program files\python27\lib\site-packages\streamlink\plugin\plugin.py" , line 288, in streams ostreams = self._get_streams() File "c:\program files\python27\lib\site-packages\streamlink\plugins\resolve.p y", line 480, in _get_streams IndexError: list index out of range ``` ### Reproduction steps / Explicit stream URLs to test 1. ` streamlink "https://www.tf1.fr/lci/direct"` ### Logs ``` streamlink -l debug [cli][debug] OS: Windows 7 [cli][debug] Python: 2.7.13 [cli][debug] Streamlink: 0.12.1+8.ge2a5546 [cli][debug] Requests(2.18.4), Socks(1.6.7), Websocket(0.46.0) ``` Both tests were made with the latest streamlink build, I just replaced newer tf1 plugin with older. Thanks for up.
0.0
e2a55461decc6856912325e8103cefb359027811
[ "tests/test_plugin_tf1.py::TestPluginTF1::test_can_handle_url" ]
[ "tests/test_plugin_tf1.py::TestPluginTF1::test_can_handle_url_negative" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_git_commit_hash" ], "has_test_patch": true, "is_lite": false }
2018-05-16 14:48:22+00:00
bsd-2-clause
5,759
streamlink__streamlink-1670
diff --git a/docs/plugin_matrix.rst b/docs/plugin_matrix.rst index b13dd541..6a472d95 100644 --- a/docs/plugin_matrix.rst +++ b/docs/plugin_matrix.rst @@ -111,6 +111,7 @@ idf1 idf1.fr Yes Yes ine ine.com --- Yes itvplayer itv.com/itvplayer Yes Yes Streams may be geo-restricted to Great Britain. kanal7 kanal7.com Yes No +kingkong www.kingkong.com.tw Yes Yes liveedu - liveedu.tv Yes -- Some streams require a login. - livecoding.tv liveme liveme.com Yes -- diff --git a/src/streamlink/plugins/kingkong.py b/src/streamlink/plugins/kingkong.py new file mode 100644 index 00000000..e50b8144 --- /dev/null +++ b/src/streamlink/plugins/kingkong.py @@ -0,0 +1,98 @@ +import re + +from streamlink.plugin import Plugin +from streamlink.plugin.api import http, validate +from streamlink.stream import HTTPStream, HLSStream + +API_URL = "https://g-api.langlive.com/webapi/v1/room/info?room_id={0}" +VOD_API_URL = ( + "https://g-api.langlive.com/webapi/v1/replayer/detail?live_id={0}") +STATUS_ONLINE = 1 +STATUS_OFFLINE = 0 +STREAM_WEIGHTS = { + "360P": 360, + "480P": 480, + "720P": 720, + "source": 1080 +} + +_url_re = re.compile(r""" + https://www\.kingkong\.com\.tw/ + (?: + video/(?P<vid>[0-9]+G[0-9A-Za-z]+)| + (?P<channel>[0-9]+) + ) +""", re.VERBOSE) + +_room_schema = validate.Schema( + { + "data": { + "live_info": { + "live_status": int, + "stream_items": [{ + "title": validate.text, + "video": validate.any('', validate.url( + scheme="https", + path=validate.endswith(".flv") + )) + }] + } + } + }, + validate.get("data") +) + +_vod_schema = validate.Schema( + { + "data": { + "live_info": { + "video": validate.text + } + } + }, + validate.get("data") +) + + +class Kingkong(Plugin): + @classmethod + def can_handle_url(cls, url): + return _url_re.match(url) + + @classmethod + def stream_weight(cls, stream): + if stream in STREAM_WEIGHTS: + return STREAM_WEIGHTS[stream], "kingkong" + return Plugin.stream_weight(stream) + + def _get_streams(self): + match = _url_re.match(self.url) + vid = match.group("vid") + + if vid: + res = http.get(VOD_API_URL.format(vid)) + data = http.json(res, schema=_vod_schema) + yield "source", HLSStream( + self.session, data["live_info"]["video"]) + return + + channel = match.group("channel") + res = http.get(API_URL.format(channel)) + room = http.json(res, schema=_room_schema) + if not room: + self.logger.info("Not a valid room url.") + return + + live_info = room["live_info"] + if live_info["live_status"] != STATUS_ONLINE: + self.logger.info("Stream currently unavailable.") + return + + for item in live_info["stream_items"]: + quality = item["title"] + if quality == u"\u6700\u4f73": # "Best" in Chinese + quality = "source" + yield quality, HTTPStream(self.session, item["video"]) + + +__plugin__ = Kingkong diff --git a/src/streamlink/plugins/vidio.py b/src/streamlink/plugins/vidio.py index fe5f61aa..a465dfb2 100644 --- a/src/streamlink/plugins/vidio.py +++ b/src/streamlink/plugins/vidio.py @@ -1,36 +1,61 @@ -''' +""" Plugin for vidio.com - https://www.vidio.com/live/5075-dw-tv-stream - https://www.vidio.com/watch/766861-5-rekor-fantastis-zidane-bersama-real-madrid -''' +""" import re from streamlink.plugin import Plugin -from streamlink.plugin.api import http +from streamlink.plugin.api import http, useragents, validate from streamlink.stream import HLSStream - -_url_re = re.compile(r"https?://(?:www\.)?vidio\.com/(?:en/)?(?P<type>live|watch)/(?P<id>\d+)-(?P<name>[^/?#&]+)") -_playlist_re = re.compile(r'''hls-url=["'](?P<url>[^"']+)["']''') +from streamlink.utils import parse_json class Vidio(Plugin): + _url_re = re.compile(r"https?://(?:www\.)?vidio\.com/(?:en/)?(?P<type>live|watch)/(?P<id>\d+)-(?P<name>[^/?#&]+)") + _playlist_re = re.compile(r'''hls-url=["'](?P<url>[^"']+)["']''') + _data_id_re = re.compile(r'''meta\s+data-id=["'](?P<id>[^"']+)["']''') + + csrf_tokens_url = "https://www.vidio.com/csrf_tokens" + tokens_url = "https://www.vidio.com/live/{id}/tokens" + token_schema = validate.Schema(validate.transform(parse_json), + {"token": str}, + validate.get("token")) + @classmethod def can_handle_url(cls, url): - return _url_re.match(url) + return cls._url_re.match(url) + + def get_csrf_tokens(self): + return http.get(self.csrf_tokens_url, + schema=self.token_schema) + + def get_url_tokens(self, stream_id): + self.logger.debug("Getting stream tokens") + csrf_token = self.get_csrf_tokens() + return http.post(self.tokens_url.format(id=stream_id), + files={"authenticity_token": (None, csrf_token)}, + headers={"User-Agent": useragents.CHROME, + "Referer": self.url}, + schema=self.token_schema) def _get_streams(self): res = http.get(self.url) - match = _playlist_re.search(res.text) - if match is None: - return + plmatch = self._playlist_re.search(res.text) + idmatch = self._data_id_re.search(res.text) + + hls_url = plmatch and plmatch.group("url") + stream_id = idmatch and idmatch.group("id") - url = match.group('url') + tokens = self.get_url_tokens(stream_id) - if url: - self.logger.debug('HLS URL: {0}'.format(url)) - for s in HLSStream.parse_variant_playlist(self.session, url).items(): - yield s + if hls_url: + self.logger.debug("HLS URL: {0}".format(hls_url)) + self.logger.debug("Tokens: {0}".format(tokens)) + return HLSStream.parse_variant_playlist(self.session, hls_url+"?"+tokens, + headers={"User-Agent": useragents.CHROME, + "Referer": self.url}) __plugin__ = Vidio
streamlink/streamlink
1bf90e845f6165eafe04716f5e8cb4b3c1579e2d
diff --git a/tests/test_plugin_kingkong.py b/tests/test_plugin_kingkong.py new file mode 100644 index 00000000..311041bb --- /dev/null +++ b/tests/test_plugin_kingkong.py @@ -0,0 +1,17 @@ +import unittest +from streamlink.plugins.kingkong import Kingkong + + +class TestPluginKingkong(unittest.TestCase): + def test_can_handle_url(self): + # Valid stream and VOD URLS + self.assertTrue(Kingkong.can_handle_url( + "https://www.kingkong.com.tw/600000")) + self.assertTrue(Kingkong.can_handle_url( + "https://www.kingkong.com.tw/video/2152350G38400MJTU")) + + # Others + self.assertFalse(Kingkong.can_handle_url( + "https://www.kingkong.com.tw/category/lol")) + self.assertFalse(Kingkong.can_handle_url( + "https://www.kingkong.com.tw/videos/2152350"))
[plugin issue] plugin.vidio.com / can't handle stream URLs anymore - [x] This is a bug report. - [ ] This is a feature request. - [ ] This is a plugin (improvement) request. - [ ] I have read the contribution guidelines. ### Description plugin handling of https://www.vidio.com/live URls not working anymore due to changes at provided stream structure ### Expected / Actual behavior streamlink -l debug www.vidio.com/live/665-rcti-tv-stream [cli][debug] OS: Windows 10 [cli][debug] Python: 3.5.2 [cli][debug] Streamlink: 0.12.1 [cli][debug] Requests(2.18.4), Socks(1.6.7), Websocket(0.47.0) [cli][info] Found matching plugin vidio for URL www.vidio.com/live/665-rcti-tv-stream [plugin.vidio][debug] HLS URL: https://kmklive-lh.akamaihd.net/i/rcti_ta_regular@94478/master.m3u8 error: Unable to open URL: https://kmklive-lh.akamaihd.net/i/rcti_ta_regular@94478/master.m3u8 (403 Client Error: Forbidden for url: https://kmklive-lh.akamaihd.net/i/rcti_ta_regular@94478/master.m3u8)
0.0
1bf90e845f6165eafe04716f5e8cb4b3c1579e2d
[ "tests/test_plugin_kingkong.py::TestPluginKingkong::test_can_handle_url" ]
[]
{ "failed_lite_validators": [ "has_hyperlinks", "has_added_files", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2018-05-19 17:19:24+00:00
bsd-2-clause
5,760
streamlink__streamlink-1696
diff --git a/src/streamlink/plugins/tvcatchup.py b/src/streamlink/plugins/tvcatchup.py index ca6a60d2..bd150295 100644 --- a/src/streamlink/plugins/tvcatchup.py +++ b/src/streamlink/plugins/tvcatchup.py @@ -5,7 +5,7 @@ from streamlink.plugin.api import http from streamlink.stream import HLSStream USER_AGENT = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36" -_url_re = re.compile(r"http://(?:www\.)?tvcatchup.com/watch/\w+") +_url_re = re.compile(r"https?://(?:www\.)?tvcatchup.com/watch/\w+") _stream_re = re.compile(r'''source.*?(?P<q>["'])(?P<stream_url>https?://.*m3u8\?.*clientKey=.*?)(?P=q)''')
streamlink/streamlink
8029d10153b51e76a83a7d6d29c7d7bb83256feb
diff --git a/tests/test_plugin_tvcatchup.py b/tests/test_plugin_tvcatchup.py new file mode 100644 index 00000000..d52b81cd --- /dev/null +++ b/tests/test_plugin_tvcatchup.py @@ -0,0 +1,16 @@ +import unittest + +from streamlink.plugins.tvcatchup import TVCatchup + + +class TestPluginTVCatchup(unittest.TestCase): + def test_can_handle_url(self): + # should match + self.assertTrue(TVCatchup.can_handle_url("http://tvcatchup.com/watch/bbcone")) + self.assertTrue(TVCatchup.can_handle_url("http://www.tvcatchup.com/watch/five")) + self.assertTrue(TVCatchup.can_handle_url("https://www.tvcatchup.com/watch/bbctwo")) + + # shouldn't match + self.assertFalse(TVCatchup.can_handle_url("http://www.tvplayer.com/")) + self.assertFalse(TVCatchup.can_handle_url("http://www.tvcatchup.com/")) + self.assertFalse(TVCatchup.can_handle_url("http://www.youtube.com/")) \ No newline at end of file
[patch] Support https on tvcatchup.com The problem: ``` tmp (lonefox): streamlink https://tvcatchup.com/watch/bbcone best error: No plugin can handle URL: https://tvcatchup.com/watch/bbcone ``` The solution: ``` diff -bur streamlink-0.12.1-orig/src/streamlink/plugins/tvcatchup.py streamlink-0.12.1/src/streamlink/plugins/tvcatchup.py --- streamlink-0.12.1-orig/src/streamlink/plugins/tvcatchup.py 2018-05-07 18:01:30.000000000 +0300 +++ streamlink-0.12.1/src/streamlink/plugins/tvcatchup.py 2018-05-26 08:54:47.000000000 +0300 @@ -5,7 +5,7 @@ from streamlink.stream import HLSStream USER_AGENT = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36" -_url_re = re.compile(r"http://(?:www\.)?tvcatchup.com/watch/\w+") +_url_re = re.compile(r"https?://(?:www\.)?tvcatchup.com/watch/\w+") _stream_re = re.compile(r'''source.*?(?P<q>["'])(?P<stream_url>https?://.*m3u8\?.*clientKey=.*?)(?P=q)''') ```
0.0
8029d10153b51e76a83a7d6d29c7d7bb83256feb
[ "tests/test_plugin_tvcatchup.py::TestPluginTVCatchup::test_can_handle_url" ]
[]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2018-05-26 08:30:49+00:00
bsd-2-clause
5,761
streamlink__streamlink-1705
diff --git a/docs/plugin_matrix.rst b/docs/plugin_matrix.rst index 0de102ab..d9b24173 100644 --- a/docs/plugin_matrix.rst +++ b/docs/plugin_matrix.rst @@ -247,6 +247,7 @@ tvrplus tvrplus.ro Yes No Streams may be geo-rest twitch twitch.tv Yes Yes Possible to authenticate for access to subscription streams. ustreamtv ustream.tv Yes Yes +ustvnow ustvnow.com Yes -- All streams require an account, some streams require a subscription. vaughnlive - vaughnlive.tv Yes -- - breakers.tv - instagib.tv diff --git a/src/streamlink/plugins/ustvnow.py b/src/streamlink/plugins/ustvnow.py new file mode 100644 index 00000000..12a395e1 --- /dev/null +++ b/src/streamlink/plugins/ustvnow.py @@ -0,0 +1,96 @@ +import re + +from streamlink.plugin import Plugin, PluginArguments, PluginArgument +from streamlink.plugin.api import http, useragents +from streamlink.plugin.api.utils import itertags +from streamlink.stream import HLSStream + + +class USTVNow(Plugin): + _url_re = re.compile(r"https?://(?:watch\.)?ustvnow\.com(?:/(?:watch|guide)/(?P<scode>\w+))?") + _token_re = re.compile(r'''var\s+token\s*=\s*"(.*?)";''') + _login_url = "https://watch.ustvnow.com/account/login" + _signin_url = "https://watch.ustvnow.com/account/signin" + _guide_url = "http://m.ustvnow.com/gtv/1/live/channelguidehtml" + _stream_url = "http://m.ustvnow.com/stream/1/live/view" + + arguments = PluginArguments( + PluginArgument( + "username", + metavar="USERNAME", + required=True, + help="Your USTV Now account username" + ), + PluginArgument( + "password", + sensitive=True, + metavar="PASSWORD", + required=True, + help="Your USTV Now account password", + prompt="Enter USTV Now account password" + ), + PluginArgument( + "station-code", + metavar="CODE", + help="USTV Now station code" + ), + ) + + @classmethod + def can_handle_url(cls, url): + return cls._url_re.match(url) is not None + + def login(self, username, password): + r = http.get(self._signin_url) + csrf = None + + for input in itertags(r.text, "input"): + if input.attributes['name'] == "csrf_ustvnow": + csrf = input.attributes['value'] + + self.logger.debug("CSRF: {0}", csrf) + + r = http.post(self._login_url, data={'csrf_ustvnow': csrf, + 'signin_email': username, + 'signin_password': password, + 'signin_remember': '1'}) + m = self._token_re.search(r.text) + return m and m.group(1) + + def _get_streams(self): + """ + Finds the streams from tvcatchup.com. + """ + token = self.login(self.get_option("username"), self.get_option("password")) + m = self._url_re.match(self.url) + scode = m and m.group("scode") or self.get_option("station_code") + + res = http.get(self._guide_url) + + channels = {} + for t in itertags(res.text, "a"): + if t.attributes.get('cs'): + channels[t.attributes.get('cs').lower()] = t.attributes.get('title').replace("Watch ", "") + + if not scode: + self.logger.error("Station code not provided, use --ustvnow-station-code.") + self.logger.error("Available stations are: {0}", ", ".join(channels.keys())) + return + + if scode in channels: + self.logger.debug("Finding streams for: {0}", channels.get(scode)) + + r = http.get(self._stream_url, params={"scode": scode, + "token": token, + "br_n": "Firefox", + "br_v": "52", + "br_d": "desktop"}, + headers={"User-Agent": useragents.FIREFOX}) + + data = http.json(r) + return HLSStream.parse_variant_playlist(self.session, data["stream"]) + else: + self.logger.error("Invalid station-code: {0}", scode) + + +__plugin__ = USTVNow
streamlink/streamlink
c408ec6deec0abd28d98a2f64f674a77c4807ff9
diff --git a/tests/test_plugin_ustvnow.py b/tests/test_plugin_ustvnow.py new file mode 100644 index 00000000..c7195265 --- /dev/null +++ b/tests/test_plugin_ustvnow.py @@ -0,0 +1,16 @@ +import unittest + +from streamlink.plugins.ustvnow import USTVNow + + +class TestPluginUSTVNow(unittest.TestCase): + def test_can_handle_url(self): + self.assertTrue(USTVNow.can_handle_url("http://watch.ustvnow.com")) + self.assertTrue(USTVNow.can_handle_url("https://watch.ustvnow.com/")) + self.assertTrue(USTVNow.can_handle_url("http://watch.ustvnow.com/watch")) + self.assertTrue(USTVNow.can_handle_url("https://watch.ustvnow.com/watch")) + self.assertTrue(USTVNow.can_handle_url("https://watch.ustvnow.com/watch/syfy")) + self.assertTrue(USTVNow.can_handle_url("https://watch.ustvnow.com/guide/foxnews")) + + def test_can_not_handle_url(self): + self.assertFalse(USTVNow.can_handle_url("http://www.tvplayer.com"))
Plugin request: USTVnow ### Checklist - [ ] This is a bug report. - [ ] This is a feature request. - [x] This is a plugin (improvement) request. - [x] I have read the contribution guidelines. ### Description Hi, i would like to request a plugin for [USTVnow](https://www.ustvnow.com/). They offer [free](https://www.ustvnow.com/register.php?sub=7) access to [7 US TV Channels](https://support.ustvnow.com/hc/en-us/articles/214145143-What-plans-channels-are-available-) and paid access to 30 channels, [some in HD](https://support.ustvnow.com/hc/en-us/articles/214145203-What-USTVnow-channels-are-available-in-HD-on-the-paid-plans-). Access-URL: http://m.ustvnow.com/iphone (iStuff) http://www.ustvnow.com/gtv/ (SmartTVs) http://watch.ustvnow.com/guide (Webbrowsers) The direct links are javascript-obfuscated and i can't see deep-links to the programs They use various protocols, including HLS and RTMP, **but HLS access only works for 30 days on the free account**. HLS seems to offer a bit more quality (even on the SD-Only free account) There are already several projects in python that can produce an m3u playlist (the urls are only valid for about 30mins): https://github.com/mathsgrinds/ustvnow-iptv-m3u-playlist (HLS playlist, worked a week ago) https://github.com/guilleiguaran/ustvnow-m3u-server (RTMP playlist, stopped working about a year ago). A choice of the protocol(s) would be great (as mentioned, HLS only works for 30 days for free), but i would be happy with anything that "just works" :) Thanks :D
0.0
c408ec6deec0abd28d98a2f64f674a77c4807ff9
[ "tests/test_plugin_ustvnow.py::TestPluginUSTVNow::test_can_handle_url", "tests/test_plugin_ustvnow.py::TestPluginUSTVNow::test_can_not_handle_url" ]
[]
{ "failed_lite_validators": [ "has_hyperlinks", "has_added_files" ], "has_test_patch": true, "is_lite": false }
2018-05-28 23:35:04+00:00
bsd-2-clause
5,762
streamlink__streamlink-1717
diff --git a/docs/plugin_matrix.rst b/docs/plugin_matrix.rst index a122186d..112bd9c7 100644 --- a/docs/plugin_matrix.rst +++ b/docs/plugin_matrix.rst @@ -43,8 +43,7 @@ btsports sport.bt.com Yes Yes Requires subscription a btv btv.bg Yes No Requires login, and geo-restricted to Bulgaria. cam4 cam4.com Yes No camsoda camsoda.com Yes No -canalplus - mycanal.fr No Yes Streams may be geo-restricted to France. - - cnews.fr +canalplus mycanal.fr No Yes Streams may be geo-restricted to France. cdnbg - tv.bnt.bg Yes No Streams may be geo-restricted to Bulgaria. - bgonair.bg - kanal3.bg @@ -57,6 +56,7 @@ cinergroup - showtv.com.tr Yes No - showmax.com.tr - showturk.com.tr - bloomberght.com +cnews cnews.fr Yes Yes crunchyroll crunchyroll.com -- Yes cybergame cybergame.tv Yes Yes dailymotion dailymotion.com Yes Yes @@ -192,6 +192,7 @@ srgssr - srf.ch Yes No Streams are geo-restric - rtr.ch ssh101 ssh101.com Yes No startv startv.com.tr Yes No +steam steamcommunity.com Yes No Some streams will require a Steam account. streamable streamable.com - Yes streamboat streamboat.tv Yes No streamingvideoprovider streamingvid... [2]_ Yes -- RTMP streams requires rtmpdump with diff --git a/src/streamlink/plugins/canalplus.py b/src/streamlink/plugins/canalplus.py index b0c4bb23..8279ce0b 100644 --- a/src/streamlink/plugins/canalplus.py +++ b/src/streamlink/plugins/canalplus.py @@ -13,10 +13,9 @@ class CanalPlus(Plugin): SECRET = 'pqzerjlsmdkjfoiuerhsdlfknaes' _url_re = re.compile(r''' - (https|http):// + https?:// ( - www.mycanal.fr/(.*)/(.*)/p/(?P<video_id>[0-9]+) | - www\.cnews\.fr/.+ + www.mycanal.fr/(.*)/(.*)/p/(?P<video_id>[0-9]+) ) ''', re.VERBOSE) _video_id_re = re.compile(r'(\bdata-video="|<meta property="og:video" content=".+?&videoId=)(?P<video_id>[0-9]+)"') diff --git a/src/streamlink/plugins/cnews.py b/src/streamlink/plugins/cnews.py new file mode 100644 index 00000000..824d4d3f --- /dev/null +++ b/src/streamlink/plugins/cnews.py @@ -0,0 +1,24 @@ +import re + +from streamlink.plugin import Plugin +from streamlink.plugin.api import http, useragents + + +class CNEWS(Plugin): + _url_re = re.compile(r'https?://www.cnews.fr/[^ ]+') + _embed_video_url_re = re.compile(r'class="dm-video-embed_video" src="(?P<dm_url>.*)"') + _embed_live_url_re = re.compile(r'class="wrapper-live-player main-live-player"><iframe src="(?P<dm_url>.*)"') + + @classmethod + def can_handle_url(cls, url): + return cls._url_re.match(url) + + def _get_streams(self): + # Retrieve URL page and search for Dailymotion URL + res = http.get(self.url, headers={'User-Agent': useragents.CHROME}) + match = self._embed_live_url_re.search(res.text) or self._embed_video_url_re.search(res.text) + if match is not None: + return self.session.streams(match.group('dm_url')) + + +__plugin__ = CNEWS diff --git a/src/streamlink/plugins/steam.py b/src/streamlink/plugins/steam.py new file mode 100644 index 00000000..fcbf0ce5 --- /dev/null +++ b/src/streamlink/plugins/steam.py @@ -0,0 +1,210 @@ +import base64 +import logging +import re +import time + +from Crypto.Cipher import PKCS1_v1_5 +from Crypto.PublicKey import RSA + +import streamlink +from streamlink.exceptions import FatalPluginError +from streamlink.plugin import Plugin, PluginArguments, PluginArgument +from streamlink.plugin.api import http +from streamlink.plugin.api import validate +from streamlink.plugin.api.validate import Schema +from streamlink.stream.dash import DASHStream + +log = logging.getLogger(__name__) + + +class SteamLoginFailed(Exception): + pass + + +class SteamBroadcastPlugin(Plugin): + _url_re = re.compile(r"https?://steamcommunity.com/broadcast/watch/(\d+)") + _get_broadcast_url = "https://steamcommunity.com/broadcast/getbroadcastmpd/" + _user_agent = "streamlink/{}".format(streamlink.__version__) + _broadcast_schema = Schema({ + "success": validate.any("ready", "unavailable", "waiting", "waiting_to_start", "waiting_for_start"), + "retry": int, + "broadcastid": validate.any(validate.text, int), + validate.optional("url"): validate.url(), + validate.optional("viewertoken"): validate.text + }) + _get_rsa_key_url = "https://steamcommunity.com/login/getrsakey/" + _rsa_key_schema = validate.Schema({ + "publickey_exp": validate.all(validate.text, validate.transform(lambda x: int(x, 16))), + "publickey_mod": validate.all(validate.text, validate.transform(lambda x: int(x, 16))), + "success": True, + "timestamp": validate.text, + "token_gid": validate.text + }) + _dologin_url = "https://steamcommunity.com/login/dologin/" + _dologin_schema = validate.Schema({ + "success": bool, + "requires_twofactor": bool, + validate.optional("message"): validate.text, + validate.optional("emailauth_needed"): bool, + validate.optional("emaildomain"): validate.text, + validate.optional("emailsteamid"): validate.text, + validate.optional("login_complete"): bool, + validate.optional("captcha_needed"): bool, + validate.optional("captcha_gid"): validate.any(validate.text, int) + }) + _captcha_url = "https://steamcommunity.com/public/captcha.php?gid={}" + + arguments = PluginArguments( + PluginArgument( + "email", + metavar="EMAIL", + requires=["password"], + help=""" + A Steam account email address to access friends/private streams + """ + ), + PluginArgument( + "password", + metavar="PASSWORD", + sensitive=True, + help=""" + A Steam account password to use with --steam-email. + """ + )) + + def __init__(self, url): + super(SteamBroadcastPlugin, self).__init__(url) + http.headers["User-Agent"] = self._user_agent + + @classmethod + def can_handle_url(cls, url): + return cls._url_re.match(url) is not None + + @property + def donotcache(self): + return str(int(time.time() * 1000)) + + def encrypt_password(self, email, password): + """ + Get the RSA key for the user and encrypt the users password + :param email: steam account + :param password: password for account + :return: encrypted password + """ + res = http.get(self._get_rsa_key_url, params=dict(username=email, donotcache=self.donotcache)) + rsadata = http.json(res, schema=self._rsa_key_schema) + + rsa = RSA.construct((rsadata["publickey_mod"], rsadata["publickey_exp"])) + cipher = PKCS1_v1_5.new(rsa) + return base64.b64encode(cipher.encrypt(password.encode("utf8"))), rsadata["timestamp"] + + def dologin(self, email, password, emailauth="", emailsteamid="", captchagid="-1", captcha_text="", twofactorcode=""): + """ + Logs in to Steam + + """ + epassword, rsatimestamp = self.encrypt_password(email, password) + + login_data = { + 'username': email, + "password": epassword, + "emailauth": emailauth, + "loginfriendlyname": "Streamlink", + "captchagid": captchagid, + "captcha_text": captcha_text, + "emailsteamid": emailsteamid, + "rsatimestamp": rsatimestamp, + "remember_login": True, + "donotcache": self.donotcache, + "twofactorcode": twofactorcode + } + + res = http.post(self._dologin_url, data=login_data) + + resp = http.json(res, schema=self._dologin_schema) + + if not resp[u"success"]: + if resp.get(u"captcha_needed"): + # special case for captcha + captchagid = resp[u"captcha_gid"] + log.error("Captcha result required, open this URL to see the captcha: {}".format( + self._captcha_url.format(captchagid))) + try: + captcha_text = self.input_ask("Captcha text") + except FatalPluginError: + captcha_text = None + if not captcha_text: + return False + else: + # If the user must enter the code that was emailed to them + if resp.get(u"emailauth_needed"): + if not emailauth: + try: + emailauth = self.input_ask("Email auth code required") + except FatalPluginError: + emailauth = None + if not emailauth: + return False + else: + raise SteamLoginFailed("Email auth key error") + + # If the user must enter a two factor auth code + if resp.get(u"requires_twofactor"): + try: + twofactorcode = self.input_ask("Two factor auth code required") + except FatalPluginError: + twofactorcode = None + if not twofactorcode: + return False + + if resp.get(u"message"): + raise SteamLoginFailed(resp[u"message"]) + + return self.dologin(email, password, + emailauth=emailauth, + emailsteamid=resp.get(u"emailsteamid", u""), + captcha_text=captcha_text, + captchagid=captchagid, + twofactorcode=twofactorcode) + elif resp.get("login_complete"): + return True + else: + log.error("Something when wrong when logging in to Steam") + return False + + def login(self, email, password): + log.info("Attempting to login to Steam as {}".format(email)) + return self.dologin(email, password) + + def _get_broadcast_stream(self, steamid, viewertoken=0): + res = http.get(self._get_broadcast_url, + params=dict(broadcastid=0, + steamid=steamid, + viewertoken=viewertoken)) + return http.json(res, schema=self._broadcast_schema) + + def _get_streams(self): + streamdata = None + if self.get_option("email"): + if self.login(self.get_option("email"), self.get_option("password")): + log.info("Logged in as {0}".format(self.get_option("email"))) + self.save_cookies(lambda c: "steamMachineAuth" in c.name) + + # extract the steam ID from the URL + steamid = self._url_re.match(self.url).group(1) + + while streamdata is None or streamdata[u"success"] in ("waiting", "waiting_for_start"): + streamdata = self._get_broadcast_stream(steamid) + + if streamdata[u"success"] == "ready": + return DASHStream.parse_manifest(self.session, streamdata["url"]) + elif streamdata[u"success"] == "unavailable": + log.error("This stream is currently unavailable") + return + else: + r = streamdata[u"retry"] / 1000.0 + log.info("Waiting for stream, will retry again in {} seconds...".format(r)) + time.sleep(r) + + +__plugin__ = SteamBroadcastPlugin
streamlink/streamlink
9d63e64bbcbdaac647cd5059704c287819069d4a
diff --git a/tests/test_plugin_canalplus.py b/tests/test_plugin_canalplus.py index 62daf272..30646c58 100644 --- a/tests/test_plugin_canalplus.py +++ b/tests/test_plugin_canalplus.py @@ -10,10 +10,10 @@ class TestPluginCanalPlus(unittest.TestCase): self.assertTrue(CanalPlus.can_handle_url("https://www.mycanal.fr/sport/infosport-laurey-et-claudia/p/1473752")) self.assertTrue(CanalPlus.can_handle_url("https://www.mycanal.fr/docus-infos/ses-debuts-a-madrid-extrait-le-k-benzema/p/1469050")) self.assertTrue(CanalPlus.can_handle_url("https://www.mycanal.fr/d8-docs-mags/au-revoir-johnny-hallyday-le-doc/p/1473054")) - self.assertTrue(CanalPlus.can_handle_url("http://www.cnews.fr/direct")) - self.assertTrue(CanalPlus.can_handle_url("http://www.cnews.fr/politique/video/des-electeurs-toujours-autant-indecis-174769")) - self.assertTrue(CanalPlus.can_handle_url("http://www.cnews.fr/magazines/plus-de-recul/de-recul-du-14042017-174594")) # shouldn't match + self.assertFalse(CanalPlus.can_handle_url("http://www.cnews.fr/direct")) + self.assertFalse(CanalPlus.can_handle_url("http://www.cnews.fr/politique/video/des-electeurs-toujours-autant-indecis-174769")) + self.assertFalse(CanalPlus.can_handle_url("http://www.cnews.fr/magazines/plus-de-recul/de-recul-du-14042017-174594")) self.assertFalse(CanalPlus.can_handle_url("http://www.canalplus.fr/")) self.assertFalse(CanalPlus.can_handle_url("http://www.c8.fr/")) self.assertFalse(CanalPlus.can_handle_url("http://replay.c8.fr/")) diff --git a/tests/test_plugin_cnews.py b/tests/test_plugin_cnews.py new file mode 100644 index 00000000..c7bdfd9f --- /dev/null +++ b/tests/test_plugin_cnews.py @@ -0,0 +1,16 @@ +import unittest + +from streamlink.plugins.cnews import CNEWS + + +class TestPluginCNEWS(unittest.TestCase): + def test_can_handle_url(self): + # should match + self.assertTrue(CNEWS.can_handle_url("http://www.cnews.fr/le-direct")) + self.assertTrue(CNEWS.can_handle_url("http://www.cnews.fr/direct")) + self.assertTrue(CNEWS.can_handle_url("http://www.cnews.fr/emission/2018-06-12/meteo-du-12062018-784730")) + self.assertTrue(CNEWS.can_handle_url("http://www.cnews.fr/emission/2018-06-12/le-journal-des-faits-divers-du-12062018-784704")) + # shouldn't match + self.assertFalse(CNEWS.can_handle_url("http://www.cnews.fr/")) + self.assertFalse(CNEWS.can_handle_url("http://www.tvcatchup.com/")) + self.assertFalse(CNEWS.can_handle_url("http://www.youtube.com/")) diff --git a/tests/test_plugin_steam.py b/tests/test_plugin_steam.py new file mode 100644 index 00000000..db16601f --- /dev/null +++ b/tests/test_plugin_steam.py @@ -0,0 +1,15 @@ +import unittest + +from streamlink.plugins.steam import SteamBroadcastPlugin + + +class TestPluginSteamBroadcastPlugin(unittest.TestCase): + def test_can_handle_url(self): + self.assertTrue(SteamBroadcastPlugin.can_handle_url('https://steamcommunity.com/broadcast/watch/12432432')) + self.assertTrue(SteamBroadcastPlugin.can_handle_url('http://steamcommunity.com/broadcast/watch/342342')) + + def test_can_handle_url_negative(self): + # shouldn't match + self.assertFalse(SteamBroadcastPlugin.can_handle_url('http://steamcommunity.com/broadcast')) + self.assertFalse(SteamBroadcastPlugin.can_handle_url('https://steamcommunity.com')) + self.assertFalse(SteamBroadcastPlugin.can_handle_url('https://youtube.com'))
Support for Steam Broadcasting Hey boys and girls, Recently jumped ship over to streamlink and was wondering if you guys could figure out how to enable support for Steam Broadcasting. The folks over at livestreamer gave it a crack, but development for it soon died out. (Here's the link to the livestreamer issue thread: https://github.com/chrippa/livestreamer/issues/621) This may be a bit of an ask because it requires the user to be logged in but I'm fully happy to enter in my steam information to get it working. Here's a link to the directory of live broadcasts: http://steamcommunity.com/?subsection=broadcasts Hope this isn't too much of a challenge for you guys. Cheers.
0.0
9d63e64bbcbdaac647cd5059704c287819069d4a
[ "tests/test_plugin_canalplus.py::TestPluginCanalPlus::test_can_handle_url", "tests/test_plugin_cnews.py::TestPluginCNEWS::test_can_handle_url", "tests/test_plugin_steam.py::TestPluginSteamBroadcastPlugin::test_can_handle_url", "tests/test_plugin_steam.py::TestPluginSteamBroadcastPlugin::test_can_handle_url_negative" ]
[]
{ "failed_lite_validators": [ "has_hyperlinks", "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2018-05-30 22:15:34+00:00
bsd-2-clause
5,763
streamlink__streamlink-1813
diff --git a/docs/plugin_matrix.rst b/docs/plugin_matrix.rst index e6cd82c6..13134a95 100644 --- a/docs/plugin_matrix.rst +++ b/docs/plugin_matrix.rst @@ -113,6 +113,7 @@ liveedu - liveedu.tv Yes -- Some streams require a - livecoding.tv liveme liveme.com Yes -- livestream new.livestream.com Yes -- +lrt lrt.lt Yes No media_ccc_de - media.ccc.de Yes Yes Only mp4 and HLS are supported. - streaming... [4]_ mediaklikk mediaklikk.hu Yes No Streams may be geo-restricted to Hungary. diff --git a/src/streamlink/plugins/lrt.py b/src/streamlink/plugins/lrt.py new file mode 100644 index 00000000..2ab41b49 --- /dev/null +++ b/src/streamlink/plugins/lrt.py @@ -0,0 +1,43 @@ +import logging +import re +from functools import partial + +from streamlink.plugin import Plugin +from streamlink.plugin.api import http +from streamlink.stream import HLSStream +from streamlink.utils import parse_json +from streamlink.compat import urlparse + +log = logging.getLogger(__name__) + + +class LRT(Plugin): + _url_re = re.compile(r"https?://(?:www\.)?lrt.lt/mediateka/.") + _source_re = re.compile(r'sources\s*:\s*(\[{.*?}\]),', re.DOTALL | re.IGNORECASE) + js_to_json = partial(re.compile(r'(?!<")(\w+)\s*:\s*(["\']|\d?\.?\d+,|true|false|\[|{)').sub, r'"\1":\2') + + + @classmethod + def can_handle_url(cls, url): + return cls._url_re.match(url) + + def _get_streams(self): + page = http.get(self.url) + m = self._source_re.search(page.text) + if m: + params = "" + data = m.group(1) + log.debug("Source data: {0}".format(data)) + if "location.hash.substring" in data: + log.debug("Removing hash substring addition") + data = re.sub(r"\s*\+\s*location.hash.substring\(\d+\)", "", data) + params = urlparse(self.url).fragment + data = self.js_to_json(data) + for stream in parse_json(data): + for s in HLSStream.parse_variant_playlist(self.session, stream['file'], params=params).items(): + yield s + else: + log.debug("No match for sources regex") + + +__plugin__ = LRT diff --git a/src/streamlink/plugins/nos.py b/src/streamlink/plugins/nos.py index 7c03d388..66ee1b68 100644 --- a/src/streamlink/plugins/nos.py +++ b/src/streamlink/plugins/nos.py @@ -5,72 +5,49 @@ Supports: Live: http://www.nos.nl/livestream/* Tour: http://nos.nl/tour/live """ - +import logging import re -import json +from streamlink.compat import urljoin from streamlink.plugin import Plugin from streamlink.plugin.api import http -from streamlink.plugin.api.utils import parse_json -from streamlink.stream import HTTPStream, HLSStream +from streamlink.plugin.api.utils import itertags +from streamlink.stream import HLSStream -_url_re = re.compile(r"http(s)?://(\w+\.)?nos.nl/") -_js_re = re.compile(r'\((.*)\)') -_data_stream_re = re.compile(r'data-stream="(.*?)"', re.DOTALL | re.IGNORECASE) -_source_re = re.compile(r"<source(?P<source>[^>]+)>", re.IGNORECASE) -_source_src_re = re.compile(r"src=\"(?P<src>[^\"]+)\"", re.IGNORECASE) -_source_type_re = re.compile(r"type=\"(?P<type>[^\"]+)\"", re.IGNORECASE) +log = logging.getLogger(__name__) class NOS(Plugin): + _url_re = re.compile(r"https?://(?:\w+\.)?nos.nl/") + @classmethod def can_handle_url(cls, url): - return _url_re.match(url) + return cls._url_re.match(url) def _resolve_stream(self): res = http.get(self.url) - match = _data_stream_re.search(res.text) - if not match: - return - data_stream = match.group(1) - - resolve_data = { - 'stream': data_stream - } - res = http.post( - 'http://www-ipv4.nos.nl/livestream/resolve/', - data=json.dumps(resolve_data) - ) - data = http.json(res) - - res = http.get(data['url']) - match = _js_re.search(res.text) - if not match: - return - - stream_url = parse_json(match.group(1)) - - return HLSStream.parse_variant_playlist(self.session, stream_url) + for video in itertags(res.text, 'video'): + stream_url = video.attributes.get("data-stream") + log.debug("Stream data: {0}".format(stream_url)) + return HLSStream.parse_variant_playlist(self.session, stream_url) def _get_source_streams(self): res = http.get(self.url) - streams = {} - sources = _source_re.findall(res.text) - for source in sources: - src = _source_src_re.search(source).group("src") - pixels = _source_type_re.search(source).group("type") - - streams[pixels] = HTTPStream(self.session, src) - - return streams + for atag in itertags(res.text, 'a'): + if "video-play__link" in atag.attributes.get("class", ""): + href = urljoin(self.url, atag.attributes.get("href")) + log.debug("Loading embedded video page") + vpage = http.get(href, params=dict(ajax="true", npo_cc_skip_wall="true")) + for source in itertags(vpage.text, 'source'): + return HLSStream.parse_variant_playlist(self.session, source.attributes.get("src")) def _get_streams(self): - urlparts = self.url.split('/') - - if urlparts[-2] == 'livestream' or urlparts[-3] == 'tour': + if "/livestream/" in self.url or "/tour/" in self.url: + log.debug("Finding live streams") return self._resolve_stream() else: + log.debug("Finding VOD streams") return self._get_source_streams() diff --git a/src/streamlink/plugins/pandatv.py b/src/streamlink/plugins/pandatv.py index 028ba111..56d7ab2a 100644 --- a/src/streamlink/plugins/pandatv.py +++ b/src/streamlink/plugins/pandatv.py @@ -6,7 +6,7 @@ import json from streamlink.compat import quote from streamlink.plugin import Plugin from streamlink.plugin.api import http, validate -from streamlink.stream import HTTPStream +from streamlink.stream import HTTPStream, HLSStream ROOM_API = "https://www.panda.tv/api_room_v3?token=&hostid={0}&roomid={1}&roomkey={2}&_={3}&param={4}&time={5}&sign={6}" ROOM_API_V2 = "https://www.panda.tv/api_room_v2?roomid={0}&_={1}" @@ -14,7 +14,7 @@ SD_URL_PATTERN = "https://pl{0}.live.panda.tv/live_panda/{1}.flv?sign={2}&ts={3} HD_URL_PATTERN = "https://pl{0}.live.panda.tv/live_panda/{1}_mid.flv?sign={2}&ts={3}&rid={4}" OD_URL_PATTERN = "https://pl{0}.live.panda.tv/live_panda/{1}_small.flv?sign={2}&ts={3}&rid={4}" -_url_re = re.compile(r"http(s)?://(\w+.)?panda.tv/(?P<channel>[^/&?]+)") +_url_re = re.compile(r"http(s)?://(?P<prefix>\w+.)?panda.tv/(?P<channel>[^/&?]+)") _room_id_re = re.compile(r'data-room-id="(\d+)"') _status_re = re.compile(r'"status"\s*:\s*"(\d+)"\s*,\s*"display_type"') _room_key_re = re.compile(r'"room_key"\s*:\s*"(.+?)"') @@ -25,6 +25,13 @@ _sign_re = re.compile(r'"sign"\s*:\s*"(.+?)"') _sd_re = re.compile(r'"SD"\s*:\s*"(\d+)"') _hd_re = re.compile(r'"HD"\s*:\s*"(\d+)"') _od_re = re.compile(r'"OD"\s*:\s*"(\d+)"') +_roominfo_re = re.compile(r'window\.HOSTINFO=({.*});') + +STREAM_WEIGHTS = { + "source": 1080, + "medium": 720, + "low": 480 +} _room_schema = validate.Schema( { @@ -44,25 +51,49 @@ _room_schema = validate.Schema( }, validate.get("data")) - class Pandatv(Plugin): @classmethod def can_handle_url(cls, url): return _url_re.match(url) + @classmethod + def stream_weight(cls, stream): + if stream in STREAM_WEIGHTS: + return STREAM_WEIGHTS[stream], "pandatv" + return Plugin.stream_weight(stream) + def _get_streams(self): match = _url_re.match(self.url) + prefix = match.group("prefix") channel = match.group("channel") res = http.get(self.url) + if prefix == 'xingyan.': + roominfo = _roominfo_re.search(res.text).group(1) + roominfo = json.loads(roominfo) + videoinfo = roominfo['videoinfo'] + if videoinfo['hlsurl']: + yield 'source', HLSStream(self.session, videoinfo['hlsurl']) + + #wangsu cdn prior to others, wangsu = 0, alicloud = 1, qcloud = videoinfo['streamurl'] + _cdn = 0 + if videoinfo['zl'][_cdn]['streamurl']: + yield 'source', HTTPStream(self.session, videoinfo['zl'][_cdn]['streamurl']) + if videoinfo['zl'][_cdn]['streamtrans']['mid']: + yield 'medium', HTTPStream(self.session, videoinfo['zl'][_cdn]['streamtrans']['mid']) + if videoinfo['zl'][_cdn]['streamtrans']['small']: + yield 'low', HTTPStream(self.session, videoinfo['zl'][_cdn]['streamtrans']['small']) + return + try: channel = int(channel) except ValueError: channel = _room_id_re.search(res.text).group(1) - ts = int(time.time()) - url = ROOM_API_V2.format(channel, ts) - res = http.get(url) + + ts = int(time.time()) + url = ROOM_API_V2.format(channel, ts) + res = http.get(url) try: status = _status_re.search(res.text).group(1) @@ -98,7 +129,6 @@ class Pandatv(Plugin): self.logger.info("Please Check PandaTV Room API") return - streams = {} plflag = videoinfo.get('plflag') if not plflag or '_' not in plflag: self.logger.info("Please Check PandaTV Room API") @@ -123,15 +153,15 @@ class Pandatv(Plugin): plflag1 = plflag0[0] if sd == '1': - streams['ehq'] = HTTPStream(self.session, SD_URL_PATTERN.format(plflag1, room_key, sign, ts, rid)) + yield 'source', HTTPStream(self.session, SD_URL_PATTERN.format(plflag1, room_key, sign, ts, rid)) if hd == '1': - streams['hq'] = HTTPStream(self.session, HD_URL_PATTERN.format(plflag1, room_key, sign, ts, rid)) + yield 'medium', HTTPStream(self.session, HD_URL_PATTERN.format(plflag1, room_key, sign, ts, rid)) if od == '1': - streams['sq'] = HTTPStream(self.session, OD_URL_PATTERN.format(plflag1, room_key, sign, ts, rid)) + yield 'low', HTTPStream(self.session, OD_URL_PATTERN.format(plflag1, room_key, sign, ts, rid)) - return streams + return __plugin__ = Pandatv diff --git a/src/streamlink/plugins/vrtbe.py b/src/streamlink/plugins/vrtbe.py index 4e298d55..f6a9f4b6 100644 --- a/src/streamlink/plugins/vrtbe.py +++ b/src/streamlink/plugins/vrtbe.py @@ -1,85 +1,92 @@ +import logging import re +from streamlink.compat import urljoin from streamlink.plugin import Plugin -from streamlink.plugin.api import http from streamlink.plugin.api import validate -from streamlink.stream import HDSStream -from streamlink.stream import HLSStream -from streamlink.utils import parse_json +from streamlink.plugin.api.utils import itertags +from streamlink.stream import HLSStream, DASHStream -_url_re = re.compile(r'''https?://www\.vrt\.be/vrtnu/(?:kanalen/(?P<channel>[^/]+)|\S+)''') -_json_re = re.compile(r'''(\173[^\173\175]+\175)''') +log = logging.getLogger(__name__) -API_LIVE = 'https://services.vrt.be/videoplayer/r/live.json' -API_VOD = 'https://mediazone.vrt.be/api/v1/{0}/assets/{1}' -_stream_schema = validate.Schema({ - 'targetUrls': [ - { - 'type': validate.text, - 'url': validate.text +class VRTbe(Plugin): + _url_re = re.compile(r'''https?://www\.vrt\.be/vrtnu/(?:kanalen/(?P<channel>[^/]+)|\S+)''') + + _stream_schema = validate.Schema( + validate.any({ + "code": validate.text, + "message": validate.text }, - ], -}) + { + "drm": validate.any(None, validate.text), + 'targetUrls': [{ + 'type': validate.text, + 'url': validate.text + }], + }) + ) + _token_schema = validate.Schema({ + "vrtPlayerToken": validate.text + }, validate.get("vrtPlayerToken")) + + api_url = "https://api.vuplay.co.uk/" -class VRTbe(Plugin): @classmethod def can_handle_url(cls, url): - return _url_re.match(url) + return cls._url_re.match(url) - def _get_live_stream(self, channel): - channel = 'vualto_{0}'.format(channel) - _live_json_re = re.compile(r'''"{0}":\s(\173[^\173\175]+\175)'''.format(channel)) + def _get_api_info(self, page): + for div in itertags(page.text, 'div'): + if div.attributes.get("class") == "vrtvideo": + api_base = div.attributes.get("data-mediaapiurl") + "/" - res = http.get(API_LIVE) - match = _live_json_re.search(res.text) - if not match: - return - data = parse_json(match.group(1)) + data = {"token_url": urljoin(api_base, "tokens")} + if div.attributes.get("data-videotype") == "live": + data["stream_url"] = urljoin(urljoin(api_base, "videos/"), div.attributes.get("data-livestream")) + else: + resource = "{0}%24{1}".format(div.attributes.get("data-publicationid"), div.attributes.get("data-videoid")) + data["stream_url"] = urljoin(urljoin(api_base, "videos/"), resource) + return data - hls_url = data['hls'] + def _get_streams(self): + page = self.session.http.get(self.url) + api_info = self._get_api_info(page) - if hls_url: - for s in HLSStream.parse_variant_playlist(self.session, hls_url).items(): - yield s + if not api_info: + log.error("Could not find API info in page") + return - def _get_vod_stream(self): - vod_url = self.url - if vod_url.endswith('/'): - vod_url = vod_url[:-1] + token_res = self.session.http.post(api_info["token_url"]) + token = self.session.http.json(token_res, schema=self._token_schema) - json_url = '{0}.securevideo.json'.format(vod_url) + log.debug("Got token: {0}".format(token)) + log.debug("Getting stream data: {0}".format(api_info["stream_url"])) + res = self.session.http.get(api_info["stream_url"], + params={ + "vrtPlayerToken": token, + "client": "vrtvideo" + }, raise_for_status=False) + data = self.session.http.json(res, schema=self._stream_schema) - res = http.get(json_url) - match = _json_re.search(res.text) - if not match: + if "code" in data: + log.error("{0} ({1})".format(data['message'], data['code'])) return - data = parse_json(match.group(1)) - res = http.get(API_VOD.format(data['clientid'], data['mzid'])) - data = http.json(res, schema=_stream_schema) + log.debug("Streams have {0}DRM".format("no " if not data["drm"] else "")) - for d in data['targetUrls']: - if d['type'] == 'HDS': - hds_url = d['url'] - for s in HDSStream.parse_manifest(self.session, hds_url).items(): + for target in data["targetUrls"]: + if data["drm"]: + if target["type"] == "hls_aes": + for s in HLSStream.parse_variant_playlist(self.session, target["url"]).items(): + yield s + elif target["type"] == "hls": + for s in HLSStream.parse_variant_playlist(self.session, target["url"]).items(): yield s - - if d['type'] == 'HLS': - hls_url = d['url'] - for s in HLSStream.parse_variant_playlist(self.session, hls_url).items(): + elif target["type"] == "mpeg_dash": + for s in DASHStream.parse_manifest(self.session, target["url"]).items(): yield s - def _get_streams(self): - match = _url_re.match(self.url) - - channel = match.group('channel') - - if channel: - return self._get_live_stream(channel) - else: - return self._get_vod_stream() - __plugin__ = VRTbe diff --git a/src/streamlink/stream/dash_manifest.py b/src/streamlink/stream/dash_manifest.py index 496e1b69..5477347e 100644 --- a/src/streamlink/stream/dash_manifest.py +++ b/src/streamlink/stream/dash_manifest.py @@ -488,7 +488,7 @@ class SegmentTemplate(MPDNode): else: for segment, n in zip(self.segmentTimeline.segments, count(self.startNumber)): yield (self.make_url(self.media(Time=segment.t, Number=n, **kwargs)), - datetime.timedelta(seconds=segment.d / self.timescale)) + datetime.datetime.now(tz=utc)) else: for number, available_at in self.segment_numbers():
streamlink/streamlink
933126d6a9b15fa2ca019c1b559e5136b9c5c575
diff --git a/tests/test_plugin_lrt.py b/tests/test_plugin_lrt.py new file mode 100644 index 00000000..c7d4476c --- /dev/null +++ b/tests/test_plugin_lrt.py @@ -0,0 +1,24 @@ +import unittest + +from streamlink.plugins.lrt import LRT + + +class TestPluginLRT(unittest.TestCase): + def test_can_handle_url(self): + should_match = [ + "https://www.lrt.lt/mediateka/tiesiogiai/lrt-televizija", + "https://www.lrt.lt/mediateka/tiesiogiai/lrt-kultura", + "https://www.lrt.lt/mediateka/tiesiogiai/lrt-lituanica" + "https://www.lrt.lt/mediateka/irasas/1013694276/savanoriai-tures-galimybe-pamatyti-popieziu-is-arciau#wowzaplaystart=1511000&wowzaplayduration=168000" + ] + for url in should_match: + self.assertTrue(LRT.can_handle_url(url)) + + def test_can_handle_url_negative(self): + should_not_match = [ + "https://www.lrt.lt", + "https://www.youtube.com", + + ] + for url in should_not_match: + self.assertFalse(LRT.can_handle_url(url))
Error with nos.nl plugin ### Checklist - [x] This is a bug report. - [ ] This is a feature request. - [ ] This is a plugin (improvement) request. - [x] I have read the contribution guidelines. ### Description When I try to open a nos.nl live stream this is the output I get: ``` $ streamlink https://nos.nl/livestream/2236311 [cli][info] Found matching plugin nos for URL https://nos.nl/livestream/2236311 error: Unable to open URL: http://www-ipv4.nos.nl/livestream/resolve/ (404 Client Error: Not Found for url: http://www-ipv4.nos.nl/livestream/resolve/) ``` ### Expected / Actual behavior I have a Netherlands IP and I expect to see the stream like in the web browser. ### Reproduction steps / Explicit stream URLs to test 1. streamlink https://nos.nl/livestream/2236311 2. streamlink https://nos.nl/livestream/npo-politiek.html ### Logs ``` [cli][debug] OS: Linux-4.16.13-2-ARCH-x86_64-with-arch-Arch-Linux [cli][debug] Python: 3.6.5 [cli][debug] Streamlink: 0.13.0+35.g933126d6 [cli][debug] Requests(2.19.1), Socks(1.6.7), Websocket(0.48.0) [cli][info] Found matching plugin nos for URL https://nos.nl/livestream/2236311 error: Unable to open URL: http://www-ipv4.nos.nl/livestream/resolve/ (404 Client Error: Not Found for url: http://www-ipv4.nos.nl/livestream/resolve/) ```
0.0
933126d6a9b15fa2ca019c1b559e5136b9c5c575
[ "tests/test_plugin_lrt.py::TestPluginLRT::test_can_handle_url", "tests/test_plugin_lrt.py::TestPluginLRT::test_can_handle_url_negative" ]
[]
{ "failed_lite_validators": [ "has_hyperlinks", "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2018-06-17 22:36:19+00:00
bsd-2-clause
5,764
streamlink__streamlink-1814
diff --git a/docs/plugin_matrix.rst b/docs/plugin_matrix.rst index e6cd82c6..13134a95 100644 --- a/docs/plugin_matrix.rst +++ b/docs/plugin_matrix.rst @@ -113,6 +113,7 @@ liveedu - liveedu.tv Yes -- Some streams require a - livecoding.tv liveme liveme.com Yes -- livestream new.livestream.com Yes -- +lrt lrt.lt Yes No media_ccc_de - media.ccc.de Yes Yes Only mp4 and HLS are supported. - streaming... [4]_ mediaklikk mediaklikk.hu Yes No Streams may be geo-restricted to Hungary. diff --git a/src/streamlink/plugins/lrt.py b/src/streamlink/plugins/lrt.py new file mode 100644 index 00000000..2ab41b49 --- /dev/null +++ b/src/streamlink/plugins/lrt.py @@ -0,0 +1,43 @@ +import logging +import re +from functools import partial + +from streamlink.plugin import Plugin +from streamlink.plugin.api import http +from streamlink.stream import HLSStream +from streamlink.utils import parse_json +from streamlink.compat import urlparse + +log = logging.getLogger(__name__) + + +class LRT(Plugin): + _url_re = re.compile(r"https?://(?:www\.)?lrt.lt/mediateka/.") + _source_re = re.compile(r'sources\s*:\s*(\[{.*?}\]),', re.DOTALL | re.IGNORECASE) + js_to_json = partial(re.compile(r'(?!<")(\w+)\s*:\s*(["\']|\d?\.?\d+,|true|false|\[|{)').sub, r'"\1":\2') + + + @classmethod + def can_handle_url(cls, url): + return cls._url_re.match(url) + + def _get_streams(self): + page = http.get(self.url) + m = self._source_re.search(page.text) + if m: + params = "" + data = m.group(1) + log.debug("Source data: {0}".format(data)) + if "location.hash.substring" in data: + log.debug("Removing hash substring addition") + data = re.sub(r"\s*\+\s*location.hash.substring\(\d+\)", "", data) + params = urlparse(self.url).fragment + data = self.js_to_json(data) + for stream in parse_json(data): + for s in HLSStream.parse_variant_playlist(self.session, stream['file'], params=params).items(): + yield s + else: + log.debug("No match for sources regex") + + +__plugin__ = LRT
streamlink/streamlink
933126d6a9b15fa2ca019c1b559e5136b9c5c575
diff --git a/tests/test_plugin_lrt.py b/tests/test_plugin_lrt.py new file mode 100644 index 00000000..c7d4476c --- /dev/null +++ b/tests/test_plugin_lrt.py @@ -0,0 +1,24 @@ +import unittest + +from streamlink.plugins.lrt import LRT + + +class TestPluginLRT(unittest.TestCase): + def test_can_handle_url(self): + should_match = [ + "https://www.lrt.lt/mediateka/tiesiogiai/lrt-televizija", + "https://www.lrt.lt/mediateka/tiesiogiai/lrt-kultura", + "https://www.lrt.lt/mediateka/tiesiogiai/lrt-lituanica" + "https://www.lrt.lt/mediateka/irasas/1013694276/savanoriai-tures-galimybe-pamatyti-popieziu-is-arciau#wowzaplaystart=1511000&wowzaplayduration=168000" + ] + for url in should_match: + self.assertTrue(LRT.can_handle_url(url)) + + def test_can_handle_url_negative(self): + should_not_match = [ + "https://www.lrt.lt", + "https://www.youtube.com", + + ] + for url in should_not_match: + self.assertFalse(LRT.can_handle_url(url))
[plugn request] lrt.lt ### Checklist - [ ] This is a bug report. - [ ] This is a feature request. - [x] This is a plugin (improvement) request. - [x] I have read the contribution guidelines. ### Description Would it be possible to add a plugin for the Lithuanian National Television? Video streams are located [here](https://www.lrt.lt/mediateka/tiesiogiai/lrt-televizija), [here](https://www.lrt.lt/mediateka/tiesiogiai/lrt-kultura) and [here](https://www.lrt.lt/mediateka/tiesiogiai/lrt-lituanica). Thanks.
0.0
933126d6a9b15fa2ca019c1b559e5136b9c5c575
[ "tests/test_plugin_lrt.py::TestPluginLRT::test_can_handle_url", "tests/test_plugin_lrt.py::TestPluginLRT::test_can_handle_url_negative" ]
[]
{ "failed_lite_validators": [ "has_hyperlinks", "has_added_files" ], "has_test_patch": true, "is_lite": false }
2018-06-17 23:19:56+00:00
bsd-2-clause
5,765
streamlink__streamlink-1844
diff --git a/src/streamlink/plugins/atresplayer.py b/src/streamlink/plugins/atresplayer.py index 45702cfb..b0c4f15d 100644 --- a/src/streamlink/plugins/atresplayer.py +++ b/src/streamlink/plugins/atresplayer.py @@ -1,38 +1,56 @@ from __future__ import print_function + +import logging import re -import time -import random from streamlink.plugin import Plugin -from streamlink.plugin.api import http -from streamlink.plugin.api import validate -from streamlink.stream import HDSStream +from streamlink.plugin.api import http, validate +from streamlink.stream import HLSStream +from streamlink.utils import parse_json, update_scheme + +log = logging.getLogger(__name__) class AtresPlayer(Plugin): - url_re = re.compile(r"https?://(?:www.)?atresplayer.com/directos/television/(\w+)/?") - player_re = re.compile(r"""div.*?directo=(\d+)""") - stream_api = "https://servicios.atresplayer.com/api/urlVideoLanguage/v3/{id}/web/{id}|{time}|{hash}/es.xml" - manifest_re = re.compile(r"<resultDes>(.*?)</resultDes>") + url_re = re.compile(r"https?://(?:www.)?atresplayer.com/directos/([\w-]+)/?") + state_re = re.compile(r"""window.__PRELOADED_STATE__\s*=\s*({.*?});""", re.DOTALL) + channel_id_schema = validate.Schema( + validate.transform(state_re.search), + validate.any( + None, + validate.all( + validate.get(1), + validate.transform(parse_json), + { + "programming": { + validate.text: validate.all({"urlVideo": validate.text}, + validate.get("urlVideo")) + } + }, + validate.get("programming") + ))) + stream_schema = validate.Schema( + validate.transform(parse_json), + {"sources": [ + validate.all({"src": validate.url()}, + validate.get("src")) + ]}, validate.get("sources")) + @classmethod def can_handle_url(cls, url): return cls.url_re.match(url) is not None + def __init__(self, url): + # must be HTTPS + super(AtresPlayer, self).__init__(update_scheme("https://", url)) + def _get_streams(self): - res = http.get(self.url) - match = self.player_re.search(res.text) - if match: - channel_id = match.group(1) - - stream_api = self.stream_api.format(id=channel_id, - time=int(time.time()), - hash=''.join(random.choice("abcdef0123456789") for x in range(28))) - - res = http.get(stream_api) - f4m_url = self.manifest_re.search(res.text) - if f4m_url: - return HDSStream.parse_manifest(self.session, f4m_url.group(1)) + programming = http.get(self.url, schema=self.channel_id_schema) + for api_url in programming.values(): + for src in http.get(api_url, schema=self.stream_schema): + for s in HLSStream.parse_variant_playlist(self.session, src).items(): + yield s __plugin__ = AtresPlayer diff --git a/src/streamlink/plugins/mitele.py b/src/streamlink/plugins/mitele.py index f2e7b7c9..8d0bd47d 100644 --- a/src/streamlink/plugins/mitele.py +++ b/src/streamlink/plugins/mitele.py @@ -31,7 +31,7 @@ class Mitele(Plugin): "telecinco": livehlsdai, } - pdata_url = "https://indalo.mediaset.es/mmc-player/api/mmc/v1/{channel}/live/flash.json" + pdata_url = "https://indalo.mediaset.es/mmc-player/api/mmc/v1/{channel}/live/html5.json" gate_url = "https://gatekeeper.mediaset.es" pdata_schema = validate.Schema( @@ -39,7 +39,7 @@ class Mitele(Plugin): { "locations": [{ "gcp": validate.text, - "ogn": validate.text, + "ogn": validate.any(None, validate.text), }], }, validate.get("locations"), @@ -117,7 +117,7 @@ class Mitele(Plugin): if hls_url: self.logger.debug("HLS URL: {0}".format(hls_url)) - for s in HLSStream.parse_variant_playlist(self.session, hls_url, headers=self.headers).items(): + for s in HLSStream.parse_variant_playlist(self.session, hls_url, headers=self.headers, name_fmt="{pixels}_{bitrate}").items(): yield s diff --git a/src/streamlink/stream/dash.py b/src/streamlink/stream/dash.py index 562190a1..aa0a72fa 100644 --- a/src/streamlink/stream/dash.py +++ b/src/streamlink/stream/dash.py @@ -60,10 +60,10 @@ class DASHStreamWorker(SegmentedStreamWorker): self.period = self.stream.period @staticmethod - def get_representation(mpd, representation_id): + def get_representation(mpd, representation_id, mime_type): for aset in mpd.periods[0].adaptationSets: for rep in aset.representations: - if rep.id == representation_id: + if rep.id == representation_id and rep.mimeType == mime_type: return rep def iter_segments(self): @@ -71,7 +71,7 @@ class DASHStreamWorker(SegmentedStreamWorker): back_off_factor = 1 while not self.closed: # find the representation by ID - representation = self.get_representation(self.mpd, self.reader.representation_id) + representation = self.get_representation(self.mpd, self.reader.representation_id, self.reader.mime_type) refresh_wait = max(self.mpd.minimumUpdatePeriod.total_seconds(), self.mpd.periods[0].duration.total_seconds()) or 5 with sleeper(refresh_wait * back_off_factor): @@ -96,7 +96,7 @@ class DASHStreamWorker(SegmentedStreamWorker): return self.reader.buffer.wait_free() - log.debug("Reloading manifest ({0})".format(self.reader.representation_id)) + log.debug("Reloading manifest ({0}:{1})".format(self.reader.representation_id, self.reader.mime_type)) res = self.session.http.get(self.mpd.url, exception=StreamError) new_mpd = MPD(self.session.http.xml(res, ignore_ns=True), @@ -104,7 +104,7 @@ class DASHStreamWorker(SegmentedStreamWorker): url=self.mpd.url, timelines=self.mpd.timelines) - new_rep = self.get_representation(new_mpd, self.reader.representation_id) + new_rep = self.get_representation(new_mpd, self.reader.representation_id, self.reader.mime_type) with freeze_timeline(new_mpd): changed = len(list(itertools.islice(new_rep.segments(), 1))) > 0 @@ -118,10 +118,11 @@ class DASHStreamReader(SegmentedStreamReader): __worker__ = DASHStreamWorker __writer__ = DASHStreamWriter - def __init__(self, stream, representation_id, *args, **kwargs): + def __init__(self, stream, representation_id, mime_type, *args, **kwargs): SegmentedStreamReader.__init__(self, stream, *args, **kwargs) + self.mime_type = mime_type self.representation_id = representation_id - log.debug("Opening DASH reader for: {0}".format(self.representation_id)) + log.debug("Opening DASH reader for: {0} ({1})".format(self.representation_id, self.mime_type)) @@ -198,11 +199,11 @@ class DASHStream(Stream): def open(self): if self.video_representation: - video = DASHStreamReader(self, self.video_representation.id) + video = DASHStreamReader(self, self.video_representation.id, self.video_representation.mimeType) video.open() if self.audio_representation: - audio = DASHStreamReader(self, self.audio_representation.id) + audio = DASHStreamReader(self, self.audio_representation.id, self.audio_representation.mimeType) audio.open() if self.video_representation and self.audio_representation:
streamlink/streamlink
7ec020b6cc3802d4e199fc5ed409b56b7314a952
diff --git a/tests/streams/test_dash.py b/tests/streams/test_dash.py index ff489f7e..3b462004 100644 --- a/tests/streams/test_dash.py +++ b/tests/streams/test_dash.py @@ -107,39 +107,39 @@ class TestDASHStream(unittest.TestCase): @patch('streamlink.stream.dash.DASHStreamReader') @patch('streamlink.stream.dash.FFMPEGMuxer') def test_stream_open_video_only(self, muxer, reader): - stream = DASHStream(self.session, Mock(), Mock(id=1)) + stream = DASHStream(self.session, Mock(), Mock(id=1, mimeType="video/mp4")) open_reader = reader.return_value = Mock() stream.open() - reader.assert_called_with(stream, 1) + reader.assert_called_with(stream, 1, "video/mp4") open_reader.open.assert_called_with() muxer.assert_not_called() @patch('streamlink.stream.dash.DASHStreamReader') @patch('streamlink.stream.dash.FFMPEGMuxer') def test_stream_open_video_audio(self, muxer, reader): - stream = DASHStream(self.session, Mock(), Mock(id=1), Mock(id=2)) + stream = DASHStream(self.session, Mock(), Mock(id=1, mimeType="video/mp4"), Mock(id=2, mimeType="audio/mp3")) open_reader = reader.return_value = Mock() stream.open() - self.assertSequenceEqual(reader.mock_calls, [call(stream, 1), + self.assertSequenceEqual(reader.mock_calls, [call(stream, 1, "video/mp4"), call().open(), - call(stream, 2), + call(stream, 2, "audio/mp3"), call().open()]) self.assertSequenceEqual(muxer.mock_calls, [call(self.session, open_reader, open_reader, copyts=True), call().open()]) class TestDASHStreamWorker(unittest.TestCase): - @patch("streamlink.stream.dash_manifest.time.sleep") @patch('streamlink.stream.dash.MPD') def test_dynamic_reload(self, mpdClass, sleep): reader = MagicMock() worker = DASHStreamWorker(reader) reader.representation_id = 1 + reader.mime_type = "video/mp4" representation = Mock(id=1, mimeType="video/mp4", height=720) segments = [Mock(url="init_segment"), Mock(url="first_segment"), Mock(url="second_segment")] @@ -173,6 +173,7 @@ class TestDASHStreamWorker(unittest.TestCase): reader = MagicMock() worker = DASHStreamWorker(reader) reader.representation_id = 1 + reader.mime_type = "video/mp4" representation = Mock(id=1, mimeType="video/mp4", height=720) segments = [Mock(url="init_segment"), Mock(url="first_segment"), Mock(url="second_segment")] @@ -195,6 +196,29 @@ class TestDASHStreamWorker(unittest.TestCase): self.assertSequenceEqual(list(worker.iter_segments()), segments) representation.segments.assert_called_with(init=True) + @patch("streamlink.stream.dash_manifest.time.sleep") + def test_duplicate_rep_id(self, sleep): + representation_vid = Mock(id=1, mimeType="video/mp4", height=720) + representation_aud = Mock(id=1, mimeType="audio/aac") + + mpd = Mock(dynamic=False, + publishTime=1, + periods=[ + Mock(adaptationSets=[ + Mock(contentProtection=None, + representations=[ + representation_vid + ]), + Mock(contentProtection=None, + representations=[ + representation_aud + ]) + ]) + ]) + + self.assertEqual(representation_vid, DASHStreamWorker.get_representation(mpd, 1, "video/mp4")) + self.assertEqual(representation_aud, DASHStreamWorker.get_representation(mpd, 1, "audio/aac")) + if __name__ == "__main__": unittest.main()
Atresplayer ### Checklist - [x] This is a bug report. - [ ] This is a feature request. - [ ] This is a plugin (improvement) request. - [ ] I have read the contribution guidelines. ### Description Links Live: https://www.atresplayer.com/directos/antena3/ https://www.atresplayer.com/directos/lasexta/ https://www.atresplayer.com/directos/neox/ https://www.atresplayer.com/directos/nova/ https://www.atresplayer.com/directos/mega/ https://www.atresplayer.com/directos/atreseries/ ``` streamlink.exe https://www.atresplayer.com/directos/antena3/ best --player ffplay -l debug [console][debug] OS: Windows 7 [console][debug] Python: 3.5.2 [console][debug] Streamlink: 0.13.0 [console][debug] Requests(2.18.4), Socks(1.6.7), Websocket(0.48.0) error: No plugin can handle URL: https://www.atresplayer.com/directos/antena3/ ``` *I have executed the same command with the six links. Sorry for English, I do not speak it.
0.0
7ec020b6cc3802d4e199fc5ed409b56b7314a952
[ "tests/streams/test_dash.py::TestDASHStream::test_stream_open_video_audio", "tests/streams/test_dash.py::TestDASHStream::test_stream_open_video_only", "tests/streams/test_dash.py::TestDASHStreamWorker::test_duplicate_rep_id" ]
[ "tests/streams/test_dash.py::TestDASHStream::test_parse_manifest_audio_multi", "tests/streams/test_dash.py::TestDASHStream::test_parse_manifest_audio_only", "tests/streams/test_dash.py::TestDASHStream::test_parse_manifest_audio_single", "tests/streams/test_dash.py::TestDASHStream::test_parse_manifest_drm", "tests/streams/test_dash.py::TestDASHStream::test_parse_manifest_video_only", "tests/streams/test_dash.py::TestDASHStreamWorker::test_dynamic_reload", "tests/streams/test_dash.py::TestDASHStreamWorker::test_static" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2018-06-25 21:51:59+00:00
bsd-2-clause
5,766
streamlink__streamlink-1927
diff --git a/.travis.yml b/.travis.yml index 0da9dd5e..d60852f6 100644 --- a/.travis.yml +++ b/.travis.yml @@ -12,9 +12,14 @@ matrix: - python: '3.5' env: BUILD_DOCS=yes BUILD_INSTALLER=yes BUILD_SDIST=yes DEPLOY_PYPI=yes - python: '3.6' - - python: '3.7-dev' + - python: '3.7' + dist: xenial + sudo: true + - python: '3.8-dev' + dist: xenial + sudo: true allow_failures: - - python: '3.7-dev' + - python: '3.8-dev' before_install: - pip install --disable-pip-version-check --upgrade pip setuptools diff --git a/appveyor.yml b/appveyor.yml index c40ae00f..1b26ac10 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -5,10 +5,12 @@ environment: - PYTHON: "C:\\Python34" - PYTHON: "C:\\Python35" - PYTHON: "C:\\Python36" + - PYTHON: "C:\\Python37" - PYTHON: "C:\\Python27-x64" - PYTHON: "C:\\Python34-x64" - PYTHON: "C:\\Python35-x64" - PYTHON: "C:\\Python36-x64" + - PYTHON: "C:\\Python37-x64" install: # If there is a newer build queued for the same PR, cancel this one. diff --git a/src/streamlink/stream/dash.py b/src/streamlink/stream/dash.py index e202e53b..1d1c5b65 100644 --- a/src/streamlink/stream/dash.py +++ b/src/streamlink/stream/dash.py @@ -11,6 +11,7 @@ from streamlink.stream.stream import Stream from streamlink.stream.dash_manifest import MPD, sleeper, sleep_until, utc, freeze_timeline from streamlink.stream.ffmpegmux import FFMPEGMuxer from streamlink.stream.segmented import SegmentedStreamReader, SegmentedStreamWorker, SegmentedStreamWriter +from streamlink.utils.l10n import Language log = logging.getLogger(__name__) @@ -196,6 +197,31 @@ class DASHStream(Stream): if not audio: audio = [None] + locale = session.localization + locale_lang = locale.language + lang = None + available_languages = set() + + # if the locale is explicitly set, prefer that language over others + for aud in audio: + if aud and aud.lang: + available_languages.add(aud.lang) + try: + if locale.explicit and aud.lang and Language.get(aud.lang) == locale_lang: + lang = aud.lang + except LookupError: + continue + + if not lang: + # filter by the first language that appears + lang = audio[0] and audio[0].lang + + log.debug("Available languages for DASH audio streams: {0} (using: {1})".format(", ".join(available_languages) or "NONE", lang or "n/a")) + + # if the language is given by the stream, filter out other languages that do not match + if len(available_languages) > 1: + audio = list(filter(lambda a: a.lang is None or a.lang == lang, audio)) + for vid, aud in itertools.product(video, audio): stream = DASHStream(session, mpd, vid, aud, **args) stream_name = [] diff --git a/src/streamlink/stream/hls.py b/src/streamlink/stream/hls.py index 1faba0ae..0fe12ad5 100644 --- a/src/streamlink/stream/hls.py +++ b/src/streamlink/stream/hls.py @@ -295,15 +295,18 @@ class MuxedHLSStream(MuxedStream): def __init__(self, session, video, audio, force_restart=False, ffmpeg_options=None, **args): tracks = [video] + maps = ["0:v"] if audio: if isinstance(audio, list): tracks.extend(audio) else: tracks.append(audio) + for i in range(1, len(tracks)): + maps.append("{0}:a".format(i)) substreams = map(lambda url: HLSStream(session, url, force_restart=force_restart, **args), tracks) ffmpeg_options = ffmpeg_options or {} - super(MuxedHLSStream, self).__init__(session, *substreams, format="mpegts", **ffmpeg_options) + super(MuxedHLSStream, self).__init__(session, *substreams, format="mpegts", maps=maps, **ffmpeg_options) class HLSStream(HTTPStream): diff --git a/src/streamlink/utils/l10n.py b/src/streamlink/utils/l10n.py index 0164c7cd..ef4eb8a1 100644 --- a/src/streamlink/utils/l10n.py +++ b/src/streamlink/utils/l10n.py @@ -1,4 +1,5 @@ import locale +import logging from streamlink.compat import is_py2 @@ -16,6 +17,8 @@ DEFAULT_LANGUAGE = "en" DEFAULT_COUNTRY = "US" DEFAULT_LANGUAGE_CODE = "{0}_{1}".format(DEFAULT_LANGUAGE, DEFAULT_COUNTRY) +log = logging.getLogger(__name__) + class Country(object): def __init__(self, alpha2, alpha3, numeric, name, official_name=None): @@ -147,6 +150,7 @@ class Localization(object): self._language_code = DEFAULT_LANGUAGE_CODE else: raise + log.debug("Language code: {0}".format(self._language_code)) def equivalent(self, language=None, country=None): equivalent = True
streamlink/streamlink
6bf654a291e2a792088384c7ba7c9dc9b2a14b1d
diff --git a/tests/streams/test_dash.py b/tests/streams/test_dash.py index 807b8a18..cf406185 100644 --- a/tests/streams/test_dash.py +++ b/tests/streams/test_dash.py @@ -1,7 +1,4 @@ import unittest -import unittest -from streamlink.stream.dash import DASHStreamWorker -from tests.mock import MagicMock, patch, ANY, Mock, call from streamlink import PluginError from streamlink.stream import * @@ -41,8 +38,8 @@ class TestDASHStream(unittest.TestCase): Mock(adaptationSets=[ Mock(contentProtection=None, representations=[ - Mock(id=1, mimeType="audio/mp4", bandwidth=128.0), - Mock(id=2, mimeType="audio/mp4", bandwidth=256.0) + Mock(id=1, mimeType="audio/mp4", bandwidth=128.0, lang='en'), + Mock(id=2, mimeType="audio/mp4", bandwidth=256.0, lang='en') ]) ]) ]) @@ -63,7 +60,7 @@ class TestDASHStream(unittest.TestCase): representations=[ Mock(id=1, mimeType="video/mp4", height=720), Mock(id=2, mimeType="video/mp4", height=1080), - Mock(id=3, mimeType="audio/aac", bandwidth=128.0) + Mock(id=3, mimeType="audio/aac", bandwidth=128.0, lang='en') ]) ]) ]) @@ -84,8 +81,8 @@ class TestDASHStream(unittest.TestCase): representations=[ Mock(id=1, mimeType="video/mp4", height=720), Mock(id=2, mimeType="video/mp4", height=1080), - Mock(id=3, mimeType="audio/aac", bandwidth=128.0), - Mock(id=4, mimeType="audio/aac", bandwidth=256.0) + Mock(id=3, mimeType="audio/aac", bandwidth=128.0, lang='en'), + Mock(id=4, mimeType="audio/aac", bandwidth=256.0, lang='en') ]) ]) ]) @@ -98,6 +95,108 @@ class TestDASHStream(unittest.TestCase): sorted(["720p+a128k", "1080p+a128k", "720p+a256k", "1080p+a256k"]) ) + @patch('streamlink.stream.dash.MPD') + def test_parse_manifest_audio_multi_lang(self, mpdClass): + mpd = mpdClass.return_value = Mock(periods=[ + Mock(adaptationSets=[ + Mock(contentProtection=None, + representations=[ + Mock(id=1, mimeType="video/mp4", height=720), + Mock(id=2, mimeType="video/mp4", height=1080), + Mock(id=3, mimeType="audio/aac", bandwidth=128.0, lang='en'), + Mock(id=4, mimeType="audio/aac", bandwidth=128.0, lang='es') + ]) + ]) + ]) + + streams = DASHStream.parse_manifest(self.session, self.test_url) + mpdClass.assert_called_with(ANY, base_url="http://test.bar", url="http://test.bar/foo.mpd") + + self.assertSequenceEqual( + sorted(list(streams.keys())), + sorted(["720p", "1080p"]) + ) + + self.assertEqual(streams["720p"].audio_representation.lang, "en") + self.assertEqual(streams["1080p"].audio_representation.lang, "en") + + @patch('streamlink.stream.dash.MPD') + def test_parse_manifest_audio_multi_lang_alpha3(self, mpdClass): + mpd = mpdClass.return_value = Mock(periods=[ + Mock(adaptationSets=[ + Mock(contentProtection=None, + representations=[ + Mock(id=1, mimeType="video/mp4", height=720), + Mock(id=2, mimeType="video/mp4", height=1080), + Mock(id=3, mimeType="audio/aac", bandwidth=128.0, lang='eng'), + Mock(id=4, mimeType="audio/aac", bandwidth=128.0, lang='spa') + ]) + ]) + ]) + + streams = DASHStream.parse_manifest(self.session, self.test_url) + mpdClass.assert_called_with(ANY, base_url="http://test.bar", url="http://test.bar/foo.mpd") + + self.assertSequenceEqual( + sorted(list(streams.keys())), + sorted(["720p", "1080p"]) + ) + + self.assertEqual(streams["720p"].audio_representation.lang, "eng") + self.assertEqual(streams["1080p"].audio_representation.lang, "eng") + + @patch('streamlink.stream.dash.MPD') + def test_parse_manifest_audio_invalid_lang(self, mpdClass): + mpd = mpdClass.return_value = Mock(periods=[ + Mock(adaptationSets=[ + Mock(contentProtection=None, + representations=[ + Mock(id=1, mimeType="video/mp4", height=720), + Mock(id=2, mimeType="video/mp4", height=1080), + Mock(id=3, mimeType="audio/aac", bandwidth=128.0, lang='en_no_voice'), + ]) + ]) + ]) + + streams = DASHStream.parse_manifest(self.session, self.test_url) + mpdClass.assert_called_with(ANY, base_url="http://test.bar", url="http://test.bar/foo.mpd") + + self.assertSequenceEqual( + sorted(list(streams.keys())), + sorted(["720p", "1080p"]) + ) + + self.assertEqual(streams["720p"].audio_representation.lang, "en_no_voice") + self.assertEqual(streams["1080p"].audio_representation.lang, "en_no_voice") + + @patch('streamlink.stream.dash.MPD') + def test_parse_manifest_audio_multi_lang_locale(self, mpdClass): + self.session.localization.language.alpha2 = "es" + self.session.localization.explicit = True + + mpd = mpdClass.return_value = Mock(periods=[ + Mock(adaptationSets=[ + Mock(contentProtection=None, + representations=[ + Mock(id=1, mimeType="video/mp4", height=720), + Mock(id=2, mimeType="video/mp4", height=1080), + Mock(id=3, mimeType="audio/aac", bandwidth=128.0, lang='en'), + Mock(id=4, mimeType="audio/aac", bandwidth=128.0, lang='es') + ]) + ]) + ]) + + streams = DASHStream.parse_manifest(self.session, self.test_url) + mpdClass.assert_called_with(ANY, base_url="http://test.bar", url="http://test.bar/foo.mpd") + + self.assertSequenceEqual( + sorted(list(streams.keys())), + sorted(["720p", "1080p"]) + ) + + self.assertEqual(streams["720p"].audio_representation.lang, "es") + self.assertEqual(streams["1080p"].audio_representation.lang, "es") + @patch('streamlink.stream.dash.MPD') def test_parse_manifest_drm(self, mpdClass): mpd = mpdClass.return_value = Mock(periods=[Mock(adaptationSets=[Mock(contentProtection="DRM")])]) @@ -122,7 +221,7 @@ class TestDASHStream(unittest.TestCase): @patch('streamlink.stream.dash.DASHStreamReader') @patch('streamlink.stream.dash.FFMPEGMuxer') 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")) + 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() @@ -202,7 +301,7 @@ class TestDASHStreamWorker(unittest.TestCase): @patch("streamlink.stream.dash_manifest.time.sleep") def test_duplicate_rep_id(self, sleep): representation_vid = Mock(id=1, mimeType="video/mp4", height=720) - representation_aud = Mock(id=1, mimeType="audio/aac") + representation_aud = Mock(id=1, mimeType="audio/aac", lang='en') mpd = Mock(dynamic=False, publishTime=1,
Audio Spanish I don't hear this video in Spanish, why?, Is there any way I can keep it from being heard in English? ``` https://www.atresplayer.com/antena3/series/el-cuento-de-la-criada/temporada-1/capitulo-6-el-lugar-de-la-mujer_5b364bee7ed1a8dd360b5b7b/ ``` ### Logs ``` "C:\Program Files (x86)\Streamlink\bin\streamlink.exe" h ttps://www.atresplayer.com/antena3/series/el-cuento-de-la-criada/temporada-1/cap itulo-6-el-lugar-de-la-mujer_5b364bee7ed1a8dd360b5b7b/ best --player ffplay -l d ebug [cli][debug] OS: Windows 7 [cli][debug] Python: 3.5.2 [cli][debug] Streamlink: 0.14.2 [cli][debug] Requests(2.19.1), Socks(1.6.7), Websocket(0.48.0) [cli][info] Found matching plugin atresplayer for URL https://www.atresplayer.co m/antena3/series/el-cuento-de-la-criada/temporada-1/capitulo-6-el-lugar-de-la-mu jer_5b364bee7ed1a8dd360b5b7b/ [plugin.atresplayer][debug] API URL: https://api.atresplayer.com/client/v1/playe r/episode/5b364bee7ed1a8dd360b5b7b [plugin.atresplayer][debug] Stream source: https://geodeswowa3player.akamaized.n et/vcg/_definst_/assets4/2018/06/29/7875368D-BF45-4012-9EBC-C4F78984B672/hls.smi l/playlist.m3u8?pulse=assets4%2F2018%2F06%2F29%2F7875368D-BF45-4012-9EBC-C4F7898 4B672%2F%7C1531195580%7Cb6e79f7291966a25070a79138cd19cb9 (application/vnd.apple. mpegurl) [stream.hls][debug] Using external audio tracks for stream 1080p (language=es, n ame=Spanish) [stream.hls][debug] Using external audio tracks for stream 720p (language=es, na me=Spanish) [stream.hls][debug] Using external audio tracks for stream 480p (language=es, na me=Spanish) [stream.hls][debug] Using external audio tracks for stream 360p (language=es, na me=Spanish) [stream.hls][debug] Using external audio tracks for stream 240p (language=es, na me=Spanish) [plugin.atresplayer][debug] Stream source: https://geodeswowa3player.akamaized.n et/vcg/_definst_/assets4/2018/06/29/7875368D-BF45-4012-9EBC-C4F78984B672/dash.sm il/manifest_mvlist.mpd (application/dash+xml) [cli][info] Available streams: 240p (worst), 240p+a128k, 360p, 360p+a128k, 480p, 480p+a128k, 720p, 720p+a128k, 1080p, 1080p+a128k (best) [cli][info] Starting player: ffplay .................... .................... .................... ```
0.0
6bf654a291e2a792088384c7ba7c9dc9b2a14b1d
[ "tests/streams/test_dash.py::TestDASHStream::test_parse_manifest_audio_multi_lang", "tests/streams/test_dash.py::TestDASHStream::test_parse_manifest_audio_multi_lang_alpha3", "tests/streams/test_dash.py::TestDASHStream::test_parse_manifest_audio_multi_lang_locale" ]
[ "tests/streams/test_dash.py::TestDASHStream::test_parse_manifest_audio_invalid_lang", "tests/streams/test_dash.py::TestDASHStream::test_parse_manifest_audio_multi", "tests/streams/test_dash.py::TestDASHStream::test_parse_manifest_audio_only", "tests/streams/test_dash.py::TestDASHStream::test_parse_manifest_audio_single", "tests/streams/test_dash.py::TestDASHStream::test_parse_manifest_drm", "tests/streams/test_dash.py::TestDASHStream::test_parse_manifest_video_only", "tests/streams/test_dash.py::TestDASHStream::test_stream_open_video_audio", "tests/streams/test_dash.py::TestDASHStream::test_stream_open_video_only", "tests/streams/test_dash.py::TestDASHStreamWorker::test_duplicate_rep_id", "tests/streams/test_dash.py::TestDASHStreamWorker::test_dynamic_reload", "tests/streams/test_dash.py::TestDASHStreamWorker::test_static" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2018-07-12 11:27:40+00:00
bsd-2-clause
5,767
streamlink__streamlink-2010
diff --git a/src/streamlink/plugins/schoolism.py b/src/streamlink/plugins/schoolism.py index c71ff0dd..5285c2a7 100644 --- a/src/streamlink/plugins/schoolism.py +++ b/src/streamlink/plugins/schoolism.py @@ -1,20 +1,23 @@ from __future__ import print_function +import logging import re from functools import partial from streamlink.plugin import Plugin, PluginArguments, PluginArgument from streamlink.plugin.api import useragents from streamlink.plugin.api import validate -from streamlink.stream import HLSStream +from streamlink.stream import HLSStream, HTTPStream from streamlink.utils import parse_json +log = logging.getLogger(__name__) + class Schoolism(Plugin): - url_re = re.compile(r"https?://(?:www\.)?schoolism\.com/watchLesson.php") + url_re = re.compile(r"https?://(?:www\.)?schoolism\.com/(viewAssignment|watchLesson).php") login_url = "https://www.schoolism.com/index.php" key_time_url = "https://www.schoolism.com/video-html/key-time.php" - playlist_re = re.compile(r"var allVideos=(\[\{.*\}]);", re.DOTALL) + playlist_re = re.compile(r"var allVideos\s*=\s*(\[\{.*\}]);", re.DOTALL) js_to_json = partial(re.compile(r'(?!<")(\w+):(?!/)').sub, r'"\1":') playlist_schema = validate.Schema( validate.transform(playlist_re.search), @@ -27,13 +30,13 @@ class Schoolism(Plugin): validate.transform(parse_json), [{ "sources": validate.all([{ - "playlistTitle": validate.text, + validate.optional("playlistTitle"): validate.text, "title": validate.text, "src": validate.text, "type": validate.text, }], # only include HLS streams - validate.filter(lambda s: s["type"] == "application/x-mpegurl") + # validate.filter(lambda s: s["type"] == "application/x-mpegurl") ) }] ) @@ -63,7 +66,7 @@ class Schoolism(Plugin): default=1, metavar="PART", help=""" - Play part number PART of the lesson. + Play part number PART of the lesson, or assignment feedback video. Defaults is 1. """ @@ -83,44 +86,50 @@ class Schoolism(Plugin): """ if self.options.get("email") and self.options.get("password"): res = self.session.http.post(self.login_url, data={"email": email, - "password": password, - "redirect": None, - "submit": "Login"}) + "password": password, + "redirect": None, + "submit": "Login"}) if res.cookies.get("password") and res.cookies.get("email"): return res.cookies.get("email") else: - self.logger.error("Failed to login to Schoolism, incorrect email/password combination") + log.error("Failed to login to Schoolism, incorrect email/password combination") else: - self.logger.error("An email and password are required to access Schoolism streams") + log.error("An email and password are required to access Schoolism streams") def _get_streams(self): user = self.login(self.options.get("email"), self.options.get("password")) if user: - self.logger.debug("Logged in to Schoolism as {0}", user) + log.debug("Logged in to Schoolism as {0}", user) res = self.session.http.get(self.url, headers={"User-Agent": useragents.SAFARI_8}) lesson_playlist = self.playlist_schema.validate(res.text) part = self.options.get("part") + video_type = "Lesson" if "lesson" in self.url_re.match(self.url).group(1).lower() else "Assignment Feedback" - self.logger.info("Attempting to play lesson Part {0}", part) + log.info("Attempting to play {0} Part {1}", video_type, part) found = False # make request to key-time api, to get key specific headers - res = self.session.http.get(self.key_time_url, headers={"User-Agent": useragents.SAFARI_8}) + _ = self.session.http.get(self.key_time_url, headers={"User-Agent": useragents.SAFARI_8}) for i, video in enumerate(lesson_playlist, 1): if video["sources"] and i == part: found = True for source in video["sources"]: - for s in HLSStream.parse_variant_playlist(self.session, - source["src"], - headers={"User-Agent": useragents.SAFARI_8, - "Referer": self.url}).items(): - yield s + if source['type'] == "video/mp4": + yield "live", HTTPStream(self.session, source["src"], + headers={"User-Agent": useragents.SAFARI_8, + "Referer": self.url}) + elif source['type'] == "application/x-mpegurl": + for s in HLSStream.parse_variant_playlist(self.session, + source["src"], + headers={"User-Agent": useragents.SAFARI_8, + "Referer": self.url}).items(): + yield s if not found: - self.logger.error("Could not find lesson Part {0}", part) + log.error("Could not find {0} Part {1}", video_type, part) __plugin__ = Schoolism diff --git a/src/streamlink/plugins/steam.py b/src/streamlink/plugins/steam.py index 6a5182ab..7c33470b 100644 --- a/src/streamlink/plugins/steam.py +++ b/src/streamlink/plugins/steam.py @@ -10,8 +10,10 @@ import streamlink from streamlink.exceptions import FatalPluginError from streamlink.plugin import Plugin, PluginArguments, PluginArgument from streamlink.plugin.api import validate +from streamlink.plugin.api.utils import itertags, parse_json from streamlink.plugin.api.validate import Schema from streamlink.stream.dash import DASHStream +from streamlink.compat import html_unescape log = logging.getLogger(__name__) @@ -22,6 +24,8 @@ class SteamLoginFailed(Exception): class SteamBroadcastPlugin(Plugin): _url_re = re.compile(r"https?://steamcommunity.com/broadcast/watch/(\d+)") + _steamtv_url_re = re.compile(r"https?://steam.tv/(\w+)") + _watch_broadcast_url = "https://steamcommunity.com/broadcast/watch/" _get_broadcast_url = "https://steamcommunity.com/broadcast/getbroadcastmpd/" _user_agent = "streamlink/{}".format(streamlink.__version__) _broadcast_schema = Schema({ @@ -77,7 +81,7 @@ class SteamBroadcastPlugin(Plugin): @classmethod def can_handle_url(cls, url): - return cls._url_re.match(url) is not None + return cls._url_re.match(url) is not None or cls._steamtv_url_re.match(url) is not None @property def donotcache(self): @@ -191,6 +195,16 @@ class SteamBroadcastPlugin(Plugin): log.info("Logged in as {0}".format(self.get_option("email"))) self.save_cookies(lambda c: "steamMachineAuth" in c.name) + # Handle steam.tv URLs + if self._steamtv_url_re.match(self.url) is not None: + # extract the steam ID from the page + res = self.session.http.get(self.url) + for div in itertags(res.text, 'div'): + if div.attributes.get("id") == "webui_config": + broadcast_data = html_unescape(div.attributes.get("data-broadcast")) + steamid = parse_json(broadcast_data).get("steamid") + self.url = self._watch_broadcast_url + steamid + # extract the steam ID from the URL steamid = self._url_re.match(self.url).group(1) res = self.session.http.get(self.url) # get the page to set some cookies
streamlink/streamlink
2c9cfe84084eaec51a1dcd37a6bf0280bcdd195e
diff --git a/tests/plugins/test_steam.py b/tests/plugins/test_steam.py index db16601f..0f362f1e 100644 --- a/tests/plugins/test_steam.py +++ b/tests/plugins/test_steam.py @@ -7,6 +7,8 @@ class TestPluginSteamBroadcastPlugin(unittest.TestCase): def test_can_handle_url(self): self.assertTrue(SteamBroadcastPlugin.can_handle_url('https://steamcommunity.com/broadcast/watch/12432432')) self.assertTrue(SteamBroadcastPlugin.can_handle_url('http://steamcommunity.com/broadcast/watch/342342')) + self.assertTrue(SteamBroadcastPlugin.can_handle_url('https://steam.tv/dota2')) + self.assertTrue(SteamBroadcastPlugin.can_handle_url('http://steam.tv/dota2')) def test_can_handle_url_negative(self): # shouldn't match
Schoolism Video Feedbacks Plugins Compatibility? Checklist - [ ] This is a bug report. - [ ] This is a feature request. - [x] This is a plugin (improvement) request. - [x] I have read the contribution guidelines. With the Schoolism plugin, you can download lessons with Streamlink.exe --schoolism-email XXXX --schoolism-password XXXX --schoolism-part 1 -v "https://www.schoolism.com/watchLesson.php?type=st&id=506" best -o "LOCATION" Is there a way to download the video feedbacks from urls such as https://www.schoolism.com/viewAssignment.php?type=st&courseID=44&id=506&notSubmitted=true as well? If there isn't, I'd greatly appreciate a modification to the plugin to allow for one to download the video feedbacks.
0.0
2c9cfe84084eaec51a1dcd37a6bf0280bcdd195e
[ "tests/plugins/test_steam.py::TestPluginSteamBroadcastPlugin::test_can_handle_url" ]
[ "tests/plugins/test_steam.py::TestPluginSteamBroadcastPlugin::test_can_handle_url_negative" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2018-08-13 00:10:56+00:00
bsd-2-clause
5,768
streamlink__streamlink-2084
diff --git a/docs/plugin_matrix.rst b/docs/plugin_matrix.rst index 0bb62885..e0b05c65 100644 --- a/docs/plugin_matrix.rst +++ b/docs/plugin_matrix.rst @@ -164,6 +164,7 @@ rtve rtve.es Yes No rtvs rtvs.sk Yes No Streams may be geo-restricted to Slovakia. ruv ruv.is Yes Yes Streams may be geo-restricted to Iceland. schoolism schoolism.com -- Yes Requires a login and a subscription. +senategov senate.gov -- Yes Supports hearing streams. showroom showroom-live.com Yes No Only RTMP streams are available. skai skai.gr Yes No Only embedded youtube live streams are supported sportal sportal.bg Yes No @@ -173,6 +174,7 @@ srgssr - srf.ch Yes No Streams are geo-restric - rsi.ch - rtr.ch ssh101 ssh101.com Yes No +stadium watchstadium.com Yes No startv startv.com.tr Yes No steam steamcommunity.com Yes No Some streams will require a Steam account. streamable streamable.com - Yes diff --git a/src/streamlink/plugins/senategov.py b/src/streamlink/plugins/senategov.py new file mode 100644 index 00000000..2942b288 --- /dev/null +++ b/src/streamlink/plugins/senategov.py @@ -0,0 +1,113 @@ +import re +import logging + +from streamlink.plugin import Plugin +from streamlink.plugin.api import useragents +from streamlink.plugin.api.utils import itertags +from streamlink.stream import HLSStream +from streamlink.utils import parse_json +from streamlink.compat import urlparse, parse_qsl +from streamlink.utils.times import hours_minutes_seconds + +log = logging.getLogger(__name__) + + +class SenateGov(Plugin): + url_re = re.compile(r"""https?://(?:.+\.)?senate\.gov/(isvp)?""") + streaminfo_re = re.compile(r"""var\s+streamInfo\s+=\s+new\s+Array\s*\(\s*(\[.*\])\);""") + stt_re = re.compile(r"""^(?:(?P<hours>\d+):)?(?P<minutes>\d+):(?P<seconds>\d+)$""") + url_lookup = { + "ag": ["76440", "https://ag-f.akamaihd.net"], + "aging": ["76442", "https://aging-f.akamaihd.net"], + "approps": ["76441", "https://approps-f.akamaihd.net"], + "armed": ["76445", "https://armed-f.akamaihd.net"], + "banking": ["76446", "https://banking-f.akamaihd.net"], + "budget": ["76447", "https://budget-f.akamaihd.net"], + "cecc": ["76486", "https://srs-f.akamaihd.net"], + "commerce": ["80177", "https://commerce1-f.akamaihd.net"], + "csce": ["75229", "https://srs-f.akamaihd.net"], + "dpc": ["76590", "https://dpc-f.akamaihd.net"], + "energy": ["76448", "https://energy-f.akamaihd.net"], + "epw": ["76478", "https://epw-f.akamaihd.net"], + "ethics": ["76449", "https://ethics-f.akamaihd.net"], + "finance": ["76450", "https://finance-f.akamaihd.net"], + "foreign": ["76451", "https://foreign-f.akamaihd.net"], + "govtaff": ["76453", "https://govtaff-f.akamaihd.net"], + "help": ["76452", "https://help-f.akamaihd.net"], + "indian": ["76455", "https://indian-f.akamaihd.net"], + "intel": ["76456", "https://intel-f.akamaihd.net"], + "intlnarc": ["76457", "https://intlnarc-f.akamaihd.net"], + "jccic": ["85180", "https://jccic-f.akamaihd.net"], + "jec": ["76458", "https://jec-f.akamaihd.net"], + "judiciary": ["76459", "https://judiciary-f.akamaihd.net"], + "rpc": ["76591", "https://rpc-f.akamaihd.net"], + "rules": ["76460", "https://rules-f.akamaihd.net"], + "saa": ["76489", "https://srs-f.akamaihd.net"], + "smbiz": ["76461", "https://smbiz-f.akamaihd.net"], + "srs": ["75229", "https://srs-f.akamaihd.net"], + "uscc": ["76487", "https://srs-f.akamaihd.net"], + "vetaff": ["76462", "https://vetaff-f.akamaihd.net"], + } + + hls_url = "{base}/i/{filename}_1@{number}/master.m3u8?" + hlsarch_url = "https://ussenate-f.akamaihd.net/i/{filename}.mp4/master.m3u8" + + @classmethod + def can_handle_url(cls, url): + return cls.url_re.match(url) is not None + + def _isvp_to_m3u8(self, url): + qs = dict(parse_qsl(urlparse(url).query)) + if "comm" not in qs: + log.error("Missing `comm` value") + if "filename" not in qs: + log.error("Missing `filename` value") + + d = self.url_lookup.get(qs['comm']) + if d: + snumber, baseurl = d + stream_url = self.hls_url.format(filename=qs['filename'], number=snumber, base=baseurl) + else: + stream_url = self.hlsarch_url.format(filename=qs['filename']) + + return stream_url, self.parse_stt(qs.get('stt', 0)) + + def _get_streams(self): + self.session.http.headers.update({ + "User-Agent": useragents.CHROME, + }) + m = self.url_re.match(self.url) + if m and not m.group(1): + log.debug("Searching for ISVP URL") + isvp_url = self._get_isvp_url() + else: + isvp_url = self.url + + if not isvp_url: + log.error("Could not find the ISVP URL") + return + else: + log.debug("ISVP URL: {0}".format(isvp_url)) + + stream_url, start_offset = self._isvp_to_m3u8(isvp_url) + log.debug("Start offset is: {0}s".format(start_offset)) + return HLSStream.parse_variant_playlist(self.session, stream_url, start_offset=start_offset) + + def _get_isvp_url(self): + res = self.session.http.get(self.url) + for iframe in itertags(res.text, 'iframe'): + m = self.url_re.match(iframe.attributes.get('src')) + return m and m.group(1) is not None and iframe.attributes.get('src') + + @classmethod + def parse_stt(cls, param): + m = cls.stt_re.match(param) + if m: + return int(m.group('hours') or 0) * 3600 + \ + int(m.group('minutes')) * 60 + \ + int(m.group('seconds')) + else: + return 0 + + +__plugin__ = SenateGov diff --git a/src/streamlink/plugins/stadium.py b/src/streamlink/plugins/stadium.py new file mode 100644 index 00000000..2acd4a28 --- /dev/null +++ b/src/streamlink/plugins/stadium.py @@ -0,0 +1,42 @@ +import re +import logging + +from streamlink.plugin import Plugin +from streamlink.stream import HLSStream +from streamlink.utils import parse_json + +log = logging.getLogger(__name__) + + +class Stadium(Plugin): + url_re = re.compile(r"""https?://(?:www\.)?watchstadium\.com/live""") + API_URL = "https://player-api.new.livestream.com/accounts/{account_id}/events/{event_id}/stream_info" + _stream_data_re = re.compile(r"var StadiumSiteData = (\{.*?});", re.M | re.DOTALL) + + @classmethod + def can_handle_url(cls, url): + return cls.url_re.match(url) is not None + + def _get_streams(self): + res = self.session.http.get(self.url) + m = self._stream_data_re.search(res.text) + if m: + data = parse_json(m.group(1)) + if data['LivestreamEnabled'] == '1': + account_id = data['LivestreamArgs']['account_id'] + event_id = data['LivestreamArgs']['event_id'] + log.debug("Found account_id={account_id} and event_id={event_id}".format(account_id=account_id, event_id=event_id)) + + url = self.API_URL.format(account_id=account_id, event_id=event_id) + api_res = self.session.http.get(url) + api_data = self.session.http.json(api_res) + stream_url = api_data.get('secure_m3u8_url') or api_data.get('m3u8_url') + if stream_url: + return HLSStream.parse_variant_playlist(self.session, stream_url) + else: + log.error("Could not find m3u8_url") + else: + log.error("Stream is offline") + + +__plugin__ = Stadium
streamlink/streamlink
4e4a5a97b5eed3ddc11d11daf8368b6317695858
diff --git a/tests/plugins/test_senategov.py b/tests/plugins/test_senategov.py new file mode 100644 index 00000000..6fb5eda8 --- /dev/null +++ b/tests/plugins/test_senategov.py @@ -0,0 +1,18 @@ +from streamlink.plugins.senategov import SenateGov +import unittest + + +class TestPluginSenateGov(unittest.TestCase): + def test_can_handle_url(self): + # should match + self.assertTrue(SenateGov.can_handle_url("https://www.foreign.senate.gov/hearings/business-meeting-082218")) + self.assertTrue(SenateGov.can_handle_url("https://www.senate.gov/isvp/?comm=foreign&type=arch&stt=21:50&filename=foreign082218&auto_play=false&wmode=transparent&poster=https%3A%2F%2Fwww%2Eforeign%2Esenate%2Egov%2Fthemes%2Fforeign%2Fimages%2Fvideo-poster-flash-fit%2Epng")) + + # shouldn't match + self.assertFalse(SenateGov.can_handle_url("http://www.tvcatchup.com/")) + self.assertFalse(SenateGov.can_handle_url("http://www.youtube.com/")) + + def test_stt_parse(self): + self.assertEqual(600, SenateGov.parse_stt("10:00")) + self.assertEqual(3600, SenateGov.parse_stt("01:00:00")) + self.assertEqual(70, SenateGov.parse_stt("1:10")) diff --git a/tests/plugins/test_stadium.py b/tests/plugins/test_stadium.py new file mode 100644 index 00000000..d0154f07 --- /dev/null +++ b/tests/plugins/test_stadium.py @@ -0,0 +1,16 @@ +from streamlink.plugins.stadium import Stadium +import unittest + + +class TestPluginStadium(unittest.TestCase): + def test_can_handle_url(self): + # should match + self.assertTrue(Stadium.can_handle_url("http://www.watchstadium.com/live")) + self.assertTrue(Stadium.can_handle_url("https://www.watchstadium.com/live")) + self.assertTrue(Stadium.can_handle_url("https://watchstadium.com/live")) + self.assertTrue(Stadium.can_handle_url("http://watchstadium.com/live")) + + # shouldn't match + self.assertFalse(Stadium.can_handle_url("http://www.watchstadium.com/anything/else")) + self.assertFalse(Stadium.can_handle_url("http://www.tvcatchup.com/")) + self.assertFalse(Stadium.can_handle_url("http://www.youtube.com/"))
Stadium plugin request ### Checklist - [x ] This is a feature request. ### Description Can anyone help with a plugin for Stadium TV here: https://watchstadium.com/live/ Cheers!
0.0
4e4a5a97b5eed3ddc11d11daf8368b6317695858
[ "tests/plugins/test_senategov.py::TestPluginSenateGov::test_can_handle_url", "tests/plugins/test_senategov.py::TestPluginSenateGov::test_stt_parse", "tests/plugins/test_stadium.py::TestPluginStadium::test_can_handle_url" ]
[]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_hyperlinks", "has_added_files" ], "has_test_patch": true, "is_lite": false }
2018-10-02 09:37:46+00:00
bsd-2-clause
5,769
streamlink__streamlink-2085
diff --git a/docs/plugin_matrix.rst b/docs/plugin_matrix.rst index 0bb62885..5f27e220 100644 --- a/docs/plugin_matrix.rst +++ b/docs/plugin_matrix.rst @@ -164,6 +164,7 @@ rtve rtve.es Yes No rtvs rtvs.sk Yes No Streams may be geo-restricted to Slovakia. ruv ruv.is Yes Yes Streams may be geo-restricted to Iceland. schoolism schoolism.com -- Yes Requires a login and a subscription. +senategov senate.gov -- Yes Supports hearing streams. showroom showroom-live.com Yes No Only RTMP streams are available. skai skai.gr Yes No Only embedded youtube live streams are supported sportal sportal.bg Yes No diff --git a/src/streamlink/plugins/senategov.py b/src/streamlink/plugins/senategov.py new file mode 100644 index 00000000..2942b288 --- /dev/null +++ b/src/streamlink/plugins/senategov.py @@ -0,0 +1,113 @@ +import re +import logging + +from streamlink.plugin import Plugin +from streamlink.plugin.api import useragents +from streamlink.plugin.api.utils import itertags +from streamlink.stream import HLSStream +from streamlink.utils import parse_json +from streamlink.compat import urlparse, parse_qsl +from streamlink.utils.times import hours_minutes_seconds + +log = logging.getLogger(__name__) + + +class SenateGov(Plugin): + url_re = re.compile(r"""https?://(?:.+\.)?senate\.gov/(isvp)?""") + streaminfo_re = re.compile(r"""var\s+streamInfo\s+=\s+new\s+Array\s*\(\s*(\[.*\])\);""") + stt_re = re.compile(r"""^(?:(?P<hours>\d+):)?(?P<minutes>\d+):(?P<seconds>\d+)$""") + url_lookup = { + "ag": ["76440", "https://ag-f.akamaihd.net"], + "aging": ["76442", "https://aging-f.akamaihd.net"], + "approps": ["76441", "https://approps-f.akamaihd.net"], + "armed": ["76445", "https://armed-f.akamaihd.net"], + "banking": ["76446", "https://banking-f.akamaihd.net"], + "budget": ["76447", "https://budget-f.akamaihd.net"], + "cecc": ["76486", "https://srs-f.akamaihd.net"], + "commerce": ["80177", "https://commerce1-f.akamaihd.net"], + "csce": ["75229", "https://srs-f.akamaihd.net"], + "dpc": ["76590", "https://dpc-f.akamaihd.net"], + "energy": ["76448", "https://energy-f.akamaihd.net"], + "epw": ["76478", "https://epw-f.akamaihd.net"], + "ethics": ["76449", "https://ethics-f.akamaihd.net"], + "finance": ["76450", "https://finance-f.akamaihd.net"], + "foreign": ["76451", "https://foreign-f.akamaihd.net"], + "govtaff": ["76453", "https://govtaff-f.akamaihd.net"], + "help": ["76452", "https://help-f.akamaihd.net"], + "indian": ["76455", "https://indian-f.akamaihd.net"], + "intel": ["76456", "https://intel-f.akamaihd.net"], + "intlnarc": ["76457", "https://intlnarc-f.akamaihd.net"], + "jccic": ["85180", "https://jccic-f.akamaihd.net"], + "jec": ["76458", "https://jec-f.akamaihd.net"], + "judiciary": ["76459", "https://judiciary-f.akamaihd.net"], + "rpc": ["76591", "https://rpc-f.akamaihd.net"], + "rules": ["76460", "https://rules-f.akamaihd.net"], + "saa": ["76489", "https://srs-f.akamaihd.net"], + "smbiz": ["76461", "https://smbiz-f.akamaihd.net"], + "srs": ["75229", "https://srs-f.akamaihd.net"], + "uscc": ["76487", "https://srs-f.akamaihd.net"], + "vetaff": ["76462", "https://vetaff-f.akamaihd.net"], + } + + hls_url = "{base}/i/{filename}_1@{number}/master.m3u8?" + hlsarch_url = "https://ussenate-f.akamaihd.net/i/{filename}.mp4/master.m3u8" + + @classmethod + def can_handle_url(cls, url): + return cls.url_re.match(url) is not None + + def _isvp_to_m3u8(self, url): + qs = dict(parse_qsl(urlparse(url).query)) + if "comm" not in qs: + log.error("Missing `comm` value") + if "filename" not in qs: + log.error("Missing `filename` value") + + d = self.url_lookup.get(qs['comm']) + if d: + snumber, baseurl = d + stream_url = self.hls_url.format(filename=qs['filename'], number=snumber, base=baseurl) + else: + stream_url = self.hlsarch_url.format(filename=qs['filename']) + + return stream_url, self.parse_stt(qs.get('stt', 0)) + + def _get_streams(self): + self.session.http.headers.update({ + "User-Agent": useragents.CHROME, + }) + m = self.url_re.match(self.url) + if m and not m.group(1): + log.debug("Searching for ISVP URL") + isvp_url = self._get_isvp_url() + else: + isvp_url = self.url + + if not isvp_url: + log.error("Could not find the ISVP URL") + return + else: + log.debug("ISVP URL: {0}".format(isvp_url)) + + stream_url, start_offset = self._isvp_to_m3u8(isvp_url) + log.debug("Start offset is: {0}s".format(start_offset)) + return HLSStream.parse_variant_playlist(self.session, stream_url, start_offset=start_offset) + + def _get_isvp_url(self): + res = self.session.http.get(self.url) + for iframe in itertags(res.text, 'iframe'): + m = self.url_re.match(iframe.attributes.get('src')) + return m and m.group(1) is not None and iframe.attributes.get('src') + + @classmethod + def parse_stt(cls, param): + m = cls.stt_re.match(param) + if m: + return int(m.group('hours') or 0) * 3600 + \ + int(m.group('minutes')) * 60 + \ + int(m.group('seconds')) + else: + return 0 + + +__plugin__ = SenateGov
streamlink/streamlink
4e4a5a97b5eed3ddc11d11daf8368b6317695858
diff --git a/tests/plugins/test_senategov.py b/tests/plugins/test_senategov.py new file mode 100644 index 00000000..6fb5eda8 --- /dev/null +++ b/tests/plugins/test_senategov.py @@ -0,0 +1,18 @@ +from streamlink.plugins.senategov import SenateGov +import unittest + + +class TestPluginSenateGov(unittest.TestCase): + def test_can_handle_url(self): + # should match + self.assertTrue(SenateGov.can_handle_url("https://www.foreign.senate.gov/hearings/business-meeting-082218")) + self.assertTrue(SenateGov.can_handle_url("https://www.senate.gov/isvp/?comm=foreign&type=arch&stt=21:50&filename=foreign082218&auto_play=false&wmode=transparent&poster=https%3A%2F%2Fwww%2Eforeign%2Esenate%2Egov%2Fthemes%2Fforeign%2Fimages%2Fvideo-poster-flash-fit%2Epng")) + + # shouldn't match + self.assertFalse(SenateGov.can_handle_url("http://www.tvcatchup.com/")) + self.assertFalse(SenateGov.can_handle_url("http://www.youtube.com/")) + + def test_stt_parse(self): + self.assertEqual(600, SenateGov.parse_stt("10:00")) + self.assertEqual(3600, SenateGov.parse_stt("01:00:00")) + self.assertEqual(70, SenateGov.parse_stt("1:10"))
How to Stream Akamai (?) Video from Senate Foreign Relations Committee Website ## Issue <!-- Replace [ ] with [x] in order to check the box --> - [x] This is not a bug report, feature request, or plugin issue/request. - [x] I have read the contribution guidelines. ### Description I am attempting to load archived video and live video streams of the US Senate Foreign Relations Committee ([Example](https://www.foreign.senate.gov/hearings/business-meeting-082218)) in VLC via streamlink. It appears their video streaming is done via Akamai and AMP v4.90.9 from right-clicking the player embedded in provided examples. ### Expected / Actual behavior Ideally, pointing streamlink to the hearing page containing an embedded player would automagically identify available streams and open the best quality stream in VLC: `streamlink "https://www.foreign.senate.gov/hearings/business-meeting-082218" best` What actually happens is that streamlink fails with an error `error: No plugin can handle URL: https://www.foreign.senate.gov/hearings/business-meeting-082218` ### Reproduction steps / Explicit stream URLs to test I have discovered that the URL for their embedded player gets a little closer ([Example](http://www.senate.gov/isvp/?comm=foreign&type=live&filename=foreign082218)), but streamlink still doesn't find any streams at this URL. That is, until I replace https:// with *akamaihd://*: `streamlink "akamaihd://www.senate.gov/isvp/?comm=foreign&type=live&filename=foreign082218"` Results in: ```[cli][info] Found matching plugin akamaihd for URL akamaihd://www.senate.gov/isvp/?comm=foreign&type=live&filename=foreign082218 Available streams: live (worst, best) ``` When I specify "best" and run the command again, the result is: ```[cli][info] Found matching plugin akamaihd for URL akamaihd://www.senate.gov/isvp/?comm=foreign&type=live&filename=foreign082218 [cli][info] Available streams: live (worst, best) [cli][info] Opening stream: live (akamaihd) [cli][error] Try 1/1: Could not open stream <AkamaiHDStream('http://www.senate.gov/isvp/?comm=foreign&type=live&filename=foreign082218', swf=None)> (Could not open stream: Unable to open URL: http://www.senate.gov/isvp/ (503 Server Error: Service Unavailable for url: http://www.senate.gov/isvp/?fp=LNX+11%2C1%2C102%2C63&r=PPJRC&g=VFVQOIITOQRF&v=2.5.8)) error: Could not open stream <AkamaiHDStream('http://www.senate.gov/isvp/?comm=foreign&type=live&filename=foreign082218', swf=None)>, tried 1 times, exiting ``` ### Logs ``` [cli][debug] OS: macOS 10.13.6 [cli][debug] Python: 2.7.15 [cli][debug] Streamlink: 0.14.2 [cli][debug] Requests(2.19.1), Socks(1.6.7), Websocket(0.48.0) [cli][info] Found matching plugin akamaihd for URL akamaihd://www.senate.gov/isvp/?comm=foreign&type=live&filename=foreign082218 [plugin.akamaihd][debug] URL=http://www.senate.gov/isvp/?comm=foreign&type=live&filename=foreign082218; params={} [cli][info] Available streams: live (worst, best) [cli][info] Opening stream: live (akamaihd) [stream.akamaihd][debug] Opening host=http://www.senate.gov streamname=isvp/ [cli][error] Try 1/1: Could not open stream <AkamaiHDStream('http://www.senate.gov/isvp/?comm=foreign&type=live&filename=foreign082218', swf=None)> (Could not open stream: Unable to open URL: http://www.senate.gov/isvp/ (503 Server Error: Service Unavailable for url: http://www.senate.gov/isvp/?fp=LNX+11%2C1%2C102%2C63&r=VREJP&g=JOHWJGPLHFNA&v=2.5.8)) error: Could not open stream <AkamaiHDStream('http://www.senate.gov/isvp/?comm=foreign&type=live&filename=foreign082218', swf=None)>, tried 1 times, exiting ``` ### Additional comments, screenshots, etc. It appears the Senate Foreign Relations Committee uses the date of the hearing as the main reference ID. Since the committee only meets once a day, there's only ever one stream on any given day. There's possibly useful information in the source of each player page. In the source code for the example link I've used above, there's this snippet: ``` <a id="watch-live-now" class="small btn" href="javascript:openVideoWin('/hearings/watch?hearingid=AA0FF459-5056-A066-60A0-8B11F704E85E');">Open New Window</a> ``` Also, from the source code the video player code can have a lot of parameters specified: ``` https://www.senate.gov/isvp/?comm=foreign&type=arch&stt=21:50&filename=foreign082218&auto_play=false&wmode=transparent&poster=https%3A%2F%2Fwww%2Eforeign%2Esenate%2Egov%2Fthemes%2Fforeign%2Fimages%2Fvideo%2Dposter%2Dflash%2Dfit%2Epng ``` [Love Streamlink? Please consider supporting our collective. Thanks!](https://opencollective.com/streamlink/donate)
0.0
4e4a5a97b5eed3ddc11d11daf8368b6317695858
[ "tests/plugins/test_senategov.py::TestPluginSenateGov::test_can_handle_url", "tests/plugins/test_senategov.py::TestPluginSenateGov::test_stt_parse" ]
[]
{ "failed_lite_validators": [ "has_hyperlinks", "has_added_files" ], "has_test_patch": true, "is_lite": false }
2018-10-02 13:49:25+00:00
bsd-2-clause
5,770
streamlink__streamlink-2102
diff --git a/docs/plugin_matrix.rst b/docs/plugin_matrix.rst index e0b05c65..eea5b215 100644 --- a/docs/plugin_matrix.rst +++ b/docs/plugin_matrix.rst @@ -120,7 +120,7 @@ npo - npo.nl Yes Yes Streams may be geo-rest - zappelin.nl nrk - tv.nrk.no Yes Yes Streams may be geo-restricted to Norway. - radio.nrk.no -ok_live ok.ru Yes -- +ok_live ok.ru Yes Yes olympicchannel olympicchannel.com Yes Yes Only non-premium content is available. onetv - 1tv.ru Yes Yes Streams may be geo-restricted to Russia. VOD only for 1tv.ru - ctc.ru diff --git a/src/streamlink/plugins/ok_live.py b/src/streamlink/plugins/ok_live.py index 233c510c..9528ca99 100644 --- a/src/streamlink/plugins/ok_live.py +++ b/src/streamlink/plugins/ok_live.py @@ -5,7 +5,7 @@ from streamlink.plugin.api import validate from streamlink.plugin.api import useragents from streamlink.stream import HLSStream -_url_re = re.compile(r"https?://(www\.)?ok\.ru/live/\d+") +_url_re = re.compile(r"https?://(www\.)?ok\.ru/(live|video)/\d+") _vod_re = re.compile(r";(?P<hlsurl>[^;]+video\.m3u8.+?)\\&quot;") _schema = validate.Schema( @@ -21,7 +21,7 @@ _schema = validate.Schema( class OK_live(Plugin): """ - Support for ok.ru live stream: http://www.ok.ru/live/ + Support for ok.ru live stream: http://www.ok.ru/live/ and for ok.ru VoDs: http://www.ok.ru/video/ """ @classmethod def can_handle_url(cls, url): diff --git a/src/streamlink/stream/dash_manifest.py b/src/streamlink/stream/dash_manifest.py index cb3d76aa..68c7f56f 100644 --- a/src/streamlink/stream/dash_manifest.py +++ b/src/streamlink/stream/dash_manifest.py @@ -509,6 +509,10 @@ class SegmentTemplate(MPDNode): def format_media(self, **kwargs): if self.segmentTimeline: + if self.parent.id is None: + # workaround for invalid `self.root.timelines[self.parent.id]` + # creates a timeline for every mimeType instead of one for both + self.parent.id = self.parent.mimeType log.debug("Generating segment timeline for {0} playlist (id={1}))".format(self.root.type, self.parent.id)) if self.root.type == "dynamic": # if there is no delay, use a delay of 3 seconds
streamlink/streamlink
e29c8b75e664671216abc8c660f2dec21310cec9
diff --git a/tests/plugins/test_ok_live.py b/tests/plugins/test_ok_live.py index 60a02bcc..bfdcf458 100644 --- a/tests/plugins/test_ok_live.py +++ b/tests/plugins/test_ok_live.py @@ -9,6 +9,7 @@ class TestPluginOK_live(unittest.TestCase): self.assertTrue(OK_live.can_handle_url("https://ok.ru/live/12345")) self.assertTrue(OK_live.can_handle_url("http://ok.ru/live/12345")) self.assertTrue(OK_live.can_handle_url("http://www.ok.ru/live/12345")) + self.assertTrue(OK_live.can_handle_url("https://ok.ru/video/266205792931")) # shouldn't match self.assertFalse(OK_live.can_handle_url("http://www.tvcatchup.com/"))
ok.ru VODs <!-- Thanks for reporting a plugin issue! USE THE TEMPLATE. Otherwise your plugin issue may be rejected. First, see the contribution guidelines: https://github.com/streamlink/streamlink/blob/master/CONTRIBUTING.md#contributing-to-streamlink Also check the list of open and closed plugin issues: https://github.com/streamlink/streamlink/issues?q=is%3Aissue+label%3A%22plugin+issue%22 Please see the text preview to avoid unnecessary formatting errors. --> ## Plugin Issue <!-- Replace [ ] with [x] in order to check the box --> - [x ] This is a plugin issue and I have read the contribution guidelines. ### Description i enter link in #1884 but "https://raw.githubusercontent.com/back-to/plugins/master/plugins/ok_live.py" 404: Not Found. Thanks <!-- Explain the plugin issue as thoroughly as you can. --> ### Reproduction steps / Explicit stream URLs to test <!-- How can we reproduce this? Please note the exact steps below using the list format supplied. If you need more steps please add them. --> 1. D:\my\Streamlinkl\bin>streamlink -l debug "https://ok.ru/video/266205792931" best ### Log output <!-- TEXT LOG OUTPUT IS REQUIRED for a plugin issue! Use the `--loglevel debug` parameter and avoid using parameters which suppress log output. https://streamlink.github.io/cli.html#cmdoption-l Make sure to **remove usernames and passwords** You can copy the output to https://gist.github.com/ or paste it below. --> ``` [cli][debug] OS: Windows 8.1 [cli][debug] Python: 3.5.2 [cli][debug] Streamlink: 0.14.2 [cli][debug] Requests(2.19.1), Socks(1.6.7), Websocket(0.48.0) error: No plugin can handle URL: https://ok.ru/video/266205792931 ``` ### Additional comments, screenshots, etc. [Love Streamlink? Please consider supporting our collective. Thanks!](https://opencollective.com/streamlink/donate)
0.0
e29c8b75e664671216abc8c660f2dec21310cec9
[ "tests/plugins/test_ok_live.py::TestPluginOK_live::test_can_handle_url" ]
[]
{ "failed_lite_validators": [ "has_hyperlinks", "has_issue_reference", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2018-10-07 00:44:28+00:00
bsd-2-clause
5,771
streamlink__streamlink-2108
diff --git a/docs/plugin_matrix.rst b/docs/plugin_matrix.rst index 9cb83e2b..c34c9516 100644 --- a/docs/plugin_matrix.rst +++ b/docs/plugin_matrix.rst @@ -188,6 +188,7 @@ svtplay - svtplay.se Yes Yes Streams may be geo-rest - oppetarkiv.se swisstxt - srf.ch Yes No Streams are geo-restricted to Switzerland. - rsi.ch +tamago player.tamago.live Yes -- teamliquid teamliquid.net Yes Yes teleclubzoom teleclubzoom.ch Yes No Streams are geo-restricted to Switzerland. telefe telefe.com No Yes Streams are geo-restricted to Argentina. diff --git a/src/streamlink/plugins/tamago.py b/src/streamlink/plugins/tamago.py new file mode 100644 index 00000000..0b6dc719 --- /dev/null +++ b/src/streamlink/plugins/tamago.py @@ -0,0 +1,52 @@ +import re + +from streamlink.plugin import Plugin +from streamlink.plugin.api import validate +from streamlink.stream import HTTPStream +from streamlink import NoStreamsError + + +class Tamago(Plugin): + + _url_re = re.compile(r"https?://(?:player\.)?tamago\.live/w/(?P<id>\d+)") + + _api_url_base = "https://player.tamago.live/api/rooms/{id}" + + _api_response_schema = validate.Schema({ + u"status": 200, + u"message": u"Success", + u"data": { + u"room_number": validate.text, + u"stream": {validate.text: validate.url()} + } + }) + + _stream_qualities = { + u"150": "144p", + u"350": "360p", + u"550": "540p", + u"900": "720p", + } + + @classmethod + def can_handle_url(cls, url): + return cls._url_re.match(url) is not None + + def _get_streams(self): + user_id = self._url_re.match(self.url).group('id') + + try: + api_response = self.session.http.get(self._api_url_base.format(id=user_id)) + streams = self.session.http.json(api_response, schema=self._api_response_schema)['data']['stream'] + except Exception: + raise NoStreamsError(self.url) + + unique_stream_urls = [] + for stream in streams.keys(): + if streams[stream] not in unique_stream_urls: + unique_stream_urls.append(streams[stream]) + quality = self._stream_qualities[stream] if stream in self._stream_qualities.keys() else "720p+" + yield quality, HTTPStream(self.session, streams[stream]) + + +__plugin__ = Tamago diff --git a/src/streamlink_cli/utils/progress.py b/src/streamlink_cli/utils/progress.py index dc7a0687..46dca155 100644 --- a/src/streamlink_cli/utils/progress.py +++ b/src/streamlink_cli/utils/progress.py @@ -13,22 +13,51 @@ PROGRESS_FORMATS = ( "[download] {written}" ) +# widths generated from +# http://www.unicode.org/Public/4.0-Update/EastAsianWidth-4.0.0.txt -def terminal_len(value): - """Returns the length of the string it would be when displayed. - Attempts to decode the string as UTF-8 first if it's a bytestring. - """ +widths = [ + (13, 1), (15, 0), (126, 1), (159, 0), (687, 1), (710, 0), + (711, 1), (727, 0), (733, 1), (879, 0), (1154, 1), (1161, 0), + (4347, 1), (4447, 2), (7467, 1), (7521, 0), (8369, 1), (8426, 0), + (9000, 1), (9002, 2), (11021, 1), (12350, 2), (12351, 1), (12438, 2), + (12442, 0), (19893, 2), (19967, 1), (55203, 2), (63743, 1), (64106, 2), + (65039, 1), (65059, 0), (65131, 2), (65279, 1), (65376, 2), (65500, 1), + (65510, 2), (120831, 1), (262141, 2), (1114109, 1) +] + + +def get_width(o): + """Returns the screen column width for unicode ordinal.""" + for num, wid in widths: + if o <= num: + return wid + return 1 + + +def terminal_width(value): + """Returns the width of the string it would be when displayed.""" if isinstance(value, bytes): value = value.decode("utf8", "ignore") + return sum(map(get_width, map(ord, value))) + - return len(value) +def get_cut_prefix(value, max_len): + """Drops Characters by unicode not by bytes.""" + should_convert = isinstance(value, bytes) + if should_convert: + value = value.decode("utf8", "ignore") + for i in range(len(value)): + if terminal_width(value[i:]) <= max_len: + break + return value[i:].encode("utf8", "ignore") if should_convert else value[i:] def print_inplace(msg): """Clears out the previous line and prints a new one.""" term_width = get_terminal_size().columns - spacing = term_width - terminal_len(msg) + spacing = term_width - terminal_width(msg) # On windows we need one less space or we overflow the line for some reason. if is_win32: @@ -89,7 +118,8 @@ def progress(iterator, prefix): - Time elapsed - Average speed, based on the last few seconds. """ - prefix = (".." + prefix[-23:]) if len(prefix) > 25 else prefix + if terminal_width(prefix) > 25: + prefix = (".." + get_cut_prefix(prefix, 23)) speed_updated = start = time() speed_written = written = 0 speed_history = deque(maxlen=5)
streamlink/streamlink
934ad3f0eb39cdc2d07b683756544ccca174916c
diff --git a/tests/plugins/test_tamago.py b/tests/plugins/test_tamago.py new file mode 100644 index 00000000..06afc7db --- /dev/null +++ b/tests/plugins/test_tamago.py @@ -0,0 +1,24 @@ +import unittest + +from streamlink.plugins.tamago import Tamago + + +class TestPluginTamago(unittest.TestCase): + def test_can_handle_url(self): + should_match = [ + 'https://player.tamago.live/w/2009642', + 'https://player.tamago.live/w/1882066', + 'https://player.tamago.live/w/1870142', + 'https://player.tamago.live/w/1729968', + ] + for url in should_match: + self.assertTrue(Tamago.can_handle_url(url)) + + def test_can_handle_url_negative(self): + should_not_match = [ + 'https://download.tamago.live/faq', + 'https://player.tamago.live/gaming/pubg', + 'https://www.twitch.tv/twitch' + ] + for url in should_not_match: + self.assertFalse(Tamago.can_handle_url(url)) diff --git a/tests/test_cli_util_progress.py b/tests/test_cli_util_progress.py new file mode 100644 index 00000000..77afe5c2 --- /dev/null +++ b/tests/test_cli_util_progress.py @@ -0,0 +1,20 @@ +# coding: utf-8 +from streamlink_cli.utils.progress import terminal_width, get_cut_prefix +import unittest + + +class TestCliUtilProgess(unittest.TestCase): + def test_terminal_width(self): + self.assertEqual(10, terminal_width("ABCDEFGHIJ")) + self.assertEqual(30, terminal_width("A你好世界こんにちは안녕하세요B")) + self.assertEqual(30, terminal_width("·「」『』【】-=!@#¥%……&×()")) + pass + + def test_get_cut_prefix(self): + self.assertEqual("녕하세요CD", + get_cut_prefix("你好世界こんにちは안녕하세요CD", 10)) + self.assertEqual("하세요CD", + get_cut_prefix("你好世界こんにちは안녕하세요CD", 9)) + self.assertEqual("こんにちは안녕하세요CD", + get_cut_prefix("你好世界こんにちは안녕하세요CD", 23)) + pass
player.tamago.live Plugin <!-- Thanks for requesting a plugin! USE THE TEMPLATE. Otherwise your plugin request may be rejected. First, see the contribution guidelines and plugin request requirements: https://github.com/streamlink/streamlink/blob/master/CONTRIBUTING.md#contributing-to-streamlink Plugin requests which fall into the categories we will not implement will be closed immediately. Also check the list of open and closed plugin requests: https://github.com/streamlink/streamlink/issues?q=is%3Aissue+label%3A%22plugin+request%22 Please see the text preview to avoid unnecessary formatting errors. --> ## Plugin Request <!-- Replace [ ] with [x] in order to check the box --> - [x] This is a plugin request and I have read the contribution guidelines and plugin request requirements. ### Description https://player.tamago.live **Tamago** is a live streaming social network that lets you watch or broadcast live video anytime, anywhere. Like *Twitch*, streamers can interact with their viewers in a chat box. Get exclusive content, from your favourite TV shows and concerts, to the hottest e-sports leagues and more, get front row seats or go behind the scenes with Tamago. Showcase your talent to a wide audience of viewers and fellow broadcasters. Live video streaming is spontaneous and does not have to be perfect, so anyone can be a broadcaster! You can get rewarded for broadcasting too! Collect gifts during your live streams and keep the profits when you cash out. https://download.tamago.live/faq ### Example stream URLs <!-- Example URLs for streams are required. Plugin requests which do not have example URLs will be closed. --> 1. https://player.tamago.live/w/2009642 2. https://player.tamago.live/w/1882066 3. https://player.tamago.live/w/1870142 4. https://player.tamago.live/w/1729968 5. ... ### Additional comments, screenshots, etc. [Love Streamlink? Please consider supporting our collective. Thanks!](https://opencollective.com/streamlink/donate)
0.0
934ad3f0eb39cdc2d07b683756544ccca174916c
[ "tests/plugins/test_tamago.py::TestPluginTamago::test_can_handle_url", "tests/plugins/test_tamago.py::TestPluginTamago::test_can_handle_url_negative", "tests/test_cli_util_progress.py::TestCliUtilProgess::test_get_cut_prefix", "tests/test_cli_util_progress.py::TestCliUtilProgess::test_terminal_width" ]
[]
{ "failed_lite_validators": [ "has_hyperlinks", "has_added_files", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2018-10-10 20:38:57+00:00
bsd-2-clause
5,772
streamlink__streamlink-2127
diff --git a/src/streamlink/plugin/plugin.py b/src/streamlink/plugin/plugin.py index 1f5513d7..ef38ac47 100644 --- a/src/streamlink/plugin/plugin.py +++ b/src/streamlink/plugin/plugin.py @@ -384,6 +384,7 @@ class Plugin(object): stream_names = filter(stream_weight_only, streams.keys()) sorted_streams = sorted(stream_names, key=stream_weight_only) + unfiltered_sorted_streams = sorted_streams if isinstance(sorting_excludes, list): for expr in sorting_excludes: @@ -402,6 +403,11 @@ class Plugin(object): worst = sorted_streams[0] final_sorted_streams["worst"] = streams[worst] final_sorted_streams["best"] = streams[best] + elif len(unfiltered_sorted_streams) > 0: + best = unfiltered_sorted_streams[-1] + worst = unfiltered_sorted_streams[0] + final_sorted_streams["worst-unfiltered"] = streams[worst] + final_sorted_streams["best-unfiltered"] = streams[best] return final_sorted_streams diff --git a/src/streamlink_cli/argparser.py b/src/streamlink_cli/argparser.py index 0c77adb3..6af91976 100644 --- a/src/streamlink_cli/argparser.py +++ b/src/streamlink_cli/argparser.py @@ -107,7 +107,7 @@ def build_parser(): help=""" Stream to play. - Use "best" or "worst" for selecting the highest or lowest available + Use ``best`` or ``worst`` for selecting the highest or lowest available quality. Fallback streams can be specified by using a comma-separated list: @@ -523,7 +523,7 @@ def build_parser(): help=""" Stream to play. - Use "best" or "worst" for selecting the highest or lowest available + Use ``best`` or ``worst`` for selecting the highest or lowest available quality. Fallback streams can be specified by using a comma-separated list: @@ -590,13 +590,17 @@ def build_parser(): metavar="STREAMS", type=comma_list, help=""" - Fine tune best/worst synonyms by excluding unwanted streams. + Fine tune the ``best`` and ``worst`` stream name synonyms by excluding unwanted streams. + + If all of the available streams get excluded, ``best`` and ``worst`` will become + inaccessible and new special stream synonyms ``best-unfiltered`` and ``worst-unfiltered`` + can be used as a fallback selection method. Uses a filter expression in the format: [operator]<value> - Valid operators are >, >=, < and <=. If no operator is specified then + Valid operators are ``>``, ``>=``, ``<`` and ``<=``. If no operator is specified then equality is tested. For example this will exclude streams ranked higher than "480p": diff --git a/src/streamlink_cli/constants.py b/src/streamlink_cli/constants.py index 05ec5dba..45eb7894 100644 --- a/src/streamlink_cli/constants.py +++ b/src/streamlink_cli/constants.py @@ -28,7 +28,7 @@ else: ] PLUGINS_DIR = os.path.expanduser(XDG_CONFIG_HOME + "/streamlink/plugins") -STREAM_SYNONYMS = ["best", "worst"] +STREAM_SYNONYMS = ["best", "worst", "best-unfiltered", "worst-unfiltered"] STREAM_PASSTHROUGH = ["hls", "http", "rtmp"] __all__ = [
streamlink/streamlink
7b5f4f775b70281c0970af9048e556258da11582
diff --git a/tests/plugins/testplugin.py b/tests/plugins/testplugin.py index 06b693c4..66822ef4 100644 --- a/tests/plugins/testplugin.py +++ b/tests/plugins/testplugin.py @@ -37,6 +37,14 @@ class TestPlugin(Plugin): def _get_streams(self): if "empty" in self.url: return + + if "UnsortableStreamNames" in self.url: + def gen(): + for i in range(3): + yield "vod", HTTPStream(self.session, "http://test.se/stream") + + return gen() + if "NoStreamsError" in self.url: raise NoStreamsError(self.url) diff --git a/tests/test_cli_main.py b/tests/test_cli_main.py index dccd30a7..2b58ea5f 100644 --- a/tests/test_cli_main.py +++ b/tests/test_cli_main.py @@ -3,8 +3,9 @@ import os.path import tempfile import streamlink_cli.main -from streamlink_cli.main import resolve_stream_name, check_file_output +from streamlink_cli.main import resolve_stream_name, format_valid_streams, check_file_output from streamlink_cli.output import FileOutput +from streamlink.plugin.plugin import Plugin import unittest from tests.mock import Mock, patch @@ -59,19 +60,71 @@ class TestCLIMain(unittest.TestCase): tmpfile.close() def test_resolve_stream_name(self): - high = Mock() - medium = Mock() - low = Mock() + a = Mock() + b = Mock() + c = Mock() + d = Mock() + e = Mock() streams = { - "low": low, - "medium": medium, - "high": high, - "worst": low, - "best": high + "160p": a, + "360p": b, + "480p": c, + "720p": d, + "1080p": e, + "worst": b, + "best": d, + "worst-unfiltered": a, + "best-unfiltered": e } - self.assertEqual("high", resolve_stream_name(streams, "best")) - self.assertEqual("low", resolve_stream_name(streams, "worst")) - self.assertEqual("medium", resolve_stream_name(streams, "medium")) - self.assertEqual("high", resolve_stream_name(streams, "high")) - self.assertEqual("low", resolve_stream_name(streams, "low")) + self.assertEqual(resolve_stream_name(streams, "unknown"), "unknown") + self.assertEqual(resolve_stream_name(streams, "160p"), "160p") + self.assertEqual(resolve_stream_name(streams, "360p"), "360p") + self.assertEqual(resolve_stream_name(streams, "480p"), "480p") + self.assertEqual(resolve_stream_name(streams, "720p"), "720p") + self.assertEqual(resolve_stream_name(streams, "1080p"), "1080p") + self.assertEqual(resolve_stream_name(streams, "worst"), "360p") + self.assertEqual(resolve_stream_name(streams, "best"), "720p") + self.assertEqual(resolve_stream_name(streams, "worst-unfiltered"), "160p") + self.assertEqual(resolve_stream_name(streams, "best-unfiltered"), "1080p") + + def test_format_valid_streams(self): + class FakePlugin: + @classmethod + def stream_weight(cls, stream): + return Plugin.stream_weight(stream) + a = Mock() + b = Mock() + c = Mock() + + streams = { + "audio": a, + "720p": b, + "1080p": c, + "worst": b, + "best": c + } + self.assertEqual( + format_valid_streams(FakePlugin, streams), + ", ".join([ + "audio", + "720p (worst)", + "1080p (best)" + ]) + ) + + streams = { + "audio": a, + "720p": b, + "1080p": c, + "worst-unfiltered": b, + "best-unfiltered": c + } + self.assertEqual( + format_valid_streams(FakePlugin, streams), + ", ".join([ + "audio", + "720p (worst-unfiltered)", + "1080p (best-unfiltered)" + ]) + ) diff --git a/tests/test_session.py b/tests/test_session.py index 573aae37..e923ab53 100644 --- a/tests/test_session.py +++ b/tests/test_session.py @@ -99,12 +99,23 @@ class TestSession(unittest.TestCase): self.assertTrue(isinstance(streams["480p"], RTMPStream)) self.assertTrue(isinstance(streams["480p_http"], HTTPStream)) - def test_plugin_stream_sorted_excludes(self): + def test_plugin_stream_sorting_excludes(self): channel = self.session.resolve_url("http://test.se/channel") - streams = channel.streams(sorting_excludes=["1080p", "3000k"]) + streams = channel.streams(sorting_excludes=[]) self.assertTrue("best" in streams) self.assertTrue("worst" in streams) + self.assertFalse("best-unfiltered" in streams) + self.assertFalse("worst-unfiltered" in streams) + self.assertTrue(streams["worst"] is streams["350k"]) + self.assertTrue(streams["best"] is streams["1080p"]) + + streams = channel.streams(sorting_excludes=["1080p", "3000k"]) + self.assertTrue("best" in streams) + self.assertTrue("worst" in streams) + self.assertFalse("best-unfiltered" in streams) + self.assertFalse("worst-unfiltered" in streams) + self.assertTrue(streams["worst"] is streams["350k"]) self.assertTrue(streams["best"] is streams["1500k"]) streams = channel.streams(sorting_excludes=[">=1080p", ">1500k"]) @@ -113,6 +124,24 @@ class TestSession(unittest.TestCase): streams = channel.streams(sorting_excludes=lambda q: not q.endswith("p")) self.assertTrue(streams["best"] is streams["3000k"]) + streams = channel.streams(sorting_excludes=lambda q: False) + self.assertFalse("best" in streams) + self.assertFalse("worst" in streams) + self.assertTrue("best-unfiltered" in streams) + self.assertTrue("worst-unfiltered" in streams) + self.assertTrue(streams["worst-unfiltered"] is streams["350k"]) + self.assertTrue(streams["best-unfiltered"] is streams["1080p"]) + + channel = self.session.resolve_url("http://test.se/UnsortableStreamNames") + streams = channel.streams() + self.assertFalse("best" in streams) + self.assertFalse("worst" in streams) + self.assertFalse("best-unfiltered" in streams) + self.assertFalse("worst-unfiltered" in streams) + self.assertTrue("vod" in streams) + self.assertTrue("vod_alt" in streams) + self.assertTrue("vod_alt2" in streams) + def test_plugin_support(self): channel = self.session.resolve_url("http://test.se/channel") streams = channel.streams()
Fallback selection for --stream-sorting-excludes ### Checklist - [ ] This is a bug report. - [x] This is a feature request. - [ ] This is a plugin (improvement) request. - [ ] I have read the contribution guidelines. ### Description Related issue: https://github.com/streamlink/streamlink-twitch-gui/issues/481 In certain situations, the usage of `--stream-sorting-excludes` can lead to an empty stream selection. This is an issue for applications which try to map the available streams to a custom list of qualities. The Streamlink Twitch GUI needs to do this stream quality mapping because of Twitch's inconsistent quality naming. This is an example of trying to find the "low" quality: ``` # available: 160p, 360p, 480p, 720p, 1080p streamlink --stream-sorting-excludes ">360p" twitch.tv/CHANNEL low,best # will open 360p # available: low, medium, high, source streamlink --stream-sorting-excludes ">360p" twitch.tv/CHANNEL low,best # will open low # available: 720p streamlink --stream-sorting-excludes ">360p" twitch.tv/CHANNEL low,best # returns an empty selection (channel doesn't have re-encoded qualities) ``` Having a fallback parameter (eg. `--stream-sorting-excludes-fallback`) with a list of streams that will be opened if no matching stream could be found would fix this situation. Another solution could be having a different notation in the actual quality selection, but this is probably a bit too complex. ``` # 1. try to find the quality labeled "medium" # 2. look for qualities named by video resolution matching the defined range # 3. fall back to lower qualities # 4. use any available quality streamlink twitch.tv/CHANNEL "medium||>360p&&<=480p||<=360p||best" streamlink twitch.tv/CHANNEL "medium,>360p<=480p,<=360p,best" ```
0.0
7b5f4f775b70281c0970af9048e556258da11582
[ "tests/test_cli_main.py::TestCLIMain::test_format_valid_streams", "tests/test_cli_main.py::TestCLIMain::test_resolve_stream_name", "tests/test_session.py::TestSession::test_plugin_stream_sorting_excludes" ]
[ "tests/test_cli_main.py::TestCLIMain::test_check_file_output", "tests/test_cli_main.py::TestCLIMain::test_check_file_output_exists", "tests/test_cli_main.py::TestCLIMain::test_check_file_output_exists_force", "tests/test_cli_main.py::TestCLIMain::test_check_file_output_exists_no", "tests/test_cli_main.py::TestCLIMain::test_check_file_output_exists_notty", "tests/test_session.py::TestSession::test_builtin_plugins", "tests/test_session.py::TestSession::test_exceptions", "tests/test_session.py::TestSession::test_load_plugins", "tests/test_session.py::TestSession::test_options", "tests/test_session.py::TestSession::test_plugin", "tests/test_session.py::TestSession::test_plugin_stream_types", "tests/test_session.py::TestSession::test_plugin_support", "tests/test_session.py::TestSession::test_resolve_url", "tests/test_session.py::TestSession::test_resolve_url_no_redirect", "tests/test_session.py::TestSession::test_resolve_url_priority", "tests/test_session.py::TestSession::test_set_and_get_locale", "tests/test_session.py::TestSession::test_short_exception" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2018-10-22 12:13:43+00:00
bsd-2-clause
5,773
streamlink__streamlink-2134
diff --git a/src/streamlink/plugins/huomao.py b/src/streamlink/plugins/huomao.py index aee762b3..e0d5770f 100644 --- a/src/streamlink/plugins/huomao.py +++ b/src/streamlink/plugins/huomao.py @@ -4,8 +4,8 @@ simply extracts the videos stream_id, stream_url and stream_quality by scraping the HTML and JS of one of Huomaos mobile webpages. When viewing a stream on huomao.com, the base URL references a room_id. This -room_id is mapped one-to-one to a stream_id which references the actual .flv -video. Both stream_id, stream_url and stream_quality can be found in the +room_id is mapped one-to-one to a stream_id which references the actual .m3u8 +file. Both stream_id, stream_url and stream_quality can be found in the HTML and JS source of the mobile_page. Since one stream can occur in many different qualities, we scrape all stream_url and stream_quality occurrences and return each option to the user. @@ -14,7 +14,7 @@ and return each option to the user. import re from streamlink.plugin import Plugin -from streamlink.stream import HTTPStream +from streamlink.stream import HLSStream # URL pattern for recognizing inputed Huomao.tv / Huomao.com URL. url_re = re.compile(r""" @@ -35,18 +35,15 @@ mobile_url = "http://www.huomao.com/mobile/mob_live/{0}" # <input id="html_stream" value="efmrCH" type="hidden"> stream_id_pattern = re.compile(r'id=\"html_stream\" value=\"(?P<stream_id>\w+)\"') -# Pattern for extracting each stream_url, stream_quality_url and a prettified +# Pattern for extracting each stream_url and # stream_quality_name used for quality naming. # # Example from HTML: -# "2: 'http://live-ws.huomaotv.cn/live/'+stream+'_720/playlist.m3u8'" +# src="http://live-ws-hls.huomaotv.cn/live/<stream_id>_720/playlist.m3u8" stream_info_pattern = re.compile(r""" - [1-9]: - \s+ - '(?P<stream_url>(?:\w|\.|:|-|/)+) - '\+stream\+' - (?P<stream_quality_url>_?(?P<stream_quality_name>\d*)) - /playlist.m3u8' + (?P<stream_url>(?:[\w\/\.\-:]+) + \/[^_\"]+(?:_(?P<stream_quality_name>\d+)) + ?/playlist.m3u8) """, re.VERBOSE) @@ -65,11 +62,11 @@ class Huomao(Plugin): return stream_id.group("stream_id") def get_stream_info(self, html): - """Returns a nested list of different stream options. + """ + Returns a nested list of different stream options. - Each entry in the list will contain a stream_url, stream_quality_url - and stream_quality_name for each stream occurrence that was found in - the JS. + Each entry in the list will contain a stream_url and stream_quality_name + for each stream occurrence that was found in the JS. """ stream_info = stream_info_pattern.findall(html) @@ -80,8 +77,8 @@ class Huomao(Plugin): # list and reassigning. stream_info_list = [] for info in stream_info: - if not info[2]: - stream_info_list.append([info[0], info[1], "source"]) + if not info[1]: + stream_info_list.append([info[0], "source"]) else: stream_info_list.append(list(info)) @@ -95,8 +92,8 @@ class Huomao(Plugin): streams = {} for info in stream_info: - streams[info[2]] = HTTPStream(self.session, - info[0] + stream_id + info[1] + ".flv") + if stream_id in info[0]: + streams[info[1]] = HLSStream(self.session, info[0]) return streams
streamlink/streamlink
c1a2962d992be93da495aa82627b9a736377380f
diff --git a/tests/plugins/test_huomao.py b/tests/plugins/test_huomao.py index a27efdcb..1261680f 100644 --- a/tests/plugins/test_huomao.py +++ b/tests/plugins/test_huomao.py @@ -15,15 +15,12 @@ class TestPluginHuomao(unittest.TestCase): # room_id = 123456 # stream_id = 9qsvyF24659 # stream_url = http://live-ws.huomaotv.cn/live/ - # stream_quality = source, _720 and _480 # stream_quality_name = source, 720 and 480 self.mock_html = """ <input id="html_stream" value="9qsvyF24659" type="hidden"> - <!-- urls:{--> - <!-- 1: 'http://live-ws.huomaotv.cn/live/'+stream+'/playlist.m3u8',--> - <!-- 2: 'http://live-ws.huomaotv.cn/live/'+stream+'_720/playlist.m3u8',--> - <!-- 3: 'http://live-ws.huomaotv.cn/live/'+stream+'_480/playlist.m3u8'--> - <!-- },--> + <source src="http://live-ws-hls.huomaotv.cn/live/9qsvyF24659/playlist.m3u8"> + <source src="http://live-ws-hls.huomaotv.cn/live/9qsvyF24659_720/playlist.m3u8"> + <source src="http://live-ws-hls.huomaotv.cn/live/9qsvyF24659_480/playlist.m3u8"> """ # Create a mock Huomao object. @@ -43,9 +40,9 @@ class TestPluginHuomao(unittest.TestCase): # Assert that the stream_url, stream_quality and stream_quality_name # is correctly extracted from the mock HTML. self.assertEqual(self.mock_huomao.get_stream_info(self.mock_html), [ - ["http://live-ws.huomaotv.cn/live/", "", "source"], - ["http://live-ws.huomaotv.cn/live/", "_720", "720"], - ["http://live-ws.huomaotv.cn/live/", "_480", "480"] + ["http://live-ws-hls.huomaotv.cn/live/9qsvyF24659/playlist.m3u8", "source"], + ["http://live-ws-hls.huomaotv.cn/live/9qsvyF24659_720/playlist.m3u8", "720"], + ["http://live-ws-hls.huomaotv.cn/live/9qsvyF24659_480/playlist.m3u8", "480"] ]) def test_can_handle_url(self):
Huomao plugin not work <!-- Thanks for reporting a plugin issue! USE THE TEMPLATE. Otherwise your plugin issue may be rejected. First, see the contribution guidelines: https://github.com/streamlink/streamlink/blob/master/CONTRIBUTING.md#contributing-to-streamlink Also check the list of open and closed plugin issues: https://github.com/streamlink/streamlink/issues?q=is%3Aissue+label%3A%22plugin+issue%22 Please see the text preview to avoid unnecessary formatting errors. --> ## Plugin Issue <!-- Replace [ ] with [x] in order to check the box --> - [x] This is a plugin issue and I have read the contribution guidelines. ### Description I found huomao plugin seems not work, i can use browser to watch stream but streamlink says no playable stream <!-- Explain the plugin issue as thoroughly as you can. --> ### Reproduction steps / Explicit stream URLs to test <!-- How can we reproduce this? Please note the exact steps below using the list format supplied. If you need more steps please add them. --> 1. https://www.huomao.com/9755 2. https://www.huomao.com/777777 3. https://www.huomao.com/888 ### Log output <!-- TEXT LOG OUTPUT IS REQUIRED for a plugin issue! Use the `--loglevel debug` parameter and avoid using parameters which suppress log output. https://streamlink.github.io/cli.html#cmdoption-l Make sure to **remove usernames and passwords** You can copy the output to https://gist.github.com/ or paste it below. --> ``` [cli][info] Found matching plugin huomao for URL https://www.huomao.com/888 [plugin.huomao][error] Failed to extract stream_info. error: No playable streams found on this URL: https://www.huomao.com/888 ```
0.0
c1a2962d992be93da495aa82627b9a736377380f
[ "tests/plugins/test_huomao.py::TestPluginHuomao::test_get_stream_quality" ]
[ "tests/plugins/test_huomao.py::TestPluginHuomao::test_can_handle_url", "tests/plugins/test_huomao.py::TestPluginHuomao::test_get_stream_id" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2018-10-23 20:47:35+00:00
bsd-2-clause
5,774
streamlink__streamlink-2160
diff --git a/src/streamlink/plugins/ine.py b/src/streamlink/plugins/ine.py index 8ebc9109..e0389b7e 100644 --- a/src/streamlink/plugins/ine.py +++ b/src/streamlink/plugins/ine.py @@ -23,7 +23,7 @@ class INE(Plugin): validate.all( validate.get(1), validate.transform(json.loads), - {"playlist": str}, + {"playlist": validate.text}, validate.get("playlist") ) ) diff --git a/src/streamlink/plugins/skai.py b/src/streamlink/plugins/skai.py index 61fba7ec..d43fcafd 100644 --- a/src/streamlink/plugins/skai.py +++ b/src/streamlink/plugins/skai.py @@ -3,20 +3,15 @@ import re from streamlink.plugin import Plugin from streamlink.plugin.api import validate -YOUTUBE_URL = "https://www.youtube.com/watch?v={0}" -_url_re = re.compile(r'http(s)?://www\.skai.gr/.*') -_youtube_id = re.compile(r'<span\s+itemprop="contentUrl"\s+href="(.*)"></span>', re.MULTILINE) -_youtube_url_schema = validate.Schema( - validate.all( - validate.transform(_youtube_id.search), - validate.any( - None, - validate.all( - validate.get(1), - validate.text - ) - ) - ) + +_url_re = re.compile(r'http(s)?://www\.skai(?:tv)?.gr/.*') +_api_url = "http://www.skaitv.gr/json/live.php" +_api_res_schema = validate.Schema(validate.all( + validate.get("now"), + { + "livestream": validate.url() + }, + validate.get("livestream")) ) @@ -26,9 +21,10 @@ class Skai(Plugin): return _url_re.match(url) def _get_streams(self): - channel_id = self.session.http.get(self.url, schema=_youtube_url_schema) - if channel_id: - return self.session.streams(YOUTUBE_URL.format(channel_id)) + api_res = self.session.http.get(_api_url) + yt_url = self.session.http.json(api_res, schema=_api_res_schema) + if yt_url: + return self.session.streams(yt_url) __plugin__ = Skai
streamlink/streamlink
649f483ab3b4906a6c4b352c0b21d08efb40d700
diff --git a/tests/plugins/test_skai.py b/tests/plugins/test_skai.py index f2347407..f07e61ee 100644 --- a/tests/plugins/test_skai.py +++ b/tests/plugins/test_skai.py @@ -7,6 +7,7 @@ class TestPluginSkai(unittest.TestCase): def test_can_handle_url(self): should_match = [ 'http://www.skai.gr/player/tvlive/', + 'http://www.skaitv.gr/live', ] for url in should_match: self.assertTrue(Skai.can_handle_url(url))
Skai plugin broken <!-- Thanks for reporting a plugin issue! USE THE TEMPLATE. Otherwise your plugin issue may be rejected. First, see the contribution guidelines: https://github.com/streamlink/streamlink/blob/master/CONTRIBUTING.md#contributing-to-streamlink Also check the list of open and closed plugin issues: https://github.com/streamlink/streamlink/issues?q=is%3Aissue+label%3A%22plugin+issue%22 Please see the text preview to avoid unnecessary formatting errors. --> ## Plugin Issue - [x] This is a plugin issue and I have read the contribution guidelines. ### Description Skai plugin is broken since yesterday, but actually it is no longer needed because they provide a lot more stable stream (they don't change stream three or so times a day). **Imho it can be removed.** New live url as follows: http://www.skaitv.gr/live
0.0
649f483ab3b4906a6c4b352c0b21d08efb40d700
[ "tests/plugins/test_skai.py::TestPluginSkai::test_can_handle_url" ]
[ "tests/plugins/test_skai.py::TestPluginSkai::test_can_handle_url_negative" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2018-11-09 19:15:05+00:00
bsd-2-clause
5,775
streamlink__streamlink-2228
diff --git a/setup.py b/setup.py index 54007193..2ec570ab 100644 --- a/setup.py +++ b/setup.py @@ -13,8 +13,8 @@ deps = [ 'futures;python_version<"3.0"', # Require singledispatch on Python <3.4 'singledispatch;python_version<"3.4"', - "requests>=2.2,!=2.12.0,!=2.12.1,!=2.16.0,!=2.16.1,!=2.16.2,!=2.16.3,!=2.16.4,!=2.16.5,!=2.17.1,<3.0", - 'urllib3[secure]<1.23,>=1.21.1;python_version<"3.0"', + "requests>=2.21.0,<3.0", + 'urllib3[secure]>=1.23;python_version<"3.0"', "isodate", "websocket-client", # Support for SOCKS proxies diff --git a/src/streamlink/plugins/filmon.py b/src/streamlink/plugins/filmon.py index ffc0fbe6..1a2e77eb 100644 --- a/src/streamlink/plugins/filmon.py +++ b/src/streamlink/plugins/filmon.py @@ -164,7 +164,7 @@ class Filmon(Plugin): | (?:tv/)channel/(?:export\?)? | - tv/(?!channel) + tv/(?!channel/) | channel/ | diff --git a/src/streamlink_cli/output.py b/src/streamlink_cli/output.py index 925a802c..976884af 100644 --- a/src/streamlink_cli/output.py +++ b/src/streamlink_cli/output.py @@ -207,7 +207,11 @@ class PlayerOutput(Output): def _open_call(self): args = self._create_arguments() - log.debug(u"Calling: {0}".format(subprocess.list2cmdline(args))) + if is_win32: + fargs = args + else: + fargs = subprocess.list2cmdline(args) + log.debug(u"Calling: {0}".format(fargs)) subprocess.call(args, stdout=self.stdout, stderr=self.stderr) @@ -216,7 +220,11 @@ class PlayerOutput(Output): # Force bufsize=0 on all Python versions to avoid writing the # unflushed buffer when closing a broken input pipe args = self._create_arguments() - log.debug(u"Opening subprocess: {0}".format(subprocess.list2cmdline(args))) + if is_win32: + fargs = args + else: + fargs = subprocess.list2cmdline(args) + log.debug(u"Opening subprocess: {0}".format(fargs)) self.player = subprocess.Popen(args, stdin=self.stdin, bufsize=0, stdout=self.stdout,
streamlink/streamlink
94a8a7301c45dfdee89dd7d4d14043438dda4b38
diff --git a/tests/plugins/test_filmon.py b/tests/plugins/test_filmon.py index a62d407d..ab30fc5d 100644 --- a/tests/plugins/test_filmon.py +++ b/tests/plugins/test_filmon.py @@ -10,24 +10,25 @@ class TestPluginFilmon(unittest.TestCase): 'http://www.filmon.tv/index/popout?channel_id=5510&quality=low', 'http://www.filmon.tv/tv/channel/export?channel_id=5510&autoPlay=1', 'http://www.filmon.tv/tv/channel/grandstand-show', + 'http://www.filmon.tv/tv/channel-4', 'https://www.filmon.com/tv/bbc-news', 'https://www.filmon.tv/tv/55', 'http://www.filmon.tv/vod/view/10250-0-crime-boss', 'http://www.filmon.tv/group/comedy', ] for url in should_match: - self.assertTrue(Filmon.can_handle_url(url)) + self.assertTrue(Filmon.can_handle_url(url), url) def test_can_handle_url_negative(self): should_not_match = [ 'https://example.com/index.html', ] for url in should_not_match: - self.assertFalse(Filmon.can_handle_url(url)) + self.assertFalse(Filmon.can_handle_url(url), url) def _test_regex(self, url, expected): m = Filmon.url_re.match(url) - self.assertIsNotNone(m) + self.assertIsNotNone(m, url) # expected must return [is_group, channel, vod_id] self.assertEqual(expected, list(m.groups())) @@ -51,6 +52,10 @@ class TestPluginFilmon(unittest.TestCase): self._test_regex('https://www.filmon.com/tv/bbc-news', [None, 'bbc-news', None]) + def test_regex_live_stream_tv_with_channel_in_name(self): + self._test_regex('https://www.filmon.com/tv/channel-4', + [None, 'channel-4', None]) + def test_regex_live_stream_tv_number(self): self._test_regex('https://www.filmon.tv/tv/55', [None, '55', None])
FilmOn.py No plugin can handle ## Error Report - [x] This is a bug report and I have read the post guidelines. ### Description On the homepage of Film On the UK channels are played without problem. Unfortunately not with Streamlink. Here it fails with the transmitter Channel4 and Channel5 ### Expected / actual behavior I enter the address and there is no picture. streamlink http://www.filmon.com/tv/channel-4 best ### Reproduction steps / Explicit stream URLs to test 1.https: //www.filmon.com/tv/channel-4 2.https: //www.filmon.com/tv/channel-5 ### log output Not Work with Channel4: WINDOWS> streamlink http://www.filmon.com/tv/channel-4 best error: No plugin can handle URL: http://www.filmon.com/tv/channel-4 Work with More4 WINDOWS> streamlink https://www.filmon.com/tv/more4 best [cli][info] Found matching plugin filmon for URL https://www.filmon.com/tv/more4 [cli][info] Available streams: low (worst), high (best) [cli][info] Opening stream: high (hls-filmon) [cli][info] Starting player: "C:\Program Files (x86)\VideoLAN\VLC\vlc.exe" [cli][info] Player closed [cli][info] Stream ended [cli][info] Closing currently open stream... ### Additional comments, screenshots, etc. https://i.ibb.co/FDs2QtX/film-on.jpg
0.0
94a8a7301c45dfdee89dd7d4d14043438dda4b38
[ "tests/plugins/test_filmon.py::TestPluginFilmon::test_can_handle_url", "tests/plugins/test_filmon.py::TestPluginFilmon::test_regex_live_stream_tv_with_channel_in_name" ]
[ "tests/plugins/test_filmon.py::TestPluginFilmon::test_can_handle_url_negative", "tests/plugins/test_filmon.py::TestPluginFilmon::test_regex_group", "tests/plugins/test_filmon.py::TestPluginFilmon::test_regex_live_stream_channel", "tests/plugins/test_filmon.py::TestPluginFilmon::test_regex_live_stream_export", "tests/plugins/test_filmon.py::TestPluginFilmon::test_regex_live_stream_index_popout", "tests/plugins/test_filmon.py::TestPluginFilmon::test_regex_live_stream_tv", "tests/plugins/test_filmon.py::TestPluginFilmon::test_regex_live_stream_tv_channel", "tests/plugins/test_filmon.py::TestPluginFilmon::test_regex_live_stream_tv_number", "tests/plugins/test_filmon.py::TestPluginFilmon::test_regex_vod" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_media", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2019-01-03 12:48:51+00:00
bsd-2-clause
5,776
streamlink__streamlink-2524
diff --git a/src/streamlink/plugins/cdnbg.py b/src/streamlink/plugins/cdnbg.py index 79b0172b..ee7a8a82 100644 --- a/src/streamlink/plugins/cdnbg.py +++ b/src/streamlink/plugins/cdnbg.py @@ -23,6 +23,7 @@ class CDNBG(Plugin): mmtvmusic\.com/live| mu-vi\.tv/LiveStreams/pages/Live\.aspx| videochanel\.bstv\.bg| + live\.bstv\.bg| bloombergtv.bg/video )/? """, re.VERBOSE) diff --git a/src/streamlink/plugins/pixiv.py b/src/streamlink/plugins/pixiv.py index c1f83685..7cdee837 100644 --- a/src/streamlink/plugins/pixiv.py +++ b/src/streamlink/plugins/pixiv.py @@ -73,6 +73,25 @@ class Pixiv(Plugin): A pixiv.net account password to use with --pixiv-username """ ), + PluginArgument( + "sessionid", + requires=["devicetoken"], + sensitive=True, + metavar="SESSIONID", + help=""" + The pixiv.net sessionid thats used in pixivs PHPSESSID cookie. + can be used instead of the username/password login process. + """ + ), + PluginArgument( + "devicetoken", + sensitive=True, + metavar="DEVICETOKEN", + help=""" + The pixiv.net device token thats used in pixivs device_token cookie. + can be used instead of the username/password login process. + """ + ), PluginArgument( "purge-credentials", action="store_true", @@ -125,6 +144,17 @@ class Pixiv(Plugin): else: log.error("Failed to log in.") + + def _login_using_session_id_and_device_token(self, session_id, device_token): + res = self.session.http.get(self.login_url_get) + + self.session.http.cookies.set('PHPSESSID', session_id, domain='.pixiv.net', path='/') + self.session.http.cookies.set('device_token', device_token, domain='.pixiv.net', path='/') + + self.save_cookies() + log.info("Successfully set sessionId and deviceToken") + + def hls_stream(self, hls_url): log.debug("URL={0}".format(hls_url)) for s in HLSStream.parse_variant_playlist(self.session, hls_url).items(): @@ -146,6 +176,9 @@ class Pixiv(Plugin): login_username = self.get_option("username") login_password = self.get_option("password") + login_session_id = self.get_option("sessionid") + login_device_token = self.get_option("devicetoken") + if self.options.get("purge_credentials"): self.clear_cookies() self._authed = False @@ -155,6 +188,8 @@ class Pixiv(Plugin): log.debug("Attempting to authenticate using cached cookies") elif not self._authed and login_username and login_password: self._login(login_username, login_password) + elif not self._authed and login_session_id and login_device_token: + self._login_using_session_id_and_device_token(login_session_id, login_device_token) streamer_data = self.get_streamer_data() performers = streamer_data.get("performers") diff --git a/src/streamlink/plugins/schoolism.py b/src/streamlink/plugins/schoolism.py index 5285c2a7..88d33312 100644 --- a/src/streamlink/plugins/schoolism.py +++ b/src/streamlink/plugins/schoolism.py @@ -17,8 +17,9 @@ class Schoolism(Plugin): url_re = re.compile(r"https?://(?:www\.)?schoolism\.com/(viewAssignment|watchLesson).php") login_url = "https://www.schoolism.com/index.php" key_time_url = "https://www.schoolism.com/video-html/key-time.php" - playlist_re = re.compile(r"var allVideos\s*=\s*(\[\{.*\}]);", re.DOTALL) + playlist_re = re.compile(r"var allVideos\s*=\s*(\[.*\]);", re.DOTALL) js_to_json = partial(re.compile(r'(?!<")(\w+):(?!/)').sub, r'"\1":') + fix_brackets = partial(re.compile(r',\s*\}').sub, r'}') playlist_schema = validate.Schema( validate.transform(playlist_re.search), validate.any( @@ -26,7 +27,7 @@ class Schoolism(Plugin): validate.all( validate.get(1), validate.transform(js_to_json), - validate.transform(lambda x: x.replace(",}", "}")), # remove invalid , + validate.transform(fix_brackets), # remove invalid , validate.transform(parse_json), [{ "sources": validate.all([{ diff --git a/src/streamlink/plugins/ustvnow.py b/src/streamlink/plugins/ustvnow.py index f02446df..4d6c213d 100644 --- a/src/streamlink/plugins/ustvnow.py +++ b/src/streamlink/plugins/ustvnow.py @@ -1,24 +1,33 @@ from __future__ import unicode_literals +import argparse +import base64 +import json import logging import re -from collections import OrderedDict +from uuid import uuid4 +from Crypto.Cipher import AES +from Crypto.Hash import SHA256 +from Crypto.Util.Padding import pad, unpad + +from streamlink import PluginError +from streamlink.compat import urljoin, urlparse from streamlink.plugin import Plugin, PluginArguments, PluginArgument -from streamlink.plugin.api import useragents -from streamlink.plugin.api.utils import itertags from streamlink.stream import HLSStream log = logging.getLogger(__name__) class USTVNow(Plugin): - _url_re = re.compile(r"https?://(?:watch\.)?ustvnow\.com(?:/(?:watch|guide)/(?P<scode>\w+))?") - _token_re = re.compile(r'''var\s+token\s*=\s*"(.*?)";''') - _login_url = "https://watch.ustvnow.com/account/login" - _signin_url = "https://watch.ustvnow.com/account/signin" - _guide_url = "http://m.ustvnow.com/gtv/1/live/channelguidehtml" - _stream_url = "http://m.ustvnow.com/stream/1/live/view" + _url_re = re.compile(r"https?://(?:www\.)?ustvnow\.com/live/(?P<scode>\w+)/-(?P<id>\d+)") + _main_js_re = re.compile(r"""src=['"](main\..*\.js)['"]""") + _enc_key_re = re.compile(r'(?P<key>AES_(?:Key|IV))\s*:\s*"(?P<value>[^"]+)"') + + TENANT_CODE = "ustvnow" + _api_url = "https://teleupapi.revlet.net/service/api/v1/" + _token_url = _api_url + "get/token" + _signin_url = "https://www.ustvnow.com/signin" arguments = PluginArguments( PluginArgument( @@ -38,65 +47,135 @@ class USTVNow(Plugin): PluginArgument( "station-code", metavar="CODE", - help="USTV Now station code" + help=argparse.SUPPRESS ), ) + def __init__(self, url): + super(USTVNow, self).__init__(url) + self._encryption_config = {} + self._token = None + @classmethod def can_handle_url(cls, url): return cls._url_re.match(url) is not None - def login(self, username, password): - r = self.session.http.get(self._signin_url) - csrf = None + @classmethod + def encrypt_data(cls, data, key, iv): + rkey = "".join(reversed(key)).encode('utf8') + riv = "".join(reversed(iv)).encode('utf8') + + fkey = SHA256.new(rkey).hexdigest()[:32].encode("utf8") + + cipher = AES.new(fkey, AES.MODE_CBC, riv) + encrypted = cipher.encrypt(pad(data, 16, 'pkcs7')) + return base64.b64encode(encrypted) - for input in itertags(r.text, "input"): - if input.attributes['name'] == "csrf_ustvnow": - csrf = input.attributes['value'] + @classmethod + def decrypt_data(cls, data, key, iv): + rkey = "".join(reversed(key)).encode('utf8') + riv = "".join(reversed(iv)).encode('utf8') - log.debug("CSRF: {0}", csrf) + fkey = SHA256.new(rkey).hexdigest()[:32].encode("utf8") - r = self.session.http.post(self._login_url, data={'csrf_ustvnow': csrf, - 'signin_email': username, - 'signin_password': password, - 'signin_remember': '1'}) - m = self._token_re.search(r.text) - return m and m.group(1) + cipher = AES.new(fkey, AES.MODE_CBC, riv) + decrypted = cipher.decrypt(base64.b64decode(data)) + if decrypted: + return unpad(decrypted, 16, 'pkcs7') + else: + return decrypted + + def _get_encryption_config(self, url): + # find the path to the main.js + # load the main.js and extract the config + if not self._encryption_config: + res = self.session.http.get(url) + m = self._main_js_re.search(res.text) + main_js_path = m and m.group(1) + if main_js_path: + res = self.session.http.get(urljoin(url, main_js_path)) + self._encryption_config = dict(self._enc_key_re.findall(res.text)) + + return self._encryption_config.get("AES_Key"), self._encryption_config.get("AES_IV") + + @property + def box_id(self): + if not self.cache.get("box_id"): + self.cache.set("box_id", str(uuid4())) + return self.cache.get("box_id") + + def get_token(self): + """ + Get the token for USTVNow + :return: a valid token + """ + + if not self._token: + log.debug("Getting new session token") + res = self.session.http.get(self._token_url, params={ + "tenant_code": self.TENANT_CODE, + "box_id": self.box_id, + "product": self.TENANT_CODE, + "device_id": 5, + "display_lang_code": "ENG", + "device_sub_type": "", + "timezone": "UTC" + }) + + data = res.json() + if data['status']: + self._token = data['response']['sessionId'] + log.debug("New token: {}".format(self._token)) + else: + log.error("Token acquisition failed: {details} ({detail})".format(**data['error'])) + raise PluginError("could not obtain token") + + return self._token + + def api_request(self, path, data, metadata=None): + key, iv = self._get_encryption_config(self._signin_url) + post_data = { + "data": self.encrypt_data(json.dumps(data).encode('utf8'), key, iv).decode("utf8"), + "metadata": self.encrypt_data(json.dumps(metadata).encode('utf8'), key, iv).decode("utf8") + } + headers = {"box-id": self.box_id, + "session-id": self.get_token(), + "tenant-code": self.TENANT_CODE, + "content-type": "application/json"} + res = self.session.http.post(self._api_url + path, data=json.dumps(post_data), headers=headers).json() + data = dict((k, v and json.loads(self.decrypt_data(v, key, iv)))for k, v in res.items()) + return data + + def login(self, username, password): + log.debug("Trying to login...") + resp = self.api_request("send", + { + "login_id": username, + "login_key": password, + "login_mode": "1", + "manufacturer": "123" + }, + {"request": "signin"}) + + return resp['data']['status'] def _get_streams(self): """ - Finds the streams from tvcatchup.com. + Finds the streams from ustvnow.com. """ - token = self.login(self.get_option("username"), self.get_option("password")) - m = self._url_re.match(self.url) - scode = m and m.group("scode") or self.get_option("station_code") - - res = self.session.http.get(self._guide_url, params=dict(token=token)) - - channels = OrderedDict() - for t in itertags(res.text, "a"): - if t.attributes.get('cs'): - channels[t.attributes.get('cs').lower()] = t.attributes.get('title').replace("Watch ", "").strip() - - if not scode: - log.error("Station code not provided, use --ustvnow-station-code.") - log.info("Available stations are: \n{0} ".format('\n'.join(' {0} ({1})'.format(c, n) for c, n in channels.items()))) - return - - if scode in channels: - log.debug("Finding streams for: {0}", channels.get(scode)) - - r = self.session.http.get(self._stream_url, params={"scode": scode, - "token": token, - "br_n": "Firefox", - "br_v": "52", - "br_d": "desktop"}, - headers={"User-Agent": useragents.FIREFOX}) - - data = self.session.http.json(r) - return HLSStream.parse_variant_playlist(self.session, data["stream"]) + if self.login(self.get_option("username"), self.get_option("password")): + path = urlparse(self.url).path.strip("/") + resp = self.api_request("send", {"path": path}, {"request": "page/stream"}) + if resp['data']['status']: + for stream in resp['data']['response']['streams']: + if stream['keys']['licenseKey']: + log.warning("Stream possibly protected by DRM") + for q, s in HLSStream.parse_variant_playlist(self.session, stream['url']).items(): + yield (q, s) + else: + log.error("Could not find any streams: {code}: {message}".format(**resp['data']['error'])) else: - log.error("Invalid station-code: {0}", scode) + log.error("Failed to login, check username and password") __plugin__ = USTVNow
streamlink/streamlink
209e43186b6bcf34c58f06019e8491f7ee2587d7
diff --git a/tests/plugins/test_cdnbg.py b/tests/plugins/test_cdnbg.py index b98b16ee..898cb598 100644 --- a/tests/plugins/test_cdnbg.py +++ b/tests/plugins/test_cdnbg.py @@ -23,6 +23,7 @@ class TestPluginCDNBG(unittest.TestCase): self.assertTrue(CDNBG.can_handle_url("https://mmtvmusic.com/live/")) self.assertTrue(CDNBG.can_handle_url("http://mu-vi.tv/LiveStreams/pages/Live.aspx")) self.assertTrue(CDNBG.can_handle_url("http://videochanel.bstv.bg/")) + self.assertTrue(CDNBG.can_handle_url("http://live.bstv.bg/")) self.assertTrue(CDNBG.can_handle_url("https://www.bloombergtv.bg/video")) # shouldn't match diff --git a/tests/plugins/test_schoolism.py b/tests/plugins/test_schoolism.py index 8890ee11..f37e85e8 100644 --- a/tests/plugins/test_schoolism.py +++ b/tests/plugins/test_schoolism.py @@ -17,3 +17,37 @@ class TestPluginSchoolism(unittest.TestCase): ] for url in should_not_match: self.assertFalse(Schoolism.can_handle_url(url)) + + def test_playlist_parse_subs(self): + with_subs = """var allVideos=[ + {sources:[{type:"application/x-mpegurl",src:"https://d8u31iyce9xic.cloudfront.net/44/2/part1.m3u8?Policy=TOKEN&Signature=TOKEN&Key-Pair-Id=TOKEN",title:"Digital Painting - Lesson 2 - Part 1",playlistTitle:"Part 1",}], subtitles: [{ + "default": true, + kind: "subtitles", srclang: "en", label: "English", + src: "https://s3.amazonaws.com/schoolism-encoded/44/subtitles/2/2-1.vtt", + }], + }, + {sources:[{type:"application/x-mpegurl",src:"https://d8u31iyce9xic.cloudfront.net/44/2/part2.m3u8?Policy=TOKEN&Signature=TOKEN&Key-Pair-Id=TOKEN",title:"Digital Painting - Lesson 2 - Part 2",playlistTitle:"Part 2",}], subtitles: [{ + "default": true, + kind: "subtitles", srclang: "en", label: "English", + src: "https://s3.amazonaws.com/schoolism-encoded/44/subtitles/2/2-2.vtt", + }] + }]; + """ + + data = Schoolism.playlist_schema.validate(with_subs) + + self.assertIsNotNone(data) + self.assertEqual(2, len(data)) + + + def test_playlist_parse(self): + without_subs = """var allVideos=[ + {sources:[{type:"application/x-mpegurl",src:"https://d8u31iyce9xic.cloudfront.net/14/1/part1.m3u8?Policy=TOKEN&Signature=TOKEN&Key-Pair-Id=TOKEN",title:"Gesture Drawing - Lesson 1 - Part 1",playlistTitle:"Part 1",}],}, + {sources:[{type:"application/x-mpegurl",src:"https://d8u31iyce9xic.cloudfront.net/14/1/part2.m3u8?Policy=TOKEN&Signature=TOKEN&Key-Pair-Id=TOKEN",title:"Gesture Drawing - Lesson 1 - Part 2",playlistTitle:"Part 2",}]} + ]; + """ + + data = Schoolism.playlist_schema.validate(without_subs) + + self.assertIsNotNone(data) + self.assertEqual(2, len(data)) diff --git a/tests/plugins/test_ustvnow.py b/tests/plugins/test_ustvnow.py index c7195265..4e7160d9 100644 --- a/tests/plugins/test_ustvnow.py +++ b/tests/plugins/test_ustvnow.py @@ -5,12 +5,27 @@ from streamlink.plugins.ustvnow import USTVNow class TestPluginUSTVNow(unittest.TestCase): def test_can_handle_url(self): - self.assertTrue(USTVNow.can_handle_url("http://watch.ustvnow.com")) - self.assertTrue(USTVNow.can_handle_url("https://watch.ustvnow.com/")) - self.assertTrue(USTVNow.can_handle_url("http://watch.ustvnow.com/watch")) - self.assertTrue(USTVNow.can_handle_url("https://watch.ustvnow.com/watch")) - self.assertTrue(USTVNow.can_handle_url("https://watch.ustvnow.com/watch/syfy")) - self.assertTrue(USTVNow.can_handle_url("https://watch.ustvnow.com/guide/foxnews")) + self.assertTrue(USTVNow.can_handle_url("http://www.ustvnow.com/live/foo/-65")) def test_can_not_handle_url(self): self.assertFalse(USTVNow.can_handle_url("http://www.tvplayer.com")) + + def test_encrypt_data(self): + + key = "80035ad42d7d-bb08-7a14-f726-78403b29" + iv = "3157b5680927cc4a" + + self.assertEqual( + b"uawIc5n+TnmsmR+aP2iEDKG/eMKji6EKzjI4mE+zMhlyCbHm7K4hz7IDJDWwM3aE+Ro4ydSsgJf4ZInnoW6gqvXvG0qB/J2WJeypTSt4W124zkJpvfoJJmGAvBg2t0HT", + USTVNow.encrypt_data(b'{"login_id":"[email protected]","login_key":"testtest1234","login_mode":"1","manufacturer":"123"}', key, iv) + ) + + def test_decrypt_data(self): + + key = "80035ad42d7d-bb08-7a14-f726-78403b29" + iv = "3157b5680927cc4a" + + self.assertEqual( + b'{"status":false,"error":{"code":-2,"type":"","message":"Invalid credentials.","details":{}}}', + USTVNow.decrypt_data(b"KcRLETVAmHlosM0OyUd5hdTQ6WhBRTe/YRAHiLJWrzf94OLkSueXTtQ9QZ1fjOLCbpX2qteEPUWVnzvvSgVDkQmRUttN/royoxW2aL0gYQSoH1NWoDV8sIgvS5vDiQ85", key, iv) + )
Schoolism plugin not working with videos which have subtitles <!-- Thanks for reporting a bug! USE THE TEMPLATE. Otherwise your bug report may be rejected. First, see the contribution guidelines: https://github.com/streamlink/streamlink/blob/master/CONTRIBUTING.md#contributing-to-streamlink Also check the list of open and closed bug reports: https://github.com/streamlink/streamlink/issues?q=is%3Aissue+label%3A%22bug%22 Please see the text preview to avoid unnecessary formatting errors. --> ## Bug Report <!-- Replace [ ] with [x] in order to check the box --> - [x] This is a bug report and I have read the contribution guidelines. ### Description <!-- Explain the bug as thoroughly as you can. Don't leave out information which is necessary for us to reproduce and debug this issue. --> Schoolism plugin works fine with other courses except the two courses below. it'll get error when opening video with subtitles. - Digital Painting with Craig Mullins - Drawing Fundamentals with Thomas Fluharty I'm using streamlink 1.1.1 in python 2.7. I think I have detected the reason why this bug happens but unfortunately I'm not familiar with python and streamlink itself so I may need some help:/ The javascript variable "allVideos" (which stores video URL link and other information) in HTML code is different when video contains subtitles. - Videos without subtitles: ``` var allVideos=[ {sources:[{type:"application/x-mpegurl",src:"https://d8u31iyce9xic.cloudfront.net/14/1/part1.m3u8?Policy=CiAgICAgICAgICAgIHsgCiAgICAgICAgICAgICAgICJTdGF0ZW1lbnQiOiBbCiAgICAgICAgICAgICAgICAgIHsgCiAgICAgICAgICAgICAgICAgICAgICJSZXNvdXJjZSI6Imh0dHBzOi8vZDh1MzFpeWNlOXhpYy5jbG91ZGZyb250Lm5ldC8xNC8xLyoiLAogICAgICAgICAgICAgICAgICAgICAiQ29uZGl0aW9uIjp7CiAgICAgICAgICAgICAgICAgICAgICAgICJEYXRlR3JlYXRlclRoYW4iOnsiQVdTOkVwb2NoVGltZSI6MTU1Njk2Mjc3MH0sCiAgICAgICAgICAgICAgICAgICAgICAgICJEYXRlTGVzc1RoYW4iOnsiQVdTOkVwb2NoVGltZSI6MTU1NzA0OTE3MH0KICAgICAgICAgICAgICAgICAgICAgfSAKICAgICAgICAgICAgICAgICAgfQogICAgICAgICAgICAgICBdIAogICAgICAgICAgICB9CiAgICAgICAg&Signature=HE0~u~zThmbVd0QMbmSuHe3Pxxcg4-ZZXf6N8Fyczbae5Ov1BSfuJgWOeGPk1Y7zuVVE2vO5TlEWNR2aVIvQIAkVQNuaohOf9xuOdnn96SFq6J-LxTEPZthTvhbb3SJeDLWzdEj9-f93pfptKsTd8gABIAltfM1A-~Wjv~jiMVd19T0GJA9PUMNIeNkY7snBE7bMT85ARGrrHynWR71g31U1O-JvfAcnHLEcql-kc~5ZbV0HiJlvqicYhyJUsLzO3lR7sBihjmdq2FDH3-ckhzX3LJhJ9mpZYqZJ6r5DF1LApM870Ct-0KOe84EqdkCxUO4eaCd2ggJx8XLGbibaGQ__&Key-Pair-Id=APKAJHWRPDT6BGTTH7LA",title:"Gesture Drawing - Lesson 1 - Part 1",playlistTitle:"Part 1",}],}, {sources:[{type:"application/x-mpegurl",src:"https://d8u31iyce9xic.cloudfront.net/14/1/part2.m3u8?Policy=CiAgICAgICAgICAgIHsgCiAgICAgICAgICAgICAgICJTdGF0ZW1lbnQiOiBbCiAgICAgICAgICAgICAgICAgIHsgCiAgICAgICAgICAgICAgICAgICAgICJSZXNvdXJjZSI6Imh0dHBzOi8vZDh1MzFpeWNlOXhpYy5jbG91ZGZyb250Lm5ldC8xNC8xLyoiLAogICAgICAgICAgICAgICAgICAgICAiQ29uZGl0aW9uIjp7CiAgICAgICAgICAgICAgICAgICAgICAgICJEYXRlR3JlYXRlclRoYW4iOnsiQVdTOkVwb2NoVGltZSI6MTU1Njk2Mjc3MH0sCiAgICAgICAgICAgICAgICAgICAgICAgICJEYXRlTGVzc1RoYW4iOnsiQVdTOkVwb2NoVGltZSI6MTU1NzA0OTE3MH0KICAgICAgICAgICAgICAgICAgICAgfSAKICAgICAgICAgICAgICAgICAgfQogICAgICAgICAgICAgICBdIAogICAgICAgICAgICB9CiAgICAgICAg&Signature=HE0~u~zThmbVd0QMbmSuHe3Pxxcg4-ZZXf6N8Fyczbae5Ov1BSfuJgWOeGPk1Y7zuVVE2vO5TlEWNR2aVIvQIAkVQNuaohOf9xuOdnn96SFq6J-LxTEPZthTvhbb3SJeDLWzdEj9-f93pfptKsTd8gABIAltfM1A-~Wjv~jiMVd19T0GJA9PUMNIeNkY7snBE7bMT85ARGrrHynWR71g31U1O-JvfAcnHLEcql-kc~5ZbV0HiJlvqicYhyJUsLzO3lR7sBihjmdq2FDH3-ckhzX3LJhJ9mpZYqZJ6r5DF1LApM870Ct-0KOe84EqdkCxUO4eaCd2ggJx8XLGbibaGQ__&Key-Pair-Id=APKAJHWRPDT6BGTTH7LA",title:"Gesture Drawing - Lesson 1 - Part 2",playlistTitle:"Part 2",}]} ]; ``` - Videos with subtitles: ``` var allVideos=[ {sources:[{type:"application/x-mpegurl",src:"https://d8u31iyce9xic.cloudfront.net/44/2/part1.m3u8?Policy=CiAgICAgICAgICAgIHsgCiAgICAgICAgICAgICAgICJTdGF0ZW1lbnQiOiBbCiAgICAgICAgICAgICAgICAgIHsgCiAgICAgICAgICAgICAgICAgICAgICJSZXNvdXJjZSI6Imh0dHBzOi8vZDh1MzFpeWNlOXhpYy5jbG91ZGZyb250Lm5ldC80NC8yLyoiLAogICAgICAgICAgICAgICAgICAgICAiQ29uZGl0aW9uIjp7CiAgICAgICAgICAgICAgICAgICAgICAgICJEYXRlR3JlYXRlclRoYW4iOnsiQVdTOkVwb2NoVGltZSI6MTU1Njk2MjkyMH0sCiAgICAgICAgICAgICAgICAgICAgICAgICJEYXRlTGVzc1RoYW4iOnsiQVdTOkVwb2NoVGltZSI6MTU1NzA0OTMyMH0KICAgICAgICAgICAgICAgICAgICAgfSAKICAgICAgICAgICAgICAgICAgfQogICAgICAgICAgICAgICBdIAogICAgICAgICAgICB9CiAgICAgICAg&Signature=WysPwDFhH0K75hoVq~XPrOjp-Lv5SbNTaM~x0NGpLUJTmzHw83Zz~HAqbpZPaeJiKRaEieC2y7uYJzzLlOdZvPWLyCoy76-5nav1bcihyD2DeJ7lIdCmsNlJarlODdxot3HaO0E7V2rv7WikNol5DmuL-dRsld8Y8JUWm4gJT5SSLVOSBWlCHI~TPrdDyjujMX1k2cLjLc7mHeOuBJOrJGWwwtb3DB48h8rjavZ6R5SXP3YU8uUDow8W74H27nKFd1mhd6ic0CBMVVEucL91ZkyGklNpoRTDqK2nHm6gZk7VWr6it7~XGtYpmHqOJf7BT0p1qaKHLNZnms~S3rKq0A__&Key-Pair-Id=APKAJHWRPDT6BGTTH7LA",title:"Digital Painting - Lesson 2 - Part 1",playlistTitle:"Part 1",}], subtitles: [{ "default": true, kind: "subtitles", srclang: "en", label: "English", src: "https://s3.amazonaws.com/schoolism-encoded/44/subtitles/2/2-1.vtt", }], }, {sources:[{type:"application/x-mpegurl",src:"https://d8u31iyce9xic.cloudfront.net/44/2/part2.m3u8?Policy=CiAgICAgICAgICAgIHsgCiAgICAgICAgICAgICAgICJTdGF0ZW1lbnQiOiBbCiAgICAgICAgICAgICAgICAgIHsgCiAgICAgICAgICAgICAgICAgICAgICJSZXNvdXJjZSI6Imh0dHBzOi8vZDh1MzFpeWNlOXhpYy5jbG91ZGZyb250Lm5ldC80NC8yLyoiLAogICAgICAgICAgICAgICAgICAgICAiQ29uZGl0aW9uIjp7CiAgICAgICAgICAgICAgICAgICAgICAgICJEYXRlR3JlYXRlclRoYW4iOnsiQVdTOkVwb2NoVGltZSI6MTU1Njk2MjkyMH0sCiAgICAgICAgICAgICAgICAgICAgICAgICJEYXRlTGVzc1RoYW4iOnsiQVdTOkVwb2NoVGltZSI6MTU1NzA0OTMyMH0KICAgICAgICAgICAgICAgICAgICAgfSAKICAgICAgICAgICAgICAgICAgfQogICAgICAgICAgICAgICBdIAogICAgICAgICAgICB9CiAgICAgICAg&Signature=WysPwDFhH0K75hoVq~XPrOjp-Lv5SbNTaM~x0NGpLUJTmzHw83Zz~HAqbpZPaeJiKRaEieC2y7uYJzzLlOdZvPWLyCoy76-5nav1bcihyD2DeJ7lIdCmsNlJarlODdxot3HaO0E7V2rv7WikNol5DmuL-dRsld8Y8JUWm4gJT5SSLVOSBWlCHI~TPrdDyjujMX1k2cLjLc7mHeOuBJOrJGWwwtb3DB48h8rjavZ6R5SXP3YU8uUDow8W74H27nKFd1mhd6ic0CBMVVEucL91ZkyGklNpoRTDqK2nHm6gZk7VWr6it7~XGtYpmHqOJf7BT0p1qaKHLNZnms~S3rKq0A__&Key-Pair-Id=APKAJHWRPDT6BGTTH7LA",title:"Digital Painting - Lesson 2 - Part 2",playlistTitle:"Part 2",}], subtitles: [{ "default": true, kind: "subtitles", srclang: "en", label: "English", src: "https://s3.amazonaws.com/schoolism-encoded/44/subtitles/2/2-2.vtt", }] ]; ``` ### Expected / Actual behavior <!-- What do you expect to happen, and what is actually happening? --> The plugin works whether videos have subtitles or not. / It gets error with videos with subtitles. ### Reproduction steps / Explicit stream URLs to test <!-- How can we reproduce this? Please note the exact steps below using the list format supplied. If you need more steps please add them. --> 1. Login to Schoolism and switch course to "Digital Painting with Craig Mullins" 2. Open lesson 1 part 1 with streamlink, for example. The course page URL is "https://www.schoolism.com/watchLesson.php?type=st&id=506 ### Log output <!-- TEXT LOG OUTPUT IS REQUIRED for a bug report! Use the `--loglevel debug` parameter and avoid using parameters which suppress log output. https://streamlink.github.io/cli.html#cmdoption-l Make sure to **remove usernames and passwords** You can copy the output to https://gist.github.com/ or paste it below. --> ``` [cli][debug] OS: Linux-4.4.0-17134-Microsoft-x86_64-with-Ubuntu-18.04-bionic [cli][debug] Python: 2.7.15rc1 [cli][debug] Streamlink: 1.1.1 [cli][debug] Requests(2.21.0), Socks(1.6.7), Websocket(0.56.0) [cli][info] Found matching plugin schoolism for URL https://www.schoolism.com/watchLesson.php?type=st&id=506 [cli][debug] Plugin specific arguments: [cli][debug] --schoolism-email=(email omitted) [cli][debug] --schoolism-password=(password omitted) [cli][debug] --schoolism-part=1 (part) [plugin.schoolism][debug] Logged in to Schoolism as (email omitted) error: Unable to parse JSON: Expecting property name enclosed in double quotes: line 5 column 9 (char 1337) (u'[{"sources":[{"type":"application ...) ``` ### Additional comments, screenshots, etc. I have a schoolism account valid till August so I can help testing. Or if someone can give me some hint fixing this issue, I can make a merge request myself. Thank you! [Love Streamlink? Please consider supporting our collective. Thanks!](https://opencollective.com/streamlink/donate)
0.0
209e43186b6bcf34c58f06019e8491f7ee2587d7
[ "tests/plugins/test_cdnbg.py::TestPluginCDNBG::test_can_handle_url", "tests/plugins/test_schoolism.py::TestPluginSchoolism::test_playlist_parse", "tests/plugins/test_schoolism.py::TestPluginSchoolism::test_playlist_parse_subs", "tests/plugins/test_ustvnow.py::TestPluginUSTVNow::test_can_handle_url", "tests/plugins/test_ustvnow.py::TestPluginUSTVNow::test_decrypt_data", "tests/plugins/test_ustvnow.py::TestPluginUSTVNow::test_encrypt_data" ]
[ "tests/plugins/test_schoolism.py::TestPluginSchoolism::test_can_handle_url", "tests/plugins/test_schoolism.py::TestPluginSchoolism::test_can_handle_url_negative", "tests/plugins/test_ustvnow.py::TestPluginUSTVNow::test_can_not_handle_url" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2019-07-04 12:01:09+00:00
bsd-2-clause
5,777
streamlink__streamlink-2527
diff --git a/src/streamlink/plugins/cdnbg.py b/src/streamlink/plugins/cdnbg.py index 79b0172b..ee7a8a82 100644 --- a/src/streamlink/plugins/cdnbg.py +++ b/src/streamlink/plugins/cdnbg.py @@ -23,6 +23,7 @@ class CDNBG(Plugin): mmtvmusic\.com/live| mu-vi\.tv/LiveStreams/pages/Live\.aspx| videochanel\.bstv\.bg| + live\.bstv\.bg| bloombergtv.bg/video )/? """, re.VERBOSE)
streamlink/streamlink
209e43186b6bcf34c58f06019e8491f7ee2587d7
diff --git a/tests/plugins/test_cdnbg.py b/tests/plugins/test_cdnbg.py index b98b16ee..898cb598 100644 --- a/tests/plugins/test_cdnbg.py +++ b/tests/plugins/test_cdnbg.py @@ -23,6 +23,7 @@ class TestPluginCDNBG(unittest.TestCase): self.assertTrue(CDNBG.can_handle_url("https://mmtvmusic.com/live/")) self.assertTrue(CDNBG.can_handle_url("http://mu-vi.tv/LiveStreams/pages/Live.aspx")) self.assertTrue(CDNBG.can_handle_url("http://videochanel.bstv.bg/")) + self.assertTrue(CDNBG.can_handle_url("http://live.bstv.bg/")) self.assertTrue(CDNBG.can_handle_url("https://www.bloombergtv.bg/video")) # shouldn't match
Plugin: cdnbg Domain for BSTV has been changed to https://live.bstv.bg/.
0.0
209e43186b6bcf34c58f06019e8491f7ee2587d7
[ "tests/plugins/test_cdnbg.py::TestPluginCDNBG::test_can_handle_url" ]
[]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2019-07-05 07:42:20+00:00
bsd-2-clause
5,778
streamlink__streamlink-2568
diff --git a/src/streamlink/plugins/wwenetwork.py b/src/streamlink/plugins/wwenetwork.py index 6200c462..cb18a093 100644 --- a/src/streamlink/plugins/wwenetwork.py +++ b/src/streamlink/plugins/wwenetwork.py @@ -1,47 +1,29 @@ from __future__ import print_function -import re -from pprint import pprint -import time +import json +import logging +import re from streamlink import PluginError -from streamlink.cache import Cache from streamlink.plugin import Plugin, PluginArguments, PluginArgument from streamlink.plugin.api import useragents -from streamlink.plugin.api import validate -from streamlink.compat import urlparse, parse_qsl from streamlink.stream import HLSStream +from streamlink.utils import memoize +from streamlink.compat import urlparse, parse_qsl +from streamlink.utils.times import seconds_to_hhmmss + +log = logging.getLogger(__name__) class WWENetwork(Plugin): - url_re = re.compile(r"https?://network.wwe.com") - content_id_re = re.compile(r'''"content_id" : "(\d+)"''') - playback_scenario = "HTTP_CLOUD_WIRED" - login_url = "https://secure.net.wwe.com/workflow.do" - login_page_url = "https://secure.net.wwe.com/enterworkflow.do?flowId=account.login&forwardUrl=http%3A%2F%2Fnetwork.wwe.com" - api_url = "https://ws.media.net.wwe.com/ws/media/mf/op-findUserVerifiedEvent/v-2.3" - _info_schema = validate.Schema( - validate.union({ - "status": validate.union({ - "code": validate.all(validate.xml_findtext(".//status-code"), validate.transform(int)), - "message": validate.xml_findtext(".//status-message"), - }), - "urls": validate.all( - validate.xml_findall(".//url"), - [validate.getattr("text")] - ), - validate.optional("fingerprint"): validate.xml_findtext(".//updated-fingerprint"), - validate.optional("session_key"): validate.xml_findtext(".//session-key"), - "session_attributes": validate.all( - validate.xml_findall(".//session-attribute"), - [validate.getattr("attrib"), - validate.union({ - "name": validate.get("name"), - "value": validate.get("value") - })] - ) - }) - ) + url_re = re.compile(r"https?://watch.wwe.com/(channel)?") + site_config_re = re.compile(r'''">window.__data = (\{.*?\})</script>''') + stream_url = "https://dce-frontoffice.imggaming.com/api/v2/stream/{id}" + live_url = "https://dce-frontoffice.imggaming.com/api/v2/event/live" + login_url = "https://dce-frontoffice.imggaming.com/api/v2/login" + API_KEY = "cca51ea0-7837-40df-a055-75eb6347b2e7" + + customer_id = 16 arguments = PluginArguments( PluginArgument( "email", @@ -66,105 +48,105 @@ class WWENetwork(Plugin): def __init__(self, url): super(WWENetwork, self).__init__(url) self.session.http.headers.update({"User-Agent": useragents.CHROME}) - self._session_attributes = Cache(filename="plugin-cache.json", key_prefix="wwenetwork:attributes") - self._session_key = self.cache.get("session_key") - self._authed = self._session_attributes.get("ipid") and self._session_attributes.get("fprt") + self.auth_token = None @classmethod def can_handle_url(cls, url): return cls.url_re.match(url) is not None + def get_title(self): + if self.page_config: + for page in self.page_config["cache"]["page"].values(): + return page['item']['title'] + + def request(self, method, url, **kwargs): + headers = kwargs.pop("headers", {}) + headers.update({"x-api-key": self.API_KEY, + "Origin": "https://watch.wwe.com", + "Referer": "https://watch.wwe.com/signin", + "Accept": "application/json", + "Realm": "dce.wwe"}) + if self.auth_token: + headers["Authorization"] = "Bearer {0}".format(self.auth_token) + + kwargs["raise_for_status"] = False + log.debug("API request: {0} {1}".format(method, url)) + res = self.session.http.request(method, url, headers=headers, **kwargs) + data = self.session.http.json(res) + + if "status" in data and data["status"] != 200: + log.debug("API request failed: {0}:{1} ({2})".format(data["status"], data.get("code"), "; ".join(data.get("messages", [])))) + return data + def login(self, email, password): self.logger.debug("Attempting login as {0}", email) # sets some required cookies to login - self.session.http.get(self.login_page_url) - # login - res = self.session.http.post(self.login_url, data=dict(registrationAction='identify', - emailAddress=email, - password=password, - submitButton=""), - headers={"Referer": self.login_page_url}, - allow_redirects=False) - - self._authed = "Authentication Error" not in res.text - if self._authed: - self._session_attributes.set("ipid", res.cookies.get("ipid"), expires=3600 * 1.5) - self._session_attributes.set("fprt", res.cookies.get("fprt"), expires=3600 * 1.5) - - return self._authed - - def _update_session_attribute(self, key, value): - if value: - self._session_attributes.set(key, value, expires=3600 * 1.5) # 1h30m expiry - self.session.http.cookies.set(key, value) + data = self.request('POST', self.login_url, + data=json.dumps({"id": email, "secret": password}), + headers={"Content-Type": "application/json"}) + if "authorisationToken" in data: + self.auth_token = data["authorisationToken"] - @property - def session_key(self): - return self._session_key + return self.auth_token - @session_key.setter - def session_key(self, value): - self.cache.set("session_key", value) - self._session_key = value + @property + @memoize + def page_config(self): + log.debug("Loading page config") + res = self.session.http.get(self.url) + m = self.site_config_re.search(res.text) + return m and json.loads(m.group(1)) def _get_media_info(self, content_id): """ Get the info about the content, based on the ID - :param content_id: + :param content_id: contentId for the video :return: """ - params = {"identityPointId": self._session_attributes.get("ipid"), - "fingerprint": self._session_attributes.get("fprt"), - "contentId": content_id, - "playbackScenario": self.playback_scenario, - "platform": "WEB_MEDIAPLAYER_5", - "subject": "LIVE_EVENT_COVERAGE", - "frameworkURL": "https://ws.media.net.wwe.com", - "_": int(time.time())} - if self.session_key: - params["sessionKey"] = self.session_key - url = self.api_url.format(id=content_id) - res = self.session.http.get(url, params=params) - return self.session.http.xml(res, ignore_ns=True, schema=self._info_schema) - - def _get_content_id(self): + info = self.request('GET', self.stream_url.format(id=content_id)) + return self.request('GET', info.get("playerUrlCallback")) + + def _get_video_id(self): # check the page to find the contentId - res = self.session.http.get(self.url) - m = self.content_id_re.search(res.text) - if m: - return m.group(1) + log.debug("Searching for content ID") + if self.page_config: + for page in self.page_config["cache"]["page"].values(): + try: + if page['item']['type'] == "channel": + return self._get_live_id() + else: + return "vod/{id}".format(id=page['item']['customFields']['DiceVideoId']) + except KeyError: + log.error("Could not find video ID") + return + + def _get_live_id(self): + log.debug("Loading live event") + res = self.request('GET', self.live_url) + for event in res.get('events', []): + return "event/{sportId}/{propertyId}/{tournamentId}/{id}".format(**event) def _get_streams(self): - email = self.get_option("email") - password = self.get_option("password") + if not self.login(self.get_option("email"), self.get_option("password")): + raise PluginError("Login failed") - if not self._authed and (not email and not password): - self.logger.error("A login for WWE Network is required, use --wwenetwork-email/" - "--wwenetwork-password to set them") - return + try: + start_point = int(float(dict(parse_qsl(urlparse(self.url).query)).get("startPoint", 0.0))) + if start_point > 0: + log.info("Stream will start at {0}".format(seconds_to_hhmmss(start_point))) + except ValueError: + start_point = 0 - if not self._authed: - if not self.login(email, password): - self.logger.error("Failed to login, check your username/password") - return + content_id = self._get_video_id() - content_id = self._get_content_id() if content_id: self.logger.debug("Found content ID: {0}", content_id) info = self._get_media_info(content_id) - if info["status"]["code"] == 1: - # update the session attributes - self._update_session_attribute("fprt", info.get("fingerprint")) - for attr in info["session_attributes"]: - self._update_session_attribute(attr["name"], attr["value"]) - - if info.get("session_key"): - self.session_key = info.get("session_key") - for url in info["urls"]: - for s in HLSStream.parse_variant_playlist(self.session, url, name_fmt="{pixels}_{bitrate}").items(): - yield s + if info.get("hlsUrl"): + for s in HLSStream.parse_variant_playlist(self.session, info["hlsUrl"], start_offset=start_point).items(): + yield s else: - raise PluginError("Could not load streams: {message} ({code})".format(**info["status"])) + log.error("Could not find the HLS URL") __plugin__ = WWENetwork diff --git a/src/streamlink/utils/times.py b/src/streamlink/utils/times.py index ae509fde..2226477e 100644 --- a/src/streamlink/utils/times.py +++ b/src/streamlink/utils/times.py @@ -48,6 +48,13 @@ def hours_minutes_seconds(value): return s +def seconds_to_hhmmss(seconds): + hours, seconds = divmod(seconds, 3600) + minutes, seconds = divmod(seconds, 60) + return "{0:02d}:{1:02d}:{2}".format(int(hours), int(minutes), "{0:02.1f}".format(seconds) if seconds % 1 else "{0:02d}".format(int(seconds))) + + __all__ = [ "hours_minutes_seconds", + "seconds_to_hhmmss" ]
streamlink/streamlink
1aaab4bf0b1d21f3e4b5f452dfd8653efc537c7a
diff --git a/tests/plugins/test_wwenetwork.py b/tests/plugins/test_wwenetwork.py index bd51724d..bc485a9a 100644 --- a/tests/plugins/test_wwenetwork.py +++ b/tests/plugins/test_wwenetwork.py @@ -6,7 +6,7 @@ from streamlink.plugins.wwenetwork import WWENetwork class TestPluginWWENetwork(unittest.TestCase): def test_can_handle_url(self): should_match = [ - 'http://network.wwe.com/shows/collections/267406022', + 'https://watch.wwe.com/in-ring/3622', ] for url in should_match: self.assertTrue(WWENetwork.can_handle_url(url)) diff --git a/tests/test_utils_times.py b/tests/test_utils_times.py index a1f5b81d..927f9459 100644 --- a/tests/test_utils_times.py +++ b/tests/test_utils_times.py @@ -1,6 +1,6 @@ import unittest -from streamlink.utils.times import hours_minutes_seconds +from streamlink.utils.times import hours_minutes_seconds, seconds_to_hhmmss class TestUtilsTimes(unittest.TestCase): @@ -37,3 +37,13 @@ class TestUtilsTimes(unittest.TestCase): with self.assertRaises(ValueError): hours_minutes_seconds("11:ERR:00") + + def test_seconds_to_hhmmss(self): + + self.assertEqual(seconds_to_hhmmss(0), "00:00:00") + self.assertEqual(seconds_to_hhmmss(1), "00:00:01") + self.assertEqual(seconds_to_hhmmss(60), "00:01:00") + self.assertEqual(seconds_to_hhmmss(3600), "01:00:00") + + self.assertEqual(seconds_to_hhmmss(13997), "03:53:17") + self.assertEqual(seconds_to_hhmmss(13997.4), "03:53:17.4")
Updated WWEN plugin PLZ <!-- Thanks for reporting a plugin issue! USE THE TEMPLATE. Otherwise your plugin issue may be rejected. First, see the contribution guidelines: https://github.com/streamlink/streamlink/blob/master/CONTRIBUTING.md#contributing-to-streamlink Also check the list of open and closed plugin issues: https://github.com/streamlink/streamlink/issues?q=is%3Aissue+label%3A%22plugin+issue%22 Please see the text preview to avoid unnecessary formatting errors. --> ## Plugin Issue WWE have now gone to 2.0 and is doing 1080p VOD, plugin needs updating PLZ ### Description WWE have now gone to 2.0 and is doing 1080p VOD, plugin needs updating PLZ I have tried letmeatit and still same problem and adownloader. uses index.m3u8 and not bitrate.m3u8 master has added code as well. ### Reproduction steps / Explicit stream URLs to test <!-- How can we reproduce this? Please note the exact steps below using the list format supplied. If you need more steps please add them. --> 1. ... 2. ... 3. ... ### Log output <!-- TEXT LOG OUTPUT IS REQUIRED for a plugin issue! Use the `--loglevel debug` parameter and avoid using parameters which suppress log output. https://streamlink.github.io/cli.html#cmdoption-l Make sure to **remove usernames and passwords** You can copy the output to https://gist.github.com/ or paste it below. --> ``` REPLACE THIS TEXT WITH THE LOG OUTPUT ``` ### Additional comments, screenshots, etc. [Love Streamlink? Please consider supporting our collective. Thanks!](https://opencollective.com/streamlink/donate)
0.0
1aaab4bf0b1d21f3e4b5f452dfd8653efc537c7a
[ "tests/plugins/test_wwenetwork.py::TestPluginWWENetwork::test_can_handle_url", "tests/plugins/test_wwenetwork.py::TestPluginWWENetwork::test_can_handle_url_negative", "tests/test_utils_times.py::TestUtilsTimes::test_hours_minutes_seconds", "tests/test_utils_times.py::TestUtilsTimes::test_seconds_to_hhmmss" ]
[]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2019-07-29 11:41:50+00:00
bsd-2-clause
5,779
streamlink__streamlink-2597
diff --git a/CHANGELOG.md b/CHANGELOG.md index 2e239ac0..d024fba0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,97 @@ # Changelog +## streamlink 1.2.0 (2019-08-18) + +Here are the changes for this month's release + +- Multiple plugin fixes +- Fixed single hyphen params at the beginning of --player-args (#2333) +- `--http-proxy` will set the default value of `--https-proxy` to same as `--http-proxy`. (#2536) +- DASH Streams will handle headers correctly (#2545) +- the timestamp for FFMPEGMuxer streams will start with zero (#2559) + + +```text +Davi Guimarães <[email protected]> (1): + plugins.cubetv: base url changes (#2430) + +Forrest <[email protected]> (1): + Add a sponsor button (#2478) + +Jiting <[email protected]> (1): + plugin.youtube: bug fix for YouTube live streams check + +Juan Ramirez <[email protected]> (2): + Invalid use of console.logger in CLI + Too many arguments for logging format string + +Mohamed El Morabity <[email protected]> (9): + plugins.vimeo: new plugin for Vimeo streams + plugins.vimeo: add subtitle support for vimeo plugin + plugins.vimeo: fix alphabetical order in plugin matrix + Use class parameter instead of class name in class method + [plugins.bfmtv] Fix player regex + [plugins.idf1] Update for new website layout + plugins.gulli: enable HTTPS support + plugins.gulli: fix live stream fetching + plugins.tvrplus: fix for new website layout + +Mohamed El Morabity <[email protected]> (1): + plugins.clubbingtv: new plugin for Clubbing TV website (#2569) + +Viktor Kálmán <[email protected]> (1): + plugins.mediaklikk: update broken plugin (#2401) + +Vladimir Stavrinov <[email protected]> (2): + plugins.live_russia_tv: adjust to site changes (#2523) + plugins.oneplusone: fix site changes (#2425) + +YuuichiMizuoka <[email protected]> (1): + add login posibility for pixiv using sessionid and devicetoken + +aqxa1 <[email protected]> (1): + Handle keyboard interrupts in can_handle_url checks (#2318) + +back-to <[email protected]> (12): + cli.argparser: Fix single hyphen params at the beginning of --player-args + plugins.reuters: New Plugin + plugins: Removed rte and tvcatchup + utils.__init__: remove cElementTree, it's just an alias for ElementTree + plugins.teamliquid: New domain, fix stream_weight + plugins.vimeo: Fixed DASH Livestreams + plugin.api.useragents: update CHROME and FIREFOX User-Agent + ffmpegmux: use -start_at_zero with -copyts + plugins.youtube: fixed reason msg, updated _url_re + plugins.TV1Channel: Fixed new livestream iframe + plugins.npo: removed due to DRM + plugins.lrt: fixed livestreams + +bastimeyer <[email protected]> (1): + plugins.welt: fix plugin + +beardypig <[email protected]> (13): + plugins.bbciplayer: small change to where the VPID is extracted from (#2376) + plugins.goodgame: fix for debug logging error + plugins.cdnbg: fix for bstv url + plugins.ustvnow: updated to handle new auth, and site design + plugin.schoolism: bug fix for videos with subtitles (#2524) + stream.dash: use the stream args in the writer and worker + session: default https-proxy to the same as http-proxy, can be overridden + plugins.beattv: partial fix for the be-at.tv streams + tests: test the behaviour of setting http-proxy and https-proxy + plugins.twitch: support for different clips URL + plugins.wwenetwork: support for new site + plugins.ustreamtv: add support for proxying WebSocket connections + plugins.wwenetwork: update for small page/api change + +skulblakka <[email protected]> (1): + plugins.DLive: New Plugin for dlive.tv (#2419) + +ssaqua <[email protected]> (1): + plugins.linelive: new plugin for LINE LIVE (live.line.me) (#2574) +``` + + ## streamlink 1.1.1 (2019-04-02) This is just a small patch release which fixes a build/deploy issue with the new special wheels for Windows on PyPI. (#2392) diff --git a/docs/plugin_matrix.rst b/docs/plugin_matrix.rst index 802f5a90..c69c7f37 100644 --- a/docs/plugin_matrix.rst +++ b/docs/plugin_matrix.rst @@ -125,6 +125,7 @@ nbc nbc.com No Yes Streams are geo-restric nbcsports nbcsports.com No Yes Streams maybe be geo-restricted to USA. Authentication is not supported. nhkworld nhk.or.jp/nhkworld Yes No nos nos.nl Yes Yes Streams may be geo-restricted to Netherlands. +nownews news.now.com Yes No nrk - tv.nrk.no Yes Yes Streams may be geo-restricted to Norway. - radio.nrk.no ntv ntv.ru Yes No diff --git a/src/streamlink/plugins/bbciplayer.py b/src/streamlink/plugins/bbciplayer.py index a4c4f7da..68ccef88 100644 --- a/src/streamlink/plugins/bbciplayer.py +++ b/src/streamlink/plugins/bbciplayer.py @@ -34,11 +34,8 @@ class BBCiPlayer(Plugin): tvip_re = re.compile(r'channel"\s*:\s*{\s*"id"\s*:\s*"(\w+?)"') tvip_master_re = re.compile(r'event_master_brand=(\w+?)&') account_locals_re = re.compile(r'window.bbcAccount.locals\s*=\s*({.*?});') - swf_url = "http://emp.bbci.co.uk/emp/SMPf/1.18.3/StandardMediaPlayerChromelessFlash.swf" - hash = base64.b64decode( - b"N2RmZjc2NzFkMGM2OTdmZWRiMWQ5MDVkOWExMjE3MTk5MzhiOTJiZg==") - api_url = ("http://open.live.bbc.co.uk/mediaselector/6/select/" - "version/2.0/mediaset/{platform}/vpid/{vpid}/format/json/atk/{vpid_hash}/asn/1/") + hash = base64.b64decode(b"N2RmZjc2NzFkMGM2OTdmZWRiMWQ5MDVkOWExMjE3MTk5MzhiOTJiZg==") + api_url = "https://open.live.bbc.co.uk/mediaselector/6/select/version/2.0/mediaset/{platform}/vpid/{vpid}/format/json/atk/{vpid_hash}/asn/1/" platforms = ("pc", "iptv-all") session_url = "https://session.bbc.com/session" auth_url = "https://account.bbc.com/signin" diff --git a/src/streamlink/plugins/nownews.py b/src/streamlink/plugins/nownews.py new file mode 100644 index 00000000..02bd76de --- /dev/null +++ b/src/streamlink/plugins/nownews.py @@ -0,0 +1,49 @@ +import logging +import re +import json + +from streamlink.plugin import Plugin +from streamlink.stream import HLSStream + +log = logging.getLogger(__name__) + + +class NowNews(Plugin): + _url_re = re.compile(r"https?://news.now.com/home/live") + epg_re = re.compile(r'''epg.getEPG\("(\d+)"\);''') + api_url = "https://hkt-mobile-api.nowtv.now.com/09/1/getLiveURL" + backup_332_api = "https://d7lz7jwg8uwgn.cloudfront.net/apps_resource/news/live.json" + backup_332_stream = "https://d3i3yn6xwv1jpw.cloudfront.net/live/now332/playlist.m3u8" + + @classmethod + def can_handle_url(cls, url): + return cls._url_re.match(url) is not None + + def _get_streams(self): + res = self.session.http.get(self.url) + m = self.epg_re.search(res.text) + channel_id = m and m.group(1) + if channel_id: + log.debug("Channel ID: {0}".format(channel_id)) + + if channel_id == "332": + # there is a special backup stream for channel 332 + bk_res = self.session.http.get(self.backup_332_api) + bk_data = self.session.http.json(bk_res) + if bk_data and bk_data["backup"]: + log.info("Using backup stream for channel 332") + return HLSStream.parse_variant_playlist(self.session, self.backup_332_stream) + + api_res = self.session.http.post(self.api_url, + headers={"Content-Type": 'application/json'}, + data=json.dumps(dict(channelno=channel_id, + mode="prod", + audioCode="", + format="HLS", + callerReferenceNo="20140702122500"))) + data = self.session.http.json(api_res) + for stream_url in data.get("asset", {}).get("hls", {}).get("adaptive", []): + return HLSStream.parse_variant_playlist(self.session, stream_url) + + +__plugin__ = NowNews
streamlink/streamlink
a2e576b44d482d2ced4494732f643139ab769217
diff --git a/tests/plugins/test_nownews.py b/tests/plugins/test_nownews.py new file mode 100644 index 00000000..583aa0eb --- /dev/null +++ b/tests/plugins/test_nownews.py @@ -0,0 +1,27 @@ +import unittest + +import pytest + +from streamlink.plugins.nownews import NowNews + + +class TestPluginNowNews: + valid_urls = [ + ("https://news.now.com/home/live",), + ("http://news.now.com/home/live",), + ("https://news.now.com/home/live331a",), + ("http://news.now.com/home/live331a",) + ] + invalid_urls = [ + ("https://news.now.com/home/local",), + ("http://media.now.com.hk/",), + ("https://www.youtube.com",) + ] + + @pytest.mark.parametrize(["url"], valid_urls) + def test_can_handle_url(self, url): + assert NowNews.can_handle_url(url), "url should be handled" + + @pytest.mark.parametrize(["url"], invalid_urls) + def test_can_handle_url_negative(self, url): + assert not NowNews.can_handle_url(url), "url should not be handled"
Now News Live (News and Live channel) ## Plugin Request <!-- Replace [ ] with [x] in order to check the box --> - [x] This is a plugin request and I have read the contribution guidelines and plugin request requirements. ### Description <!-- Explain the plugin and site as clearly as you can. What is the site about? Who runs it? What content does it provide? What value does it bring to Streamlink? Etc. --> One of a local television station from Hong Kong which currently only accessible via Internet streaming or paid cable subscription. Now News is one of a few disinterested news channel which provide fare perspective reports compared to major aired television in Hong Kong. ### Example stream URLs <!-- Example URLs for streams are required. Plugin requests which do not have example URLs will be closed. --> 1. https://news.now.com/home/live331a 2. https://news.now.com/home/live ### Additional comments, screenshots, etc. ![chrome_2019-08-18_20-27-07](https://user-images.githubusercontent.com/771955/63224427-92c4d700-c1f6-11e9-8010-500d19f97187.png) [Love Streamlink? Please consider supporting our collective. Thanks!](https://opencollective.com/streamlink/donate)
0.0
a2e576b44d482d2ced4494732f643139ab769217
[ "tests/plugins/test_nownews.py::TestPluginNowNews::test_can_handle_url[https://news.now.com/home/live]", "tests/plugins/test_nownews.py::TestPluginNowNews::test_can_handle_url[http://news.now.com/home/live]", "tests/plugins/test_nownews.py::TestPluginNowNews::test_can_handle_url[https://news.now.com/home/live331a]", "tests/plugins/test_nownews.py::TestPluginNowNews::test_can_handle_url[http://news.now.com/home/live331a]", "tests/plugins/test_nownews.py::TestPluginNowNews::test_can_handle_url_negative[https://news.now.com/home/local]", "tests/plugins/test_nownews.py::TestPluginNowNews::test_can_handle_url_negative[http://media.now.com.hk/]", "tests/plugins/test_nownews.py::TestPluginNowNews::test_can_handle_url_negative[https://www.youtube.com]" ]
[]
{ "failed_lite_validators": [ "has_hyperlinks", "has_media", "has_added_files", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2019-08-19 11:35:30+00:00
bsd-2-clause
5,780
streamlink__streamlink-2653
diff --git a/.travis.yml b/.travis.yml index 0a83c747..6f9a25b8 100644 --- a/.travis.yml +++ b/.travis.yml @@ -33,7 +33,7 @@ before_install: pip install doctr; fi - if [[ $BUILD_INSTALLER == 'yes' ]]; then - pip install git+https://github.com/takluyver/pynsist.git@88f56f9e86af9c55522147a67f8b7806ac2ca55b; + pip install pynsist==2.4; fi install: diff --git a/docs/plugin_matrix.rst b/docs/plugin_matrix.rst index 7ffd8bd5..6f3f327f 100644 --- a/docs/plugin_matrix.rst +++ b/docs/plugin_matrix.rst @@ -16,6 +16,9 @@ abematv abema.tv Yes Yes Streams are geo-restric abweb abweb.com Yes No Requires a login and a subscription. adultswim adultswim.com Yes Yes Streams may be geo-restricted, some VOD streams are protected by DRM. afreeca play.afreecatv.com Yes No +albavision - tvc.com.ec Yes No Some streams are geo-restricted. + - rts.com.ec + - elnueve.com.ar aljazeeraen aljazeera.com Yes Yes English version of the site. animelab animelab.com -- Yes Requires a login. Streams may be geo-restricted to Australia and New Zealand. app17 17app.co Yes -- @@ -261,6 +264,7 @@ viasat - juicyplay.dk Yes Yes Streams may be geo-rest vidio vidio.com Yes Yes vimeo vimeo.com Yes Yes Password-protected videos are not supported. vinhlongtv thvli.vn Yes No Streams are geo-restricted to Vietnam +viutv viu.tv Yes No Streams are geo-restricted to Hong Kong vk vk.com Yes Yes vrtbe vrt.be/vrtnu Yes Yes vtvgo vtvgo.vn Yes No diff --git a/src/streamlink/plugins/albavision.py b/src/streamlink/plugins/albavision.py new file mode 100644 index 00000000..6d8d4625 --- /dev/null +++ b/src/streamlink/plugins/albavision.py @@ -0,0 +1,117 @@ +""" +Support for the live streams on Albavision sites + - http://www.tvc.com.ec + - http://www.rts.com.ec + - https://www.elnueve.com.ar +""" +import logging +import re +import time + +from streamlink import PluginError +from streamlink.compat import quote, urlencode +from streamlink.plugin import Plugin +from streamlink.plugin.api.utils import itertags +from streamlink.stream import HLSStream +from streamlink.utils import update_scheme + +log = logging.getLogger(__name__) + + +class Albavision(Plugin): + _url_re = re.compile(r"https?://(?:www\.)?(tvc.com.ec|rts.com.ec|elnueve.com.ar)/en-?vivo") + _token_input_re = re.compile(r"Math.floor\(Date.now\(\) / 3600000\),'([a-f0-9OK]+)'") + _live_url_re = re.compile(r"LIVE_URL = '(.*?)';") + _playlist_re = re.compile(r"file:\s*'(http.*m3u8)'") + _token_url_re = re.compile(r"https://.*/token/.*?\?rsk=") + + _channel_urls = { + 'Quito': 'http://d3aacg6baj4jn0.cloudfront.net/reproductor_rts_o_quito.html?iut=', + 'Guayaquil': 'http://d2a6tcnofawcbm.cloudfront.net/player_rts.html?iut=', + 'Canal5': 'http://dxejh4fchgs18.cloudfront.net/player_televicentro.html?iut=' + } + + def __init__(self, url): + super(Albavision, self).__init__(url) + self._page = None + + @classmethod + def can_handle_url(cls, url): + return cls._url_re.match(url) is not None + + @property + def page(self): + if not self._page: + self._page = self.session.http.get(self.url) + return self._page + + def _get_token_url(self): + token = self._get_live_url_token() + if token: + m = self._token_url_re.search(self.page.text) + token_url = m and m.group(0) + if token_url: + log.debug("token_url={0}{1}".format(token_url, token)) + return token_url + token + else: + log.error("Could not find site token") + + @staticmethod + def transform_token(token_in, date): + token_out = list(token_in) + offset = len(token_in) + for i in range(offset - 1, -1, -1): + p = (i * date) % offset + # swap chars at p and i + token_out[i], token_out[p] = token_out[p], token_out[i] + token_out = ''.join(token_out) + if token_out.endswith("OK"): + return token_out[:-2] # return token without OK suffix + else: + log.error("Invalid site token: {0} => {1}".format(token_in, token_out)) + + def _get_live_url_token(self): + m = self._token_input_re.search(self.page.text) + if m: + date = int(time.time()//3600) + return self.transform_token(m.group(1), date) or self.transform_token(m.group(1), date - 1) + + def _get_token(self): + token_url = self._get_token_url() + if token_url: + res = self.session.http.get(token_url) + data = self.session.http.json(res) + if data['success']: + return data['token'] + + def _get_streams(self): + m = self._live_url_re.search(self.page.text) + playlist_url = m and update_scheme(self.url, m.group(1)) + player_url = self.url + token = self._get_token() + + if playlist_url: + log.debug("Found playlist URL in the page") + else: + live_channel = None + for div in itertags(self.page.text, "div"): + if div.attributes.get("id") == "botonLive": + live_channel = div.attributes.get("data-canal") + + if live_channel: + log.debug("Live channel: {0}".format(live_channel)) + player_url = self._channel_urls[live_channel]+quote(token) + page = self.session.http.get(player_url, raise_for_status=False) + if "block access from your country." in page.text: + raise PluginError("Content is geo-locked") + m = self._playlist_re.search(page.text) + playlist_url = m and update_scheme(self.url, m.group(1)) + else: + log.error("Could not find the live channel") + + if playlist_url: + stream_url = "{0}?{1}".format(playlist_url, urlencode({"iut": token})) + return HLSStream.parse_variant_playlist(self.session, stream_url, headers={"referer": player_url}) + + +__plugin__ = Albavision diff --git a/src/streamlink/plugins/bloomberg.py b/src/streamlink/plugins/bloomberg.py index 638151a6..1d768ce7 100644 --- a/src/streamlink/plugins/bloomberg.py +++ b/src/streamlink/plugins/bloomberg.py @@ -1,11 +1,14 @@ -from functools import partial +import logging import re +from functools import partial from streamlink.plugin import Plugin -from streamlink.plugin.api import validate +from streamlink.plugin.api import validate, useragents from streamlink.stream import HDSStream, HLSStream, HTTPStream from streamlink.utils import parse_json, update_scheme +log = logging.getLogger(__name__) + class Bloomberg(Plugin): VOD_API_URL = 'https://www.bloomberg.com/api/embed?id={0}' @@ -21,23 +24,26 @@ class Bloomberg(Plugin): } _url_re = re.compile(r''' - https?://www\.bloomberg\.com/( - news/videos/[^/]+/[^/]+ | - (?P<channel>live/(?:stream|emea|asia_stream|europe|us|asia)|audio)/? + https?://(?:www\.)?bloomberg\.com/ + (?: + news/videos/[^/]+/[^/]+| + live/(?P<channel>.+)/? ) ''', re.VERBOSE) _live_player_re = re.compile(r'{APP_BUNDLE:"(?P<live_player_url>.+?/app.js)"') _js_to_json_re = partial(re.compile(r'(\w+):(["\']|\d?\.?\d+,|true|false|\[|{)').sub, r'"\1":\2') _video_id_re = re.compile(r'data-bmmr-id=\\"(?P<video_id>.+?)\\"') _mp4_bitrate_re = re.compile(r'.*_(?P<bitrate>[0-9]+)\.mp4') + _preload_state_re = re.compile(r'window.__PRELOADED_STATE__\s*=\s*({.*});', re.DOTALL) + _live_stream_info_re = re.compile(r'12:.*t.exports=({.*})},{}],13:', re.DOTALL) _live_streams_schema = validate.Schema( validate.transform(_js_to_json_re), validate.transform(lambda x: x.replace(':.', ':0.')), validate.transform(parse_json), - validate.Schema( - { - 'cdns': validate.all( + validate.Schema({ + validate.text: { + validate.optional('cdns'): validate.all( [ validate.Schema( { @@ -54,11 +60,21 @@ class Bloomberg(Plugin): ], validate.transform(lambda x: [i for y in x for i in y]) ) - }, - validate.get('cdns') + } + }, ) ) + _channel_list_schema = validate.Schema( + validate.transform(parse_json), + {"live": {"channels": {"byChannelId": { + validate.text: validate.all({"liveId": validate.text}, validate.get("liveId")) + }}}}, + validate.get("live"), + validate.get("channels"), + validate.get("byChannelId"), + ) + _vod_api_schema = validate.Schema( { 'secureStreams': validate.all([ @@ -87,23 +103,39 @@ class Bloomberg(Plugin): match = self._url_re.match(self.url) channel = match.group('channel') - # Retrieve live player URL - res = self.session.http.get(self.PLAYER_URL) - match = self._live_player_re.search(res.text) - if match is None: - return [] - live_player_url = update_scheme(self.url, match.group('live_player_url')) - - # Extract streams from the live player page - res = self.session.http.get(live_player_url) - stream_datas = re.findall(r'{0}(?:_MINI)?:({{.+?}}]}}]}})'.format(self.CHANNEL_MAP[channel]), res.text) - streams = [] - for s in stream_datas: - for u in self._live_streams_schema.validate(s): - if u not in streams: - streams.append(u) - - return streams + res = self.session.http.get(self.url, headers={ + "authority": "www.bloomberg.com", + "upgrade-insecure-requests": "1", + "dnt": "1", + "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3" + }) + if "Are you a robot?" in res.text: + log.error("Are you a robot?") + match = self._preload_state_re.search(res.text) + if match: + live_ids = self._channel_list_schema.validate(match.group(1)) + live_id = live_ids.get(channel) + if live_id: + log.debug("Found liveId = {0}".format(live_id)) + # Retrieve live player URL + res = self.session.http.get(self.PLAYER_URL) + match = self._live_player_re.search(res.text) + if match is None: + return [] + live_player_url = update_scheme(self.url, match.group('live_player_url')) + + # Extract streams from the live player page + log.debug("Player URL: {0}".format(live_player_url)) + res = self.session.http.get(live_player_url) + match = self._live_stream_info_re.search(res.text) + if match: + stream_info = self._live_streams_schema.validate(match.group(1)) + data = stream_info.get(live_id, {}) + return data.get('cdns', []) + else: + log.error("Could not find liveId for channel '{0}'".format(channel)) + + return [] def _get_vod_streams(self): # Retrieve URL page and search for video ID @@ -118,6 +150,7 @@ class Bloomberg(Plugin): return streams def _get_streams(self): + self.session.http.headers.update({"User-Agent": useragents.CHROME}) if '/news/videos/' in self.url: # VOD streams = self._get_vod_streams() @@ -126,6 +159,7 @@ class Bloomberg(Plugin): streams = self._get_live_streams() for video_url in streams: + log.debug("Found stream: {0}".format(video_url)) if '.f4m' in video_url: for stream in HDSStream.parse_manifest(self.session, video_url).items(): yield stream diff --git a/src/streamlink/plugins/viutv.py b/src/streamlink/plugins/viutv.py new file mode 100644 index 00000000..24b6cbb9 --- /dev/null +++ b/src/streamlink/plugins/viutv.py @@ -0,0 +1,46 @@ +import datetime +import logging +import random +import re +import json + +from streamlink.plugin import Plugin +from streamlink.stream import HLSStream + +log = logging.getLogger(__name__) + + +class ViuTV(Plugin): + _url_re = re.compile(r"https?://viu\.tv/ch/(\d+)") + api_url = "https://api.viu.now.com/p8/2/getLiveURL" + + @classmethod + def can_handle_url(cls, url): + return cls._url_re.match(url) is not None + + @property + def device_id(self): + return "".join(random.choice("abcdef0123456789") for _ in range(18)) + + @property + def channel_id(self): + return self._url_re.match(self.url).group(1) + + def _get_streams(self): + api_res = self.session.http.post(self.api_url, + headers={"Content-Type": 'application/json'}, + data=json.dumps({"callerReferenceNo": datetime.datetime.now().strftime("%Y%m%d%H%M%S"), + "channelno": self.channel_id.zfill(3), + "mode": "prod", + "deviceId": self.device_id, + "deviceType": "5", + "format": "HLS"})) + data = self.session.http.json(api_res) + if data['responseCode'] == 'SUCCESS': + for stream_url in data.get("asset", {}).get("hls", {}).get("adaptive", []): + return HLSStream.parse_variant_playlist(self.session, stream_url) + else: + log.error("Failed to get stream URL: {0}".format(data['responseCode'])) + + +__plugin__ = ViuTV
streamlink/streamlink
d78efc47e7d7de201372fe8481cf2f36236a4dae
diff --git a/tests/plugins/test_albavision.py b/tests/plugins/test_albavision.py new file mode 100644 index 00000000..0fd72001 --- /dev/null +++ b/tests/plugins/test_albavision.py @@ -0,0 +1,29 @@ +import unittest + +import pytest + +from streamlink.plugins.albavision import Albavision + + +class TestPluginAlbavision: + valid_urls = [ + ("https://www.elnueve.com.ar/en-vivo",), + ("http://www.rts.com.ec/envivo",), + ("https://www.tvc.com.ec/envivo",), + ] + invalid_urls = [ + ("https://news.now.com/home/local",), + ("http://media.now.com.hk/",), + ("https://www.youtube.com",) + ] + + @pytest.mark.parametrize(["url"], valid_urls) + def test_can_handle_url(self, url): + assert Albavision.can_handle_url(url), "url should be handled" + + @pytest.mark.parametrize(["url"], invalid_urls) + def test_can_handle_url_negative(self, url): + assert not Albavision.can_handle_url(url), "url should not be handled" + + def test_transform(self): + assert Albavision.transform_token(u'6b425761cc8a86569b1a05a9bf1870c95fca717dOK', 436171) == "6b425761cc8a86569b1a05a9bf1870c95fca717d" diff --git a/tests/plugins/test_viutv.py b/tests/plugins/test_viutv.py new file mode 100644 index 00000000..7b978808 --- /dev/null +++ b/tests/plugins/test_viutv.py @@ -0,0 +1,23 @@ +import unittest + +import pytest + +from streamlink.plugins.viutv import ViuTV + + +class TestPluginViuTV: + valid_urls = [ + ("https://viu.tv/ch/99",), + ] + invalid_urls = [ + ("https://viu.tv/encore/king-maker-ii/king-maker-iie4fuk-hei-baan-hui-ji-on-ji-sun-dang-cheung",), + ("https://www.youtube.com",) + ] + + @pytest.mark.parametrize(["url"], valid_urls) + def test_can_handle_url(self, url): + assert ViuTV.can_handle_url(url), "url should be handled" + + @pytest.mark.parametrize(["url"], invalid_urls) + def test_can_handle_url_negative(self, url): + assert not ViuTV.can_handle_url(url), "url should not be handled"
RTS and TVC - [ ] This is a bug report. - [ ] This is a feature request. - [x] This is a plugin (improvement) request. - [ ] I have read the contribution guidelines. I'm requesting a plugin for cloudfront.net its streamed it serves a generated .m3u8 (for 30ish seconds) along with its 1ish second chunk every second or so Sites that use this server to stream: http://www.rts.com.ec/envivo http://www.tvc.com.ec/envivo XHR: http://d36zvzlneynve1.cloudfront.net/liverts/smil:liverts.smil/playlist.m3u8 http://d36zvzlneynve1.cloudfront.net/liverts/smil:liverts.smil/media-u5wu5zzkr_b899152_3340.ts http://d36zvzlneynve1.cloudfront.net/liverts/smil:liverts.smil/media-u5wu5zzkr_b899152_3341.ts http://d36zvzlneynve1.cloudfront.net/liverts/smil:liverts.smil/media-u5wu5zzkr_b899152_3342.ts http://d36zvzlneynve1.cloudfront.net/liverts/smil:liverts.smil/media-u5wu5zzkr_b899152_3343.ts These links were captured with IDM: http://d36zvzlneynve1.cloudfront.net/liverts/smil:liverts.smil/chunklist_b899152.m3u8 (360p) http://d36zvzlneynve1.cloudfront.net/liverts/smil:liverts.smil/chunklist_b249152.m3u8 (160p) http://d36zvzlneynve1.cloudfront.net/liverts/smil:liverts.smil/chunklist_b1073152.m3u8 (480p) A look at the .m3u8: ``` #EXTM3U #EXT-X-VERSION:3 #EXT-X-STREAM-INF:BANDWIDTH=899152,CODECS="avc1.77.31,mp4a.40.2",RESOLUTION=640x360 chunklist_b899152.m3u8 #EXT-X-STREAM-INF:BANDWIDTH=249152,CODECS="avc1.66.21,mp4a.40.2",RESOLUTION=284x160 chunklist_b249152.m3u8 #EXT-X-STREAM-INF:BANDWIDTH=1073152,CODECS="avc1.77.32,mp4a.40.2",RESOLUTION=854x480 chunklist_b1073152.m3u8 ``` When I tried to download the stream, usually Streamlink says "Error 403", but other times Streamlink says it does not have the plugin.
0.0
d78efc47e7d7de201372fe8481cf2f36236a4dae
[ "tests/plugins/test_albavision.py::TestPluginAlbavision::test_can_handle_url[https://www.elnueve.com.ar/en-vivo]", "tests/plugins/test_albavision.py::TestPluginAlbavision::test_can_handle_url[http://www.rts.com.ec/envivo]", "tests/plugins/test_albavision.py::TestPluginAlbavision::test_can_handle_url[https://www.tvc.com.ec/envivo]", "tests/plugins/test_albavision.py::TestPluginAlbavision::test_can_handle_url_negative[https://news.now.com/home/local]", "tests/plugins/test_albavision.py::TestPluginAlbavision::test_can_handle_url_negative[http://media.now.com.hk/]", "tests/plugins/test_albavision.py::TestPluginAlbavision::test_can_handle_url_negative[https://www.youtube.com]", "tests/plugins/test_albavision.py::TestPluginAlbavision::test_transform", "tests/plugins/test_viutv.py::TestPluginViuTV::test_can_handle_url[https://viu.tv/ch/99]", "tests/plugins/test_viutv.py::TestPluginViuTV::test_can_handle_url_negative[https://viu.tv/encore/king-maker-ii/king-maker-iie4fuk-hei-baan-hui-ji-on-ji-sun-dang-cheung]", "tests/plugins/test_viutv.py::TestPluginViuTV::test_can_handle_url_negative[https://www.youtube.com]" ]
[]
{ "failed_lite_validators": [ "has_hyperlinks", "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2019-10-04 23:44:29+00:00
bsd-2-clause
5,781
streamlink__streamlink-2654
diff --git a/docs/plugin_matrix.rst b/docs/plugin_matrix.rst index 7ffd8bd5..2363fc1e 100644 --- a/docs/plugin_matrix.rst +++ b/docs/plugin_matrix.rst @@ -261,6 +261,7 @@ viasat - juicyplay.dk Yes Yes Streams may be geo-rest vidio vidio.com Yes Yes vimeo vimeo.com Yes Yes Password-protected videos are not supported. vinhlongtv thvli.vn Yes No Streams are geo-restricted to Vietnam +viutv viu.tv Yes No Streams are geo-restricted to Hong Kong vk vk.com Yes Yes vrtbe vrt.be/vrtnu Yes Yes vtvgo vtvgo.vn Yes No diff --git a/src/streamlink/plugins/viutv.py b/src/streamlink/plugins/viutv.py new file mode 100644 index 00000000..24b6cbb9 --- /dev/null +++ b/src/streamlink/plugins/viutv.py @@ -0,0 +1,46 @@ +import datetime +import logging +import random +import re +import json + +from streamlink.plugin import Plugin +from streamlink.stream import HLSStream + +log = logging.getLogger(__name__) + + +class ViuTV(Plugin): + _url_re = re.compile(r"https?://viu\.tv/ch/(\d+)") + api_url = "https://api.viu.now.com/p8/2/getLiveURL" + + @classmethod + def can_handle_url(cls, url): + return cls._url_re.match(url) is not None + + @property + def device_id(self): + return "".join(random.choice("abcdef0123456789") for _ in range(18)) + + @property + def channel_id(self): + return self._url_re.match(self.url).group(1) + + def _get_streams(self): + api_res = self.session.http.post(self.api_url, + headers={"Content-Type": 'application/json'}, + data=json.dumps({"callerReferenceNo": datetime.datetime.now().strftime("%Y%m%d%H%M%S"), + "channelno": self.channel_id.zfill(3), + "mode": "prod", + "deviceId": self.device_id, + "deviceType": "5", + "format": "HLS"})) + data = self.session.http.json(api_res) + if data['responseCode'] == 'SUCCESS': + for stream_url in data.get("asset", {}).get("hls", {}).get("adaptive", []): + return HLSStream.parse_variant_playlist(self.session, stream_url) + else: + log.error("Failed to get stream URL: {0}".format(data['responseCode'])) + + +__plugin__ = ViuTV
streamlink/streamlink
d78efc47e7d7de201372fe8481cf2f36236a4dae
diff --git a/tests/plugins/test_viutv.py b/tests/plugins/test_viutv.py new file mode 100644 index 00000000..7b978808 --- /dev/null +++ b/tests/plugins/test_viutv.py @@ -0,0 +1,23 @@ +import unittest + +import pytest + +from streamlink.plugins.viutv import ViuTV + + +class TestPluginViuTV: + valid_urls = [ + ("https://viu.tv/ch/99",), + ] + invalid_urls = [ + ("https://viu.tv/encore/king-maker-ii/king-maker-iie4fuk-hei-baan-hui-ji-on-ji-sun-dang-cheung",), + ("https://www.youtube.com",) + ] + + @pytest.mark.parametrize(["url"], valid_urls) + def test_can_handle_url(self, url): + assert ViuTV.can_handle_url(url), "url should be handled" + + @pytest.mark.parametrize(["url"], invalid_urls) + def test_can_handle_url_negative(self, url): + assert not ViuTV.can_handle_url(url), "url should not be handled"
ViuTV live ## Plugin Request <!-- Replace [ ] with [x] in order to check the box --> - [x] This is a plugin request and I have read the contribution guidelines and plugin request requirements. ### Description <!-- Explain the plugin and site as clearly as you can. What is the site about? Who runs it? What content does it provide? What value does it bring to Streamlink? Etc. --> One of a local television station from Hong Kong which currently accessible via Internet streaming. ViuTV is one of a few disinterested news channel which provide fare perspective reports compared to major aired television in Hong Kong. ### Example stream URLs <!-- Example URLs for streams are required. Plugin requests which do not have example URLs will be closed. --> 1. https://viu.tv/ch/99 ### Additional comments, screenshots, etc. ![chrome_2019-09-07_22-29-31](https://user-images.githubusercontent.com/771955/64476235-071fe400-d1bf-11e9-964e-1807da742eed.png) ViuTV is also run by Now, so the method for fetching playback should be the same as NowTV https://github.com/streamlink/streamlink/issues/2592 [Love Streamlink? Please consider supporting our collective. Thanks!](https://opencollective.com/streamlink/donate)
0.0
d78efc47e7d7de201372fe8481cf2f36236a4dae
[ "tests/plugins/test_viutv.py::TestPluginViuTV::test_can_handle_url[https://viu.tv/ch/99]", "tests/plugins/test_viutv.py::TestPluginViuTV::test_can_handle_url_negative[https://viu.tv/encore/king-maker-ii/king-maker-iie4fuk-hei-baan-hui-ji-on-ji-sun-dang-cheung]", "tests/plugins/test_viutv.py::TestPluginViuTV::test_can_handle_url_negative[https://www.youtube.com]" ]
[]
{ "failed_lite_validators": [ "has_hyperlinks", "has_media", "has_added_files" ], "has_test_patch": true, "is_lite": false }
2019-10-05 20:16:07+00:00
bsd-2-clause
5,782
streamlink__streamlink-2671
diff --git a/docs/plugin_matrix.rst b/docs/plugin_matrix.rst index b88febc7..1423894b 100644 --- a/docs/plugin_matrix.rst +++ b/docs/plugin_matrix.rst @@ -110,7 +110,7 @@ itvplayer itv.com/itvplayer Yes Yes Streams may be geo-rest kanal7 - kanal7.com Yes No - tvt.tv.tr kingkong kingkong.com.tw Yes -- -linelive live.line.me Yes -- +linelive live.line.me Yes Yes live_russia_tv live.russia.tv Yes -- liveedu - liveedu.tv Yes -- Some streams require a login. - livecoding.tv @@ -267,6 +267,7 @@ vimeo vimeo.com Yes Yes Password-protected vide vinhlongtv thvli.vn Yes No Streams are geo-restricted to Vietnam viutv viu.tv Yes No Streams are geo-restricted to Hong Kong vk vk.com Yes Yes +vlive vlive.tv Yes No Embedded Naver VODs are not supported. vrtbe vrt.be/vrtnu Yes Yes vtvgo vtvgo.vn Yes No webcast_india_gov webcast.gov.in Yes No You can use #Channel to indicate CH number. diff --git a/src/streamlink/plugins/linelive.py b/src/streamlink/plugins/linelive.py index 24a2c33b..e524a32c 100644 --- a/src/streamlink/plugins/linelive.py +++ b/src/streamlink/plugins/linelive.py @@ -23,26 +23,43 @@ class LineLive(Plugin): "360": validate.any(None, validate.url(scheme="http", path=validate.endswith(".m3u8"))), "240": validate.any(None, validate.url(scheme="http", path=validate.endswith(".m3u8"))), "144": validate.any(None, validate.url(scheme="http", path=validate.endswith(".m3u8"))), - }) - } - ) + }), + "archivedHLSURLs": validate.any(None, { + "720": validate.any(None, validate.url(scheme="http", path=validate.endswith(".m3u8"))), + "480": validate.any(None, validate.url(scheme="http", path=validate.endswith(".m3u8"))), + "360": validate.any(None, validate.url(scheme="http", path=validate.endswith(".m3u8"))), + "240": validate.any(None, validate.url(scheme="http", path=validate.endswith(".m3u8"))), + "144": validate.any(None, validate.url(scheme="http", path=validate.endswith(".m3u8"))), + }), + }) @classmethod def can_handle_url(cls, url): return cls._url_re.match(url) is not None + def _get_live_streams(self, json): + for stream in json["liveHLSURLs"]: + url = json["liveHLSURLs"][stream] + if url is not None: + yield "{0}p.".format(stream), HLSStream(self.session, url) + + def _get_vod_streams(self, json): + for stream in json["archivedHLSURLs"]: + url = json["archivedHLSURLs"][stream] + if url is not None: + yield "{0}p.".format(stream), HLSStream(self.session, url) + def _get_streams(self): match = self._url_re.match(self.url) channel = match.group("channel") broadcast = match.group("broadcast") res = self.session.http.get(self._api_url.format(channel, broadcast)) json = self.session.http.json(res, schema=self._player_status_schema) - if json["liveStatus"] != "LIVE": - return - for stream in json["liveHLSURLs"]: - url = json["liveHLSURLs"][stream] - if url != None: - yield "{0}p".format(stream), HLSStream(self.session, url) + if json["liveStatus"] == "LIVE": + return self._get_live_streams(json) + elif json["liveStatus"] == "FINISHED": + return self._get_vod_streams(json) + return __plugin__ = LineLive diff --git a/src/streamlink/plugins/vlive.py b/src/streamlink/plugins/vlive.py new file mode 100644 index 00000000..71a3f645 --- /dev/null +++ b/src/streamlink/plugins/vlive.py @@ -0,0 +1,55 @@ +import re +import json + +from streamlink.plugin import Plugin, PluginError +from streamlink.stream import HLSStream + + +class Vlive(Plugin): + _url_re = re.compile(r"https?://(?:www.)vlive\.tv/video/(\d+)") + _video_status = re.compile(r'oVideoStatus = (.+)<', re.DOTALL) + _video_init_url = "https://www.vlive.tv/video/init/view" + + @classmethod + def can_handle_url(cls, url): + return cls._url_re.match(url) is not None + + @property + def video_id(self): + return self._url_re.match(self.url).group(1) + + def _get_streams(self): + vinit_req = self.session.http.get(self._video_init_url, + params=dict(videoSeq=self.video_id), + headers=dict(referer=self.url)) + if vinit_req.status_code != 200: + raise PluginError('Could not get video init page (HTTP Status {})' + .format(vinit_req.status_code)) + + video_status_js = self._video_status.search(vinit_req.text) + if not video_status_js: + raise PluginError('Could not find video status information!') + + video_status = json.loads(video_status_js.group(1)) + + if video_status['viewType'] == 'vod': + raise PluginError('VODs are not supported') + + if 'liveStreamInfo' not in video_status: + raise PluginError('Stream is offline') + + stream_info = json.loads(video_status['liveStreamInfo']) + + streams = dict() + # All "resolutions" have a variant playlist with only one entry, so just combine them + for i in stream_info['resolutions']: + res_streams = HLSStream.parse_variant_playlist(self.session, i['cdnUrl']) + if len(res_streams.values()) > 1: + self.logger.warning('More than one stream in variant playlist, using first entry!') + + streams[i['name']] = res_streams.popitem()[1] + + return streams + + +__plugin__ = Vlive
streamlink/streamlink
cc32730ea7c9749169df34e2f1a82c1fdb704df4
diff --git a/tests/plugins/test_vlive.py b/tests/plugins/test_vlive.py new file mode 100644 index 00000000..31f7c8f8 --- /dev/null +++ b/tests/plugins/test_vlive.py @@ -0,0 +1,23 @@ +import unittest + +import pytest + +from streamlink.plugins.vlive import Vlive + + +class TestPluginVlive: + valid_urls = [ + ("https://www.vlive.tv/video/156824",), + ] + invalid_urls = [ + ("https://www.vlive.tv/events/2019vheartbeat?lang=en",), + ("https://twitch.tv/",) + ] + + @pytest.mark.parametrize(["url"], valid_urls) + def test_can_handle_url(self, url): + assert Vlive.can_handle_url(url), "url should be handled" + + @pytest.mark.parametrize(["url"], invalid_urls) + def test_can_handle_url_negative(self, url): + assert not Vlive.can_handle_url(url), "url should not be handled"
[Plugin Request] Vlive.tv <!-- Thanks for requesting a plugin! USE THE TEMPLATE. Otherwise your plugin request may be rejected. First, see the contribution guidelines and plugin request requirements: https://github.com/streamlink/streamlink/blob/master/CONTRIBUTING.md#contributing-to-streamlink Plugin requests which fall into the categories we will not implement will be closed immediately. Also check the list of open and closed plugin requests: https://github.com/streamlink/streamlink/issues?q=is%3Aissue+label%3A%22plugin+request%22 Please see the text preview to avoid unnecessary formatting errors. --> ## Plugin Request <!-- Replace [ ] with [x] in order to check the box --> - [x] This is a plugin request and I have read the contribution guidelines and plugin request requirements. ### Description This is a live streaming site. This site was originally mainly for idols who want to interact with fans, but now it has grown more, many people have registered and broadcast a number of more diverse programs. <!-- Explain the plugin and site as clearly as you can. What is the site about? Who runs it? What content does it provide? What value does it bring to Streamlink? Etc. --> ### Example stream URLs <!-- Example URLs for streams are required. Plugin requests which do not have example URLs will be closed. --> 1. https://www.vlive.tv/ (Home page) 2. https://www.vlive.tv/upcoming (Upcoming broadcasts will be show here) ### Additional comments, screenshots, etc. This site has no live streaming 24/7 so you can visit the homepage and look down, sometimes seeing some people broadcasting there (IMG: https://i.imgur.com/rHBMmli.jpg). Or visit this page to see upcoming shows: https://www.vlive.tv/upcoming Hope you can support this page, thanks so much. [Love Streamlink? Please consider supporting our collective. Thanks!](https://opencollective.com/streamlink/donate)
0.0
cc32730ea7c9749169df34e2f1a82c1fdb704df4
[ "tests/plugins/test_vlive.py::TestPluginVlive::test_can_handle_url[https://www.vlive.tv/video/156824]", "tests/plugins/test_vlive.py::TestPluginVlive::test_can_handle_url_negative[https://www.vlive.tv/events/2019vheartbeat?lang=en]", "tests/plugins/test_vlive.py::TestPluginVlive::test_can_handle_url_negative[https://twitch.tv/]" ]
[]
{ "failed_lite_validators": [ "has_hyperlinks", "has_media", "has_added_files", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2019-10-25 12:25:46+00:00
bsd-2-clause
5,783
streamlink__streamlink-2765
diff --git a/src/streamlink_cli/output.py b/src/streamlink_cli/output.py index e04471be..c8f2b3f0 100644 --- a/src/streamlink_cli/output.py +++ b/src/streamlink_cli/output.py @@ -190,7 +190,7 @@ class PlayerOutput(Output): if self.player_name == "mpv": # see https://mpv.io/manual/stable/#property-expansion, allow escaping with \$, respect mpv's $> self.title = self._mpv_title_escape(self.title) - extra_args.extend(["--title", self.title]) + extra_args.append("--title={}".format(self.title)) # potplayer if self.player_name == "potplayer": @@ -202,7 +202,7 @@ class PlayerOutput(Output): args = self.args.format(filename=filename) cmd = self.cmd - + # player command if is_win32: eargs = maybe_decode(subprocess.list2cmdline(extra_args))
streamlink/streamlink
f90d560511523d67c71387eb67bb91fd577ec1bb
diff --git a/tests/test_cmdline_title.py b/tests/test_cmdline_title.py index 2c6a9fac..61cb53b8 100644 --- a/tests/test_cmdline_title.py +++ b/tests/test_cmdline_title.py @@ -26,7 +26,7 @@ class TestCommandLineWithTitlePOSIX(CommandLineTestCase): def test_open_player_with_title_mpv(self): self._test_args(["streamlink", "-p", "/usr/bin/mpv", "--title", "{title}", "http://test.se", "test"], - ["/usr/bin/mpv", "--title", 'Test Title', "-"]) + ["/usr/bin/mpv", "--title=Test Title", "-"]) @unittest.skipIf(not is_win32, "test only applicable on Windows")
Change in mpv options for 2 dashes options breaks it connection to Streamlink lately mpv changed the way they handle [2 dashes options](https://github.com/mpv-player/mpv/commit/d3cef97ad38fb027262a905bd82e1d3d2549aec7) ``` --- mpv 0.31.1 --- - change behavior when using legacy option syntax with options that start with two dashes (``--`` instead of a ``-``). Now, using the recommended syntax is required for options starting with ``--``, which means an option value must be strictly passed after a ``=``, instead of as separate argument. For example, ``--log-file f.txt`` was previously accepted and behaved like ``--log-file=f.txt``, but now causes an error. Use of legacy syntax that is still supported now prints a deprecation warning. ``` So now mpv just closes with no errors when used with streamlink as streamlink creates an mpv command with --title "title" instead of --title="title" ``` [15:57] zouhair@box <5402:63> [~] -> :) ┖╴$ streamlink --verbose-player --loglevel debug https://www.twitch.tv/videos/533706108 best [cli][debug] OS: CYGWIN_NT-10.0-18362-3.1.2-340.x86_64-x86_64-64bit-WindowsPE [cli][debug] Python: 3.7.4 [cli][debug] Streamlink: 1.3.0 [cli][debug] Requests(2.22.0), Socks(1.7.0), Websocket(0.56.0) [cli][info] Found matching plugin twitch for URL https://www.twitch.tv/videos/533706108 [plugin.twitch][debug] Getting video HLS streams for gamesdonequick [utils.l10n][debug] Language code: en_US [cli][info] Available streams: audio, 160p (worst), 360p, 480p, 720p, 720p60, 1080p60 (best) [cli][info] Opening stream: 1080p60 (hls) [cli][info] Starting player: /home/zouhair/mpv.exe --cache 2048 [cli.output][debug] Calling: /home/zouhair/mpv.exe --cache 2048 --title https://www.twitch.tv/videos/533706108 https://vod-secure.twitch.tv/7dc8f3a102cc1793f7bc_gamesdonequick_36629634272_1358097847/chunked/index-dvr.m3u8 [15:57] zouhair@box <5403:64> [~] -> :) ┖╴$ echo $? 0 [15:57] zouhair@box <5404:65> [~] -> :) ┖╴$ ```
0.0
f90d560511523d67c71387eb67bb91fd577ec1bb
[ "tests/test_cmdline_title.py::TestCommandLineWithTitlePOSIX::test_open_player_with_title_mpv" ]
[ "tests/test_cmdline_title.py::TestCommandLineWithTitlePOSIX::test_open_player_with_default_title_vlc", "tests/test_cmdline_title.py::TestCommandLineWithTitlePOSIX::test_open_player_with_default_title_vlc_args", "tests/test_cmdline_title.py::TestCommandLineWithTitlePOSIX::test_open_player_with_title_vlc", "tests/test_cmdline_title.py::TestCommandLineWithTitlePOSIX::test_open_player_with_unicode_author_vlc" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2020-01-12 23:18:51+00:00
bsd-2-clause
5,784
streamlink__streamlink-3016
diff --git a/docs/plugin_matrix.rst b/docs/plugin_matrix.rst index 0d003504..6b15eb5b 100644 --- a/docs/plugin_matrix.rst +++ b/docs/plugin_matrix.rst @@ -38,7 +38,7 @@ bilibili live.bilibili.com Yes ? bloomberg bloomberg.com Yes Yes brightcove players.brig... [6]_ Yes Yes btsports sport.bt.com Yes Yes Requires subscription account -btv btv.bg Yes No Requires login, and geo-restricted to Bulgaria. +btv btvplus.bg Yes No Streams are geo-restricted to Bulgaria. canalplus mycanal.fr No Yes Streams may be geo-restricted to France. cdnbg - tv.bnt.bg Yes No Streams may be geo-restricted to Bulgaria. - bgonair.bg diff --git a/src/streamlink/plugin/plugin.py b/src/streamlink/plugin/plugin.py index 9e8471cf..696a0dc6 100644 --- a/src/streamlink/plugin/plugin.py +++ b/src/streamlink/plugin/plugin.py @@ -377,7 +377,7 @@ class Plugin(object): # Force lowercase name and replace space with underscore. streams[name.lower()] = stream - # Create the best/worst synonmys + # Create the best/worst synonyms def stream_weight_only(s): return (self.stream_weight(s)[0] or (len(streams) == 1 and 1)) diff --git a/src/streamlink/plugins/bigo.py b/src/streamlink/plugins/bigo.py index 9b895071..7d0e9286 100644 --- a/src/streamlink/plugins/bigo.py +++ b/src/streamlink/plugins/bigo.py @@ -1,37 +1,37 @@ -import logging import re from streamlink.plugin import Plugin -from streamlink.plugin.api import useragents +from streamlink.plugin.api import useragents, validate from streamlink.stream import HLSStream -log = logging.getLogger(__name__) - class Bigo(Plugin): - _url_re = re.compile(r"^https?://(?:www\.)?bigo\.tv/[^/]+$") - _video_re = re.compile( - r"""videoSrc:\s?["'](?P<url>[^"']+)["']""", - re.M) + _url_re = re.compile(r"https?://(?:www\.)?bigo\.tv/([^/]+)$") + _api_url = "https://www.bigo.tv/OInterface/getVideoParam?bigoId={0}" + + _video_info_schema = validate.Schema({ + "code": 0, + "msg": "success", + "data": { + "videoSrc": validate.any(None, "", validate.url()) + } + }) @classmethod def can_handle_url(cls, url): return cls._url_re.match(url) is not None def _get_streams(self): - page = self.session.http.get( - self.url, + match = self._url_re.match(self.url) + res = self.session.http.get( + self._api_url.format(match.group(1)), allow_redirects=True, headers={"User-Agent": useragents.IPHONE_6} ) - videomatch = self._video_re.search(page.text) - if not videomatch: - log.error("No playlist found.") - return - - videourl = videomatch.group(1) - log.debug("URL={0}".format(videourl)) - yield "live", HLSStream(self.session, videourl) + data = self.session.http.json(res, schema=self._video_info_schema) + videourl = data["data"]["videoSrc"] + if videourl: + yield "live", HLSStream(self.session, videourl) __plugin__ = Bigo diff --git a/src/streamlink/plugins/btv.py b/src/streamlink/plugins/btv.py index a026c641..680711cc 100644 --- a/src/streamlink/plugins/btv.py +++ b/src/streamlink/plugins/btv.py @@ -1,38 +1,30 @@ -from __future__ import print_function +import argparse +import logging import re -from streamlink import PluginError -from streamlink.plugin import Plugin +from streamlink.plugin import Plugin, PluginArguments, PluginArgument from streamlink.plugin.api import validate from streamlink.stream import HLSStream from streamlink.utils import parse_json -from streamlink.plugin import PluginArgument, PluginArguments + +log = logging.getLogger(__name__) class BTV(Plugin): arguments = PluginArguments( PluginArgument( "username", - metavar="USERNAME", - requires=["password"], - help=""" - A BTV username required to access any stream. - """ + help=argparse.SUPPRESS ), PluginArgument( "password", sensitive=True, - metavar="PASSWORD", - help=""" - A BTV account password to use with --btv-username. - """ + help=argparse.SUPPRESS ) ) - url_re = re.compile(r"https?://(?:www\.)?btv\.bg/live/?") - api_url = "http://www.btv.bg/lbin/global/player_config.php" - check_login_url = "http://www.btv.bg/lbin/userRegistration/check_user_login.php" - login_url = "https://www.btv.bg/bin/registration2/login.php?action=login&settings=0" + url_re = re.compile(r"https?://(?:www\.)?btvplus\.bg/live/?") + api_url = "https://btvplus.bg/lbin/v3/btvplus/player_config.php" media_id_re = re.compile(r"media_id=(\d+)") src_re = re.compile(r"src: \"(http.*?)\"") @@ -55,35 +47,19 @@ class BTV(Plugin): def can_handle_url(cls, url): return cls.url_re.match(url) is not None - def login(self, username, password): - res = self.session.http.post(self.login_url, data={"username": username, "password": password}) - if "success_logged_in" in res.text: - return True - else: - return False - def get_hls_url(self, media_id): res = self.session.http.get(self.api_url, params=dict(media_id=media_id)) - try: - return parse_json(res.text, schema=self.api_schema) - except PluginError: - return + return parse_json(res.text, schema=self.api_schema) def _get_streams(self): - if not self.options.get("username") or not self.options.get("password"): - self.logger.error("BTV requires registration, set the username and password" - " with --btv-username and --btv-password") - elif self.login(self.options.get("username"), self.options.get("password")): - res = self.session.http.get(self.url) - media_match = self.media_id_re.search(res.text) - media_id = media_match and media_match.group(1) - if media_id: - self.logger.debug("Found media id: {0}", media_id) - stream_url = self.get_hls_url(media_id) - if stream_url: - return HLSStream.parse_variant_playlist(self.session, stream_url) - else: - self.logger.error("Login failed, a valid username and password is required") + res = self.session.http.get(self.url) + media_match = self.media_id_re.search(res.text) + media_id = media_match and media_match.group(1) + if media_id: + log.debug("Found media id: {0}", media_id) + stream_url = self.get_hls_url(media_id) + if stream_url: + return HLSStream.parse_variant_playlist(self.session, stream_url) __plugin__ = BTV
streamlink/streamlink
ad8113bbb6a9fb0006d7a243418dfe5936e5a1a9
diff --git a/tests/plugins/test_bigo.py b/tests/plugins/test_bigo.py index 313ec7e8..11eb435e 100644 --- a/tests/plugins/test_bigo.py +++ b/tests/plugins/test_bigo.py @@ -5,26 +5,33 @@ from streamlink.plugins.bigo import Bigo class TestPluginBigo(unittest.TestCase): def test_can_handle_url(self): - # Correct urls - self.assertTrue(Bigo.can_handle_url("http://bigo.tv/00000000")) - self.assertTrue(Bigo.can_handle_url("https://bigo.tv/00000000")) - self.assertTrue(Bigo.can_handle_url("https://www.bigo.tv/00000000")) - self.assertTrue(Bigo.can_handle_url("http://www.bigo.tv/00000000")) - self.assertTrue(Bigo.can_handle_url("http://www.bigo.tv/fancy1234")) - self.assertTrue(Bigo.can_handle_url("http://www.bigo.tv/abc.123")) - self.assertTrue(Bigo.can_handle_url("http://www.bigo.tv/000000.00")) + should_match = [ + "http://bigo.tv/00000000", + "https://bigo.tv/00000000", + "https://www.bigo.tv/00000000", + "http://www.bigo.tv/00000000", + "http://www.bigo.tv/fancy1234", + "http://www.bigo.tv/abc.123", + "http://www.bigo.tv/000000.00" + ] + for url in should_match: + self.assertTrue(Bigo.can_handle_url(url), url) - # Old URLs don't work anymore - self.assertFalse(Bigo.can_handle_url("http://live.bigo.tv/00000000")) - self.assertFalse(Bigo.can_handle_url("https://live.bigo.tv/00000000")) - self.assertFalse(Bigo.can_handle_url("http://www.bigoweb.co/show/00000000")) - self.assertFalse(Bigo.can_handle_url("https://www.bigoweb.co/show/00000000")) - self.assertFalse(Bigo.can_handle_url("http://bigoweb.co/show/00000000")) - self.assertFalse(Bigo.can_handle_url("https://bigoweb.co/show/00000000")) + def test_can_handle_url_negative(self): + should_not_match = [ + # Old URLs don't work anymore + "http://live.bigo.tv/00000000", + "https://live.bigo.tv/00000000", + "http://www.bigoweb.co/show/00000000", + "https://www.bigoweb.co/show/00000000", + "http://bigoweb.co/show/00000000", + "https://bigoweb.co/show/00000000" - # Wrong URL structure - self.assertFalse(Bigo.can_handle_url("ftp://www.bigo.tv/00000000")) - self.assertFalse(Bigo.can_handle_url("https://www.bigo.tv/show/00000000")) - self.assertFalse(Bigo.can_handle_url("http://www.bigo.tv/show/00000000")) - self.assertFalse(Bigo.can_handle_url("http://bigo.tv/show/00000000")) - self.assertFalse(Bigo.can_handle_url("https://bigo.tv/show/00000000")) + # Wrong URL structure + "https://www.bigo.tv/show/00000000", + "http://www.bigo.tv/show/00000000", + "http://bigo.tv/show/00000000", + "https://bigo.tv/show/00000000" + ] + for url in should_not_match: + self.assertFalse(Bigo.can_handle_url(url), url) diff --git a/tests/plugins/test_btv.py b/tests/plugins/test_btv.py index b04e1933..32304e92 100644 --- a/tests/plugins/test_btv.py +++ b/tests/plugins/test_btv.py @@ -6,9 +6,9 @@ from streamlink.plugins.btv import BTV class TestPluginBTV(unittest.TestCase): def test_can_handle_url(self): # should match - self.assertTrue(BTV.can_handle_url("http://btv.bg/live")) - self.assertTrue(BTV.can_handle_url("http://btv.bg/live/")) - self.assertTrue(BTV.can_handle_url("http://www.btv.bg/live/")) + self.assertTrue(BTV.can_handle_url("http://btvplus.bg/live")) + self.assertTrue(BTV.can_handle_url("http://btvplus.bg/live/")) + self.assertTrue(BTV.can_handle_url("http://www.btvplus.bg/live/")) # shouldn't match self.assertFalse(BTV.can_handle_url("http://www.tvcatchup.com/"))
Bigo TV cannot successfully get the videoSrc URL <!-- Thanks for reporting a plugin issue! USE THE TEMPLATE. Otherwise your plugin issue may be rejected. First, see the contribution guidelines: https://github.com/streamlink/streamlink/blob/master/CONTRIBUTING.md#contributing-to-streamlink Also check the list of open and closed plugin issues: https://github.com/streamlink/streamlink/issues?q=is%3Aissue+label%3A%22plugin+issue%22 Please see the text preview to avoid unnecessary formatting errors. --> ## Plugin Issue <!-- Replace [ ] with [x] in order to check the box --> - [x] This is a plugin issue and I have read the contribution guidelines. ### Description <!-- Explain the plugin issue as thoroughly as you can. --> I try to use streamlink to watch the bigo live tv, but the command line pops up the error message as "[plugin.bigo][error] No playlist found." ### Reproduction steps / Explicit stream URLs to test <!-- How can we reproduce this? Please note the exact steps below using the list format supplied. If you need more steps please add them. --> 1. streamlink http://www.bigo.tv/11819287 best & ### Log output <!-- TEXT LOG OUTPUT IS REQUIRED for a plugin issue! Use the `--loglevel debug` parameter and avoid using parameters which suppress log output. https://streamlink.github.io/cli.html#cmdoption-l Make sure to **remove usernames and passwords** You can copy the output to https://gist.github.com/ or paste it below. --> ``` [cli][debug] OS: Linux-5.4.0-33-generic-x86_64-with-glibc2.29 [cli][debug] Python: 3.8.2 [cli][debug] Streamlink: 1.4.1 [cli][debug] Requests(2.22.0), Socks(1.6.7), Websocket(0.53.0) [cli][info] Found matching plugin bigo for URL http://www.bigo.tv/11819287 [plugin.bigo][error] No playlist found. error: No playable streams found on this URL: http://www.bigo.tv/11819287 ``` ### Additional comments, screenshots, etc. After reviewing the bigo.py in streamlink/plugin, I found that the original method attempts to get the videoSrc in the webpage. However, recently the web page excluded the parameter in the page. So, here is the alternative 1. Add new API URL. ``` api_url = "http://www.bigo.tv/OInterface/getVideoParam?bigoId=" ``` 2. Extract bigo_id from self.url. ``` extract_id = self.url.split('/')[-1] ``` 3. Use composed url to get the videoSrc. ``` page = self.session.http.get(api_url + extract_id, ...) ``` 4. Change the videomatch & videourl. ``` videomatch = page.json()['data']['videoSrc']; videourl = videomatch ```
0.0
ad8113bbb6a9fb0006d7a243418dfe5936e5a1a9
[ "tests/plugins/test_btv.py::TestPluginBTV::test_can_handle_url" ]
[ "tests/plugins/test_bigo.py::TestPluginBigo::test_can_handle_url", "tests/plugins/test_bigo.py::TestPluginBigo::test_can_handle_url_negative" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2020-06-07 14:35:33+00:00
bsd-2-clause
5,785
streamlink__streamlink-3019
diff --git a/docs/plugin_matrix.rst b/docs/plugin_matrix.rst index 0d003504..6b15eb5b 100644 --- a/docs/plugin_matrix.rst +++ b/docs/plugin_matrix.rst @@ -38,7 +38,7 @@ bilibili live.bilibili.com Yes ? bloomberg bloomberg.com Yes Yes brightcove players.brig... [6]_ Yes Yes btsports sport.bt.com Yes Yes Requires subscription account -btv btv.bg Yes No Requires login, and geo-restricted to Bulgaria. +btv btvplus.bg Yes No Streams are geo-restricted to Bulgaria. canalplus mycanal.fr No Yes Streams may be geo-restricted to France. cdnbg - tv.bnt.bg Yes No Streams may be geo-restricted to Bulgaria. - bgonair.bg diff --git a/src/streamlink/plugins/btv.py b/src/streamlink/plugins/btv.py index a026c641..680711cc 100644 --- a/src/streamlink/plugins/btv.py +++ b/src/streamlink/plugins/btv.py @@ -1,38 +1,30 @@ -from __future__ import print_function +import argparse +import logging import re -from streamlink import PluginError -from streamlink.plugin import Plugin +from streamlink.plugin import Plugin, PluginArguments, PluginArgument from streamlink.plugin.api import validate from streamlink.stream import HLSStream from streamlink.utils import parse_json -from streamlink.plugin import PluginArgument, PluginArguments + +log = logging.getLogger(__name__) class BTV(Plugin): arguments = PluginArguments( PluginArgument( "username", - metavar="USERNAME", - requires=["password"], - help=""" - A BTV username required to access any stream. - """ + help=argparse.SUPPRESS ), PluginArgument( "password", sensitive=True, - metavar="PASSWORD", - help=""" - A BTV account password to use with --btv-username. - """ + help=argparse.SUPPRESS ) ) - url_re = re.compile(r"https?://(?:www\.)?btv\.bg/live/?") - api_url = "http://www.btv.bg/lbin/global/player_config.php" - check_login_url = "http://www.btv.bg/lbin/userRegistration/check_user_login.php" - login_url = "https://www.btv.bg/bin/registration2/login.php?action=login&settings=0" + url_re = re.compile(r"https?://(?:www\.)?btvplus\.bg/live/?") + api_url = "https://btvplus.bg/lbin/v3/btvplus/player_config.php" media_id_re = re.compile(r"media_id=(\d+)") src_re = re.compile(r"src: \"(http.*?)\"") @@ -55,35 +47,19 @@ class BTV(Plugin): def can_handle_url(cls, url): return cls.url_re.match(url) is not None - def login(self, username, password): - res = self.session.http.post(self.login_url, data={"username": username, "password": password}) - if "success_logged_in" in res.text: - return True - else: - return False - def get_hls_url(self, media_id): res = self.session.http.get(self.api_url, params=dict(media_id=media_id)) - try: - return parse_json(res.text, schema=self.api_schema) - except PluginError: - return + return parse_json(res.text, schema=self.api_schema) def _get_streams(self): - if not self.options.get("username") or not self.options.get("password"): - self.logger.error("BTV requires registration, set the username and password" - " with --btv-username and --btv-password") - elif self.login(self.options.get("username"), self.options.get("password")): - res = self.session.http.get(self.url) - media_match = self.media_id_re.search(res.text) - media_id = media_match and media_match.group(1) - if media_id: - self.logger.debug("Found media id: {0}", media_id) - stream_url = self.get_hls_url(media_id) - if stream_url: - return HLSStream.parse_variant_playlist(self.session, stream_url) - else: - self.logger.error("Login failed, a valid username and password is required") + res = self.session.http.get(self.url) + media_match = self.media_id_re.search(res.text) + media_id = media_match and media_match.group(1) + if media_id: + log.debug("Found media id: {0}", media_id) + stream_url = self.get_hls_url(media_id) + if stream_url: + return HLSStream.parse_variant_playlist(self.session, stream_url) __plugin__ = BTV
streamlink/streamlink
5059d64be20b3cd6adc6374e921382ef2c261978
diff --git a/tests/plugins/test_btv.py b/tests/plugins/test_btv.py index b04e1933..32304e92 100644 --- a/tests/plugins/test_btv.py +++ b/tests/plugins/test_btv.py @@ -6,9 +6,9 @@ from streamlink.plugins.btv import BTV class TestPluginBTV(unittest.TestCase): def test_can_handle_url(self): # should match - self.assertTrue(BTV.can_handle_url("http://btv.bg/live")) - self.assertTrue(BTV.can_handle_url("http://btv.bg/live/")) - self.assertTrue(BTV.can_handle_url("http://www.btv.bg/live/")) + self.assertTrue(BTV.can_handle_url("http://btvplus.bg/live")) + self.assertTrue(BTV.can_handle_url("http://btvplus.bg/live/")) + self.assertTrue(BTV.can_handle_url("http://www.btvplus.bg/live/")) # shouldn't match self.assertFalse(BTV.can_handle_url("http://www.tvcatchup.com/"))
[bug] BTV plugin needs updating ## Bug Report - [x] This is a bug report and I have read the contribution guidelines. ### Description The location of the BTV livestream has moved to https://btvplus.bg/live/ **Edit**: Livestreaming no longer requires a user to login, so that can be removed from the plugin info page. ### Expected / Actual behavior Streamlink should be able to handle the link. ### Reproduction steps / Explicit stream URLs to test 1. streamlink https://btvplus.bg/live/ best 2. error: No plugin can handle URL: https://btvplus.bg/live/
0.0
5059d64be20b3cd6adc6374e921382ef2c261978
[ "tests/plugins/test_btv.py::TestPluginBTV::test_can_handle_url" ]
[]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2020-06-09 17:47:45+00:00
bsd-2-clause
5,786
streamlink__streamlink-3034
diff --git a/docs/plugin_matrix.rst b/docs/plugin_matrix.rst index 6b15eb5b..eea306bc 100644 --- a/docs/plugin_matrix.rst +++ b/docs/plugin_matrix.rst @@ -125,6 +125,7 @@ metube metube.id Yes Yes mitele mitele.es Yes No Streams may be geo-restricted to Spain. mixer mixer.com Yes Yes mjunoon mjunoon.tv Yes Yes +n13tv 13tv.co.il Yes Yes Streams may be geo-restricted to Israel. nbc nbc.com No Yes Streams are geo-restricted to USA. Authentication is not supported. nbcnews nbcnews.com Yes No nbcsports nbcsports.com No Yes Streams maybe be geo-restricted to USA. Authentication is not supported. diff --git a/src/streamlink/plugins/n13tv.py b/src/streamlink/plugins/n13tv.py new file mode 100644 index 00000000..0e2662ee --- /dev/null +++ b/src/streamlink/plugins/n13tv.py @@ -0,0 +1,147 @@ +import logging +import re + +from streamlink.compat import urljoin, urlunparse +from streamlink.exceptions import PluginError +from streamlink.plugin import Plugin +from streamlink.plugin.api import validate +from streamlink.stream import HLSStream + +log = logging.getLogger(__name__) + + +class N13TV(Plugin): + url_re = re.compile(r"https?://(?:www\.)?13tv\.co\.il/(live|.*?/)") + api_url = "https://13tv-api.oplayer.io/api/getlink/" + main_js_url_re = re.compile(r'type="text/javascript" src="(.*?main\..+\.js)"') + user_id_re = re.compile(r'"data-ccid":"(.*?)"') + video_name_re = re.compile(r'"videoRef":"(.*?)"') + server_addr_re = re.compile(r'(.*[^/])(/.*)') + media_file_re = re.compile(r'(.*)(\.[^\.].*)') + + live_schema = validate.Schema(validate.all( + [{'Link': validate.url()}], + validate.get(0), + validate.get('Link') + )) + + vod_schema = validate.Schema(validate.all([{ + 'ShowTitle': validate.text, + 'ProtocolType': validate.all( + validate.text, + validate.transform(lambda x: x.replace("://", "")) + ), + 'ServerAddress': validate.text, + 'MediaRoot': validate.text, + 'MediaFile': validate.text, + 'Bitrates': validate.text, + 'StreamingType': validate.text, + 'Token': validate.all( + validate.text, + validate.transform(lambda x: x.lstrip("?")) + ) + }], validate.get(0))) + + @classmethod + def can_handle_url(cls, url): + return cls.url_re.match(url) is not None + + def _get_live(self, user_id): + res = self.session.http.get( + self.api_url, + params=dict( + userId=user_id, + serverType="web", + ch=1, + cdnName="casttime" + ) + ) + + url = self.session.http.json(res, schema=self.live_schema) + log.debug("URL={0}".format(url)) + + return HLSStream.parse_variant_playlist(self.session, url) + + def _get_vod(self, user_id, video_name): + res = self.session.http.get( + urljoin(self.api_url, "getVideoByFileName"), + params=dict( + userId=user_id, + videoName=video_name, + serverType="web", + callback="x" + ) + ) + + vod_data = self.session.http.json(res, schema=self.vod_schema) + + if video_name == vod_data['ShowTitle']: + host, base_path = self.server_addr_re.search( + vod_data['ServerAddress'] + ).groups() + if not host or not base_path: + raise PluginError("Could not split 'ServerAddress' components") + + base_file, file_ext = self.media_file_re.search( + vod_data['MediaFile'] + ).groups() + if not base_file or not file_ext: + raise PluginError("Could not split 'MediaFile' components") + + media_path = "{0}{1}{2}{3}{4}{5}".format( + base_path, + vod_data['MediaRoot'], + base_file, + vod_data['Bitrates'], + file_ext, + vod_data['StreamingType'] + ) + log.debug("Media path={0}".format(media_path)) + + vod_url = urlunparse(( + vod_data['ProtocolType'], + host, + media_path, + '', + vod_data['Token'], + '' + )) + log.debug("URL={0}".format(vod_url)) + + return HLSStream.parse_variant_playlist(self.session, vod_url) + + def _get_streams(self): + m = self.url_re.match(self.url) + url_type = m and m.group(1) + log.debug("URL type={0}".format(url_type)) + + res = self.session.http.get(self.url) + + if url_type != "live": + m = self.video_name_re.search(res.text) + video_name = m and m.group(1) + if not video_name: + raise PluginError('Could not determine video_name') + log.debug("Video name={0}".format(video_name)) + + m = self.main_js_url_re.search(res.text) + main_js_path = m and m.group(1) + if not main_js_path: + raise PluginError('Could not determine main_js_path') + log.debug("Main JS path={0}".format(main_js_path)) + + res = self.session.http.get(urljoin(self.url, main_js_path)) + + m = self.user_id_re.search(res.text) + user_id = m and m.group(1) + if not user_id: + raise PluginError('Could not determine user_id') + log.debug("User ID={0}".format(user_id)) + + if url_type == "live": + return self._get_live(user_id) + else: + return self._get_vod(user_id, video_name) + + +__plugin__ = N13TV
streamlink/streamlink
bc3951ac444b351ea27ab66b18a28784530700d4
diff --git a/tests/plugins/test_n13tv.py b/tests/plugins/test_n13tv.py new file mode 100644 index 00000000..dc80f3f7 --- /dev/null +++ b/tests/plugins/test_n13tv.py @@ -0,0 +1,30 @@ +import unittest + +from streamlink.plugins.n13tv import N13TV + + +class TestPluginN13TV(unittest.TestCase): + def test_can_handle_url(self): + should_match = [ + "http://13tv.co.il/live", + "https://13tv.co.il/live", + "http://www.13tv.co.il/live/", + "https://www.13tv.co.il/live/", + "http://13tv.co.il/item/entertainment/ambush/season-02/episodes/ffuk3-2026112/", + "https://13tv.co.il/item/entertainment/ambush/season-02/episodes/ffuk3-2026112/", + "http://www.13tv.co.il/item/entertainment/ambush/season-02/episodes/ffuk3-2026112/", + "https://www.13tv.co.il/item/entertainment/ambush/season-02/episodes/ffuk3-2026112/" + "http://13tv.co.il/item/entertainment/tzhok-mehamatzav/season-01/episodes/vkdoc-2023442/", + "https://13tv.co.il/item/entertainment/tzhok-mehamatzav/season-01/episodes/vkdoc-2023442/", + "http://www.13tv.co.il/item/entertainment/tzhok-mehamatzav/season-01/episodes/vkdoc-2023442/" + "https://www.13tv.co.il/item/entertainment/tzhok-mehamatzav/season-01/episodes/vkdoc-2023442/" + ] + for url in should_match: + self.assertTrue(N13TV.can_handle_url(url)) + + def test_can_handle_url_negative(self): + should_not_match = [ + "https://www.youtube.com", + ] + for url in should_not_match: + self.assertFalse(N13TV.can_handle_url(url))
Plugin 'reshet' changed URL <!-- Thanks for reporting a plugin issue! USE THE TEMPLATE. Otherwise your plugin issue may be rejected. First, see the contribution guidelines: https://github.com/streamlink/streamlink/blob/master/CONTRIBUTING.md#contributing-to-streamlink Also check the list of open and closed plugin issues: https://github.com/streamlink/streamlink/issues?q=is%3Aissue+label%3A%22plugin+issue%22 Please see the text preview to avoid unnecessary formatting errors. --> ## Plugin Issue <!-- Replace [ ] with [x] in order to check the box --> - [x] This is a plugin issue and I have read the contribution guidelines. ### Description <!-- Explain the plugin issue as thoroughly as you can. --> Hi, "reshet.tv" has changed to "13tv.co.il", making the plugin unuseable. I suspect there are also changes to the API.
0.0
bc3951ac444b351ea27ab66b18a28784530700d4
[ "tests/plugins/test_n13tv.py::TestPluginN13TV::test_can_handle_url", "tests/plugins/test_n13tv.py::TestPluginN13TV::test_can_handle_url_negative" ]
[]
{ "failed_lite_validators": [ "has_added_files" ], "has_test_patch": true, "is_lite": false }
2020-06-18 03:28:37+00:00
bsd-2-clause
5,787
streamlink__streamlink-3142
diff --git a/src/streamlink/plugins/crunchyroll.py b/src/streamlink/plugins/crunchyroll.py index aebafe45..9f3bc698 100644 --- a/src/streamlink/plugins/crunchyroll.py +++ b/src/streamlink/plugins/crunchyroll.py @@ -10,7 +10,6 @@ from streamlink.stream import HLSStream log = logging.getLogger(__name__) - STREAM_WEIGHTS = { "low": 240, "mid": 420, @@ -72,7 +71,7 @@ _media_schema = validate.Schema( validate.get("stream_data") ) _login_schema = validate.Schema({ - "auth": validate.text, + "auth": validate.any(validate.text, None), "expires": validate.all( validate.text, validate.transform(parse_timestamp) @@ -214,9 +213,16 @@ class CrunchyrollAPI(object): return login def authenticate(self): - data = self._api_call("authenticate", {"auth": self.auth}, schema=_login_schema) - self.auth = data["auth"] - self.cache.set("auth", data["auth"], expires_at=data["expires"]) + try: + data = self._api_call("authenticate", {"auth": self.auth}, schema=_login_schema) + except CrunchyrollAPIError: + self.auth = None + self.cache.set("auth", None, expires_at=0) + log.warning("Saved credentials have expired") + return + + log.debug("Credentials expire at: {}".format(data["expires"])) + self.cache.set("auth", self.auth, expires_at=data["expires"]) return data def get_info(self, media_id, fields=None, schema=None): @@ -321,7 +327,7 @@ class Crunchyroll(Plugin): # The adaptive quality stream sometimes a subset of all the other streams listed, ultra is no included has_adaptive = any([s[u"quality"] == u"adaptive" for s in info[u"streams"]]) if has_adaptive: - self.logger.debug(u"Loading streams from adaptive playlist") + log.debug(u"Loading streams from adaptive playlist") for stream in filter(lambda x: x[u"quality"] == u"adaptive", info[u"streams"]): for q, s in HLSStream.parse_variant_playlist(self.session, stream[u"url"]).items(): # rename the bitrates to low, mid, or high. ultra doesn't seem to appear in the adaptive streams @@ -361,27 +367,28 @@ class Crunchyroll(Plugin): locale=locale) if not self.get_option("session_id"): - self.logger.debug("Creating session with locale: {0}", locale) + log.debug("Creating session with locale: {0}", locale) api.start_session() if api.auth: - self.logger.debug("Using saved credentials") + log.debug("Using saved credentials") login = api.authenticate() - self.logger.info("Successfully logged in as '{0}'", - login["user"]["username"] or login["user"]["email"]) - elif self.options.get("username"): + if login: + log.info("Successfully logged in as '{0}'", + login["user"]["username"] or login["user"]["email"]) + if not api.auth and self.options.get("username"): try: - self.logger.debug("Attempting to login using username and password") + log.debug("Attempting to login using username and password") api.login(self.options.get("username"), self.options.get("password")) login = api.authenticate() - self.logger.info("Logged in as '{0}'", - login["user"]["username"] or login["user"]["email"]) + log.info("Logged in as '{0}'", + login["user"]["username"] or login["user"]["email"]) except CrunchyrollAPIError as err: raise PluginError(u"Authentication error: {0}".format(err.msg)) - else: - self.logger.warning( + if not api.auth: + log.warning( "No authentication provided, you won't be able to access " "premium restricted content" ) diff --git a/src/streamlink/plugins/nicolive.py b/src/streamlink/plugins/nicolive.py index a03f4984..9393d1dc 100644 --- a/src/streamlink/plugins/nicolive.py +++ b/src/streamlink/plugins/nicolive.py @@ -200,7 +200,7 @@ class NicoLive(Plugin): "type": "startWatching", "data": { "stream": { - "quality": "high", + "quality": "abr", "protocol": "hls", "latency": "high", "chasePlay": False diff --git a/src/streamlink/plugins/sportschau.py b/src/streamlink/plugins/sportschau.py index 1b6d1599..e7309433 100644 --- a/src/streamlink/plugins/sportschau.py +++ b/src/streamlink/plugins/sportschau.py @@ -1,46 +1,52 @@ -import re -import json - -from streamlink.plugin import Plugin -from streamlink.stream import HDSStream -from streamlink.utils import update_scheme - -_url_re = re.compile(r"http(s)?://(\w+\.)?sportschau.de/") -_player_js = re.compile(r"https?://deviceids-medp.wdr.de/ondemand/.*\.js") - - -class sportschau(Plugin): - @classmethod - def can_handle_url(cls, url): - return _url_re.match(url) - - def _get_streams(self): - res = self.session.http.get(self.url) - match = _player_js.search(res.text) - if match: - player_js = match.group(0) - self.logger.info("Found player js {0}", player_js) - else: - self.logger.info("Didn't find player js. Probably this page doesn't contain a video") - return - - res = self.session.http.get(player_js) - - jsonp_start = res.text.find('(') + 1 - jsonp_end = res.text.rfind(')') - - if jsonp_start <= 0 or jsonp_end <= 0: - self.logger.info("Couldn't extract json metadata from player.js: {0}", player_js) - return - - json_s = res.text[jsonp_start:jsonp_end] - - stream_metadata = json.loads(json_s) - - hds_url = stream_metadata['mediaResource']['dflt']['videoURL'] - hds_url = update_scheme(self.url, hds_url) - - return HDSStream.parse_manifest(self.session, hds_url).items() - - -__plugin__ = sportschau +import logging +import re + +from streamlink.plugin import Plugin +from streamlink.plugin.api import validate +from streamlink.stream import HLSStream +from streamlink.utils import parse_json, update_scheme + +log = logging.getLogger(__name__) + + +class Sportschau(Plugin): + _re_url = re.compile(r"https?://(?:\w+\.)*sportschau.de/") + + _re_player = re.compile(r"https?:(//deviceids-medp.wdr.de/ondemand/\S+\.js)") + _re_json = re.compile(r"\$mediaObject.jsonpHelper.storeAndPlay\(({.+})\);?") + + _schema_player = validate.Schema( + validate.transform(_re_player.search), + validate.any(None, validate.Schema( + validate.get(1), + validate.transform(lambda url: update_scheme("https:", url)) + )) + ) + _schema_json = validate.Schema( + validate.transform(_re_json.match), + validate.get(1), + validate.transform(parse_json), + validate.get("mediaResource"), + validate.get("dflt"), + validate.get("videoURL"), + validate.transform(lambda url: update_scheme("https:", url)) + ) + + @classmethod + def can_handle_url(cls, url): + return cls._re_url.match(url) is not None + + def _get_streams(self): + player_js = self.session.http.get(self.url, schema=self._schema_player) + if not player_js: + return + + log.debug("Found player js {0}".format(player_js)) + + hls_url = self.session.http.get(player_js, schema=self._schema_json) + + for stream in HLSStream.parse_variant_playlist(self.session, hls_url).items(): + yield stream + + +__plugin__ = Sportschau
streamlink/streamlink
d24467f8dd1195ba04bd15569750bf74a21437e6
diff --git a/tests/plugins/test_sportschau.py b/tests/plugins/test_sportschau.py index e0ecbe39..37b008d1 100644 --- a/tests/plugins/test_sportschau.py +++ b/tests/plugins/test_sportschau.py @@ -1,20 +1,20 @@ import unittest -from streamlink.plugins.sportschau import sportschau +from streamlink.plugins.sportschau import Sportschau class TestPluginSportschau(unittest.TestCase): def test_can_handle_url(self): should_match = [ 'http://www.sportschau.de/wintersport/videostream-livestream---wintersport-im-ersten-242.html', - 'http://www.sportschau.de/weitere/allgemein/video-kite-surf-world-tour-100.html', + 'https://www.sportschau.de/weitere/allgemein/video-kite-surf-world-tour-100.html', ] for url in should_match: - self.assertTrue(sportschau.can_handle_url(url)) + self.assertTrue(Sportschau.can_handle_url(url)) def test_can_handle_url_negative(self): should_not_match = [ 'https://example.com/index.html', ] for url in should_not_match: - self.assertFalse(sportschau.can_handle_url(url)) + self.assertFalse(Sportschau.can_handle_url(url))
sportschau plugin fails with "Unable to parse manifest XML" error ## Plugin Issue - [x ] This is a plugin issue and I have read the contribution guidelines. ### Description streamlink errors out when trying to watch a stream on sportschau.de, e.g. https://www.sportschau.de/tourdefrance/live/videostream-livestream---die--etappe-der-tour-de-france-nach-privas-100.html. It errors out with: "error: Unable to parse manifest XML: syntax error: line 1, column 0 (b'#EXTM3U\n#EXT-X-VERSION:3\n#EXT-X ...)" ### Reproduction steps / Explicit stream URLs to test 1. streamlink "https://www.sportschau.de/tourdefrance/live/videostream-livestream---die--etappe-der-tour-de-france-nach-privas-100.html" ### Log output ``` [14:25:23,464][cli][debug] OS: Linux-5.8.4-x86_64-with-glibc2.2.5 [14:25:23,464][cli][debug] Python: 3.8.5 [14:25:23,464][cli][debug] Streamlink: 1.5.0 [14:25:23,464][cli][debug] Requests(2.24.0), Socks(1.7.1), Websocket(0.57.0) [14:25:23,465][cli][info] Found matching plugin sportschau for URL https://www.sportschau.de/tourdefrance/live/videostream-livestream---die--etappe-der-tour-de-france-nach-privas-100.html [14:25:23,734][plugin.sportschau][info] Found player js http://deviceids-medp.wdr.de/ondemand/221/2214170.js error: Unable to parse manifest XML: syntax error: line 1, column 0 (b'#EXTM3U\n#EXT-X-VERSION:3\n#EXT-X ...) ``` ### Additional comments, screenshots, etc. Not sure that I understand the cause of the error, especially as the problematic part seems truncated. This is what the .m3u file looks like: ``` #EXTM3U #EXT-X-VERSION:3 #EXT-X-INDEPENDENT-SEGMENTS #EXT-X-STREAM-INF:BANDWIDTH=5388416,AVERAGE-BANDWIDTH=4048000,CODECS="avc1.640020,mp4a.40.2",RESOLUTION=1280x720,FRAME-RATE=50.000 https://ardevent2.akamaized.net/hls/live/681512/ardevent2_geo/master_3680.m3u8 #EXT-X-STREAM-INF:BANDWIDTH=5388416,AVERAGE-BANDWIDTH=4048000,CODECS="avc1.640020,mp4a.40.2",RESOLUTION=1280x720,FRAME-RATE=50.000 https://ardevent2.akamaized.net/hls/live/681512-b/ardevent2_geo/master_3680.m3u8 #EXT-X-STREAM-INF:BANDWIDTH=2758800,AVERAGE-BANDWIDTH=2085600,CODECS="avc1.4d401f,mp4a.40.2",RESOLUTION=960x540,FRAME-RATE=50.000 https://ardevent2.akamaized.net/hls/live/681512/ardevent2_geo/master_1896.m3u8 #EXT-X-STREAM-INF:BANDWIDTH=2758800,AVERAGE-BANDWIDTH=2085600,CODECS="avc1.4d401f,mp4a.40.2",RESOLUTION=960x540,FRAME-RATE=50.000 https://ardevent2.akamaized.net/hls/live/681512-b/ardevent2_geo/master_1896.m3u8 #EXT-X-STREAM-INF:BANDWIDTH=1614976,AVERAGE-BANDWIDTH=1232000,CODECS="avc1.4d401f,mp4a.40.2",RESOLUTION=640x360,FRAME-RATE=50.000 https://ardevent2.akamaized.net/hls/live/681512/ardevent2_geo/master_1120.m3u8 #EXT-X-STREAM-INF:BANDWIDTH=1614976,AVERAGE-BANDWIDTH=1232000,CODECS="avc1.4d401f,mp4a.40.2",RESOLUTION=640x360,FRAME-RATE=50.000 https://ardevent2.akamaized.net/hls/live/681512-b/ardevent2_geo/master_1120.m3u8 #EXT-X-STREAM-INF:BANDWIDTH=860288,AVERAGE-BANDWIDTH=668800,CODECS="avc1.77.30,mp4a.40.2",RESOLUTION=512x288,FRAME-RATE=50.000 https://ardevent2.akamaized.net/hls/live/681512/ardevent2_geo/master_608.m3u8 #EXT-X-STREAM-INF:BANDWIDTH=860288,AVERAGE-BANDWIDTH=668800,CODECS="avc1.77.30,mp4a.40.2",RESOLUTION=512x288,FRAME-RATE=50.000 https://ardevent2.akamaized.net/hls/live/681512-b/ardevent2_geo/master_608.m3u8 #EXT-X-STREAM-INF:BANDWIDTH=482944,AVERAGE-BANDWIDTH=387200,CODECS="avc1.66.30,mp4a.40.2",RESOLUTION=480x270,FRAME-RATE=50.000 https://ardevent2.akamaized.net/hls/live/681512/ardevent2_geo/master_352.m3u8 #EXT-X-STREAM-INF:BANDWIDTH=482944,AVERAGE-BANDWIDTH=387200,CODECS="avc1.66.30,mp4a.40.2",RESOLUTION=480x270,FRAME-RATE=50.000 https://ardevent2.akamaized.net/hls/live/681512-b/ardevent2_geo/master_352.m3u8 #EXT-X-STREAM-INF:BANDWIDTH=294272,AVERAGE-BANDWIDTH=246400,CODECS="avc1.42c015,mp4a.40.2",RESOLUTION=320x180,FRAME-RATE=50.000 https://ardevent2.akamaized.net/hls/live/681512/ardevent2_geo/master_224.m3u8 #EXT-X-STREAM-INF:BANDWIDTH=294272,AVERAGE-BANDWIDTH=246400,CODECS="avc1.42c015,mp4a.40.2",RESOLUTION=320x180,FRAME-RATE=50.000 https://ardevent2.akamaized.net/hls/live/681512-b/ardevent2_geo/master_224.m3u8 ```
0.0
d24467f8dd1195ba04bd15569750bf74a21437e6
[ "tests/plugins/test_sportschau.py::TestPluginSportschau::test_can_handle_url", "tests/plugins/test_sportschau.py::TestPluginSportschau::test_can_handle_url_negative" ]
[]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2020-09-02 13:44:51+00:00
bsd-2-clause
5,788
streamlink__streamlink-3202
diff --git a/.codecov.yml b/.codecov.yml new file mode 100644 index 00000000..1df71070 --- /dev/null +++ b/.codecov.yml @@ -0,0 +1,44 @@ +codecov: + notify: + require_ci_to_pass: true + # wait until at all test runners have uploaded a report (see the test job's build matrix) + # otherwise, coverage failures may be shown while some reports are still missing + after_n_builds: 10 +comment: + # this also configures the layout of PR check summaries / comments + layout: "reach, diff, flags, files" + # don't ever let the codecov bot comment on PRs + after_n_builds: 999999999 +coverage: + range: "50...100" + precision: 2 + round: down + status: + changes: false + patch: false + # split up coverage reports by path + # don't set coverage targets and instead set coverage thresholds + project: + # we can't disable the overall default project, because only this will have PR check summaries / comments + # this replaces the PR comment + default: + target: 50 + streamlink: + threshold: 1 + paths: + - "src/streamlink/" + - "!src/streamlink/plugins/" + streamlink_cli: + threshold: 1 + paths: + - "src/streamlink_cli/" + plugins: + # don't set a threshold on plugins + target: 30 + paths: + - "src/streamlink/plugins/" + tests: + # new tests should always be fully covered + threshold: 0 + paths: + - "tests/" diff --git a/.coveragerc b/.coveragerc index 742386c4..f99370cf 100644 --- a/.coveragerc +++ b/.coveragerc @@ -1,6 +1,7 @@ [run] source = src + tests [report] omit = diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 3200d07a..a74d6186 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -17,7 +17,8 @@ jobs: name: Test strategy: fail-fast: false - # when changing the build matrix, the `after_n_builds` value in codecov.yml may need to be updated + # please remember to change the `codecov.notify.after_n_builds` value in .codecov.yml + # when changing the build matrix and changing the number of test runners matrix: os: [ubuntu-latest, windows-latest] python: [2.7, 3.5, 3.6, 3.7, 3.8] @@ -36,7 +37,7 @@ jobs: run: bash ./script/install-dependencies.sh - name: Test continue-on-error: ${{ matrix.continue || false }} - run: pytest -r a --cov --cov-report=xml + run: pytest -r a --cov --cov-branch --cov-report=xml - name: Lint continue-on-error: ${{ matrix.continue || false }} run: flake8 diff --git a/codecov.yml b/codecov.yml deleted file mode 100644 index 3d94e1bb..00000000 --- a/codecov.yml +++ /dev/null @@ -1,21 +0,0 @@ -codecov: - notify: - require_ci_to_pass: true - # wait until at least one linux and one windows build has succeeded (see the test job's build matrix) - after_n_builds: 6 -comment: - behavior: default - layout: header, diff - require_changes: false -coverage: - precision: 2 - range: - - 50.0 - - 100.0 - round: down - status: - changes: false - patch: false - project: - default: - target: 30 diff --git a/docs/plugin_matrix.rst b/docs/plugin_matrix.rst index 48371bf2..08eb88bc 100644 --- a/docs/plugin_matrix.rst +++ b/docs/plugin_matrix.rst @@ -118,6 +118,7 @@ lrt lrt.lt Yes No ltv_lsm_lv ltv.lsm.lv Yes No Streams may be geo-restricted to Latvia. mediaklikk mediaklikk.hu Yes No Streams may be geo-restricted to Hungary. metube metube.id Yes Yes +mico micous.com Yes -- mitele mitele.es Yes No Streams may be geo-restricted to Spain. mjunoon mjunoon.tv Yes Yes mrtmk play.mrt.com.mk Yes Yes Streams may be geo-restricted to North Macedonia. diff --git a/src/streamlink/plugins/mico.py b/src/streamlink/plugins/mico.py new file mode 100644 index 00000000..2f2b40bb --- /dev/null +++ b/src/streamlink/plugins/mico.py @@ -0,0 +1,72 @@ +import logging +import re + +from streamlink.plugin import Plugin +from streamlink.plugin.api import validate +from streamlink.stream import HLSStream +from streamlink.utils import parse_json +from streamlink.utils.url import update_scheme + +log = logging.getLogger(__name__) + + +class Mico(Plugin): + author = None + category = None + title = None + + url_re = re.compile(r'https?://(?:www\.)?micous\.com/live/\d+') + json_data_re = re.compile(r'win._profile\s*=\s*({.*})') + + _json_data_schema = validate.Schema( + validate.transform(json_data_re.search), + validate.any(None, validate.all( + validate.get(1), + validate.transform(parse_json), + validate.any(None, validate.all({ + 'mico_id': int, + 'nickname': validate.text, + 'h5_url': validate.all( + validate.transform(lambda x: update_scheme('http:', x)), + validate.url(), + ), + 'is_live': bool, + })), + )), + ) + + @classmethod + def can_handle_url(cls, url): + return cls.url_re.match(url) is not None + + def get_author(self): + if self.author is not None: + return self.author + + def get_category(self): + if self.category is not None: + return self.category + + def get_title(self): + if self.title is not None: + return self.title + + def _get_streams(self): + json_data = self.session.http.get(self.url, schema=self._json_data_schema) + + if not json_data: + log.error('Failed to get JSON data') + return + + if not json_data['is_live']: + log.info('This stream is no longer online') + return + + self.author = json_data['mico_id'] + self.category = 'Live' + self.title = json_data['nickname'] + + return HLSStream.parse_variant_playlist(self.session, json_data['h5_url']) + + +__plugin__ = Mico diff --git a/src/streamlink/plugins/zattoo.py b/src/streamlink/plugins/zattoo.py index b845c305..ce79fe98 100644 --- a/src/streamlink/plugins/zattoo.py +++ b/src/streamlink/plugins/zattoo.py @@ -19,6 +19,7 @@ log = logging.getLogger(__name__) class Zattoo(Plugin): API_CHANNELS = '{0}/zapi/v2/cached/channels/{1}?details=False' API_HELLO = '{0}/zapi/session/hello' + API_HELLO_V2 = '{0}/zapi/v2/session/hello' API_HELLO_V3 = '{0}/zapi/v3/session/hello' API_LOGIN = '{0}/zapi/v2/account/login' API_LOGIN_V3 = '{0}/zapi/v3/account/login' @@ -158,18 +159,21 @@ class Zattoo(Plugin): # a new session is required for the app_token self.session.http.cookies = cookiejar_from_dict({}) if self.base_url == 'https://zattoo.com': - app_token_url = 'https://zattoo.com/int/' + app_token_url = 'https://zattoo.com/client/token-2fb69f883fea03d06c68c6e5f21ddaea.json' elif self.base_url == 'https://www.quantum-tv.com': app_token_url = 'https://www.quantum-tv.com/token-4d0d61d4ce0bf8d9982171f349d19f34.json' else: app_token_url = self.base_url - res = self.session.http.get(app_token_url) - match = self._app_token_re.search(res.text) + res = self.session.http.get(app_token_url) if self.base_url == 'https://www.quantum-tv.com': app_token = self.session.http.json(res)["session_token"] hello_url = self.API_HELLO_V3.format(self.base_url) + elif self.base_url == 'https://zattoo.com': + app_token = self.session.http.json(res)['app_tid'] + hello_url = self.API_HELLO_V2.format(self.base_url) else: + match = self._app_token_re.search(res.text) app_token = match.group(1) hello_url = self.API_HELLO.format(self.base_url) @@ -180,10 +184,17 @@ class Zattoo(Plugin): self._session_attributes.set( 'uuid', __uuid, expires=self.TIME_SESSION) - params = { - 'client_app_token': app_token, - 'uuid': __uuid, - } + if self.base_url == 'https://zattoo.com': + params = { + 'uuid': __uuid, + 'app_tid': app_token, + 'app_version': '1.0.0' + } + else: + params = { + 'client_app_token': app_token, + 'uuid': __uuid, + } if self.base_url == 'https://www.quantum-tv.com': params['app_version'] = '3.2028.3'
streamlink/streamlink
4fa902fc93470af30616e29e0fd49692a05ae84c
diff --git a/tests/plugins/test_mico.py b/tests/plugins/test_mico.py new file mode 100644 index 00000000..cab44d96 --- /dev/null +++ b/tests/plugins/test_mico.py @@ -0,0 +1,23 @@ +import unittest + +from streamlink.plugins.mico import Mico + + +class TestPluginMico(unittest.TestCase): + def test_can_handle_url(self): + should_match = [ + 'http://micous.com/live/73750760', + 'http://www.micous.com/live/73750760', + 'https://micous.com/live/73750760', + 'https://www.micous.com/live/73750760', + ] + for url in should_match: + self.assertTrue(Mico.can_handle_url(url)) + + def test_can_handle_url_negative(self): + should_not_match = [ + 'http://www.micous.com/73750760', + 'https://example.com/index.html', + ] + for url in should_not_match: + self.assertFalse(Mico.can_handle_url(url))
Zattoo (403 Client Error) <!-- Thanks for reporting a plugin issue! USE THE TEMPLATE. Otherwise your plugin issue may be rejected. First, see the contribution guidelines: https://github.com/streamlink/streamlink/blob/master/CONTRIBUTING.md#contributing-to-streamlink Also check the list of open and closed plugin issues: https://github.com/streamlink/streamlink/issues?q=is%3Aissue+label%3A%22plugin+issue%22 Please see the text preview to avoid unnecessary formatting errors. --> ## Plugin Issue <!-- Replace [ ] with [x] in order to check the box --> - [x] This is a plugin issue and I have read the contribution guidelines. ### Description <!-- Explain the plugin issue as thoroughly as you can. --> ### Reproduction steps / Explicit stream URLs to test <!-- How can we reproduce this? Please note the exact steps below using the list format supplied. If you need more steps please add them. --> 1. streamlink -o "RTS Un SD.ts" https://zattoo.com/watch/rts_un 1500k --zattoo-email [email protected] --zattoo-password xxx ### Log output <!-- TEXT LOG OUTPUT IS REQUIRED for a plugin issue! Use the `--loglevel debug` parameter and avoid using parameters which suppress log output. https://streamlink.github.io/cli.html#cmdoption-l Make sure to **remove usernames and passwords** You can copy the output to https://gist.github.com/ or paste it below. --> ``` [plugin.zattoo][debug] Restored cookies: zattoo.session, pzuid, beaker.session.id [cli][debug] OS: Linux-4.19.0-0.bpo.6-amd64-x86_64-with-debian-9.13 [cli][debug] Python: 3.5.3 [cli][debug] Streamlink: 1.5.0 [cli][debug] Requests(2.24.0), Socks(1.7.1), Websocket(0.57.0) [cli][info] Found matching plugin zattoo for URL https://zattoo.com/watch/rts_un [cli][debug] Plugin specific arguments: [cli][debug] --zattoo-email=********@********.******** (email) [cli][debug] --zattoo-password=******** (password) [cli][debug] --zattoo-stream-types=['hls'] (stream_types) [plugin.zattoo][debug] Session control for zattoo.com [plugin.zattoo][debug] User is not logged in [plugin.zattoo][debug] _hello ... error: Unable to open URL: https://zattoo.com/zapi/session/hello (403 Client Error: Forbidden for url: https://zatt oo.com/zapi/session/hello) [1] 15604 exit 1 streamlink -o "RTS Un SD.ts" https://zattoo.com/watch/rts_un 1500 ``` ### Additional comments, screenshots, etc. [Love Streamlink? Please consider supporting our collective. Thanks!](https://opencollective.com/streamlink/donate)
0.0
4fa902fc93470af30616e29e0fd49692a05ae84c
[ "tests/plugins/test_mico.py::TestPluginMico::test_can_handle_url", "tests/plugins/test_mico.py::TestPluginMico::test_can_handle_url_negative" ]
[]
{ "failed_lite_validators": [ "has_hyperlinks", "has_added_files", "has_removed_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2020-09-24 09:28:22+00:00
bsd-2-clause
5,789
streamlink__streamlink-3422
diff --git a/src/streamlink/cache.py b/src/streamlink/cache.py index a86aa0ce..9e55e4b1 100644 --- a/src/streamlink/cache.py +++ b/src/streamlink/cache.py @@ -38,7 +38,7 @@ class Cache: pruned = [] for key, value in self._cache.items(): - expires = value.get("expires", time()) + expires = value.get("expires", now) if expires <= now: pruned.append(key) @@ -69,10 +69,13 @@ class Cache: if self.key_prefix: key = "{0}:{1}".format(self.key_prefix, key) - expires += time() - - if expires_at: - expires = mktime(expires_at.timetuple()) + if expires_at is None: + expires += time() + else: + try: + expires = mktime(expires_at.timetuple()) + except OverflowError: + expires = 0 self._cache[key] = dict(value=value, expires=expires) self._save()
streamlink/streamlink
030dbc5f744c05aac4733b2c37bfd771df9b4c00
diff --git a/tests/test_cache.py b/tests/test_cache.py index 712d2c4f..895aabdd 100644 --- a/tests/test_cache.py +++ b/tests/test_cache.py @@ -55,6 +55,11 @@ class TestCache(unittest.TestCase): self.cache.set("value", 10, expires_at=datetime.datetime.now() + datetime.timedelta(seconds=20)) self.assertEqual(10, self.cache.get("value")) + @patch("streamlink.cache.mktime", side_effect=OverflowError) + def test_expired_at_raise_overflowerror(self, mock): + self.cache.set("value", 10, expires_at=datetime.datetime.now()) + self.assertEqual(None, self.cache.get("value")) + def test_not_expired(self): self.cache.set("value", 10, expires=20) self.assertEqual(10, self.cache.get("value"))
mktime argument out of range when logging in to Crunchyroll after --crunchyroll-purge-credentials <!-- Thanks for reporting a plugin issue! USE THE TEMPLATE. Otherwise your plugin issue may be rejected. First, see the contribution guidelines: https://github.com/streamlink/streamlink/blob/master/CONTRIBUTING.md#contributing-to-streamlink Also check the list of open and closed plugin issues: https://github.com/streamlink/streamlink/issues?q=is%3Aissue+label%3A%22plugin+issue%22 Please see the text preview to avoid unnecessary formatting errors. --> ## Plugin Issue <!-- Replace the space character between the square brackets with an x in order to check the boxes --> - [x] This is a plugin issue and I have read the contribution guidelines. - [x] I am using the latest development version from the master branch. ### Description Whenver I try to log in to Crunchyroll via streamlink I get an error. <!-- Explain the plugin issue as thoroughly as you can. --> ### Reproduction steps / Explicit stream URLs to test <!-- How can we reproduce this? Please note the exact steps below using the list format supplied. If you need more steps please add them. --> 1. I enter the command streamlink --crunchyroll-username=xxxx --crunchyroll-password=yyy --crunchyroll-purge-credentials https://www.crunchyroll.com/my/episode/to/watch best and I get it every time ### Log output <!-- TEXT LOG OUTPUT IS REQUIRED for a plugin issue! Use the `--loglevel debug` parameter and avoid using parameters which suppress log output. https://streamlink.github.io/cli.html#cmdoption-l Make sure to **remove usernames and passwords** You can copy the output to https://gist.github.com/ or paste it below. Don't post screenshots of the log output and instead copy the text from your terminal application. --> ``` [cli][debug] OS: Windows 10 [cli][debug] Python: 3.6.6 [cli][debug] Streamlink: 1.7.0 [cli][debug] Requests(2.24.0), Socks(1.7.1), Websocket(0.57.0) [cli][info] Found matching plugin crunchyroll for URL https://www.crunchyroll.com/jujutsu-kaisen/episode-10-idle-transfiguration-797874 [cli][debug] Plugin specific arguments: [cli][debug] [email protected] (username) [cli][debug] --crunchyroll-password=******** (password) [cli][debug] --crunchyroll-purge-credentials=True (purge_credentials) [utils.l10n][debug] Language code: en_US [plugin.crunchyroll][debug] Creating session with locale: en_US [plugin.crunchyroll][debug] Session created with ID: 576c3d5d7a83d1dd18217343a6df37ff [plugin.crunchyroll][debug] Attempting to login using username and password [plugin.crunchyroll][debug] Credentials expire at: 1969-12-31 08:00:00 Traceback (most recent call last): File "runpy.py", line 193, in _run_module_as_main File "runpy.py", line 85, in _run_code File "C:\Program Files (x86)\Streamlink\bin\streamlink.exe\__main__.py", line 18, in <module> File "C:\Program Files (x86)\Streamlink\pkgs\streamlink_cli\main.py", line 1029, in main handle_url() File "C:\Program Files (x86)\Streamlink\pkgs\streamlink_cli\main.py", line 585, in handle_url streams = fetch_streams(plugin) File "C:\Program Files (x86)\Streamlink\pkgs\streamlink_cli\main.py", line 465, in fetch_streams sorting_excludes=args.stream_sorting_excludes) File "C:\Program Files (x86)\Streamlink\pkgs\streamlink\plugin\plugin.py", line 317, in streams ostreams = self._get_streams() File "C:\Program Files (x86)\Streamlink\pkgs\streamlink\plugins\crunchyroll.py", line 312, in _get_streams api = self._create_api() File "C:\Program Files (x86)\Streamlink\pkgs\streamlink\plugins\crunchyroll.py", line 384, in _create_api login = api.authenticate() File "C:\Program Files (x86)\Streamlink\pkgs\streamlink\plugins\crunchyroll.py", line 225, in authenticate self.cache.set("auth", self.auth, expires_at=data["expires"]) File "C:\Program Files (x86)\Streamlink\pkgs\streamlink\cache.py", line 75, in set expires = mktime(expires_at.timetuple()) OverflowError: mktime argument out of range ``` ### Additional comments, etc. [Love Streamlink? Please consider supporting our collective. Thanks!](https://opencollective.com/streamlink/donate)
0.0
030dbc5f744c05aac4733b2c37bfd771df9b4c00
[ "tests/test_cache.py::TestCache::test_expired_at_raise_overflowerror" ]
[ "tests/test_cache.py::TestCache::test_create_directory", "tests/test_cache.py::TestCache::test_create_directory_fail", "tests/test_cache.py::TestCache::test_expired", "tests/test_cache.py::TestCache::test_expired_at_after", "tests/test_cache.py::TestCache::test_expired_at_before", "tests/test_cache.py::TestCache::test_get_all", "tests/test_cache.py::TestCache::test_get_all_prefix", "tests/test_cache.py::TestCache::test_get_all_prune", "tests/test_cache.py::TestCache::test_get_no_file", "tests/test_cache.py::TestCache::test_key_prefix", "tests/test_cache.py::TestCache::test_load_fail", "tests/test_cache.py::TestCache::test_not_expired", "tests/test_cache.py::TestCache::test_put_get", "tests/test_cache.py::TestCache::test_put_get_prefix" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2020-12-18 16:08:02+00:00
bsd-2-clause
5,790
streamlink__streamlink-3762
diff --git a/docs/plugin_matrix.rst b/docs/plugin_matrix.rst index b2fb70c8..11841b25 100644 --- a/docs/plugin_matrix.rst +++ b/docs/plugin_matrix.rst @@ -122,7 +122,8 @@ nrk - tv.nrk.no Yes Yes Streams may be geo-rest - radio.nrk.no ntv ntv.ru Yes No okru ok.ru Yes Yes -olympicchannel olympicchannel.com Yes Yes Only non-premium content is available. +olympicchannel - olympicchannel.com Yes Yes Only non-premium content is available. + - olympics.com oneplusone 1plus1.video Yes No onetv 1tv.ru Yes No Streams may be geo-restricted to Russia. openrectv openrec.tv Yes Yes diff --git a/src/streamlink/plugins/olympicchannel.py b/src/streamlink/plugins/olympicchannel.py index 7ea41a80..d91924ff 100644 --- a/src/streamlink/plugins/olympicchannel.py +++ b/src/streamlink/plugins/olympicchannel.py @@ -1,58 +1,67 @@ -import json import logging import re +from html import unescape as html_unescape from time import time from urllib.parse import urljoin, urlparse from streamlink.plugin import Plugin from streamlink.plugin.api import validate from streamlink.stream import HLSStream +from streamlink.utils import parse_json log = logging.getLogger(__name__) class OlympicChannel(Plugin): - _url_re = re.compile(r"https?://(\w+\.)olympicchannel.com/../(?P<type>live|video|original-series|films)/?(?:\w?|[-\w]+)") - _tokenizationApiDomainUrl = """"tokenizationApiDomainUrl" content="/OcsTokenization/api/v1/tokenizedUrl">""" - _live_api_path = "/OcsTokenization/api/v1/tokenizedUrl?url={url}&domain={netloc}&_ts={time}" - + _url_re = re.compile(r"https?://(\w+\.)?(?:olympics|olympicchannel)\.com/(?:[\w-]+/)?../.+") + _token_api_path = "/tokenGenerator?url={url}&domain={netloc}&_ts={time}" _api_schema = validate.Schema( - validate.text, - validate.transform(lambda v: json.loads(v)), - validate.url() + validate.transform(parse_json), + [{ + validate.optional("src"): validate.url(), + validate.optional("srcType"): "HLS", + }], + validate.transform(lambda v: v[0].get("src")), + ) + _data_url_re = re.compile(r'data-content-url="([^"]+)"') + _data_content_re = re.compile(r'data-d3vp-plugin="THEOplayer"\s*data-content="([^"]+)"') + _data_content_schema = validate.Schema( + validate.any( + validate.all( + validate.transform(_data_url_re.search), + validate.any(None, validate.get(1)), + ), + validate.all( + validate.transform(_data_content_re.search), + validate.any(None, validate.get(1)), + ), + ), + validate.any(None, validate.transform(html_unescape)), ) - _video_url_re = re.compile(r""""video_url"\scontent\s*=\s*"(?P<value>[^"]+)""") - _video_url_schema = validate.Schema( - validate.contains(_tokenizationApiDomainUrl), - validate.transform(_video_url_re.search), - validate.any(None, validate.get("value")), - validate.url() + _stream_schema = validate.Schema( + validate.transform(parse_json), + validate.url(), ) @classmethod def can_handle_url(cls, url): return cls._url_re.match(url) - def _get_vod_streams(self): - stream_url = self.session.http.get(self.url, schema=self._video_url_schema) - return HLSStream.parse_variant_playlist(self.session, stream_url) + def _get_streams(self): + api_url = self.session.http.get(self.url, schema=self._data_content_schema) + if api_url and (api_url.startswith("/") or api_url.startswith("http")): + api_url = urljoin(self.url, api_url) + stream_url = self.session.http.get(api_url, schema=self._api_schema, headers={"Referer": self.url}) + elif api_url and api_url.startswith("[{"): + stream_url = self._api_schema.validate(api_url) + else: + return - def _get_live_streams(self): - video_url = self.session.http.get(self.url, schema=self._video_url_schema) - parsed = urlparse(video_url) - api_url = urljoin(self.url, self._live_api_path.format(url=video_url, + parsed = urlparse(stream_url) + api_url = urljoin(self.url, self._token_api_path.format(url=stream_url, netloc="{0}://{1}".format(parsed.scheme, parsed.netloc), time=int(time()))) - stream_url = self.session.http.get(api_url, schema=self._api_schema) + stream_url = self.session.http.get(api_url, schema=self._stream_schema, headers={"Referer": self.url}) return HLSStream.parse_variant_playlist(self.session, stream_url) - def _get_streams(self): - match = self._url_re.match(self.url) - type_of_stream = match.group('type') - - if type_of_stream == 'live': - return self._get_live_streams() - elif type_of_stream in ('video', 'original-series', 'films'): - return self._get_vod_streams() - __plugin__ = OlympicChannel diff --git a/src/streamlink/plugins/twitch.py b/src/streamlink/plugins/twitch.py index 4b067620..4ef7f1d1 100644 --- a/src/streamlink/plugins/twitch.py +++ b/src/streamlink/plugins/twitch.py @@ -15,6 +15,7 @@ from streamlink.stream import HLSStream, HTTPStream from streamlink.stream.hls import HLSStreamReader, HLSStreamWorker, HLSStreamWriter from streamlink.stream.hls_playlist import M3U8, M3U8Parser, load as load_hls_playlist from streamlink.utils.times import hours_minutes_seconds +from streamlink.utils.url import update_qsd log = logging.getLogger(__name__) @@ -346,47 +347,89 @@ class TwitchAPI: )) def clips(self, clipname): - query = """{{ - clip(slug: "{clipname}") {{ - broadcaster {{ - displayName - }} - title - game {{ - name - }} - videoQualities {{ - quality - sourceURL - }} - }} - }}""".format(clipname=clipname) - - return self.call_gql({"query": query}, schema=validate.Schema( - {"data": { - "clip": validate.any(None, validate.all({ - "broadcaster": validate.all({"displayName": validate.text}, validate.get("displayName")), - "title": validate.text, - "game": validate.all({"name": validate.text}, validate.get("name")), - "videoQualities": [validate.all({ - "quality": validate.all( - validate.text, - validate.transform(lambda q: "{0}p".format(q)) - ), - "sourceURL": validate.url() - }, validate.union(( - validate.get("quality"), - validate.get("sourceURL") - )))] - }, validate.union(( - validate.get("broadcaster"), - validate.get("title"), - validate.get("game"), - validate.get("videoQualities") - )))) - }}, - validate.get("data"), - validate.get("clip") + queries = [ + { + "operationName": "VideoAccessToken_Clip", + "extensions": { + "persistedQuery": { + "version": 1, + "sha256Hash": "36b89d2507fce29e5ca551df756d27c1cfe079e2609642b4390aa4c35796eb11" + } + }, + "variables": {"slug": clipname} + }, + { + "operationName": "ClipsView", + "extensions": { + "persistedQuery": { + "version": 1, + "sha256Hash": "4480c1dcc2494a17bb6ef64b94a5213a956afb8a45fe314c66b0d04079a93a8f" + } + }, + "variables": {"slug": clipname} + }, + { + "operationName": "ClipsTitle", + "extensions": { + "persistedQuery": { + "version": 1, + "sha256Hash": "f6cca7f2fdfbfc2cecea0c88452500dae569191e58a265f97711f8f2a838f5b4" + } + }, + "variables": {"slug": clipname} + } + ] + + return self.call_gql(queries, schema=validate.Schema( + [ + validate.all( + {"data": { + "clip": validate.all({ + "playbackAccessToken": validate.all({ + "__typename": "PlaybackAccessToken", + "signature": str, + "value": str + }, validate.union(( + validate.get("signature"), + validate.get("value") + ))), + "videoQualities": [validate.all({ + "frameRate": validate.any(int, float), + "quality": str, + "sourceURL": validate.url() + }, validate.union(( + validate.transform(lambda q: f"{q['quality']}p{int(q['frameRate'])}"), + validate.get("sourceURL") + )))] + }, validate.union(( + validate.get("playbackAccessToken"), + validate.get("videoQualities") + ))) + }}, + validate.get("data"), + validate.get("clip") + ), + validate.all( + {"data": { + "clip": validate.all({ + "broadcaster": validate.all({"displayName": str}, validate.get("displayName")), + "game": validate.all({"name": str}, validate.get("name")) + }, validate.union(( + validate.get("broadcaster"), + validate.get("game") + ))) + }}, + validate.get("data"), + validate.get("clip") + ), + validate.all( + {"data": { + "clip": validate.all({"title": str}, validate.get("title")) + }}, + validate.get("data"), + validate.get("clip") + ) + ] )) def stream_metadata(self, channel): @@ -662,12 +705,12 @@ class Twitch(Plugin): def _get_clips(self): try: - (self.author, self.title, self.category, streams) = self.api.clips(self.clip_name) + (((sig, token), streams), (self.author, self.category), self.title) = self.api.clips(self.clip_name) except (PluginError, TypeError): return for quality, stream in streams: - yield quality, HTTPStream(self.session, stream) + yield quality, HTTPStream(self.session, update_qsd(stream, {"sig": sig, "token": token})) def _get_streams(self): if self.video_id: diff --git a/src/streamlink/utils/url.py b/src/streamlink/utils/url.py index 7776c648..bc967126 100644 --- a/src/streamlink/utils/url.py +++ b/src/streamlink/utils/url.py @@ -1,24 +1,38 @@ +import re from collections import OrderedDict from urllib.parse import parse_qsl, quote_plus, urlencode, urljoin, urlparse, urlunparse -def update_scheme(current, target): +_re_uri_implicit_scheme = re.compile(r"""^[a-z0-9][a-z0-9.+-]*://""", re.IGNORECASE) + + +def update_scheme(current: str, target: str) -> str: """ - Take the scheme from the current URL and applies it to the - target URL if the target URL startswith // or is missing a scheme + Take the scheme from the current URL and apply it to the + target URL if the target URL starts with // or is missing a scheme :param current: current URL :param target: target URL :return: target URL with the current URLs scheme """ target_p = urlparse(target) + + if ( + # target URLs with implicit scheme and netloc including a port: ("http://", "foo.bar:1234") -> "http://foo.bar:1234" + # urllib.parse.urlparse has incorrect behavior in py<3.9, so we'll have to use a regex here + # py>=3.9: urlparse("127.0.0.1:1234") == ParseResult(scheme='127.0.0.1', netloc='', path='1234', ...) + # py<3.9 : urlparse("127.0.0.1:1234") == ParseResult(scheme='', netloc='', path='127.0.0.1:1234', ...) + not _re_uri_implicit_scheme.search(target) and not target.startswith("//") + # target URLs without scheme and netloc: ("http://", "foo.bar/foo") -> "http://foo.bar/foo" + or not target_p.scheme and not target_p.netloc + ): + return f"{urlparse(current).scheme}://{urlunparse(target_p)}" + + # target URLs without scheme but with netloc: ("http://", "//foo.bar/foo") -> "http://foo.bar/foo" if not target_p.scheme and target_p.netloc: - return "{0}:{1}".format(urlparse(current).scheme, - urlunparse(target_p)) - elif not target_p.scheme and not target_p.netloc: - return "{0}://{1}".format(urlparse(current).scheme, - urlunparse(target_p)) - else: - return target + return f"{urlparse(current).scheme}:{urlunparse(target_p)}" + + # target URLs with scheme + return target def url_equal(first, second, ignore_scheme=False, ignore_netloc=False, ignore_path=False, ignore_params=False,
streamlink/streamlink
e747226d2917a611cae9594722434376968fab00
diff --git a/tests/plugins/test_olympicchannel.py b/tests/plugins/test_olympicchannel.py index c859a4d0..39d4dc1a 100644 --- a/tests/plugins/test_olympicchannel.py +++ b/tests/plugins/test_olympicchannel.py @@ -11,10 +11,16 @@ class TestPluginCanHandleUrlOlympicChannel(PluginCanHandleUrl): "https://www.olympicchannel.com/en/live/video/detail/olympic-ceremonies-channel/", "https://www.olympicchannel.com/de/video/detail/stefanidi-husband-coach-krier-relationship/", "https://www.olympicchannel.com/de/original-series/detail/body/body-season-season-1/episodes/" - + "treffen-sie-aaron-wheelz-fotheringham-den-paten-des-rollstuhl-extremsports/", + "treffen-sie-aaron-wheelz-fotheringham-den-paten-des-rollstuhl-extremsports/", + "https://olympics.com/en/sport-events/2021-fiba-3x3-olympic-qualifier-graz/?" + "slug=final-day-fiba-3x3-olympic-qualifier-graz", + "https://olympics.com/en/video/spider-woman-shauna-coxsey-great-britain-climbing-interview", + "https://olympics.com/en/original-series/episode/how-fun-fuels-this-para-taekwondo-world-champion-unleash-the-new", + "https://olympics.com/tokyo-2020/en/news/videos/tokyo-2020-1-message", ] should_not_match = [ "https://www.olympicchannel.com/en/", - "https://www.olympicchannel.com/en/channel/olympic-channel/", + "https://www.olympics.com/en/", + "https://olympics.com/tokyo-2020/en/", ] diff --git a/tests/test_utils_url.py b/tests/test_utils_url.py index 9f283316..f5b725fd 100644 --- a/tests/test_utils_url.py +++ b/tests/test_utils_url.py @@ -9,6 +9,9 @@ def test_update_scheme(): assert update_scheme("http://other.com/bar", "//example.com/foo") == "http://example.com/foo", "should become http" assert update_scheme("https://other.com/bar", "http://example.com/foo") == "http://example.com/foo", "should remain http" assert update_scheme("https://other.com/bar", "example.com/foo") == "https://example.com/foo", "should become https" + assert update_scheme("http://", "127.0.0.1:1234/foo") == "http://127.0.0.1:1234/foo", "implicit scheme with IPv4+port" + assert update_scheme("http://", "foo.bar:1234/foo") == "http://foo.bar:1234/foo", "implicit scheme with hostname+port" + assert update_scheme("http://", "foo.1+2-bar://baz") == "foo.1+2-bar://baz", "correctly parses all kinds of schemes" def test_url_equal():
plugins.twitch: clips 404 - require access token <!-- Thanks for reporting a bug! USE THE TEMPLATE. Otherwise your bug report may be rejected. First, see the contribution guidelines: https://github.com/streamlink/streamlink/blob/master/CONTRIBUTING.md#contributing-to-streamlink Bugs are the result of broken functionality within Streamlink's main code base. Use the plugin issue template if your report is about a broken plugin. Also check the list of open and closed bug reports: https://github.com/streamlink/streamlink/issues?q=is%3Aissue+label%3A%22bug%22 Please see the text preview to avoid unnecessary formatting errors. --> ## Bug Report <!-- Replace the space character between the square brackets with an x in order to check the boxes --> - [x] This is a bug report and I have read the contribution guidelines. - [x] I am using the latest development version from the master branch. ### Description When running streamlink with a twitchclip URL it results in an 404 error ### Expected / Actual behavior It shouldn't 404 ### Reproduction steps / Explicit stream URLs to test <!-- How can we reproduce this? Please note the exact steps below using the list format supplied. If you need more steps please add them. --> 1. run stramlink with a twitch clip URL 2. results in a 404 error ### Log output <!-- DEBUG LOG OUTPUT IS REQUIRED for a bug report! INCLUDE THE ENTIRE COMMAND LINE and make sure to **remove usernames and passwords** Use the `--loglevel debug` parameter and avoid using parameters which suppress log output. Debug log includes important details about your platform. Don't remove it. https://streamlink.github.io/latest/cli.html#cmdoption-loglevel You can copy the output to https://gist.github.com/ or paste it below. Don't post screenshots of the log output and instead copy the text from your terminal application. --> ``` [cli][debug] OS: Windows 10 [cli][debug] Python: 3.8.2 [cli][debug] Streamlink: 2.1.2+10.ge747226 [cli][debug] Requests(2.25.1), Socks(1.7.1), Websocket(1.0.1) [cli][debug] Arguments: [cli][debug] url=https://clips.twitch.tv/GrossRamshacklePheasantPipeHype-vb-LdFjwD-kLo87L [cli][debug] stream=['best'] [cli][debug] --loglevel=debug [cli][debug] --rtmpdump=D:\Program Files (x86)\Streamlink\rtmpdump\rtmpdump.exe [cli][debug] --ffmpeg-ffmpeg=D:\Program Files (x86)\Streamlink\ffmpeg\ffmpeg.exe [cli][info] Found matching plugin twitch for URL https://clips.twitch.tv/GrossRamshacklePheasantPipeHype-vb-LdFjwD-kLo87L [cli][info] Available streams: 360p (worst), 480p, 720p, 1080p (best) [cli][info] Opening stream: 1080p (http) [cli][error] Try 1/1: Could not open stream <HTTPStream('https://production.assets.clips.twitchcdn.net/AT-cm%7C1198016717.mp4')> (Could not open stream: Unable to open URL: https://production.assets.clips.twitchcdn.net/AT-cm%7C1198016717.mp4 (404 Client Error: for url: https://production.assets.clips.twitchcdn.net/AT-cm%7C1198016717.mp4)) error: Could not open stream <HTTPStream('https://production.assets.clips.twitchcdn.net/AT-cm%7C1198016717.mp4')>, tried 1 times, exiting ``` ### Additional comments, etc. Twitch now needs a JWT in the URL for authentication. The page 404 if it isn't present. The JSON is just plaintext, but urlencoded and has the form: {"authorization":{"forbidden":false,"reason":""},"clip_uri":"","device_id":str,"expires":int,"user_id":str,"version":2} The signature appears to be sha1, but I couldn't figure out what exactly that were hashing as nothing I tried resulted in a valid hash. [Love Streamlink? Please consider supporting our collective. Thanks!](https://opencollective.com/streamlink/donate)
0.0
e747226d2917a611cae9594722434376968fab00
[ "tests/plugins/test_olympicchannel.py::TestPluginCanHandleUrlOlympicChannel::test_can_handle_url_positive[https://olympics.com/en/sport-events/2021-fiba-3x3-olympic-qualifier-graz/?slug=final-day-fiba-3x3-olympic-qualifier-graz]", "tests/plugins/test_olympicchannel.py::TestPluginCanHandleUrlOlympicChannel::test_can_handle_url_positive[https://olympics.com/en/video/spider-woman-shauna-coxsey-great-britain-climbing-interview]", "tests/plugins/test_olympicchannel.py::TestPluginCanHandleUrlOlympicChannel::test_can_handle_url_positive[https://olympics.com/en/original-series/episode/how-fun-fuels-this-para-taekwondo-world-champion-unleash-the-new]", "tests/plugins/test_olympicchannel.py::TestPluginCanHandleUrlOlympicChannel::test_can_handle_url_positive[https://olympics.com/tokyo-2020/en/news/videos/tokyo-2020-1-message]", "tests/test_utils_url.py::test_update_scheme" ]
[ "tests/plugins/test_olympicchannel.py::TestPluginCanHandleUrlOlympicChannel::test_class_setup", "tests/plugins/test_olympicchannel.py::TestPluginCanHandleUrlOlympicChannel::test_can_handle_url_positive[https://www.olympicchannel.com/en/video/detail/stefanidi-husband-coach-krier-relationship/]", "tests/plugins/test_olympicchannel.py::TestPluginCanHandleUrlOlympicChannel::test_can_handle_url_positive[https://www.olympicchannel.com/en/live/]", "tests/plugins/test_olympicchannel.py::TestPluginCanHandleUrlOlympicChannel::test_can_handle_url_positive[https://www.olympicchannel.com/en/live/video/detail/olympic-ceremonies-channel/]", "tests/plugins/test_olympicchannel.py::TestPluginCanHandleUrlOlympicChannel::test_can_handle_url_positive[https://www.olympicchannel.com/de/video/detail/stefanidi-husband-coach-krier-relationship/]", "tests/plugins/test_olympicchannel.py::TestPluginCanHandleUrlOlympicChannel::test_can_handle_url_positive[https://www.olympicchannel.com/de/original-series/detail/body/body-season-season-1/episodes/treffen-sie-aaron-wheelz-fotheringham-den-paten-des-rollstuhl-extremsports/]", "tests/plugins/test_olympicchannel.py::TestPluginCanHandleUrlOlympicChannel::test_can_handle_url_negative[https://www.olympicchannel.com/en/]", "tests/plugins/test_olympicchannel.py::TestPluginCanHandleUrlOlympicChannel::test_can_handle_url_negative[https://www.olympics.com/en/]", "tests/plugins/test_olympicchannel.py::TestPluginCanHandleUrlOlympicChannel::test_can_handle_url_negative[https://olympics.com/tokyo-2020/en/]", "tests/plugins/test_olympicchannel.py::TestPluginCanHandleUrlOlympicChannel::test_can_handle_url_negative[http://example.com/]", "tests/plugins/test_olympicchannel.py::TestPluginCanHandleUrlOlympicChannel::test_can_handle_url_negative[https://example.com/]", "tests/plugins/test_olympicchannel.py::TestPluginCanHandleUrlOlympicChannel::test_can_handle_url_negative[https://example.com/index.html]", "tests/test_utils_url.py::test_url_equal", "tests/test_utils_url.py::test_url_concat", "tests/test_utils_url.py::test_update_qsd" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_media", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2021-05-30 19:54:39+00:00
bsd-2-clause
5,791
streamlink__streamlink-3765
diff --git a/src/streamlink/utils/url.py b/src/streamlink/utils/url.py index 7776c648..bc967126 100644 --- a/src/streamlink/utils/url.py +++ b/src/streamlink/utils/url.py @@ -1,24 +1,38 @@ +import re from collections import OrderedDict from urllib.parse import parse_qsl, quote_plus, urlencode, urljoin, urlparse, urlunparse -def update_scheme(current, target): +_re_uri_implicit_scheme = re.compile(r"""^[a-z0-9][a-z0-9.+-]*://""", re.IGNORECASE) + + +def update_scheme(current: str, target: str) -> str: """ - Take the scheme from the current URL and applies it to the - target URL if the target URL startswith // or is missing a scheme + Take the scheme from the current URL and apply it to the + target URL if the target URL starts with // or is missing a scheme :param current: current URL :param target: target URL :return: target URL with the current URLs scheme """ target_p = urlparse(target) + + if ( + # target URLs with implicit scheme and netloc including a port: ("http://", "foo.bar:1234") -> "http://foo.bar:1234" + # urllib.parse.urlparse has incorrect behavior in py<3.9, so we'll have to use a regex here + # py>=3.9: urlparse("127.0.0.1:1234") == ParseResult(scheme='127.0.0.1', netloc='', path='1234', ...) + # py<3.9 : urlparse("127.0.0.1:1234") == ParseResult(scheme='', netloc='', path='127.0.0.1:1234', ...) + not _re_uri_implicit_scheme.search(target) and not target.startswith("//") + # target URLs without scheme and netloc: ("http://", "foo.bar/foo") -> "http://foo.bar/foo" + or not target_p.scheme and not target_p.netloc + ): + return f"{urlparse(current).scheme}://{urlunparse(target_p)}" + + # target URLs without scheme but with netloc: ("http://", "//foo.bar/foo") -> "http://foo.bar/foo" if not target_p.scheme and target_p.netloc: - return "{0}:{1}".format(urlparse(current).scheme, - urlunparse(target_p)) - elif not target_p.scheme and not target_p.netloc: - return "{0}://{1}".format(urlparse(current).scheme, - urlunparse(target_p)) - else: - return target + return f"{urlparse(current).scheme}:{urlunparse(target_p)}" + + # target URLs with scheme + return target def url_equal(first, second, ignore_scheme=False, ignore_netloc=False, ignore_path=False, ignore_params=False,
streamlink/streamlink
e747226d2917a611cae9594722434376968fab00
diff --git a/tests/test_utils_url.py b/tests/test_utils_url.py index 9f283316..f5b725fd 100644 --- a/tests/test_utils_url.py +++ b/tests/test_utils_url.py @@ -9,6 +9,9 @@ def test_update_scheme(): assert update_scheme("http://other.com/bar", "//example.com/foo") == "http://example.com/foo", "should become http" assert update_scheme("https://other.com/bar", "http://example.com/foo") == "http://example.com/foo", "should remain http" assert update_scheme("https://other.com/bar", "example.com/foo") == "https://example.com/foo", "should become https" + assert update_scheme("http://", "127.0.0.1:1234/foo") == "http://127.0.0.1:1234/foo", "implicit scheme with IPv4+port" + assert update_scheme("http://", "foo.bar:1234/foo") == "http://foo.bar:1234/foo", "implicit scheme with hostname+port" + assert update_scheme("http://", "foo.1+2-bar://baz") == "foo.1+2-bar://baz", "correctly parses all kinds of schemes" def test_url_equal():
--http[s]-proxy does not properly handle schemeless inputs with port due to urllib behavior change in python 3.9 ## Bug Report <!-- Replace the space character between the square brackets with an x in order to check the boxes --> - [X] This is a bug report and I have read the contribution guidelines. - [X] I am using the latest development version from the master branch. ### Description <!-- Explain the bug as thoroughly as you can. Don't leave out information which is necessary for us to reproduce and debug this issue. --> While troubleshooting an issue with a project that consumes Streamlink by way of its CLI, I discovered an apparent bug in the interaction between Streamlink and urllib w/r/t how proxy URL inputs are handled - stemming from a behavior change in urllib in Python 3.9. If the input for `--http[s]-proxy` is provided in host:port or IP:port notation WITHOUT a scheme (e.g. `--http-proxy 127.0.0.1:8050`), the `update_scheme()` function does not actually add a scheme to it under Python 3.9. When the still-schemeless url is then fed to urllib3 for connection setup, it fails with a `ProxySchemeUnknown` exception. The behavior here appears to be caused by urllib's `urlparse()` function, rather than Streamlink itself, but the intent of the Python developers seems to be that the behavior change is handled by client applications. Reference: [44007: urlparse("host:123", "http") inconsistent between 3.8 and 3.9](https://bugs.python.org/issue44007) which leads to: [27657: urlparse fails if the path is numeric](https://bugs.python.org/issue27657) as the source of the behavior change In the latter bug (specifically here: https://bugs.python.org/issue27657#msg371024) it's noted that the behavior change was apparently intentional and consumers of urllib are expected to handle it. ### Expected / Actual behavior <!-- What do you expect to happen, and what is actually happening? --> Expected: A scheme-less host:port or ip:port input to a proxy option (e.g. `--http-proxy 127.0.0.1:8050`) should be reformatted by `update_scheme()` to the appropriate format (e.g. `http://127.0.0.1:8050`) before being used as input to urllib3. Actual: *In Python 3.9* the value is used as-is, and because there is no http/https scheme on the URL, urllib3 throws a `ProxySchemeUnknown` exception. (`Proxy URL had no scheme, should start with http:// or https://`). ### Reproduction steps / Explicit stream URLs to test <!-- How can we reproduce this? Please note the exact steps below using the list format supplied. If you need more steps please add them. --> The observed behavior can be abstracted entirely away from the Streamlink CLI. In session.py, we have the following (https://github.com/streamlink/streamlink/blob/master/src/streamlink/session.py#L279-L285): ``` elif key == "http-proxy": self.http.proxies["http"] = update_scheme("http://", value) if "https" not in self.http.proxies: self.http.proxies["https"] = update_scheme("http://", value) elif key == "https-proxy": self.http.proxies["https"] = update_scheme("https://", value) ``` The `update_scheme()` function should apply the appropriate scheme to the URL, but on *Python 3.9* it does not in the case of a schemeless input with port: ``` Python 3.9.5 (default, May 24 2021, 12:50:35) [GCC 11.1.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>> from streamlink import utils >>> utils.update_scheme("http://", "127.0.0.1:8050") '127.0.0.1:8050' >>> utils.update_scheme("https://", "127.0.0.1:8050") '127.0.0.1:8050' >>> utils.update_scheme("https://", "localhost:8050") 'localhost:8050' >>> utils.update_scheme("https://", "localhost") 'https://localhost' ``` Note that the only properly-handled input above was the "schemeless hostname without port" case - any schemeless input _with_ port does not get the expected scheme added. The root of this issue is actually in urllib, as `update_scheme()` calls `urlparse()` from urllib. In Python 3.8, the `urlparse` call results in the following: ``` Python 3.8.10 (default, May 12 2021, 15:46:43) [GCC 8.3.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>> from urllib import parse >>> parse.urlparse('127.0.0.1:8080') ParseResult(scheme='', netloc='', path='127.0.0.1:8080', params='', query='', fragment='') ``` Whereas in Python 3.9, the folloiwng occurs: ``` Python 3.9.5 (default, May 12 2021, 15:26:36) [GCC 8.3.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>> from urllib import parse >>> parse.urlparse('127.0.0.1:8080') ParseResult(scheme='127.0.0.1', netloc='', path='8080', params='', query='', fragment='') ``` Note in the latter case, urllib returns the IP address in the `scheme` portion of the tuple instead of ... anywhere else (I'm honestly not sure if it should end up in `netloc` or `path`). ### Log output The consumer of Streamlink which I was troubleshooting (LazyMan) shells out to Streamlink with `--https-proxy 127.0.0.1:<port>` - a schemeless url with port - as seen here: https://github.com/StevensNJD4/LazyMan/blob/master/src/Objects/Streamlink.java#L45 This results in the following output from LM when run on a system with Python 3.9: ``` ----- ----- Streamlink starting... urlparse was ParseResult(scheme='hlsvariant', netloc='<censored> name_key=bitrate verify=False', params='', query='', fragment='') got https-proxy 127.0.0.1:8050 urlparse was ParseResult(scheme='127.0.0.1', netloc='', path='8050', params='', query='', fragment='') output of update_scheme is 127.0.0.1:8050 urlparse was ParseResult(scheme='127.0.0.1', netloc='', path='8050', params='', query='', fragment='') self.http.proxies['https'] is 127.0.0.1:8050 [cli][debug] OS: Linux-5.12.7-arch1-1-x86_64-with-glibc2.33 [cli][debug] Python: 3.9.5 [cli][debug] Streamlink: 2.1.1 [cli][debug] Requests(2.25.1), Socks(1.7.1), Websocket(0.59.0) [cli][debug] Arguments: [cli][debug] url=hlsvariant://<censored> name_key=bitrate verify=False [cli][debug] stream=['best'] [cli][debug] --loglevel=debug [cli][debug] --hls-segment-threads=4 [cli][debug] --https-proxy=127.0.0.1:8050 [cli][debug] --http-header=[('User-Agent', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36')] [cli][info] Found matching plugin hls for URL hlsvariant://<censored> name_key=bitrate verify=False urlparse was ParseResult(scheme='<censored>', params='', query='', fragment='') [plugins.hls][debug] URL=<censored>; params={'name_key': 'bitrate', 'verify': False} [utils.l10n][debug] Language code: en_US [cli][info] Available streams: 670k (worst), 1000k, 1450k, 2140k, 2900k, 4100k, 6600k (best) [cli][info] Opening stream: 6600k (hls) [stream.hls][debug] Reloading playlist [stream.hls][debug] Segments in this playlist are encrypted [stream.hls][debug] First Sequence: 0; Last Sequence: 1970 [stream.hls][debug] Start offset: 0; Duration: None; Start Sequence: 0; End Sequence: 1970 [stream.hls][debug] Adding segment 0 to queue [cli][debug] Pre-buffering 8192 bytes [stream.hls][debug] Adding segment 1 to queue [stream.hls][debug] Adding segment 2 to queue [stream.hls][debug] Adding segment 3 to queue [stream.hls][debug] Adding segment 4 to queue [stream.hls][debug] Adding segment 5 to queue [stream.hls][debug] Adding segment 6 to queue [stream.hls][debug] Adding segment 7 to queue [stream.hls][debug] Adding segment 8 to queue [stream.hls][debug] Adding segment 9 to queue [stream.hls][debug] Adding segment 10 to queue [stream.hls][debug] Adding segment 11 to queue [stream.hls][debug] Adding segment 12 to queue [stream.hls][debug] Adding segment 13 to queue [stream.hls][debug] Adding segment 14 to queue [stream.hls][debug] Adding segment 15 to queue [stream.hls][debug] Adding segment 16 to queue [stream.hls][debug] Adding segment 17 to queue [stream.hls][debug] Adding segment 18 to queue [stream.hls][debug] Adding segment 19 to queue [stream.hls][debug] Adding segment 20 to queue [stream.hls][debug] Adding segment 21 to queue [stream.hls][error] Failed to create decryptor: Unable to open URL: https://<url snipped> (Proxy URL had no scheme, should start with http:// or https://) [stream.segmented][debug] Closing writer thread [stream.segmented][debug] Closing worker thread [cli][error] Try 1/1: Could not open stream <HLSStream('<censored>', 'http://<url snipped>')> (No data returned from stream) error: Could not open stream <HLSStream('<censored>', 'http://<url snipped>')>, tried 1 times, exiting [cli][info] Closing currently open stream... ``` In the above, the notable output is the `Proxy URL had no scheme [...]` error which maps to a `ProxySchemeUnknown` exception from urllib3. ### Additional comments, etc.
0.0
e747226d2917a611cae9594722434376968fab00
[ "tests/test_utils_url.py::test_update_scheme" ]
[ "tests/test_utils_url.py::test_url_equal", "tests/test_utils_url.py::test_url_concat", "tests/test_utils_url.py::test_update_qsd" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2021-05-31 14:11:28+00:00
bsd-2-clause
5,792
streamlink__streamlink-389
diff --git a/docs/plugin_matrix.rst b/docs/plugin_matrix.rst index fd3c8d39..846f39e2 100644 --- a/docs/plugin_matrix.rst +++ b/docs/plugin_matrix.rst @@ -137,6 +137,7 @@ tv4play - tv4play.se Yes Yes Streams may be geo-restrict Only non-premium streams currently supported. - fotbollskanalen.se tv8 tv8.com.tr Yes No +tv8cat tv8.cat Yes No Streams may be geo-restricted to Spain/Catalunya. tv360 tv360.com.tr Yes No tvcatchup - tvcatchup.com Yes No Streams may be geo-restricted to Great Britain. tvplayer tvplayer.com Yes No Streams may be geo-restricted to Great Britain. Premium streams are not supported. diff --git a/src/streamlink/plugins/tf1.py b/src/streamlink/plugins/tf1.py index 337677e6..f1e6fad8 100644 --- a/src/streamlink/plugins/tf1.py +++ b/src/streamlink/plugins/tf1.py @@ -11,9 +11,9 @@ class TF1(Plugin): url_re = re.compile(r"https?://(?:www\.)?(?:tf1\.fr/(\w+)/direct|(lci).fr/direct)/?") embed_url = "http://www.wat.tv/embedframe/live{0}" embed_re = re.compile(r"urlLive.*?:.*?\"(http.*?)\"", re.MULTILINE) - api_url = "http://www.wat.tv/get/androidlive{0}/591997" - swf_url = "http://www.wat.tv/images/v70/PlayerWat.swf?rev=04.00.861" - hds_channel_remap = {"tf1": "connect"} + api_url = "http://www.wat.tv/get/{0}/591997" + swf_url = "http://www.wat.tv/images/v70/PlayerLite.swf" + hds_channel_remap = {"tf1": "androidliveconnect", "lci": "androidlivelci"} hls_channel_remap = {"lci": "LCI", "tf1": "V4"} @classmethod @@ -21,13 +21,15 @@ class TF1(Plugin): return cls.url_re.match(url) is not None def _get_hds_streams(self, channel): - channel = self.hds_channel_remap.get(channel, channel) + channel = self.hds_channel_remap.get(channel, "{0}live".format(channel)) manifest_url = http.get(self.api_url.format(channel), - params={"getURL": 1}).text + params={"getURL": 1}, + headers={"User-Agent": useragents.FIREFOX}).text for s in HDSStream.parse_manifest(self.session, manifest_url, - pvswf=self.swf_url).items(): + pvswf=self.swf_url, + headers={"User-Agent": useragents.FIREFOX}).items(): yield s def _get_hls_streams(self, channel): @@ -41,8 +43,11 @@ class TF1(Plugin): if m: hls_stream_url = m.group(1) - for s in HLSStream.parse_variant_playlist(self.session, hls_stream_url).items(): - yield s + try: + for s in HLSStream.parse_variant_playlist(self.session, hls_stream_url).items(): + yield s + except: + self.logger.error("Failed to load the HLS playlist for {0}", channel) def _get_streams(self): m = self.url_re.match(self.url) diff --git a/src/streamlink/plugins/tv8cat.py b/src/streamlink/plugins/tv8cat.py new file mode 100644 index 00000000..7c1acf83 --- /dev/null +++ b/src/streamlink/plugins/tv8cat.py @@ -0,0 +1,79 @@ +from __future__ import print_function +import re + +from streamlink.plugin import Plugin +from streamlink.plugin.api import http +from streamlink.compat import urlparse, parse_qsl +from streamlink.plugin.api import useragents +from streamlink.plugin.api import validate +from streamlink.stream import HLSStream +from streamlink.stream import RTMPStream +from streamlink.utils import parse_json + + +class TV8cat(Plugin): + url_re = re.compile(r"https?://(?:www\.)?tv8\.cat/directe/?") + live_iframe = "http://www.8tv.cat/wp-content/themes/8tv/_/inc/_live_html.php" + iframe_re = re.compile(r'iframe .*?src="((?:https?)?//[^"]*?)"') + account_id_re = re.compile(r"accountId:\"(\d+?)\"") + policy_key_re = re.compile(r"policyKey:\"(.+?)\"") + britecove = "https://edge.api.brightcove.com/playback/v1/accounts/{account_id}/videos/{video_id}" + britecove_schema = validate.Schema({ + "sources": [ + {"height": int, + validate.optional("src"): validate.url(), + validate.optional("app_name"): validate.url(scheme="rtmp"), + validate.optional("stream_name"): validate.text} + ] + }) + + @classmethod + def can_handle_url(cls, url): + return cls.url_re.match(url) is not None + + def _find_iframe(self, res): + iframe = self.iframe_re.search(res.text) + url = iframe and iframe.group(1) + if url and url.startswith("//"): + p = urlparse(self.url) + url = "{0}:{1}".format(p.scheme, url) + return url + + def _britecove_params(self, url): + res = http.get(url, headers={"User-Agent": useragents.FIREFOX, + "Referer": self.url}) + acc = self.account_id_re.search(res.text) + pk = self.policy_key_re.search(res.text) + + query = dict(parse_qsl(urlparse(url).query)) + return {"video_id": query.get("videoId"), + "account_id": acc and acc.group(1), + "policy_key": pk and pk.group(1), + } + + def _get_stream_data(self, **params): + api_url = self.britecove.format(**params) + res = http.get(api_url, headers={"Accept": "application/json;pk={policy_key}".format(**params)}) + return parse_json(res.text, schema=self.britecove_schema) + + def _get_streams(self): + res = http.get(self.live_iframe) + britecove_url = self._find_iframe(res) + + if britecove_url: + self.logger.debug("Found britecove embed url: {0}", britecove_url) + params = self._britecove_params(britecove_url) + self.logger.debug("Got britecode params: {0}", params) + stream_info = self._get_stream_data(**params) + for source in stream_info.get("sources"): + if source.get("src"): + for s in HLSStream.parse_variant_playlist(self.session, source.get("src")).items(): + yield s + else: + q = "{0}p".format(source.get("height")) + s = RTMPStream(self.session, + {"rtmp": source.get("app_name"), + "playpath": source.get("stream_name")}) + yield q, s + +__plugin__ = TV8cat diff --git a/src/streamlink/stream/hds.py b/src/streamlink/stream/hds.py index 68605bc2..c7e168ee 100644 --- a/src/streamlink/stream/hds.py +++ b/src/streamlink/stream/hds.py @@ -2,8 +2,10 @@ from __future__ import division import base64 import hmac +import random import re import os.path +import string from binascii import unhexlify from collections import namedtuple @@ -68,11 +70,15 @@ class HDSStreamWriter(SegmentedStreamWriter): return try: + request_params = self.stream.request_params.copy() + params = request_params.pop("params", {}) + params.pop("g", None) return self.session.http.get(fragment.url, stream=True, timeout=self.timeout, exception=StreamError, - **self.stream.request_params) + params=params, + **request_params) except StreamError as err: self.logger.error("Failed to open fragment {0}-{1}: {2}", fragment.segment, fragment.fragment, err) @@ -442,6 +448,7 @@ class HDSStream(Stream): if "akamaihd" in url or is_akamai: request_params["params"]["hdcore"] = HDCORE_VERSION + request_params["params"]["g"] = cls.cache_buster_string(12) res = session.http.get(url, exception=IOError, **request_params) manifest = session.http.xml(res, "manifest XML", ignore_ns=True, @@ -586,3 +593,7 @@ class HDSStream(Stream): params.extend(parse_qsl(hdntl, keep_blank_values=True)) return params + + @staticmethod + def cache_buster_string(length): + return "".join([random.choice(string.ascii_uppercase) for i in range(length)])
streamlink/streamlink
d45ec8ff5e02ccb2c29ed2eb1fe1581cda81c94b
diff --git a/tests/test_plugin_tv8cat.py b/tests/test_plugin_tv8cat.py new file mode 100644 index 00000000..6fc82153 --- /dev/null +++ b/tests/test_plugin_tv8cat.py @@ -0,0 +1,17 @@ +import unittest + +from streamlink.plugins.tv8cat import TV8cat + + +class TestPluginTV8cat(unittest.TestCase): + def test_can_handle_url(self): + # should match + self.assertTrue(TV8cat.can_handle_url("http://tv8.cat/directe")) + self.assertTrue(TV8cat.can_handle_url("http://www.tv8.cat/directe")) + self.assertTrue(TV8cat.can_handle_url("http://www.tv8.cat/directe/")) + self.assertTrue(TV8cat.can_handle_url("https://tv8.cat/directe/")) + + # shouldn't match + self.assertFalse(TV8cat.can_handle_url("http://www.tv8.cat/algo/")) + self.assertFalse(TV8cat.can_handle_url("http://www.tvcatchup.com/")) + self.assertFalse(TV8cat.can_handle_url("http://www.youtube.com/"))
Mytf1.fr : TF 1, TMC, NT 1, HD 1, LCI http://www.tf1.fr/direct Channels on TF 1 site require only a free login and French proxy. They use HDS and HLS. LCi doesn't require login just proxy : http://www.lci.fr/direct/ But it would be of course better if you can bypass login.
0.0
d45ec8ff5e02ccb2c29ed2eb1fe1581cda81c94b
[ "tests/test_plugin_tv8cat.py::TestPluginTV8cat::test_can_handle_url" ]
[]
{ "failed_lite_validators": [ "has_hyperlinks", "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2017-01-09 13:22:19+00:00
bsd-2-clause
5,793
streamlink__streamlink-415
diff --git a/docs/plugin_matrix.rst b/docs/plugin_matrix.rst index c771574b..0a900a08 100644 --- a/docs/plugin_matrix.rst +++ b/docs/plugin_matrix.rst @@ -37,6 +37,9 @@ bnt - tv.bnt.bg Yes No Streams may be geo-restrict - nova.bg bongacams bongacams.com Yes No Only RTMP streams are available. btv btv.bg Yes No Requires login, and geo-restricted to Bulgaria. +canaplus - canalplus.fr Yes Yes Streams may be geo-restricted to France. + - c8.fr + - cstar.fr chaturbate chaturbate.com Yes No cinergroup - showtv.com.tr Yes No - haberturk.com diff --git a/src/streamlink/plugins/canalplus.py b/src/streamlink/plugins/canalplus.py new file mode 100644 index 00000000..ee06516d --- /dev/null +++ b/src/streamlink/plugins/canalplus.py @@ -0,0 +1,103 @@ +import re + +from streamlink.exceptions import PluginError +from streamlink.plugin import Plugin +from streamlink.plugin.api import http, useragents, validate +from streamlink.stream import HDSStream, HLSStream, HTTPStream + + +class CanalPlus(Plugin): + API_URL = 'http://service.canal-plus.com/video/rest/getVideos/{0}/{1}?format=json' + CHANNEL_MAP = {'canalplus': 'cplus', 'c8': 'd8', 'cstar': 'd17'} + HDCORE_VERSION = '3.1.0' + # Secret parameter needed to download HTTP videos on canalplus.fr + SECRET = 'pqzerjlsmdkjfoiuerhsdlfknaes' + + _url_re = re.compile(r''' + http:// + ( + www\.(?P<channel>canalplus|c8|cstar)\.fr/.*pid.+?\.html(\?(?P<video_id>[0-9]+))? | + replay\.(?P<replay_channel>c8|cstar)\.fr/video/(?P<replay_video_id>[0-9]+) + ) +''', re.VERBOSE) + _video_id_re = re.compile(r'\bdata-video="(?P<video_id>[0-9]+)"') + _mp4_bitrate_re = re.compile(r'.*_(?P<bitrate>[0-9]+k)\.mp4') + _api_schema = validate.Schema({ + 'MEDIA': validate.Schema({ + 'VIDEOS': validate.Schema({ + validate.text: validate.any( + validate.url(), + '' + ) + }) + }) + }) + _user_agent = useragents.CHROME + + + @classmethod + def can_handle_url(cls, url): + return CanalPlus._url_re.match(url) + + + def _get_streams(self): + # Get video ID and channel from URL + match = self._url_re.match(self.url) + channel = match.group('channel') + if channel is None: + # Replay website + channel = match.group('replay_channel') + video_id = match.group('replay_video_id') + else: + video_id = match.group('video_id') + if video_id is None: + # Retrieve URL page and search for video ID + res = http.get(self.url) + match = self._video_id_re.search(res.text) + if match is None: + return + video_id = match.group('video_id') + + res = http.get(self.API_URL.format(self.CHANNEL_MAP[channel], video_id)) + videos = http.json(res, schema=self._api_schema) + parsed = [] + headers = {'User-Agent': self._user_agent} + for quality, video_url in list(videos['MEDIA']['VIDEOS'].items()): + # Ignore empty URLs + if video_url == '': + continue + + # Ignore duplicate video URLs + if video_url in parsed: + continue + parsed.append(video_url) + + try: + if '.f4m' in video_url: + for stream in HDSStream.parse_manifest(self.session, + video_url, + params={'hdcore': self.HDCORE_VERSION}, + headers=headers).items(): + yield stream + elif '.m3u8' in video_url: + for stream in HLSStream.parse_variant_playlist(self.session, + video_url, + headers=headers).items(): + yield stream + elif '.mp4' in video_url: + # Get bitrate from video filename + match = self._mp4_bitrate_re.match(video_url) + if match is not None: + bitrate = match.group('bitrate') + else: + bitrate = quality + yield bitrate, HTTPStream(self.session, + video_url, + params={'secret': self.SECRET}, + headers=headers) + except PluginError: + self.logger.error('Failed to access stream, may be due to geo-restriction') + raise + + +__plugin__ = CanalPlus diff --git a/src/streamlink/plugins/rtve.py b/src/streamlink/plugins/rtve.py index e0c31b05..0a3a6151 100644 --- a/src/streamlink/plugins/rtve.py +++ b/src/streamlink/plugins/rtve.py @@ -1,59 +1,86 @@ +import base64 import re -from streamlink.plugin import Plugin, PluginError +from Crypto.Cipher import Blowfish +from streamlink.compat import bytes, is_py3 +from streamlink.plugin import Plugin from streamlink.plugin.api import http +from streamlink.plugin.api import useragents +from streamlink.plugin.api import validate from streamlink.stream import HLSStream +from streamlink.utils import parse_xml -# The last four channel_paths repsond with 301 and provide -# a redirect location that corresponds to a channel_path above. -_url_re = re.compile(r""" - https?://www\.rtve\.es/ - (?P<channel_path> - directo/la-1| - directo/la-2| - directo/teledeporte| - directo/canal-24h| - - noticias/directo-la-1| - television/la-2-directo| - deportes/directo/teledeporte| - noticias/directo/canal-24h - ) - /? -""", re.VERBOSE) -_id_map = { - "directo/la-1": "LA1", - "directo/la-2": "LA2", - "directo/teledeporte": "TDP", - "directo/canal-24h": "24H", - "noticias/directo-la-1": "LA1", - "television/la-2-directo": "LA2", - "deportes/directo/teledeporte": "TDP", - "noticias/directo/canal-24h": "24H", -} +class ZTNRClient(object): + base_url = "http://ztnr.rtve.es/ztnr/res/" + block_size = 16 + + def __init__(self, key): + self.cipher = Blowfish.new(key, Blowfish.MODE_ECB) + + def pad(self, data): + n = self.block_size - len(data) % self.block_size + return data + bytes(chr(self.block_size - len(data) % self.block_size), "utf8") * n + + def unpad(self, data): + if is_py3: + return data[0:-data[-1]] + else: + return data[0:-ord(data[-1])] + + def encrypt(self, data): + return base64.b64encode(self.cipher.encrypt(self.pad(bytes(data, "utf-8"))), altchars=b"-_").decode("ascii") + + def decrypt(self, data): + return self.unpad(self.cipher.decrypt(base64.b64decode(data, altchars=b"-_"))) + + def request(self, data, *args, **kwargs): + res = http.get(self.base_url+self.encrypt(data), *args, **kwargs) + return self.decrypt(res.content) + + def get_cdn_list(self, vid, manager="apedemak", vtype="video", lang="es", schema=None): + data = self.request("{id}_{manager}_{type}_{lang}".format(id=vid, manager=manager, type=vtype, lang=lang)) + if schema: + return schema.validate(data) + else: + return data class Rtve(Plugin): + secret_key = base64.b64decode("eWVMJmRhRDM=") + channel_id_re = re.compile(r'<span.*?id="iniIDA">(\d+)</span>') + url_re = re.compile(r""" + https?://(?:www\.)?rtve\.es/(?:noticias|television|deportes)/.*?/? + """, re.VERBOSE) + cdn_schema = validate.Schema( + validate.transform(parse_xml), + validate.xml_findtext(".//url") + ) + @classmethod def can_handle_url(cls, url): - return _url_re.match(url) + return cls.url_re.match(url) is not None def __init__(self, url): Plugin.__init__(self, url) - match = _url_re.match(url).groupdict() - self.channel_path = match["channel_path"] + self.zclient = ZTNRClient(self.secret_key) + http.headers = {"User-Agent": useragents.SAFARI_8} + + def _get_channel_id(self): + res = http.get(self.url) + m = self.channel_id_re.search(res.text) + return m and int(m.group(1)) def _get_streams(self): - stream_id = _id_map[self.channel_path] - hls_url = "http://iphonelive.rtve.es/{0}_LV3_IPH/{0}_LV3_IPH.m3u8".format(stream_id) + channel_id = self._get_channel_id() - # Check if the stream is available - res = http.head(hls_url, raise_for_status=False) - if res.status_code == 404: - raise PluginError("The program is not available due to rights restrictions") + if channel_id: + self.logger.debug("Found channel with id: {0}", channel_id) + hls_url = self.zclient.get_cdn_list(channel_id, schema=self.cdn_schema) + self.logger.debug("Got stream URL: {0}", hls_url) + return HLSStream.parse_variant_playlist(self.session, hls_url) - return HLSStream.parse_variant_playlist(self.session, hls_url) + return __plugin__ = Rtve
streamlink/streamlink
8b710ba7f642e0906413157e60e602ce41cfe1cf
diff --git a/tests/test_plugin_canalplus.py b/tests/test_plugin_canalplus.py new file mode 100644 index 00000000..7b841e26 --- /dev/null +++ b/tests/test_plugin_canalplus.py @@ -0,0 +1,28 @@ +import unittest + +from streamlink.plugins.canalplus import CanalPlus + + +class TestPluginCanalPlus(unittest.TestCase): + def test_can_handle_url(self): + # should match + self.assertTrue(CanalPlus.can_handle_url("http://www.canalplus.fr/pid3580-live-tv-clair.html")) + self.assertTrue(CanalPlus.can_handle_url("http://www.canalplus.fr/emissions/pid8596-the-tonight-show.html")) + self.assertTrue(CanalPlus.can_handle_url("http://www.canalplus.fr/c-divertissement/pid1787-c-groland.html?vid=1430239")) + self.assertTrue(CanalPlus.can_handle_url("http://www.c8.fr/pid5323-c8-live.html")) + self.assertTrue(CanalPlus.can_handle_url("http://www.c8.fr/c8-divertissement/pid8758-c8-la-folle-histoire-de-sophie-marceau.html")) + self.assertTrue(CanalPlus.can_handle_url("http://www.c8.fr/c8-sport/pid5224-c8-direct-auto.html?vid=1430292")) + self.assertTrue(CanalPlus.can_handle_url("http://replay.c8.fr/video/1431076")) + self.assertTrue(CanalPlus.can_handle_url("http://www.cstar.fr/pid5322-cstar-live.html")) + self.assertTrue(CanalPlus.can_handle_url("http://www.cstar.fr/emissions/pid8754-wild-transport.html")) + self.assertTrue(CanalPlus.can_handle_url("http://www.cstar.fr/musique/pid6282-les-tops.html?vid=1430143")) + self.assertTrue(CanalPlus.can_handle_url("http://replay.cstar.fr/video/1430245")) + + # shouldn't match + self.assertFalse(CanalPlus.can_handle_url("http://www.canalplus.fr/")) + self.assertFalse(CanalPlus.can_handle_url("http://www.c8.fr/")) + self.assertFalse(CanalPlus.can_handle_url("http://replay.c8.fr/")) + self.assertFalse(CanalPlus.can_handle_url("http://www.cstar.fr/")) + self.assertFalse(CanalPlus.can_handle_url("http://replay.cstar.fr/")) + self.assertFalse(CanalPlus.can_handle_url("http://www.tvcatchup.com/")) + self.assertFalse(CanalPlus.can_handle_url("http://www.youtube.com/"))
RTVE.es plugin broken Spanish public TV RTVE recently changed broadcasting address and servers which made plugin broken. `livestreamer -p "C:\Users\Ddr\Downloads\VLCPortable\App\vlc\vlc" "http://www.rtve.es/noticias/mas-24/" best error: No plugin can handle URL: http://www.rtve.es/noticias/mas-24/` Below are direct addresses to channels : - La 1 : http://www.rtve.es/noticias/directo-la-1/ - La 2 : http://www.rtve.es/television/la-2-directo/ - TDP : http://www.rtve.es/deportes/directo/teledeporte/ - 24H : http://www.rtve.es/noticias/mas-24/ 24H is not geoblocked.
0.0
8b710ba7f642e0906413157e60e602ce41cfe1cf
[ "tests/test_plugin_canalplus.py::TestPluginCanalPlus::test_can_handle_url" ]
[]
{ "failed_lite_validators": [ "has_hyperlinks", "has_added_files", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2017-01-13 13:58:04+00:00
bsd-2-clause
5,794
streamlink__streamlink-469
diff --git a/docs/plugin_matrix.rst b/docs/plugin_matrix.rst index e75e8d05..1555f7f3 100644 --- a/docs/plugin_matrix.rst +++ b/docs/plugin_matrix.rst @@ -135,6 +135,8 @@ streamupcom streamup.com Yes -- svtplay - svtplay.se Yes Yes Streams may be geo-restricted to Sweden. - svtflow.se - oppetarkiv.se +swisstxt - srf.ch Yes No Streams are geo-restricted to Switzerland. + - rsi.ch tf1 - tf1.fr Yes No Streams may be geo-restricted to France. - lci.fr tga - star.plu.cn Yes No diff --git a/src/streamlink/compat.py b/src/streamlink/compat.py index b5d54136..bf2df266 100644 --- a/src/streamlink/compat.py +++ b/src/streamlink/compat.py @@ -21,14 +21,15 @@ elif is_py3: try: from urllib.parse import ( - urlparse, urlunparse, urljoin, quote, unquote, parse_qsl + urlparse, urlunparse, urljoin, quote, unquote, parse_qsl, urlencode ) import queue except ImportError: from urlparse import urlparse, urlunparse, urljoin, parse_qsl - from urllib import quote, unquote + from urllib import quote, unquote, urlencode import Queue as queue + __all__ = ["is_py2", "is_py3", "is_py33", "is_win32", "str", "bytes", "urlparse", "urlunparse", "urljoin", "parse_qsl", "quote", - "unquote", "queue", "range"] + "unquote", "queue", "range", "urlencode"] diff --git a/src/streamlink/plugins/srgssr.py b/src/streamlink/plugins/srgssr.py index 4f160501..3444492d 100644 --- a/src/streamlink/plugins/srgssr.py +++ b/src/streamlink/plugins/srgssr.py @@ -1,32 +1,46 @@ from __future__ import print_function + import re +from streamlink.compat import urlparse, parse_qsl from streamlink.plugin import Plugin from streamlink.plugin.api import http from streamlink.plugin.api import validate -from streamlink.stream import HDSStream from streamlink.stream import HLSStream -from streamlink.compat import urlparse, parse_qsl class SRGSSR(Plugin): - url_re = re.compile(r"https?://(?:www\.)?(srf|rts|rsi|rtr)\.ch/play/tv") + url_re = re.compile(r"""https?://(?:www\.)? + (srf|rts|rsi|rtr)\.ch/ + (?: + play/tv| + livestream/player| + live-streaming| + sport/direct/(\d+)- + )""", re.VERBOSE) api_url = "http://il.srgssr.ch/integrationlayer/1.0/ue/{site}/video/play/{id}.json" - video_id_re = re.compile(r'urn:(srf|rts|rsi|rtr):(?:ais:)?video:([^&"]+)') + token_url = "http://tp.srgssr.ch/akahd/token" + video_id_re = re.compile(r'urn(?:%3A|:)(srf|rts|rsi|rtr)(?:%3A|:)(?:ais(?:%3A|:))?video(?:%3A|:)([^&"]+)') video_id_schema = validate.Schema(validate.transform(video_id_re.search)) api_schema = validate.Schema( - {"Video": - {"Playlists": - {"Playlist": [{ - "@protocol": validate.text, - "url": [{"@quality": validate.text, "text": validate.url()}] - }] + { + "Video": + { + "Playlists": + { + "Playlist": [{ + "@protocol": validate.text, + "url": [{"@quality": validate.text, "text": validate.url()}] + }] + } } - } }, validate.get("Video"), validate.get("Playlists"), validate.get("Playlist")) + token_schema = validate.Schema({"token": {"authparams": validate.text}}, + validate.get("token"), + validate.get("authparams")) @classmethod def can_handle_url(cls, url): @@ -37,11 +51,14 @@ class SRGSSR(Plugin): qinfo = dict(parse_qsl(parsed.query or parsed.fragment.lstrip("?"))) site, video_id = None, None + url_m = self.url_re.match(self.url) # look for the video id in the URL, otherwise find it in the page if "tvLiveId" in qinfo: video_id = qinfo["tvLiveId"] - site = self.url_re.match(self.url).group(1) + site = url_m.group(1) + elif url_m.group(2): + site, video_id = url_m.group(1), url_m.group(2) else: video_id_m = http.get(self.url, schema=self.video_id_schema) if video_id_m: @@ -49,8 +66,16 @@ class SRGSSR(Plugin): return site, video_id + def get_authparams(self, url): + parsed = urlparse(url) + path, _ = parsed.path.rsplit("/", 1) + token_res = http.get(self.token_url, params=dict(acl=path + "/*")) + authparams = http.json(token_res, schema=self.token_schema) + self.logger.debug("Found authparams: {0}", authparams) + return dict(parse_qsl(authparams)) + def _get_streams(self): - video_id, site = self.get_video_id() + site, video_id = self.get_video_id() if video_id and site: self.logger.debug("Found {0} video ID {1}", site, video_id) @@ -59,11 +84,9 @@ class SRGSSR(Plugin): for stream_info in http.json(res, schema=self.api_schema): for url in stream_info["url"]: - if stream_info["@protocol"] == "HTTP-HDS": - for s in HDSStream.parse_manifest(self.session, url["text"]).items(): - yield s if stream_info["@protocol"] == "HTTP-HLS": - for s in HLSStream.parse_variant_playlist(self.session, url["text"]).items(): + params = self.get_authparams(url["text"]) + for s in HLSStream.parse_variant_playlist(self.session, url["text"], params=params).items(): yield s diff --git a/src/streamlink/plugins/swisstxt.py b/src/streamlink/plugins/swisstxt.py new file mode 100644 index 00000000..cacf8c0b --- /dev/null +++ b/src/streamlink/plugins/swisstxt.py @@ -0,0 +1,45 @@ +from __future__ import print_function + +import re + +from streamlink.compat import urlparse, parse_qsl, urlunparse +from streamlink.plugin import Plugin +from streamlink.plugin.api import http +from streamlink.stream import HLSStream + + +class Swisstxt(Plugin): + url_re = re.compile(r"""https?://(?: + live\.(rsi)\.ch/| + (?:www\.)?(srf)\.ch/sport/resultcenter + )""", re.VERBOSE) + api_url = "http://event.api.swisstxt.ch/v1/stream/{site}/byEventItemIdAndType/{id}/HLS" + + @classmethod + def can_handle_url(cls, url): + return cls.url_re.match(url) is not None and cls.get_event_id(url) + + @classmethod + def get_event_id(cls, url): + return dict(parse_qsl(urlparse(url).query.lower())).get("eventid") + + def get_stream_url(self, event_id): + url_m = self.url_re.match(self.url) + site = url_m.group(1) or url_m.group(2) + api_url = self.api_url.format(id=event_id, site=site.upper()) + self.logger.debug("Calling API: {0}", api_url) + + stream_url = http.get(api_url).text.strip("\"'") + + parsed = urlparse(stream_url) + query = dict(parse_qsl(parsed.query)) + return urlunparse(parsed._replace(query="")), query + + def _get_streams(self): + stream_url, params = self.get_stream_url(self.get_event_id(self.url)) + return HLSStream.parse_variant_playlist(self.session, + stream_url, + params=params) + + +__plugin__ = Swisstxt
streamlink/streamlink
26bcb3039183081bcbef1c3fa7ac0badc6206a22
diff --git a/tests/test_plugin_srgssr.py b/tests/test_plugin_srgssr.py index 3e5d5fc5..53d90488 100644 --- a/tests/test_plugin_srgssr.py +++ b/tests/test_plugin_srgssr.py @@ -3,7 +3,7 @@ import unittest from streamlink.plugins.srgssr import SRGSSR -class TestPluginCrunchyroll(unittest.TestCase): +class TestPluginSRGSSR(unittest.TestCase): def test_can_handle_url(self): # should match self.assertTrue(SRGSSR.can_handle_url("http://srf.ch/play/tv/live")) @@ -13,6 +13,8 @@ class TestPluginCrunchyroll(unittest.TestCase): self.assertTrue(SRGSSR.can_handle_url("http://rtr.ch/play/tv/live")) self.assertTrue(SRGSSR.can_handle_url("http://rts.ch/play/tv/direct#?tvLiveId=3608506")) self.assertTrue(SRGSSR.can_handle_url("http://www.srf.ch/play/tv/live#?tvLiveId=c49c1d64-9f60-0001-1c36-43c288c01a10")) + self.assertTrue(SRGSSR.can_handle_url("http://www.rts.ch/sport/direct/8328501-tennis-open-daustralie.html")) + self.assertTrue(SRGSSR.can_handle_url("http://www.rts.ch/play/tv/tennis/video/tennis-open-daustralie?id=8328501")) # shouldn't match self.assertFalse(SRGSSR.can_handle_url("http://www.crunchyroll.com/gintama")) diff --git a/tests/test_plugin_swisstxt.py b/tests/test_plugin_swisstxt.py new file mode 100644 index 00000000..c394541c --- /dev/null +++ b/tests/test_plugin_swisstxt.py @@ -0,0 +1,28 @@ +import unittest + +from streamlink.plugins.swisstxt import Swisstxt + + +class TestPluginSwisstxt(unittest.TestCase): + def test_can_handle_url(self): + # should match + self.assertTrue(Swisstxt.can_handle_url("http://www.srf.ch/sport/resultcenter/tennis?eventId=338052")) + self.assertTrue(Swisstxt.can_handle_url("http://live.rsi.ch/tennis.html?eventId=338052")) + self.assertTrue(Swisstxt.can_handle_url("http://live.rsi.ch/sport.html?eventId=12345")) + + # shouldn't match + # regular srgssr sites + self.assertFalse(Swisstxt.can_handle_url("http://srf.ch/play/tv/live")) + self.assertFalse(Swisstxt.can_handle_url("http://www.rsi.ch/play/tv/live#?tvLiveId=livestream_La1")) + self.assertFalse(Swisstxt.can_handle_url("http://rsi.ch/play/tv/live?tvLiveId=livestream_La1")) + self.assertFalse(Swisstxt.can_handle_url("http://www.rtr.ch/play/tv/live")) + self.assertFalse(Swisstxt.can_handle_url("http://rtr.ch/play/tv/live")) + self.assertFalse(Swisstxt.can_handle_url("http://rts.ch/play/tv/direct#?tvLiveId=3608506")) + self.assertFalse(Swisstxt.can_handle_url("http://www.srf.ch/play/tv/live#?tvLiveId=c49c1d64-9f60-0001-1c36-43c288c01a10")) + self.assertFalse(Swisstxt.can_handle_url("http://www.rts.ch/sport/direct/8328501-tennis-open-daustralie.html")) + self.assertFalse(Swisstxt.can_handle_url("http://www.rts.ch/play/tv/tennis/video/tennis-open-daustralie?id=8328501")) + + # other sites + self.assertFalse(Swisstxt.can_handle_url("http://www.crunchyroll.com/gintama")) + self.assertFalse(Swisstxt.can_handle_url("http://www.crunchyroll.es/gintama")) + self.assertFalse(Swisstxt.can_handle_url("http://www.youtube.com/"))
SRG SSR plugin Hello Another challenge for beardypig. ;) Swiss public TV includes channels in : - German : SRF 1, SRF 2, SRF Info : `http://www.srf.ch/play/tv/live` - French : RTS Un, RTS Deux, RTS Info : `http://www.rts.ch/play/tv/direct` - Italian : RSI La 1, RSI La 2 : `http://www.rsi.ch/play/tv/live` Sometimes they air live sports events exclusively online on their website. Channels are of course geoblocked to CH but it can be resolved with proxy. Example address source for RTS Un can be found here : `http://il.srgssr.ch/integrationlayer/1.0/ue/rts/video/play/3608506.json` They propose HDS and HLS.
0.0
26bcb3039183081bcbef1c3fa7ac0badc6206a22
[ "tests/test_plugin_srgssr.py::TestPluginSRGSSR::test_can_handle_url", "tests/test_plugin_swisstxt.py::TestPluginSwisstxt::test_can_handle_url" ]
[]
{ "failed_lite_validators": [ "has_hyperlinks", "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2017-01-23 17:27:35+00:00
bsd-2-clause
5,795
streamlink__streamlink-724
diff --git a/src/streamlink/plugins/bigo.py b/src/streamlink/plugins/bigo.py index 98101c78..365d38cd 100644 --- a/src/streamlink/plugins/bigo.py +++ b/src/streamlink/plugins/bigo.py @@ -47,7 +47,7 @@ class BigoStream(Stream): class Bigo(Plugin): - _url_re = re.compile(r"https?://(live.bigo.tv/\d+|bigoweb.co/show/\d+)") + _url_re = re.compile(r"https?://(?:www\.)?(bigo\.tv/\d+|bigoweb\.co/show/\d+)") _flashvars_re = flashvars = re.compile( r'''^\s*(?<!<!--)<param.*value="tmp=(\d+)&channel=(\d+)&srv=(\d+\.\d+\.\d+\.\d+)&port=(\d+)"''', re.M)
streamlink/streamlink
951edb3ef8127598ec518e5ebab7dedf5e00f68c
diff --git a/tests/test_plugin_bigo.py b/tests/test_plugin_bigo.py new file mode 100644 index 00000000..99bd4e17 --- /dev/null +++ b/tests/test_plugin_bigo.py @@ -0,0 +1,31 @@ +import unittest + +from streamlink.plugins.bigo import Bigo + + +class TestPluginBongacams(unittest.TestCase): + def test_can_handle_url(self): + # Correct urls + self.assertTrue(Bigo.can_handle_url("http://www.bigoweb.co/show/00000000")) + self.assertTrue(Bigo.can_handle_url("https://www.bigoweb.co/show/00000000")) + self.assertTrue(Bigo.can_handle_url("http://bigoweb.co/show/00000000")) + self.assertTrue(Bigo.can_handle_url("https://bigoweb.co/show/00000000")) + self.assertTrue(Bigo.can_handle_url("http://bigo.tv/00000000")) + self.assertTrue(Bigo.can_handle_url("https://bigo.tv/00000000")) + self.assertTrue(Bigo.can_handle_url("https://www.bigo.tv/00000000")) + self.assertTrue(Bigo.can_handle_url("http://www.bigo.tv/00000000")) + + # Old URLs don't work anymore + self.assertFalse(Bigo.can_handle_url("http://live.bigo.tv/00000000")) + self.assertFalse(Bigo.can_handle_url("https://live.bigo.tv/00000000")) + + # Wrong URL structure + self.assertFalse(Bigo.can_handle_url("ftp://www.bigo.tv/00000000")) + self.assertFalse(Bigo.can_handle_url("https://www.bigo.tv/show/00000000")) + self.assertFalse(Bigo.can_handle_url("http://www.bigo.tv/show/00000000")) + self.assertFalse(Bigo.can_handle_url("http://bigo.tv/show/00000000")) + self.assertFalse(Bigo.can_handle_url("https://bigo.tv/show/00000000")) + + +if __name__ == "__main__": + unittest.main()
bigoweb.co / bigolive.tv plugin no longer works ---- ### Checklist - [x] This is a bug report. - [ ] This is a plugin request. - [ ] This is a feature request. - [ ] I used the search function to find already opened/closed issues or pull requests. ### Description error: No plugin can handle bigoweb.co addressess as of 10 minutes ago ### Expected / Actual behavior 10 minutes ago it worked fine and now it gives an error. ... ### Reproduction steps / Stream URLs to test 1. ...http://www.bigoweb.co/ (any stream) 2. ... 3. ... ### Environment details (operating system, python version, etc.) ... ### Comments, logs, screenshots, etc. ...
0.0
951edb3ef8127598ec518e5ebab7dedf5e00f68c
[ "tests/test_plugin_bigo.py::TestPluginBongacams::test_can_handle_url" ]
[]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2017-03-21 09:08:18+00:00
bsd-2-clause
5,796
streamlink__streamlink-726
diff --git a/docs/plugin_matrix.rst b/docs/plugin_matrix.rst index 084239b3..4693f248 100644 --- a/docs/plugin_matrix.rst +++ b/docs/plugin_matrix.rst @@ -92,6 +92,7 @@ foxtr fox.com.tr Yes No funimationnow - funimation.com -- Yes - funimationnow.uk furstream furstre.am Yes No +garena garena.live Yes -- gomexp gomexp.com Yes No goodgame goodgame.ru Yes No Only HLS streams are available. gulli replay.gulli.fr Yes Yes Streams may be geo-restricted to France. diff --git a/src/streamlink/plugins/garena.py b/src/streamlink/plugins/garena.py new file mode 100644 index 00000000..8349ebc7 --- /dev/null +++ b/src/streamlink/plugins/garena.py @@ -0,0 +1,69 @@ +import re + +from streamlink.plugin import Plugin +from streamlink.plugin.api import http +from streamlink.plugin.api import validate +from streamlink.stream import HLSStream + +_url_re = re.compile(r"https?\:\/\/garena\.live\/(?:(?P<channel_id>\d+)|(?P<alias>\w+))") + + +class Garena(Plugin): + API_INFO = "https://garena.live/api/channel_info_get" + API_STREAM = "https://garena.live/api/channel_stream_get" + + _info_schema = validate.Schema( + { + "reply": validate.any({ + "channel_id": int, + }, None), + "result": validate.text + } + ) + _stream_schema = validate.Schema( + { + "reply": validate.any({ + "streams": [ + { + "url": validate.text, + "resolution": int, + "bitrate": int, + "format": int + } + ] + }, None), + "result": validate.text + } + ) + + @classmethod + def can_handle_url(self, url): + return _url_re.match(url) + + def _post_api(self, api, payload, schema): + res = http.post(api, json=payload) + data = http.json(res, schema=schema) + + if data["result"] == "success": + post_data = data["reply"] + return post_data + + def _get_streams(self): + match = _url_re.match(self.url) + if match.group("alias"): + payload = {"alias": match.group("alias")} + info_data = self._post_api(self.API_INFO, payload, self._info_schema) + channel_id = info_data["channel_id"] + elif match.group("channel_id"): + channel_id = int(match.group("channel_id")) + + if channel_id: + payload = {"channel_id": channel_id} + stream_data = self._post_api(self.API_STREAM, payload, self._stream_schema) + for stream in stream_data["streams"]: + n = "{0}p".format(stream["resolution"]) + if stream["format"] == 3: + s = HLSStream(self.session, stream["url"]) + yield n, s + +__plugin__ = Garena diff --git a/src/streamlink/utils/l10n.py b/src/streamlink/utils/l10n.py index 1791446b..461fbecc 100644 --- a/src/streamlink/utils/l10n.py +++ b/src/streamlink/utils/l10n.py @@ -12,7 +12,9 @@ except ImportError: # pragma: no cover PYCOUNTRY = True -DEFAULT_LANGUAGE_CODE = "en_US" +DEFAULT_LANGUAGE = "en" +DEFAULT_COUNTRY = "US" +DEFAULT_LANGUAGE_CODE = "{0}_{1}".format(DEFAULT_LANGUAGE, DEFAULT_COUNTRY) class Country(object): @@ -116,8 +118,15 @@ class Localization(object): def language_code(self): return self._language_code + def _parse_locale_code(self, language_code): + parts = language_code.split("_", 1) + if len(parts) != 2 or len(parts[0]) != 2 or len(parts[1]) != 2: + raise LookupError("Invalid language code: {0}".format(language_code)) + return self.get_language(parts[0]), self.get_country(parts[1]) + @language_code.setter def language_code(self, language_code): + is_system_locale = language_code is None if language_code is None: try: language_code, _ = locale.getdefaultlocale() @@ -125,16 +134,19 @@ class Localization(object): language_code = None if language_code is None or language_code == "C": # cannot be determined - language_code = DEFAULT_LANGUAGE_CODE - - parts = language_code.split("_", 1) + language_code = DEFAULT_LANGUAGE - if len(parts) != 2 or len(parts[0]) != 2 or len(parts[1]) != 2: - raise LookupError("Invalid language code: {0}".format(language_code)) - - self._language_code = language_code - self.language = self.get_language(parts[0]) - self.country = self.get_country(parts[1]) + try: + self.language, self.country = self._parse_locale_code(language_code) + self._language_code = language_code + except LookupError: + if is_system_locale: + # If the system locale returns an invalid code, use the default + self.language = self.get_language(DEFAULT_LANGUAGE) + self.country = self.get_country(DEFAULT_COUNTRY) + self._language_code = DEFAULT_LANGUAGE_CODE + else: + raise def equivalent(self, language=None, country=None): equivalent = True
streamlink/streamlink
8ba8044528b4b6e75899776e696e14f1a9f1af36
diff --git a/tests/test_localization.py b/tests/test_localization.py index 102a6472..4a17da9c 100644 --- a/tests/test_localization.py +++ b/tests/test_localization.py @@ -63,6 +63,13 @@ class LocalizationTestsMixin(object): self.assertEqual("en_US", l.language_code) self.assertTrue(l.equivalent(language="en", country="US")) + @patch("locale.getdefaultlocale") + def test_default_invalid(self, getdefaultlocale): + getdefaultlocale.return_value = ("en_150", None) + l = l10n.Localization() + self.assertEqual("en_US", l.language_code) + self.assertTrue(l.equivalent(language="en", country="US")) + def test_get_country(self): self.assertEqual("US", l10n.Localization.get_country("USA").alpha2) diff --git a/tests/test_plugin_garena.py b/tests/test_plugin_garena.py new file mode 100644 index 00000000..05b82d2a --- /dev/null +++ b/tests/test_plugin_garena.py @@ -0,0 +1,86 @@ +import json +import unittest + +from streamlink import Streamlink + +try: + from unittest.mock import patch, Mock +except ImportError: + from mock import patch, Mock + +from streamlink.plugins.garena import Garena + + +class TestPluginGarena(unittest.TestCase): + def setUp(self): + self.session = Streamlink() + + def test_can_handle_url(self): + # should match + self.assertTrue(Garena.can_handle_url("https://garena.live/LOLTW")) + self.assertTrue(Garena.can_handle_url("https://garena.live/358220")) + + # shouldn't match + self.assertFalse(Garena.can_handle_url("http://local.local/")) + self.assertFalse(Garena.can_handle_url("http://localhost.localhost/")) + + @patch('streamlink.plugins.garena.http') + def test_post_api_info(self, mock_http): + API_INFO = Garena.API_INFO + schema = Garena._info_schema + + api_data = { + "reply": { + "channel_id": 358220, + }, + "result": "success" + } + + api_resp = Mock() + api_resp.text = json.dumps(api_data) + mock_http.post.return_value = api_resp + mock_http.json.return_value = api_data + + payload = {"alias": "LOLTW"} + + plugin = Garena("https://garena.live/LOLTW") + + info_data = plugin._post_api(API_INFO, payload, schema) + + self.assertEqual(info_data["channel_id"], 358220) + + mock_http.post.assert_called_with(API_INFO, json=dict(alias="LOLTW")) + + @patch('streamlink.plugins.garena.http') + def test_post_api_stream(self, mock_http): + API_STREAM = Garena.API_STREAM + schema = Garena._stream_schema + + api_data = { + "reply": { + "streams": [ + { + "url": "https://test.se/stream1", + "bitrate": 0, + "resolution": 1080, + "format": 3 + }, + ] + }, + "result": "success" + } + + api_resp = Mock() + api_resp.text = json.dumps(api_data) + mock_http.post.return_value = api_resp + mock_http.json.return_value = api_data + + payload = {"channel_id": 358220} + + plugin = Garena("https://garena.live/358220") + + stream_data = plugin._post_api(API_STREAM, payload, schema) + + self.assertEqual(stream_data["streams"], api_data["reply"]["streams"]) + + mock_http.post.assert_called_with(API_STREAM, json=dict(channel_id=358220))
Plugin request: https://garena.live ### Checklist - [ ] This is a bug report. - [x] This is a plugin request. - [ ] This is a feature request. - [ ] I used the search function to find already opened/closed issues or pull requests. ### Description Ability to grab livestreams from https://garena.live
0.0
8ba8044528b4b6e75899776e696e14f1a9f1af36
[ "tests/test_localization.py::TestLocalization::test_bad_language_code", "tests/test_localization.py::TestLocalization::test_country_compare", "tests/test_localization.py::TestLocalization::test_default", "tests/test_localization.py::TestLocalization::test_default_invalid", "tests/test_localization.py::TestLocalization::test_equivalent_remap", "tests/test_localization.py::TestLocalization::test_get_country_miss", "tests/test_localization.py::TestLocalization::test_get_language", "tests/test_localization.py::TestLocalization::test_get_language_miss", "tests/test_localization.py::TestLocalization::test_language_code_kr", "tests/test_localization.py::TestLocalization::test_language_code_us", "tests/test_localization.py::TestLocalization::test_language_compare", "tests/test_localization.py::TestLocalization::test_not_equivalent", "tests/test_localization.py::TestLocalization::test_pycountry", "tests/test_plugin_garena.py::TestPluginGarena::test_can_handle_url", "tests/test_plugin_garena.py::TestPluginGarena::test_post_api_info", "tests/test_plugin_garena.py::TestPluginGarena::test_post_api_stream" ]
[]
{ "failed_lite_validators": [ "has_hyperlinks", "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2017-03-21 16:36:43+00:00
bsd-2-clause
5,797
streamlink__streamlink-785
diff --git a/docs/plugin_matrix.rst b/docs/plugin_matrix.rst index fc9e7792..6efe7ef9 100644 --- a/docs/plugin_matrix.rst +++ b/docs/plugin_matrix.rst @@ -134,6 +134,7 @@ openrectv openrec.tv Yes Yes orf_tvthek tvthek.orf.at Yes Yes ovvatv ovva.tv Yes No pandatv panda.tv Yes ? +pcyourfreetv pc-yourfreetv.com Yes -- Requires a login. periscope periscope.tv Yes Yes Replay/VOD is supported. picarto picarto.tv Yes -- playtv playtv.fr Yes -- Streams may be geo-restricted to France. diff --git a/src/streamlink/plugins/pcyourfreetv.py b/src/streamlink/plugins/pcyourfreetv.py new file mode 100644 index 00000000..912a31c8 --- /dev/null +++ b/src/streamlink/plugins/pcyourfreetv.py @@ -0,0 +1,62 @@ +import re + +from streamlink.plugin import Plugin, PluginOptions +from streamlink.plugin.api import http +from streamlink.stream import HLSStream + + +class PCYourFreeTV(Plugin): + _login_url = 'http://pc-yourfreetv.com/home.php' + _url_re = re.compile(r'http://pc-yourfreetv\.com/index_player\.php\?channel=.+?&page_id=\d+') + _video_url_re = re.compile(r"jwplayer\('.+?'\)\.setup\({.+?file: \"(?P<video_url>[^\"]+?)\".+?}\);", re.DOTALL) + + options = PluginOptions({ + 'username': None, + 'password': None + }) + + @classmethod + def can_handle_url(cls, url): + return PCYourFreeTV._url_re.match(url) + + def login(self, username, password): + res = http.post( + self._login_url, + data={ + 'user_name': username, + 'user_pass': password, + 'login': 'Login' + } + ) + + return username in res.text + + def _get_streams(self): + username = self.get_option('username') + password = self.get_option('password') + + if username is None or password is None: + self.logger.error("PC-YourFreeTV requires authentication, use --pcyourfreetv-username" + "and --pcyourfreetv-password to set your username/password combination") + return + + if self.login(username, password): + self.logger.info("Successfully logged in as {0}", username) + + # Retrieve URL page and search for stream data + res = http.get(self.url) + match = self._video_url_re.search(res.text) + if match is None: + return + video_url = match.group('video_url') + if '.m3u8' in video_url: + streams = HLSStream.parse_variant_playlist(self.session, video_url) + if len(streams) != 0: + for stream in streams.items(): + yield stream + else: + # Not a HLS playlist + yield 'live', HLSStream(self.session, video_url) + + +__plugin__ = PCYourFreeTV diff --git a/src/streamlink/plugins/twitch.py b/src/streamlink/plugins/twitch.py index 47cc583a..80440d22 100644 --- a/src/streamlink/plugins/twitch.py +++ b/src/streamlink/plugins/twitch.py @@ -247,7 +247,7 @@ class TwitchAPI(object): return self.call_subdomain("tmi", "/hosts", format="", **params) def clip_status(self, channel, clip_name, schema): - return http.json(self.call_subdomain("clips", "/api/v1/clips/" + channel + "/" + clip_name + "/status", format=""), schema=schema) + return http.json(self.call_subdomain("clips", "/api/v2/clips/" + clip_name + "/status", format=""), schema=schema) # Unsupported/Removed private API calls @@ -282,19 +282,36 @@ class Twitch(Plugin): def __init__(self, url): Plugin.__init__(self, url) - match = _url_re.match(url).groupdict() - self._channel = match.get("channel") and match.get("channel").lower() - self._channel_id = None - self.subdomain = match.get("subdomain") - self.video_type = match.get("video_type") - if match.get("videos_id"): - self.video_type = "v" - self.video_id = match.get("video_id") or match.get("videos_id") - self.clip_name = match.get("clip_name") self._hosted_chain = [] - + match = _url_re.match(url).groupdict() parsed = urlparse(url) self.params = parse_query(parsed.query) + self.subdomain = match.get("subdomain") + self.video_id = None + self.video_type = None + self._channel_id = None + self._channel = None + self.clip_name = None + + if self.subdomain == "player": + # pop-out player + if self.params.get("video"): + try: + self.video_type = self.params["video"][0] + self.video_id = self.params["video"][1:] + except IndexError: + self.logger.debug("Invalid video param: {0}", self.params["video"]) + self._channel = self.params.get("channel") + elif self.subdomain == "clips": + # clip share URL + self.clip_name = match.get("channel") + else: + self._channel = match.get("channel") and match.get("channel").lower() + self.video_type = match.get("video_type") + if match.get("videos_id"): + self.video_type = "v" + self.video_id = match.get("video_id") or match.get("videos_id") + self.clip_name = match.get("clip_name") self.api = TwitchAPI(beta=self.subdomain == "beta", version=5) self.usher = UsherService() @@ -596,7 +613,7 @@ class Twitch(Plugin): return self._get_video_streams() elif self.clip_name: return self._get_clips() - else: + elif self._channel: return self._get_hls_streams("live") diff --git a/src/streamlink_cli/argparser.py b/src/streamlink_cli/argparser.py index 49e4eafd..c9b57e7d 100644 --- a/src/streamlink_cli/argparser.py +++ b/src/streamlink_cli/argparser.py @@ -1204,6 +1204,20 @@ plugin.add_argument( A LiveEdu account password to use with --liveedu-email. """ ) +plugin.add_argument( + "--pcyourfreetv-username", + metavar="USERNAME", + help=""" + The username used to register with pc-yourfreetv.com. + """ +) +plugin.add_argument( + "--pcyourfreetv-password", + metavar="PASSWORD", + help=""" + A pc-yourfreetv.com account password to use with --pcyourfreetv-username. + """ +) # Deprecated options stream.add_argument( diff --git a/src/streamlink_cli/main.py b/src/streamlink_cli/main.py index dffbfc23..c1b1997d 100644 --- a/src/streamlink_cli/main.py +++ b/src/streamlink_cli/main.py @@ -244,14 +244,17 @@ def output_stream(stream): """Open stream, create output and finally write the stream to output.""" global output + success_open = False for i in range(args.retry_open): try: stream_fd, prebuffer = open_stream(stream) + success_open = True break except StreamError as err: - console.logger.error("{0}", err) - else: - return + console.logger.error("Try {0}/{1}: Could not open stream {2} ({3})", i+1, args.retry_open, stream, err) + + if not success_open: + console.exit("Could not open stream {0}, tried {1} times, exiting", stream, args.retry_open) output = create_output() @@ -307,14 +310,14 @@ def read_stream(stream, output, prebuffer, chunk_size=8192): elif is_http and err.errno in ACCEPTABLE_ERRNO: console.logger.info("HTTP connection closed") else: - console.logger.error("Error when writing to output: {0}", err) + console.exit("Error when writing to output: {0}, exiting", err) break except IOError as err: - console.logger.error("Error when reading from stream: {0}", err) - - stream.close() - console.logger.info("Stream ended") + console.exit("Error when reading from stream: {0}, exiting", err) + finally: + stream.close() + console.logger.info("Stream ended") def handle_stream(plugin, streams, stream_name): @@ -913,6 +916,17 @@ def setup_plugin_options(): if liveedu_password: streamlink.set_plugin_option("liveedu", "password", liveedu_password) + if args.pcyourfreetv_username: + streamlink.set_plugin_option("pcyourfreetv", "username", args.pcyourfreetv_username) + + if args.pcyourfreetv_username and not args.pcyourfreetv_password: + pcyourfreetv_password = console.askpass("Enter pc-yourfreetv.com password: ") + else: + pcyourfreetv_password = args.pcyourfreetv_password + + if pcyourfreetv_password: + streamlink.set_plugin_option("pcyourfreetv", "password", pcyourfreetv_password) + # Deprecated options if args.jtv_legacy_names: console.logger.warning("The option --jtv/twitch-legacy-names is "
streamlink/streamlink
4ecde12286104f05003258b8dbab782d2f7d1ed5
diff --git a/tests/test_plugin_pcyourfreetv.py b/tests/test_plugin_pcyourfreetv.py new file mode 100644 index 00000000..d1ee96dc --- /dev/null +++ b/tests/test_plugin_pcyourfreetv.py @@ -0,0 +1,18 @@ +import unittest + +from streamlink.plugins.pcyourfreetv import PCYourFreeTV + + +class TestPluginPCYourFreeTV(unittest.TestCase): + def test_can_handle_url(self): + # should match + self.assertTrue(PCYourFreeTV.can_handle_url("http://pc-yourfreetv.com/index_player.php?channel=das%20erste&page_id=41")) + self.assertTrue(PCYourFreeTV.can_handle_url("http://pc-yourfreetv.com/index_player.php?channel=srf%20eins&page_id=41")) + self.assertTrue(PCYourFreeTV.can_handle_url("http://pc-yourfreetv.com/index_player.php?channel=bbc%20one&page_id=41")) + self.assertTrue(PCYourFreeTV.can_handle_url("http://pc-yourfreetv.com/index_player.php?channel=tf1&page_id=41")) + + # shouldn't match + self.assertFalse(PCYourFreeTV.can_handle_url("http://pc-yourfreetv.com/home.php")) + self.assertFalse(PCYourFreeTV.can_handle_url("http://pc-yourfreetv.com/index_livetv.php?page_id=1")) + self.assertFalse(PCYourFreeTV.can_handle_url("http://tvcatchup.com/")) + self.assertFalse(PCYourFreeTV.can_handle_url("http://youtube.com/"))
[cli][error] Could not open stream doesn't exit with code 1, but with 0 ### Checklist - [x] This is a bug report. - [ ] This is a plugin request. - [ ] This is a feature request. - [x] I used the search function to find already opened/closed issues or pull requests. ### Description When streamlink finds a stream, but can not (for whatever reason) open it, the exit code is 0 (success) and not 1 (error). ### Expected / Actual behavior streamlink should exit with exit code 1 (error). ### Reproduction steps / Stream URLs to test 1. streamlink streamurl best 2. wait for it to open the stream 3. wait for error that it can not open the stream 4. wait for it to exit 5. echo $? 0 ### Environment details (operating system, python version, etc.) Linux, Python 3.6 ### Comments, logs, screenshots, etc. ```bash # streamlink hlsvariant://example/*.m3u8 best [cli][info] Found matching plugin stream for URL hlsvariant://example/*.m3u8 [cli][info] Available streams: 240p (worst), 480p (best) [cli][info] Opening stream: 480p (hls) [cli][error] Could not open stream: Unable to open URL: http://example/*.m3u8 (404 Client Error: Not Found for url: http://example/*.m3u8) ``` ```bash # echo $? 0 ```
0.0
4ecde12286104f05003258b8dbab782d2f7d1ed5
[ "tests/test_plugin_pcyourfreetv.py::TestPluginPCYourFreeTV::test_can_handle_url" ]
[]
{ "failed_lite_validators": [ "has_hyperlinks", "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2017-04-11 12:47:07+00:00
bsd-2-clause
5,798
streamlink__streamlink-853
diff --git a/docs/plugin_matrix.rst b/docs/plugin_matrix.rst index 143f7f09..52c5f43f 100644 --- a/docs/plugin_matrix.rst +++ b/docs/plugin_matrix.rst @@ -95,6 +95,7 @@ earthcam earthcam.com Yes Yes Only works for the cams hos eurocom eurocom.bg Yes No euronews euronews.com Yes No expressen expressen.se Yes Yes +facebook facebook.com Yes No Only 360p HLS streams. filmon filmon.com Yes Yes Only SD quality streams. filmon_us filmon.us Yes Yes foxtr fox.com.tr Yes No diff --git a/src/streamlink/plugins/facebook.py b/src/streamlink/plugins/facebook.py new file mode 100644 index 00000000..ec1220d6 --- /dev/null +++ b/src/streamlink/plugins/facebook.py @@ -0,0 +1,24 @@ +import re + +from streamlink.plugin import Plugin +from streamlink.stream import HLSStream + +_playlist_url = "https://www.facebook.com/video/playback/playlist.m3u8?v={0}" + +_url_re = re.compile(r"http(s)?://(www\.)?facebook\.com/[^/]+/videos/(?P<video_id>\d+)") + + +class Facebook(Plugin): + @classmethod + def can_handle_url(cls, url): + return _url_re.match(url) + + def _get_streams(self): + match = _url_re.match(self.url) + video = match.group("video_id") + + playlist = _playlist_url.format(video) + + return HLSStream.parse_variant_playlist(self.session, playlist) + +__plugin__ = Facebook diff --git a/src/streamlink/plugins/pcyourfreetv.py b/src/streamlink/plugins/pcyourfreetv.py index 15dde489..968ac7d3 100644 --- a/src/streamlink/plugins/pcyourfreetv.py +++ b/src/streamlink/plugins/pcyourfreetv.py @@ -1,16 +1,18 @@ import re +from streamlink.compat import parse_qsl, unquote from streamlink.plugin import Plugin, PluginOptions from streamlink.plugin.api import http from streamlink.stream import HLSStream class PCYourFreeTV(Plugin): - LIVE_TV_URL = 'http://pc-yourfreetv.com/index_livetv.php?page_id=1' + LIVE_TV_URL = 'http://pc-yourfreetv.com/indexlivetv.php?page_id=1' _login_url = 'http://pc-yourfreetv.com/home.php' - _url_re = re.compile(r'http://pc-yourfreetv\.com/index_player\.php\?channel=.+?&page_id=\d+') - _token_re = re.compile(r'\b(?P<token_key>auth_[0-9a-f]+)=(?P<token_value>[0-9a-f]+)\b') + _url_re = re.compile(r'http://pc-yourfreetv\.com/indexplayer\.php\?channel=.+?&page_id=\d+') + _token_re = re.compile(r'\bsrc="indexplayer\.php\?channel=.+?&(?P<tokens>.+?)"') + _player_re = re.compile(r"<script language=JavaScript>m='(?P<player>.+?)'", re.DOTALL) _video_url_re = re.compile(r"jwplayer\('.+?'\)\.setup\({.+?file: \"(?P<video_url>[^\"]+?)\".+?}\);", re.DOTALL) options = PluginOptions({ @@ -51,14 +53,21 @@ class PCYourFreeTV(Plugin): match = self._token_re.search(res.text) if match is None: return - token_key = match.group('token_key') - token_value = match.group('token_value') # Retrieve URL page and search for stream data - res = http.get(self.url, params={token_key: token_value}) - match = self._video_url_re.search(res.text) + res = http.get(self.url, params=parse_qsl(match.group('tokens'))) + match = self._player_re.search(res.text) if match is None: return + + while match is not None: + player = unquote(match.group('player')) + match = self._player_re.search(player) + + match = self._video_url_re.search(player) + if match is None: + return + video_url = match.group('video_url') if '.m3u8' in video_url: streams = HLSStream.parse_variant_playlist(self.session, video_url) diff --git a/src/streamlink/plugins/showroom.py b/src/streamlink/plugins/showroom.py index 4618f07b..289e0074 100644 --- a/src/streamlink/plugins/showroom.py +++ b/src/streamlink/plugins/showroom.py @@ -2,7 +2,7 @@ import re from streamlink.plugin import Plugin -from streamlink.plugin.api import http, validate +from streamlink.plugin.api import http, validate, useragents from streamlink.stream import RTMPStream _url_re = re.compile(r'''^https?:// @@ -74,11 +74,6 @@ _info_pages = set(( class Showroom(Plugin): - @staticmethod - def _get_stream_info(room_id): - res = http.get(_api_data_url.format(room_id=room_id)) - return http.json(res, schema=_api_data_schema) - @classmethod def can_handle_url(cls, url): match = _url_re.match(url) @@ -95,6 +90,10 @@ class Showroom(Plugin): def __init__(self, url): Plugin.__init__(self, url) + self._headers = { + 'Referer': self.url, + 'User-Agent': useragents.FIREFOX + } self._room_id = None self._info = None self._title = None @@ -112,6 +111,10 @@ class Showroom(Plugin): self._room_id = self._get_room_id() return self._room_id + def _get_stream_info(self, room_id): + res = http.get(_api_data_url.format(room_id=room_id), headers=self._headers) + return http.json(res, schema=_api_data_schema) + def _get_room_id(self): """ Locates unique identifier ("room_id") for the room. @@ -123,7 +126,7 @@ class Showroom(Plugin): if match_dict['room_id'] is not None: return match_dict['room_id'] else: - res = http.get(self.url) + res = http.get(self.url, headers=self._headers) match = _room_id_re.search(res.text) if not match: title = self.url.rsplit('/', 1)[-1] diff --git a/src/streamlink/plugins/tvplayer.py b/src/streamlink/plugins/tvplayer.py index a7feeda7..13464272 100644 --- a/src/streamlink/plugins/tvplayer.py +++ b/src/streamlink/plugins/tvplayer.py @@ -8,25 +8,32 @@ from streamlink.stream import HLSStream class TVPlayer(Plugin): + context_url = "http://tvplayer.com/watch/context" api_url = "http://api.tvplayer.com/api/v2/stream/live" login_url = "https://tvplayer.com/account/login" update_url = "https://tvplayer.com/account/update-detail" dummy_postcode = "SE1 9LT" # location of ITV HQ in London url_re = re.compile(r"https?://(?:www.)?tvplayer.com/(:?watch/?|watch/(.+)?)") - stream_attrs_re = re.compile(r'var\s+(validate|platform|resourceId|token)\s+=\s*(.*?);', re.S) + stream_attrs_re = re.compile(r'data-(resource|token)\s*=\s*"(.*?)"', re.S) login_token_re = re.compile(r'input.*?name="token".*?value="(\w+)"') stream_schema = validate.Schema({ "tvplayer": validate.Schema({ "status": u'200 OK', "response": validate.Schema({ - "stream": validate.url(scheme=validate.any("http")), - validate.optional("drmToken"): validate.any(None, validate.text) - }) + "stream": validate.url(scheme=validate.any("http")), + validate.optional("drmToken"): validate.any(None, validate.text) }) - }, + }) + }, validate.get("tvplayer"), validate.get("response")) + context_schema = validate.Schema({ + "validate": validate.text, + "platform": { + "key": validate.text + } + }) options = PluginOptions({ "email": None, "password": None @@ -50,6 +57,21 @@ class TVPlayer(Plugin): # there is a 302 redirect on a successful login return res2.status_code == 302 + def _get_stream_data(self, resource, token, service=1): + # Get the context info (validation token and platform) + context_res = http.get(self.context_url, params={"resource": resource, + "nonce": token}) + context_data = http.json(context_res, schema=self.context_schema) + + # get the stream urls + res = http.post(self.api_url, data=dict( + service=service, + id=resource, + validate=context_data["validate"], + platform=context_data["platform"]["key"])) + + return http.json(res, schema=self.stream_schema) + def _get_streams(self): if self.get_option("email") and self.get_option("password"): self.authenticate(self.get_option("email"), self.get_option("password")) @@ -67,25 +89,19 @@ class TVPlayer(Plugin): stream_attrs = dict((k, v.strip('"')) for k, v in self.stream_attrs_re.findall(res.text)) - if "resourceId" in stream_attrs and "validate" in stream_attrs and "platform" in stream_attrs: - # get the stream urls - res = http.post(self.api_url, data=dict( - service=1, - id=stream_attrs["resourceId"], - validate=stream_attrs["validate"], - platform=stream_attrs["platform"], - token=stream_attrs.get("token"))) - - stream_data = http.json(res, schema=self.stream_schema) - - if stream_data.get("drmToken"): - self.logger.error("This stream is protected by DRM can cannot be played") - return - else: - return HLSStream.parse_variant_playlist(self.session, stream_data["stream"]) + if "resource" in stream_attrs and "token" in stream_attrs: + stream_data = self._get_stream_data(**stream_attrs) + + if stream_data: + if stream_data.get("drmToken"): + self.logger.error("This stream is protected by DRM can cannot be played") + return + else: + return HLSStream.parse_variant_playlist(self.session, stream_data["stream"]) else: if "need to login" in res.text: - self.logger.error("You need to login using --tvplayer-email/--tvplayer-password to view this stream") + self.logger.error( + "You need to login using --tvplayer-email/--tvplayer-password to view this stream") __plugin__ = TVPlayer
streamlink/streamlink
517d3613c192538fec43394d935ee6893fbe0ee5
diff --git a/tests/test_plugin_facebook.py b/tests/test_plugin_facebook.py new file mode 100644 index 00000000..b6b171a1 --- /dev/null +++ b/tests/test_plugin_facebook.py @@ -0,0 +1,14 @@ +import unittest + +from streamlink.plugins.facebook import Facebook + + +class TestPluginFacebook(unittest.TestCase): + def test_can_handle_url(self): + # should match + self.assertTrue(Facebook.can_handle_url("https://www.facebook.com/nos/videos/1725546430794241/")) + self.assertTrue(Facebook.can_handle_url("https://www.facebook.com/nytfood/videos/1485091228202006/")) + self.assertTrue(Facebook.can_handle_url("https://www.facebook.com/SporTurkTR/videos/798553173631138/")) + + # shouldn't match + self.assertFalse(Facebook.can_handle_url("https://www.facebook.com")) diff --git a/tests/test_plugin_pcyourfreetv.py b/tests/test_plugin_pcyourfreetv.py index d1ee96dc..f5664754 100644 --- a/tests/test_plugin_pcyourfreetv.py +++ b/tests/test_plugin_pcyourfreetv.py @@ -6,13 +6,13 @@ from streamlink.plugins.pcyourfreetv import PCYourFreeTV class TestPluginPCYourFreeTV(unittest.TestCase): def test_can_handle_url(self): # should match - self.assertTrue(PCYourFreeTV.can_handle_url("http://pc-yourfreetv.com/index_player.php?channel=das%20erste&page_id=41")) - self.assertTrue(PCYourFreeTV.can_handle_url("http://pc-yourfreetv.com/index_player.php?channel=srf%20eins&page_id=41")) - self.assertTrue(PCYourFreeTV.can_handle_url("http://pc-yourfreetv.com/index_player.php?channel=bbc%20one&page_id=41")) - self.assertTrue(PCYourFreeTV.can_handle_url("http://pc-yourfreetv.com/index_player.php?channel=tf1&page_id=41")) + self.assertTrue(PCYourFreeTV.can_handle_url("http://pc-yourfreetv.com/indexplayer.php?channel=das%20erste&page_id=41")) + self.assertTrue(PCYourFreeTV.can_handle_url("http://pc-yourfreetv.com/indexplayer.php?channel=srf%20eins&page_id=41")) + self.assertTrue(PCYourFreeTV.can_handle_url("http://pc-yourfreetv.com/indexplayer.php?channel=bbc%20one&page_id=41")) + self.assertTrue(PCYourFreeTV.can_handle_url("http://pc-yourfreetv.com/indexplayer.php?channel=tf1&page_id=41")) # shouldn't match self.assertFalse(PCYourFreeTV.can_handle_url("http://pc-yourfreetv.com/home.php")) - self.assertFalse(PCYourFreeTV.can_handle_url("http://pc-yourfreetv.com/index_livetv.php?page_id=1")) + self.assertFalse(PCYourFreeTV.can_handle_url("http://pc-yourfreetv.com/indexlivetv.php?page_id=1")) self.assertFalse(PCYourFreeTV.can_handle_url("http://tvcatchup.com/")) self.assertFalse(PCYourFreeTV.can_handle_url("http://youtube.com/")) diff --git a/tests/test_plugin_tvplayer.py b/tests/test_plugin_tvplayer.py index 13c7c363..52f27dc0 100644 --- a/tests/test_plugin_tvplayer.py +++ b/tests/test_plugin_tvplayer.py @@ -1,4 +1,3 @@ -import json import unittest from streamlink import Streamlink @@ -31,28 +30,28 @@ class TestPluginTVPlayer(unittest.TestCase): self.assertFalse(TVPlayer.can_handle_url("http://www.tvcatchup.com/")) self.assertFalse(TVPlayer.can_handle_url("http://www.youtube.com/")) + @patch('streamlink.plugins.tvplayer.TVPlayer._get_stream_data') @patch('streamlink.plugins.tvplayer.http') @patch('streamlink.plugins.tvplayer.HLSStream') - def test_get_streams(self, hlsstream, mock_http): - api_data = { - "tvplayer": { - "status": "200 OK", - "response": { + def test_get_streams(self, hlsstream, mock_http, mock_get_stream_data): + mock_get_stream_data.return_value = { "stream": "http://test.se/stream1" } - } - } + page_resp = Mock() page_resp.text = u""" - var validate = "foo"; - var resourceId = "1234"; - var platform = "test"; + <div class="video-js theoplayer-skin theo-seekbar-above-controls content-box vjs-fluid" + data-resource= "89" + data-token = "1324567894561268987948596154656418448489159" + data-content-type="live" + data-environment="live" + data-subscription="free" + data-channel-id="89"> + <div id="channel-info" class="channel-info"> + <div class="row visible-xs visible-sm"> """ - api_resp = Mock() - api_resp.text = json.dumps(api_data) + mock_http.get.return_value = page_resp - mock_http.post.return_value = api_resp - mock_http.json.return_value = api_data["tvplayer"]["response"] hlsstream.parse_variant_playlist.return_value = {"test": HLSStream(self.session, "http://test.se/stream1")} plugin = TVPlayer("http://tvplayer.com/watch/dave") @@ -64,11 +63,7 @@ class TestPluginTVPlayer(unittest.TestCase): # test the url is used correctly mock_http.get.assert_called_with("http://tvplayer.com/watch/dave") # test that the correct API call is made - mock_http.post.assert_called_with("http://api.tvplayer.com/api/v2/stream/live", data=dict(service=1, - id=u"1234", - validate=u"foo", - platform=u"test", - token=None)) + mock_get_stream_data.assert_called_with(resource="89", token="1324567894561268987948596154656418448489159") # test that the correct URL is used for the HLSStream hlsstream.parse_variant_playlist.assert_called_with(ANY, "http://test.se/stream1")
Support FacebookLive streaming My own research shows that Facebook Live streams are MPEG-DASH format with the audio and video in separate streams that need to be remuxed. Once this project supports DASH video, we should also be able to support Facebook Live streams.
0.0
517d3613c192538fec43394d935ee6893fbe0ee5
[ "tests/test_plugin_facebook.py::TestPluginFacebook::test_can_handle_url", "tests/test_plugin_pcyourfreetv.py::TestPluginPCYourFreeTV::test_can_handle_url", "tests/test_plugin_tvplayer.py::TestPluginTVPlayer::test_can_handle_url", "tests/test_plugin_tvplayer.py::TestPluginTVPlayer::test_get_invalid_page", "tests/test_plugin_tvplayer.py::TestPluginTVPlayer::test_get_streams" ]
[]
{ "failed_lite_validators": [ "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2017-04-26 19:55:52+00:00
bsd-2-clause
5,799
stuartmccoll__gitlab-changelog-generator-31
diff --git a/CHANGELOG.md b/CHANGELOG.md index 57d78f7..63bc117 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ # CHANGELOG +## v1.0.6 - 2019/10/01 + +- Added a flag to disable SSL checking - [issue](https://github.com/stuartmccoll/gitlab-changelog-generator/issues/30) raised by [PhilLab](https://github.com/PhilLab). + ## v1.0.5 - 2019/06/01 - Amended the way date formatting is handled - [issue](https://github.com/stuartmccoll/gitlab-changelog-generator/issues/25) raised by [smutel](https://github.com/smutel), commit(s) contributed by [smutel](https://github.com/smutel). diff --git a/changelog_generator/calls.py b/changelog_generator/calls.py index 2546183..be30a21 100644 --- a/changelog_generator/calls.py +++ b/changelog_generator/calls.py @@ -24,6 +24,7 @@ def get_last_commit_date(cli_args: dict) -> str: if "token" in cli_args else None }, + verify=cli_args["ssl"], ) logger.info(response.status_code) response.raise_for_status() @@ -69,6 +70,7 @@ def get_closed_issues_for_project(cli_args: dict) -> dict: headers={"PRIVATE-TOKEN": cli_args["token"]} if "token" in cli_args else None, + verify=cli_args["ssl"], ) response.raise_for_status() except requests.exceptions.HTTPError as ex: @@ -103,6 +105,7 @@ def get_last_tagged_release_date(cli_args: dict) -> str: headers={"PRIVATE-TOKEN": cli_args["token"]} if "token" in cli_args else None, + verify=cli_args["ssl"], ) response.raise_for_status() except requests.exceptions.HTTPError as ex: @@ -138,6 +141,7 @@ def get_commits_since_date(date: str, cli_args: dict) -> list: headers={"PRIVATE-TOKEN": cli_args["token"]} if "token" in cli_args else None, + verify=cli_args["ssl"], ) response.raise_for_status() except requests.exceptions.HTTPError as ex: diff --git a/changelog_generator/entry_point.py b/changelog_generator/entry_point.py index e65de05..7c7d007 100644 --- a/changelog_generator/entry_point.py +++ b/changelog_generator/entry_point.py @@ -65,6 +65,15 @@ def process_arguments() -> dict: help="gitlab personal token for auth", required=False, ) + parser.add_argument( + "-s", + "--ssl", + dest="ssl", + help="specify whether or not to enable ssl", + required=False, + default=True, + type=lambda x: (str(x).lower() in ["false", "2", "no"]), + ) args = parser.parse_args() @@ -78,6 +87,7 @@ def process_arguments() -> dict: "version": args.version, "changelog": args.changelog, "token": args.token, + "ssl": args.ssl, } diff --git a/setup.py b/setup.py index dd09982..89e1dd2 100644 --- a/setup.py +++ b/setup.py @@ -5,7 +5,7 @@ with open("README.md", "r") as fh: setuptools.setup( name="gitlab-changelog-generator", - version="1.0.5", + version="1.0.6", author="Stuart McColl", author_email="[email protected]", description="A small command line utility for generating CHANGELOG.md "
stuartmccoll/gitlab-changelog-generator
bc7168731f834eaa8e89721490f58728c1291eeb
diff --git a/changelog_generator/tests/test_calls.py b/changelog_generator/tests/test_calls.py index 2147a0a..de881c1 100644 --- a/changelog_generator/tests/test_calls.py +++ b/changelog_generator/tests/test_calls.py @@ -29,6 +29,7 @@ class TestCalls(unittest.TestCase): "branch_two": "master", "version": "1", "changelog": "N", + "ssl": "True", } try: @@ -51,6 +52,7 @@ class TestCalls(unittest.TestCase): "branch_two": "master", "version": "1", "changelog": "N", + "ssl": "True", } commit_date = get_last_commit_date(cli_args) @@ -74,6 +76,7 @@ class TestCalls(unittest.TestCase): "branch_two": "master", "version": "1", "changelog": "N", + "ssl": "True", } try: @@ -103,6 +106,7 @@ class TestCalls(unittest.TestCase): "branch_two": "master", "version": "1", "changelog": "N", + "ssl": "True", } commits = get_commits_since_date( @@ -138,6 +142,7 @@ class TestCalls(unittest.TestCase): "branch_two": "master", "version": "1", "changelog": "N", + "ssl": "True", } self.assertEqual( @@ -165,6 +170,7 @@ class TestCalls(unittest.TestCase): "branch_two": "master", "version": "1", "changelog": "N", + "ssl": "True", } self.assertEqual( diff --git a/changelog_generator/tests/test_entry_point.py b/changelog_generator/tests/test_entry_point.py index c05877c..5aafc8b 100644 --- a/changelog_generator/tests/test_entry_point.py +++ b/changelog_generator/tests/test_entry_point.py @@ -32,6 +32,7 @@ class TestGenerator(unittest.TestCase): "version": "1.2.3", "changelog": "N", "token": "test-token", + "ssl": True, } result = process_arguments()
Add support for self-signed https certificates Follow-up of #23 : Now that SSL is supported, it would be awesome to have a flag for disabling the certificate check in case of a self-hosted, self-signed certificate (mostly when using an intranet instance) - https://stackoverflow.com/questions/15445981/how-do-i-disable-the-security-certificate-check-in-python-requests - maybe this answer explains the least intrusive patch: https://stackoverflow.com/a/50159273/1531708
0.0
bc7168731f834eaa8e89721490f58728c1291eeb
[ "changelog_generator/tests/test_entry_point.py::TestGenerator::test_process_arguments" ]
[ "changelog_generator/tests/test_calls.py::TestCalls::test_unsuccessful_commits_since_date", "changelog_generator/tests/test_calls.py::TestCalls::test_get_last_commit_date", "changelog_generator/tests/test_calls.py::TestCalls::test_get_closed_issues_for_project", "changelog_generator/tests/test_calls.py::TestCalls::test_unsuccessful_get_last_commit_date", "changelog_generator/tests/test_calls.py::TestCalls::test_get_last_tagged_release_date", "changelog_generator/tests/test_calls.py::TestCalls::test_commits_since_date" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_issue_reference", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2019-10-01 19:37:16+00:00
mit
5,800
stummjr__flake8-scrapy-19
diff --git a/finders/oldstyle.py b/finders/oldstyle.py index 0910d97..dceef88 100644 --- a/finders/oldstyle.py +++ b/finders/oldstyle.py @@ -12,7 +12,7 @@ class UrlJoinIssueFinder(IssueFinder): return first_param = node.args[0] - if not isinstance(first_param, ast.Attribute): + if not isinstance(first_param, ast.Attribute) or not isinstance(first_param.value, ast.Name): return if first_param.value.id == 'response' and first_param.attr == 'url': diff --git a/flake8_scrapy.py b/flake8_scrapy.py index c1198f4..839b2b8 100644 --- a/flake8_scrapy.py +++ b/flake8_scrapy.py @@ -6,7 +6,7 @@ from finders.domains import ( from finders.oldstyle import OldSelectorIssueFinder, UrlJoinIssueFinder -__version__ = '0.0.1' +__version__ = '0.0.2' class ScrapyStyleIssueFinder(ast.NodeVisitor): diff --git a/setup.py b/setup.py index 4d058d5..3518539 100644 --- a/setup.py +++ b/setup.py @@ -7,7 +7,7 @@ with open('README.md', 'r') as f: setuptools.setup( name='flake8-scrapy', license='MIT', - version='0.0.1', + version='0.0.2', long_description=long_description, long_description_content_type='text/markdown', author='Valdir Stumm Junior',
stummjr/flake8-scrapy
e09bcf1e387b52d081d2df4b6d6c459203b31a5b
diff --git a/tests/test_oldstyle.py b/tests/test_oldstyle.py index 29e9f50..6dc2d34 100644 --- a/tests/test_oldstyle.py +++ b/tests/test_oldstyle.py @@ -17,6 +17,8 @@ def test_finds_old_style_urljoin(code): @pytest.mark.parametrize('code', [ ('response.urljoin("/foo")'), ('url = urljoin()'), + ('urljoin(x, "/foo")'), + ('urljoin(x.y.z, "/foo")'), ]) def test_dont_find_old_style_urljoin(code): issues = run_checker(code)
Failed SCP03 rule check When starting the fakehaven stage in CI, I received the following error: ``` $ flakeheaven lint --format=grouped --exit-zero --import-order-style pep8 --application-import-names directories multiprocessing.pool.RemoteTraceback: """ Traceback (most recent call last): File "/usr/local/lib/python3.7/multiprocessing/pool.py", line 121, in worker result = (True, func(*args, **kwds)) File "/usr/local/lib/python3.7/multiprocessing/pool.py", line 44, in mapstar return list(map(*args)) File "/usr/local/lib/python3.7/site-packages/flake8/checker.py", line 687, in _run_checks return checker.run_checks() File "/usr/local/lib/python3.7/site-packages/flakeheaven/_patched/_checkers.py", line 282, in run_checks return super().run_checks() File "/usr/local/lib/python3.7/site-packages/flake8/checker.py", line 597, in run_checks self.run_ast_checks() File "/usr/local/lib/python3.7/site-packages/flake8/checker.py", line 500, in run_ast_checks for (line_number, offset, text, _) in runner: File "/usr/local/lib/python3.7/site-packages/flake8_scrapy.py", line 55, in run finder.visit(self.tree) File "/usr/local/lib/python3.7/ast.py", line 271, in visit return visitor(node) File "/usr/local/lib/python3.7/ast.py", line 279, in generic_visit self.visit(item) File "/usr/local/lib/python3.7/ast.py", line 271, in visit return visitor(node) File "/usr/local/lib/python3.7/ast.py", line 279, in generic_visit self.visit(item) File "/usr/local/lib/python3.7/ast.py", line 271, in visit return visitor(node) File "/usr/local/lib/python3.7/site-packages/flake8_scrapy.py", line 38, in visit_Assign self.find_issues_visitor('Assign', node) File "/usr/local/lib/python3.7/site-packages/flake8_scrapy.py", line 35, in find_issues_visitor self.generic_visit(node) File "/usr/local/lib/python3.7/ast.py", line 281, in generic_visit self.visit(value) File "/usr/local/lib/python3.7/ast.py", line 271, in visit return visitor(node) File "/usr/local/lib/python3.7/site-packages/flake8_scrapy.py", line 41, in visit_Call self.find_issues_visitor('Call', node) File "/usr/local/lib/python3.7/site-packages/flake8_scrapy.py", line 35, in find_issues_visitor self.generic_visit(node) File "/usr/local/lib/python3.7/ast.py", line 279, in generic_visit self.visit(item) File "/usr/local/lib/python3.7/ast.py", line 271, in visit return visitor(node) File "/usr/local/lib/python3.7/ast.py", line 281, in generic_visit self.visit(value) File "/usr/local/lib/python3.7/ast.py", line 271, in visit return visitor(node) File "/usr/local/lib/python3.7/site-packages/flake8_scrapy.py", line 41, in visit_Call self.find_issues_visitor('Call', node) File "/usr/local/lib/python3.7/site-packages/flake8_scrapy.py", line 34, in find_issues_visitor self.issues.extend(list(issues)) File "/usr/local/lib/python3.7/site-packages/finders/oldstyle.py", line 18, in find_issues if first_param.value.id == 'response' and first_param.attr == 'url': AttributeError: 'Attribute' object has no attribute 'id' """ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/usr/local/bin/flakeheaven", line 8, in <module> sys.exit(entrypoint()) File "/usr/local/lib/python3.7/site-packages/flakeheaven/_cli.py", line 40, in entrypoint exit_code, msg = main(argv) File "/usr/local/lib/python3.7/site-packages/flakeheaven/_cli.py", line 32, in main return COMMANDS[command_name](argv=argv[1:]) File "/usr/local/lib/python3.7/site-packages/flakeheaven/commands/_lint.py", line 12, in lint_command app.run(argv) File "/usr/local/lib/python3.7/site-packages/flake8/main/application.py", line 375, in run self._run(argv) File "/usr/local/lib/python3.7/site-packages/flake8/main/application.py", line 364, in _run self.run_checks() File "/usr/local/lib/python3.7/site-packages/flake8/main/application.py", line 271, in run_checks self.file_checker_manager.run() File "/usr/local/lib/python3.7/site-packages/flake8/checker.py", line 309, in run self.run_parallel() File "/usr/local/lib/python3.7/site-packages/flake8/checker.py", line 275, in run_parallel for ret in pool_map: File "/usr/local/lib/python3.7/multiprocessing/pool.py", line 354, in <genexpr> return (item for chunk in result for item in chunk) File "/usr/local/lib/python3.7/multiprocessing/pool.py", line 748, in next raise value AttributeError: 'Attribute' object has no attribute 'id' ``` The problem occurs in this line: ```python urljoin(settings.SERVICE_URLS.PD, '/path') ``` Where are the `settings`: ```python from pydantic import BaseSettings, BaseModel class ServiceUrlsSchema(BaseModel): PD: str class Settings(BaseSettings): SERVICE_URLS: ServiceUrlsSchema ```
0.0
e09bcf1e387b52d081d2df4b6d6c459203b31a5b
[ "tests/test_oldstyle.py::test_dont_find_old_style_urljoin[urljoin(x.y.z," ]
[ "tests/test_oldstyle.py::test_finds_old_style_urljoin[urljoin(response.url,", "tests/test_oldstyle.py::test_finds_old_style_urljoin[url", "tests/test_oldstyle.py::test_dont_find_old_style_urljoin[response.urljoin(\"/foo\")]", "tests/test_oldstyle.py::test_dont_find_old_style_urljoin[url", "tests/test_oldstyle.py::test_dont_find_old_style_urljoin[urljoin(x,", "tests/test_oldstyle.py::test_find_old_style_selector[sel" ]
{ "failed_lite_validators": [ "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2022-03-29 17:45:55+00:00
mit
5,801
suminb__base62-22
diff --git a/base62.py b/base62.py index df45c41..5017c43 100644 --- a/base62.py +++ b/base62.py @@ -16,24 +16,18 @@ CHARSET_DEFAULT = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxy CHARSET_INVERTED = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" -def encode(n, minlen=1, charset=CHARSET_DEFAULT): +def encode(n, charset=CHARSET_DEFAULT): """Encodes a given integer ``n``.""" chs = [] while n > 0: - r = n % BASE - n //= BASE + n, r = divmod(n, BASE) + chs.insert(0, charset[r]) - chs.append(charset[r]) + if not chs: + return "0" - if len(chs) > 0: - chs.reverse() - else: - chs.append("0") - - s = "".join(chs) - s = charset[0] * max(minlen - len(s), 0) + s - return s + return "".join(chs) def encodebytes(barray, charset=CHARSET_DEFAULT): @@ -45,7 +39,27 @@ def encodebytes(barray, charset=CHARSET_DEFAULT): """ _check_type(barray, bytes) - return encode(int.from_bytes(barray, "big"), charset=charset) + + # Count the number of leading zeros. + leading_zeros_count = 0 + for i in range(len(barray)): + if barray[i] != 0: + break + leading_zeros_count += 1 + + # Encode the leading zeros as "0" followed by a character indicating the count. + # This pattern may occur several times if there are many leading zeros. + n, r = divmod(leading_zeros_count, len(charset) - 1) + zero_padding = f"0{charset[-1]}" * n + if r: + zero_padding += f"0{charset[r]}" + + # Special case: the input is empty, or is entirely null bytes. + if leading_zeros_count == len(barray): + return zero_padding + + value = encode(int.from_bytes(barray, "big"), charset=charset) + return zero_padding + value def decode(encoded, charset=CHARSET_DEFAULT): @@ -56,9 +70,6 @@ def decode(encoded, charset=CHARSET_DEFAULT): """ _check_type(encoded, str) - if encoded.startswith("0z"): - encoded = encoded[2:] - l, i, v = len(encoded), 0, 0 for x in encoded: v += _value(x, charset=charset) * (BASE ** (l - (i + 1))) @@ -75,6 +86,11 @@ def decodebytes(encoded, charset=CHARSET_DEFAULT): :rtype: bytes """ + leading_null_bytes = b"" + while encoded.startswith("0") and len(encoded) >= 2: + leading_null_bytes += b"\x00" * _value(encoded[1], charset) + encoded = encoded[2:] + decoded = decode(encoded, charset=charset) buf = bytearray() while decoded > 0: @@ -82,7 +98,7 @@ def decodebytes(encoded, charset=CHARSET_DEFAULT): decoded //= 256 buf.reverse() - return bytes(buf) + return leading_null_bytes + bytes(buf) def _value(ch, charset):
suminb/base62
53b87a62e835ee6a3fb9fe3ec4999ce115161655
diff --git a/tests/test_basic.py b/tests/test_basic.py index 73f1d09..bade00f 100644 --- a/tests/test_basic.py +++ b/tests/test_basic.py @@ -4,7 +4,6 @@ import base62 bytes_int_pairs = [ - (b"\x00", 0), (b"\x01", 1), (b"\x01\x01", 0x0101), (b"\xff\xff", 0xFFFF), @@ -20,9 +19,6 @@ def test_const(): def test_basic(): assert base62.encode(0) == "0" - assert base62.encode(0, minlen=0) == "0" - assert base62.encode(0, minlen=1) == "0" - assert base62.encode(0, minlen=5) == "00000" assert base62.decode("0") == 0 assert base62.decode("0000") == 0 assert base62.decode("000001") == 1 @@ -30,19 +26,11 @@ def test_basic(): assert base62.encode(34441886726) == "base62" assert base62.decode("base62") == 34441886726 - # NOTE: For backward compatibility. When I first wrote this module in PHP, - # I used to use the `0z` prefix to denote a base62 encoded string (similar - # to `0x` for hexadecimal strings). - assert base62.decode("0zbase62") == 34441886726 - def test_basic_inverted(): kwargs = {"charset": base62.CHARSET_INVERTED} assert base62.encode(0, **kwargs) == "0" - assert base62.encode(0, minlen=0, **kwargs) == "0" - assert base62.encode(0, minlen=1, **kwargs) == "0" - assert base62.encode(0, minlen=5, **kwargs) == "00000" assert base62.decode("0", **kwargs) == 0 assert base62.decode("0000", **kwargs) == 0 assert base62.decode("000001", **kwargs) == 1 @@ -50,11 +38,6 @@ def test_basic_inverted(): assert base62.encode(10231951886, **kwargs) == "base62" assert base62.decode("base62", **kwargs) == 10231951886 - # NOTE: For backward compatibility. When I first wrote this module in PHP, - # I used to use the `0z` prefix to denote a base62 encoded string (similar - # to `0x` for hexadecimal strings). - assert base62.decode("0zbase62", **kwargs) == 10231951886 - @pytest.mark.parametrize("b, i", bytes_int_pairs) def test_bytes_to_int(b, i): @@ -77,7 +60,7 @@ def test_encodebytes_rtype(): assert isinstance(encoded, str) [email protected]("s", ["0", "1", "a", "z", "ykzvd7ga", "0z1234"]) [email protected]("s", ["0", "1", "a", "z", "ykzvd7ga"]) def test_decodebytes(s): assert int.from_bytes(base62.decodebytes(s), "big") == base62.decode(s) @@ -113,3 +96,23 @@ def test_invalid_alphabet(): def test_invalid_string(): with pytest.raises(TypeError): base62.encodebytes({}) + + [email protected]( + "input_bytes, expected_encoded_text", + ( + (b"", ""), + (b"\x00", "01"), + (b"\x00\x00", "02"), + (b"\x00\x01", "011"), + (b"\x00" * 61, "0z"), + (b"\x00" * 62, "0z01"), + ), +) +def test_leading_zeros(input_bytes, expected_encoded_text): + """Verify that leading null bytes are not lost.""" + + encoded_text = base62.encodebytes(input_bytes) + assert encoded_text == expected_encoded_text + output_bytes = base62.decodebytes(encoded_text) + assert output_bytes == input_bytes
Ignoring leading zero bytes Hello, first of all, thank you for this library. I am using it for encoding 16 byte blocks and I have noticed, that during encoding, leading bytes that are equal to `0x00` are ignored. This is due to conversion to integer, which the library internally does. I believe this is not a correct behavior, because without knowledge of the input bytes block length, you cannot reconstruct (decode) the original input from output. But for example in encryption (and many other areas), all bytes (incl. leading zero bytes) matter. I'll give an example using base64, which does this correctly: ``` encoded = b64encode(b'\x00\x00\x01').decode() print(encoded) decoded = b64decode(encoded) print(decoded) ``` This code yields: ``` AAAB b'\x00\x00\x01' ``` Now your library: ``` encoded = base62.encodebytes(b'\x00\x00\x01') print(encoded) decoded = base62.decodebytes(encoded) print(decoded) ``` Yields: ``` 1 b'\x01' ``` As you can see, decoded output is not equal the input (it misses the two leading zero bytes).
0.0
53b87a62e835ee6a3fb9fe3ec4999ce115161655
[ "tests/test_basic.py::test_leading_zeros[-]", "tests/test_basic.py::test_leading_zeros[\\x00-01]", "tests/test_basic.py::test_leading_zeros[\\x00\\x00-02]", "tests/test_basic.py::test_leading_zeros[\\x00\\x01-011]", "tests/test_basic.py::test_leading_zeros[\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00-0z]", "tests/test_basic.py::test_leading_zeros[\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00-0z01]" ]
[ "tests/test_basic.py::test_const", "tests/test_basic.py::test_basic", "tests/test_basic.py::test_basic_inverted", "tests/test_basic.py::test_bytes_to_int[\\x01-1]", "tests/test_basic.py::test_bytes_to_int[\\x01\\x01-257]", "tests/test_basic.py::test_bytes_to_int[\\xff\\xff-65535]", "tests/test_basic.py::test_bytes_to_int[\\x01\\x01\\x01-65793]", "tests/test_basic.py::test_bytes_to_int[\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08-72623859790382856]", "tests/test_basic.py::test_encodebytes[\\x01-1]", "tests/test_basic.py::test_encodebytes[\\x01\\x01-257]", "tests/test_basic.py::test_encodebytes[\\xff\\xff-65535]", "tests/test_basic.py::test_encodebytes[\\x01\\x01\\x01-65793]", "tests/test_basic.py::test_encodebytes[\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08-72623859790382856]", "tests/test_basic.py::test_encodebytes_type", "tests/test_basic.py::test_encodebytes_rtype", "tests/test_basic.py::test_decodebytes[0]", "tests/test_basic.py::test_decodebytes[1]", "tests/test_basic.py::test_decodebytes[a]", "tests/test_basic.py::test_decodebytes[z]", "tests/test_basic.py::test_decodebytes[ykzvd7ga]", "tests/test_basic.py::test_decodebytes_type", "tests/test_basic.py::test_decodebytes_rtype", "tests/test_basic.py::test_roundtrip[]", "tests/test_basic.py::test_roundtrip[0]", "tests/test_basic.py::test_roundtrip[bytes", "tests/test_basic.py::test_roundtrip[\\x01\\x00\\x80]", "tests/test_basic.py::test_invalid_alphabet", "tests/test_basic.py::test_invalid_string" ]
{ "failed_lite_validators": [ "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2023-01-25 14:33:04+00:00
bsd-2-clause
5,802
sunpy__ablog-97
diff --git a/ablog/post.py b/ablog/post.py index b6be6c8..e08dacc 100644 --- a/ablog/post.py +++ b/ablog/post.py @@ -709,7 +709,7 @@ def generate_atom_feeds(app): feed.title(feed_title) feed.link(href=url) feed.subtitle(blog.blog_feed_subtitle) - feed.link(href=feed_url) + feed.link(href=feed_url, rel="self") feed.language(app.config.language) feed.generator("ABlog", ablog.__version__, "https://ablog.readthedocs.org/") @@ -741,17 +741,18 @@ def generate_atom_feeds(app): # Entry values that support templates title = post.title - if post.excerpt: - summary = " ".join(paragraph.astext() for paragraph in post.excerpt[0]) - else: - summary = "" + summary = "".join(paragraph.astext() for paragraph in post.excerpt) template_values = {} for element in ("title", "summary", "content"): if element in feed_templates: template_values[element] = jinja2.Template(feed_templates[element]).render(**locals()) feed_entry.title(template_values.get("title", title)) - feed_entry.summary(template_values.get("summary", summary)) - feed_entry.content(content=template_values.get("content", content), type="html") + summary = template_values.get("summary", summary) + if summary: + feed_entry.summary(summary) + content = template_values.get("content", content) + if content: + feed_entry.content(content=content, type="html") parent_dir = os.path.dirname(feed_path) if not os.path.isdir(parent_dir):
sunpy/ablog
5e894ab7b2a6667eaac84a42b31d3c96b5028d34
diff --git a/tests/roots/test-build/foo-empty-post.rst b/tests/roots/test-build/foo-empty-post.rst new file mode 100644 index 0000000..e2221df --- /dev/null +++ b/tests/roots/test-build/foo-empty-post.rst @@ -0,0 +1,5 @@ +.. post:: 2021-03-23 + +############## +Foo Empty Post +############## diff --git a/tests/roots/test-build/post.rst b/tests/roots/test-build/post.rst index d8f1d1e..bef264d 100644 --- a/tests/roots/test-build/post.rst +++ b/tests/roots/test-build/post.rst @@ -4,6 +4,8 @@ Foo Post Title ============== - Foo post description. + Foo post description `with link`_. Foo post content. + +.. _`with link`: https://example.com diff --git a/tests/test_build.py b/tests/test_build.py index ff4211b..10c077b 100644 --- a/tests/test_build.py +++ b/tests/test_build.py @@ -26,13 +26,13 @@ def test_feed(app, status, warning): with feed_path.open() as feed_opened: feed_tree = lxml.etree.parse(feed_opened) entries = feed_tree.findall("{http://www.w3.org/2005/Atom}entry") - assert len(entries) == 1, "Wrong number of Atom feed entries" + assert len(entries) == 2, "Wrong number of Atom feed entries" entry = entries[0] title = entry.find("{http://www.w3.org/2005/Atom}title") assert title.text == "Foo Post Title", "Wrong Atom feed entry title" summary = entry.find("{http://www.w3.org/2005/Atom}summary") - assert summary.text == "Foo post description.", "Wrong Atom feed entry summary" + assert summary.text == "Foo post description with link.", "Wrong Atom feed entry summary" categories = entry.findall("{http://www.w3.org/2005/Atom}category") assert len(categories) == 2, "Wrong number of Atom feed categories" assert categories[0].attrib["label"] == "Foo Tag", "Wrong Atom feed first category" @@ -42,6 +42,16 @@ def test_feed(app, status, warning): content = entry.find("{http://www.w3.org/2005/Atom}content") assert "Foo post content." in content.text, "Wrong Atom feed entry content" + empty_entry = entries[1] + title = empty_entry.find("{http://www.w3.org/2005/Atom}title") + assert title.text == "Foo Empty Post", "Wrong Atom feed empty entry title" + summary = empty_entry.find("{http://www.w3.org/2005/Atom}summary") + assert summary is None, "Atom feed empty entry contains optional summary element" + categories = empty_entry.findall("{http://www.w3.org/2005/Atom}category") + assert len(categories) == 0, "Atom categories rendered for empty post" + content = empty_entry.find("{http://www.w3.org/2005/Atom}content") + assert 'id="foo-empty-post"' in content.text, "Atom feed empty entry missing post ID" + social_path = app.outdir / "blog/social.xml" assert (social_path).exists(), "Social media feed was not built" @@ -54,7 +64,7 @@ def test_feed(app, status, warning): title = social_entry.find("{http://www.w3.org/2005/Atom}title") assert title.text == "Foo Post Title", "Wrong Social media feed entry title" summary = social_entry.find("{http://www.w3.org/2005/Atom}summary") - assert summary.text == "Foo post description.", "Wrong Social media feed entry summary" + assert summary.text == "Foo post description with link.", "Wrong Social media feed entry summary" categories = social_entry.findall("{http://www.w3.org/2005/Atom}category") assert len(categories) == 2, "Wrong number of Social media feed categories" assert categories[0].attrib["label"] == "Foo Tag", "Wrong Social media feed first category"
Atom feeds fail W3C validation ### Atom feeds fail W3C validation The generated Atom feeds don't pass W3C validation ### Expected vs Actual behavior Expected behavior: Generated Atom feeds pass W3C valdation Actual behavior: Generated Atom feeds fail W3C valdation ``` This feed does not validate. line 9, column 2: Duplicate alternate links with the same type and hreflang [help] <entry> ^ In addition, interoperability with the widest range of feed readers could be improved by implementing the following recommendation. line 2, column 0: Missing atom:link with rel="self" [help] <feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en"> ``` Also, the `blog_baseurl` value needs to have a trailing slash or the validator produces a 3rd error: ``` In addition, interoperability with the widest range of feed readers could be improved by implementing the following recommendations. line 3, column 32: Identifier "https://www.rpatterson.net" is not in canonical form (the canonical form would be "https://www.rpatterson.net/") [help] <id>https://www.rpatterson.net</id> ``` I greppd that adding the trailing slash doesn't result in double slashes in the generated site. So the requirement for a trailing slash should be documented or better yet should be added when the site is built/generated. ### Steps to Reproduce 1. Create an Atom blog 2. Publish where publicly available 3. [Validate an Atom feed](https://validator.w3.org/feed/check.cgi?url=https%3A%2F%2Fwww.rpatterson.net%2Fblog%2Fatom.xml) ### System Details ``` $ ./.venv/bin/python --version Python 3.8.6 $ ./.venv/bin/pip freeze ablog==0.10.13 alabaster==0.7.12 Babel==2.9.0 certifi==2020.12.5 chardet==4.0.0 docutils==0.16 feedgen==0.9.0 idna==2.10 imagesize==1.2.0 invoke==1.5.0 Jinja2==2.11.3 lxml==4.6.2 MarkupSafe==1.1.1 packaging==20.9 Pygments==2.8.1 pygments-solarized==0.0.3 pyparsing==2.4.7 python-dateutil==2.8.1 pytz==2021.1 requests==2.25.1 six==1.15.0 snowballstemmer==2.1.0 Sphinx==3.5.2 sphinx-fasvg==0.1.4 sphinx-nervproject-theme==2.0.3 sphinxcontrib-applehelp==1.0.2 sphinxcontrib-devhelp==1.0.2 sphinxcontrib-htmlhelp==1.0.3 sphinxcontrib-jsmath==1.0.1 sphinxcontrib-qthelp==1.0.3 sphinxcontrib-serializinghtml==1.1.4 urllib3==1.26.4 watchdog==2.0.2 $ uname -a Linux rpatterson.rpatterson.net 5.8.0-7642-generic #47~1614007149~20.10~82fb226-Ubuntu SMP Tue Feb 23 02 :59:01 UTC x86_64 x86_64 x86_64 GNU/Linux ```
0.0
5e894ab7b2a6667eaac84a42b31d3c96b5028d34
[ "tests/test_build.py::test_feed" ]
[ "tests/test_build.py::test_build" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_issue_reference" ], "has_test_patch": true, "is_lite": false }
2021-03-23 03:26:01+00:00
bsd-2-clause
5,803
sunpy__ndcube-433
diff --git a/changelog/433.trivial.rst b/changelog/433.trivial.rst new file mode 100644 index 0000000..3ae9cab --- /dev/null +++ b/changelog/433.trivial.rst @@ -0,0 +1,1 @@ +Adds a function to compare the physical types of two WCS objects. diff --git a/ndcube/utils/wcs.py b/ndcube/utils/wcs.py index 25a0e47..228fc24 100644 --- a/ndcube/utils/wcs.py +++ b/ndcube/utils/wcs.py @@ -8,7 +8,7 @@ import numbers from collections import UserDict import numpy as np -from astropy.wcs.wcsapi import low_level_api +from astropy.wcs.wcsapi import BaseHighLevelWCS, BaseLowLevelWCS, low_level_api __all__ = ['array_indices_for_world_objects', 'convert_between_array_and_pixel_axes', 'calculate_world_indices_from_axes', 'wcs_ivoa_mapping', @@ -429,3 +429,51 @@ def array_indices_for_world_objects(wcs, axes=None): array_index = convert_between_array_and_pixel_axes(pixel_index, wcs.pixel_n_dim) array_indices[oinds] = tuple(array_index[::-1]) # Invert from pixel order to array order return tuple(ai for ai in array_indices if ai) + + +def get_low_level_wcs(wcs, name='wcs'): + """ + Returns a low level WCS object from a low level or high level WCS. + + Parameters + ---------- + wcs: `astropy.wcs.wcsapi.BaseHighLevelWCS` or `astropy.wcs.wcsapi.BaseLowLevelWCS` + The input WCS for getting the low level WCS object. + + name: `str`, optional + Any name for the wcs to be used in the exception that could be raised. + + Returns + ------- + wcs: `astropy.wcs.wcsapi.BaseLowLevelWCS` + """ + + if isinstance(wcs, BaseHighLevelWCS): + return wcs.low_level_wcs + elif isinstance(wcs, BaseLowLevelWCS): + return wcs + else: + raise(f'{name} must implement either BaseHighLevelWCS or BaseLowLevelWCS') + + +def compare_wcs_physical_types(source_wcs, target_wcs): + """ + Checks to see if two WCS objects have the same physical types in the same order. + + Parameters + ---------- + source_wcs : `astropy.wcs.wcsapi.BaseHighLevelWCS` or `astropy.wcs.wcsapi.BaseLowLevelWCS` + The WCS which is currently in use, usually `self.wcs`. + + target_wcs : `astropy.wcs.wcsapi.BaseHighLevelWCS` or `astropy.wcs.wcsapi.BaseLowLevelWCS` + The WCS object on which the NDCube is to be reprojected. + + Returns + ------- + result : `bool` + """ + + source_wcs = get_low_level_wcs(source_wcs, 'source_wcs') + target_wcs = get_low_level_wcs(target_wcs, 'target_wcs') + + return source_wcs.world_axis_physical_types == target_wcs.world_axis_physical_types
sunpy/ndcube
ba1a436d404e0b569a84cf90c59fd4aa3cef1f39
diff --git a/ndcube/utils/tests/test_utils_wcs.py b/ndcube/utils/tests/test_utils_wcs.py index 9361bea..6d811a8 100644 --- a/ndcube/utils/tests/test_utils_wcs.py +++ b/ndcube/utils/tests/test_utils_wcs.py @@ -157,3 +157,8 @@ def test_array_indices_for_world_objects_2(wcs_4d_lt_t_l_ln): array_indices = utils.wcs.array_indices_for_world_objects(wcs_4d_lt_t_l_ln, ('lon', 'time')) assert len(array_indices) == 2 assert array_indices == ((0, 3), (2,)) + + +def test_compare_wcs_physical_types(wcs_4d_t_l_lt_ln, wcs_3d_l_lt_ln): + assert utils.wcs.compare_wcs_physical_types(wcs_4d_t_l_lt_ln, wcs_4d_t_l_lt_ln) is True + assert utils.wcs.compare_wcs_physical_types(wcs_4d_t_l_lt_ln, wcs_3d_l_lt_ln) is False
Validate WCS Function <!-- We know asking good questions takes effort, and we appreciate your time. Thank you. Please be aware that everyone has to follow our code of conduct: https://sunpy.org/coc These comments are hidden when you submit this github issue. Please have a search on our GitHub repository to see if a similar issue has already been posted. If a similar issue is closed, have a quick look to see if you are satisfied by the resolution. If not please go ahead and open an issue! --> ### Description <!-- Provide a general description of the feature you would like. If you prefer, you can also suggest a draft design or API. --> Create a function that accepts two WCS objects, `target_wcs` and `initial_wcs`, and verifies that `target` is the same/equivalent to `initial`. (Better variable names here are welcome.) Initially, the `target_wcs` must describe all axes of the `initial_wcs`. Future versions of this function should handle invariant axes. The use case for this function is as part of verifying the input to the future `NDCube.resample` method.
0.0
ba1a436d404e0b569a84cf90c59fd4aa3cef1f39
[ "ndcube/utils/tests/test_utils_wcs.py::test_compare_wcs_physical_types" ]
[ "ndcube/utils/tests/test_utils_wcs.py::test_convert_between_array_and_pixel_axes", "ndcube/utils/tests/test_utils_wcs.py::test_pixel_axis_to_world_axes", "ndcube/utils/tests/test_utils_wcs.py::test_world_axis_to_pixel_axes", "ndcube/utils/tests/test_utils_wcs.py::test_pixel_axis_to_physical_types", "ndcube/utils/tests/test_utils_wcs.py::test_physical_type_to_pixel_axes", "ndcube/utils/tests/test_utils_wcs.py::test_physical_type_to_world_axis[wl-2]", "ndcube/utils/tests/test_utils_wcs.py::test_physical_type_to_world_axis[em.wl-2]", "ndcube/utils/tests/test_utils_wcs.py::test_get_dependent_pixel_axes", "ndcube/utils/tests/test_utils_wcs.py::test_get_dependent_array_axes", "ndcube/utils/tests/test_utils_wcs.py::test_get_dependent_world_axes", "ndcube/utils/tests/test_utils_wcs.py::test_get_dependent_physical_types", "ndcube/utils/tests/test_utils_wcs.py::test_array_indices_for_world_objects", "ndcube/utils/tests/test_utils_wcs.py::test_array_indices_for_world_objects_2" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_added_files" ], "has_test_patch": true, "is_lite": false }
2021-06-22 04:59:03+00:00
bsd-2-clause
5,804
sunpy__sunpy-6011
diff --git a/.pep8speaks.yml b/.pep8speaks.yml deleted file mode 100644 index f845da350..000000000 --- a/.pep8speaks.yml +++ /dev/null @@ -1,26 +0,0 @@ -scanner: - diff_only: False - -pycodestyle: - max-line-length: 100 - exclude: - - setup.py - - docs/conf.py - - sunpy/__init__.py - - sunpy/extern/ - ignore: - - E226 - - E501 - - W503 - - W504 - -descending_issues_order: True - -message: - opened: - header: "Hello @{name}! Thanks for opening this PR. " - footer: "Do see the [Hitchhiker's guide to code style](https://goo.gl/hqbW4r)" - updated: - header: "Hello @{name}! Thanks for updating this PR. " - footer: "" - no_errors: "There are currently no PEP 8 issues detected in this Pull Request. Cheers!" diff --git a/MANIFEST.in b/MANIFEST.in index d10ccd251..9dc53df20 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -1,24 +1,21 @@ -# Exclude specific files -# All files which are tracked by git and not explicitly excluded here are included by setuptools_scm exclude .codecov.yaml -exclude .mailmap exclude .editorconfig exclude .gitattributes exclude .gitignore -exclude .pep8speaks.yml +exclude .mailmap exclude .pre-commit-config.yaml +exclude .readthedocs.yaml exclude .test_package_pins.txt exclude .zenodo.json -exclude azure-pipelines.yml +exclude asv.conf.json +exclude CITATION.cff exclude readthedocs.yml -exclude rtd-environment.yml -# Prune folders + prune .circleci prune .github prune .jupyter +prune benchmarks prune binder prune changelog prune tools -# This subpackage is only used in development checkouts and should not be -# included in built tarballs prune sunpy/_dev diff --git a/changelog/6011.bugfix.rst b/changelog/6011.bugfix.rst new file mode 100644 index 000000000..e5f317c01 --- /dev/null +++ b/changelog/6011.bugfix.rst @@ -0,0 +1,1 @@ +Fixed `.system_info` so it returns the extra group when an optional dependency is missing. diff --git a/pyproject.toml b/pyproject.toml index d7ee23eec..5e28f304f 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,7 +1,7 @@ [build-system] requires = [ - "setuptools", - "setuptools_scm", + "setuptools>=56,!=61.0.0", + "setuptools_scm[toml]>=6.2", "wheel", "oldest-supported-numpy", "extension-helpers" diff --git a/sunpy/util/sysinfo.py b/sunpy/util/sysinfo.py index 8bb5d1c7e..1bdcf390f 100644 --- a/sunpy/util/sysinfo.py +++ b/sunpy/util/sysinfo.py @@ -5,6 +5,7 @@ import platform from collections import defaultdict from importlib.metadata import PackageNotFoundError, version, requires, distribution +from packaging.markers import Marker from packaging.requirements import Requirement import sunpy.extern.distro as distro @@ -25,20 +26,53 @@ def get_requirements(package): ------- `dict` A dictionary of requirements with keys being the extra requirement group names. + The values are a nested dictionary with keys being the package names and + values being the `packaging.requirements.Requirement` objects. """ requirements: list = requires(package) - requires_dict = defaultdict(list) + requires_dict = defaultdict(dict) for requirement in requirements: req = Requirement(requirement) package_name, package_marker = req.name, req.marker if package_marker and "extra ==" in str(package_marker): group = str(package_marker).split("extra == ")[1].strip('"').strip("'").strip() - requires_dict[group].append(package_name) else: - requires_dict["required"].append(package_name) + group = "required" + # De-duplicate (the same package could appear more than once in the extra == 'all' group) + if package_name in requires_dict[group]: + continue + requires_dict[group][package_name] = req return requires_dict +def resolve_requirement_versions(package_versions): + """ + Resolves a list of requirements for the same package. + + Given a list of package details in the form of `packaging.requirements.Requirement` + objects, combine the specifier, extras, url and marker information to create + a new requirement object. + """ + resolved = Requirement(str(package_versions[0])) + + for package_version in package_versions[1:]: + resolved.specifier = resolved.specifier & package_version.specifier + resolved.extras = resolved.extras.union(package_version.extras) + resolved.url = resolved.url or package_version.url + if resolved.marker and package_version.marker: + resolved.marker = Marker(f"{resolved.marker} or {package_version.marker}") + elif package_version.marker: + resolved.marker = package_version.marker + + return resolved + + +def format_requirement_string(requirement): + formatted_string = f"Missing {requirement}" + formatted_string = formatted_string.replace("or extra ==", "or").strip() + return formatted_string + + def find_dependencies(package="sunpy", extras=None): """ List installed and missing dependencies. @@ -49,17 +83,20 @@ def find_dependencies(package="sunpy", extras=None): """ requirements = get_requirements(package) installed_requirements = {} - missing_requirements = {} + missing_requirements = defaultdict(list) extras = extras or ["required"] for group in requirements: if group not in extras: continue - for package in requirements[group]: + for package, package_details in requirements[group].items(): try: package_version = version(package) installed_requirements[package] = package_version except PackageNotFoundError: - missing_requirements[package] = f"Missing {package}" + missing_requirements[package].append(package_details) + for package, package_versions in missing_requirements.items(): + missing_requirements[package] = format_requirement_string( + resolve_requirement_versions(package_versions)) return missing_requirements, installed_requirements @@ -80,13 +117,27 @@ def missing_dependencies_by_extra(package="sunpy", exclude_extras=None): return missing_dependencies +def get_extra_groups(groups, exclude_extras): + return list(set(groups) - set(exclude_extras)) + + +def get_keys_list(dictionary, sort=True): + keys = [*dictionary.keys()] + if sort: + return sorted(keys) + return keys + + def system_info(): """ Prints ones' system info in an "attractive" fashion. """ - base_reqs = get_requirements("sunpy")["required"] - extra_reqs = get_requirements("sunpy")["all"] - missing_packages, installed_packages = find_dependencies(package="sunpy", extras=["required", "all"]) + requirements = get_requirements("sunpy") + groups = get_keys_list(requirements) + extra_groups = get_extra_groups(groups, ['all', 'dev']) + base_reqs = get_keys_list(requirements['required']) + extra_reqs = get_keys_list(requirements['all']) + missing_packages, installed_packages = find_dependencies(package="sunpy", extras=extra_groups) extra_prop = {"System": platform.system(), "Arch": f"{platform.architecture()[0]}, ({platform.processor()})", "Python": platform.python_version(), diff --git a/tox.ini b/tox.ini index 1fd3b3e5a..5815c0fc9 100644 --- a/tox.ini +++ b/tox.ini @@ -5,7 +5,7 @@ envlist = codestyle base_deps requires = - setuptools >= 30.3.0 + setuptools >=56, !=61.0.0 pip >= 19.3.1 tox-pypi-filter >= 0.12 isolated_build = true
sunpy/sunpy
d33a7306add389e7c51c6fa5ee14b7fb0cbee869
diff --git a/sunpy/util/tests/test_sysinfo.py b/sunpy/util/tests/test_sysinfo.py index ad3ea7eeb..bba6c2ce5 100644 --- a/sunpy/util/tests/test_sysinfo.py +++ b/sunpy/util/tests/test_sysinfo.py @@ -1,4 +1,12 @@ -from sunpy.util.sysinfo import find_dependencies, missing_dependencies_by_extra, system_info +from packaging.requirements import Requirement + +from sunpy.util.sysinfo import ( + find_dependencies, + format_requirement_string, + missing_dependencies_by_extra, + resolve_requirement_versions, + system_info, +) def test_find_dependencies(): @@ -17,8 +25,19 @@ def test_find_dependencies(): def test_missing_dependencies_by_extra(): missing = missing_dependencies_by_extra() - assert sorted(list(missing.keys())) == sorted(['all', 'asdf', 'required', 'dask', 'database', 'dev', 'docs', - 'image', 'jpeg2000', 'map', 'net', 'tests', 'timeseries', + assert sorted(list(missing.keys())) == sorted(['all', + 'asdf', + 'required', + 'dask', + 'database', + 'dev', + 'docs', + 'image', + 'jpeg2000', + 'map', + 'net', + 'tests', + 'timeseries', 'visualization']) missing = missing_dependencies_by_extra(exclude_extras=["all"]) assert sorted(list(missing.keys())) == sorted(['asdf', 'required', 'dask', 'database', 'dev', 'docs', @@ -26,6 +45,35 @@ def test_missing_dependencies_by_extra(): 'visualization']) +def test_resolve_requirement_versions(): + package1 = Requirement('test-package[ext1]>=1.1.1; extra == "group1"') + package2 = Requirement('test-package[ext2]<=2.0.0; extra == "group2"') + assert str(resolve_requirement_versions([package1, package2])) == str(Requirement( + 'test-package[ext1,ext2]<=2.0.0,>=1.1.1; extra == "group1" or extra == "group2"')) + + package3 = Requirement('test-package==1.1.0; extra == "group3"') + package4 = Requirement('test-package==1.1.0; extra == "group4"') + assert str(resolve_requirement_versions([package3, package4])) == str( + Requirement('test-package==1.1.0; extra == "group3" or extra == "group4"')) + + package5 = Requirement('test-package; extra == "group5"') + package6 = Requirement('test-package[ext3]@https://foo.com') + assert str(resolve_requirement_versions([package5, package6])) == str( + Requirement('test-package[ext3]@ https://foo.com ; extra == "group5"')) + + +def test_format_requirement_string(): + package1 = Requirement('test-package[ext1]>=1.1.1; extra == "group1"') + assert format_requirement_string(package1) == 'Missing test-package[ext1]>=1.1.1; extra == "group1"' + + package2 = Requirement('test-package>=1.1.1; extra == "group1" or extra == "group2" or extra == "group3"') + assert format_requirement_string( + package2) == 'Missing test-package>=1.1.1; extra == "group1" or "group2" or "group3"' + + package3 = Requirement('test-package>=1.1.1') + assert format_requirement_string(package3) == 'Missing test-package>=1.1.1' + + def test_system_info(capsys): system_info() captured = capsys.readouterr()
system_info shows that all optional dependancies are part of the extra all rather than the more specific one ``` >>> import sunpy >>> sunpy.system_info() ============================== sunpy Installation Information ============================== General ####### OS: Arch Linux (rolling, Linux 5.16.14-arch1-1) Arch: 64bit, () sunpy: 3.1.5 Installation path: /home/stuart/.virtualenvs/sunpy-minimal/lib/python3.10/site-packages Required Dependencies ##################### parfive: 1.5.1 numpy: 1.22.3 astropy: 5.0.2 packaging: 21.3 Optional Dependencies ##################### asdf: Missing, need asdf>=2.6.0; extra == "all" beautifulsoup4: Missing, need beautifulsoup4>=4.8.0; extra == "all" cdflib: Missing, need cdflib!=0.4.0,>=0.3.19; extra == "all" dask: Missing, need dask[array]>=2.0.0; extra == "all" drms: Missing, need drms>=0.6.1; extra == "all" glymur: Missing, need glymur!=0.9.0,!=0.9.5,>=0.8.18; extra == "all" h5netcdf: Missing, need h5netcdf>=0.8.1; extra == "all" h5py: Missing, need h5py>=3.1.0; extra == "all" matplotlib: Missing, need matplotlib>=3.2.0; extra == "all" mpl-animators: Missing, need mpl-animators>=1.0.0; extra == "all" pandas: Missing, need pandas>=1.0.0; extra == "all" python-dateutil: Missing, need python-dateutil>=2.8.0; extra == "all" reproject: Missing, need reproject; extra == "all" scikit-image: Missing, need scikit-image<0.19,>=0.16.0; extra == "all" scipy: Missing, need scipy>=1.3.0; extra == "all" sqlalchemy: Missing, need sqlalchemy>=1.3.4; extra == "all" tqdm: 4.63.0 zeep: Missing, need zeep>=3.4.0; extra == "all" ```
0.0
d33a7306add389e7c51c6fa5ee14b7fb0cbee869
[ "sunpy/util/tests/test_sysinfo.py::test_find_dependencies", "sunpy/util/tests/test_sysinfo.py::test_missing_dependencies_by_extra", "sunpy/util/tests/test_sysinfo.py::test_resolve_requirement_versions", "sunpy/util/tests/test_sysinfo.py::test_format_requirement_string", "sunpy/util/tests/test_sysinfo.py::test_system_info" ]
[]
{ "failed_lite_validators": [ "has_added_files", "has_removed_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2022-03-25 03:25:07+00:00
bsd-2-clause
5,805
sunpy__sunpy-6597
diff --git a/changelog/6597.bugfix.rst b/changelog/6597.bugfix.rst new file mode 100644 index 000000000..17fb0e881 --- /dev/null +++ b/changelog/6597.bugfix.rst @@ -0,0 +1,1 @@ +Fixed the incorrect calculation in :func:`~sunpy.map.header_helper.make_fitswcs_header` of the rotation matrix from a rotation angle when the pixels are non-square. diff --git a/sunpy/map/header_helper.py b/sunpy/map/header_helper.py index f899b83eb..65faa7908 100644 --- a/sunpy/map/header_helper.py +++ b/sunpy/map/header_helper.py @@ -169,7 +169,7 @@ def _set_rotation_params(meta_wcs, rotation_angle, rotation_matrix): rotation_angle = 0 * u.deg if rotation_angle is not None: - lam = meta_wcs['cdelt1'] / meta_wcs['cdelt2'] + lam = meta_wcs['cdelt2'] / meta_wcs['cdelt1'] p = np.deg2rad(rotation_angle) rotation_matrix = np.array([[np.cos(p), -1 * lam * np.sin(p)],
sunpy/sunpy
f5bf0674f7e53df5cd6010f545ff0414bca17090
diff --git a/sunpy/map/tests/test_header_helper.py b/sunpy/map/tests/test_header_helper.py index fefd01816..1a3d5efe5 100644 --- a/sunpy/map/tests/test_header_helper.py +++ b/sunpy/map/tests/test_header_helper.py @@ -66,7 +66,14 @@ def test_metakeywords(): assert isinstance(meta, dict) -def test_deafult_rotation(map_data, hpc_coord): +def test_scale_conversion(map_data, hpc_coord): + # The header will have cunit1/2 of arcsec + header = make_fitswcs_header(map_data, hpc_coord, scale=[1, 2] * u.arcmin / u.pix) + assert header['cdelt1'] == 60 + assert header['cdelt2'] == 120 + + +def test_default_rotation(map_data, hpc_coord): header = make_fitswcs_header(map_data, hpc_coord) wcs = WCS(header) np.testing.assert_allclose(wcs.wcs.pc, [[1, 0], [0, 1]], atol=1e-5) @@ -79,6 +86,13 @@ def test_rotation_angle(map_data, hpc_coord): np.testing.assert_allclose(wcs.wcs.pc, [[0, -1], [1, 0]], atol=1e-5) +def test_rotation_angle_rectangular_pixels(map_data, hpc_coord): + header = make_fitswcs_header(map_data, hpc_coord, scale=[2, 5] * u.arcsec / u.pix, + rotation_angle=45*u.deg) + wcs = WCS(header) + np.testing.assert_allclose(wcs.wcs.pc, np.sqrt(0.5) * np.array([[1, -2.5], [0.4, 1]]), atol=1e-5) + + def test_rotation_matrix(map_data, hpc_coord): header = make_fitswcs_header(map_data, hpc_coord, rotation_matrix=np.array([[1, 0], [0, 1]]))
Header helper is bugged when creating a PCij matrix from a rotation angle for rectangular pixels As [noted on the mailing list](https://groups.google.com/d/msgid/sunpy/0352a093-e23d-4681-8113-e560bd2be92an%40googlegroups.com), the calculation in the header helper of a PCij matrix from a rotation angle is incorrect when working with rectangular pixels (`CDELT1` not equal to `CDELT2`) because `lam` is the inverse of what it should be: https://github.com/sunpy/sunpy/blob/1fa82dd5e39282ab392ae1b8ac4ad3c66b6d65da/sunpy/map/header_helper.py#L156 The analogous bug was fixed in `GenericMap` in #5766, but was missed in the header helper.
0.0
f5bf0674f7e53df5cd6010f545ff0414bca17090
[ "sunpy/map/tests/test_header_helper.py::test_rotation_angle_rectangular_pixels" ]
[ "sunpy/map/tests/test_header_helper.py::test_metakeywords", "sunpy/map/tests/test_header_helper.py::test_scale_conversion", "sunpy/map/tests/test_header_helper.py::test_default_rotation", "sunpy/map/tests/test_header_helper.py::test_rotation_angle", "sunpy/map/tests/test_header_helper.py::test_rotation_matrix", "sunpy/map/tests/test_header_helper.py::test_hpc_header", "sunpy/map/tests/test_header_helper.py::test_hgc_header", "sunpy/map/tests/test_header_helper.py::test_hgs_header", "sunpy/map/tests/test_header_helper.py::test_instrument_keyword", "sunpy/map/tests/test_header_helper.py::test_quantity_input", "sunpy/map/tests/test_header_helper.py::test_invalid_inputs", "sunpy/map/tests/test_header_helper.py::test_make_heliographic_header[CAR-shape0-carrington]", "sunpy/map/tests/test_header_helper.py::test_make_heliographic_header[CAR-shape0-stonyhurst]", "sunpy/map/tests/test_header_helper.py::test_make_heliographic_header[CAR-shape1-carrington]", "sunpy/map/tests/test_header_helper.py::test_make_heliographic_header[CAR-shape1-stonyhurst]", "sunpy/map/tests/test_header_helper.py::test_make_heliographic_header[CEA-shape0-carrington]", "sunpy/map/tests/test_header_helper.py::test_make_heliographic_header[CEA-shape0-stonyhurst]", "sunpy/map/tests/test_header_helper.py::test_make_heliographic_header[CEA-shape1-carrington]", "sunpy/map/tests/test_header_helper.py::test_make_heliographic_header[CEA-shape1-stonyhurst]", "sunpy/map/tests/test_header_helper.py::test_make_heliographic_header_invalid_inputs" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_added_files" ], "has_test_patch": true, "is_lite": false }
2022-11-11 20:13:04+00:00
bsd-2-clause
5,806
sunpy__sunpy-soar-24
diff --git a/sunpy_soar/client.py b/sunpy_soar/client.py index a2a50f4..968dcef 100644 --- a/sunpy_soar/client.py +++ b/sunpy_soar/client.py @@ -31,19 +31,14 @@ class SOARClient(BaseClient): return qrt @staticmethod - def _do_search(query): + def _construct_url(query): """ - Query the SOAR server with a single query. + Construct search URL. Parameters ---------- query : list[str] List of query items. - - Returns - ------- - astropy.table.QTable - Query results. """ base_url = ('http://soar.esac.esa.int/soar-sl-tap/tap/' 'sync?REQUEST=doQuery&') @@ -63,7 +58,24 @@ class SOARClient(BaseClient): request_str = [f'{item}={request_dict[item]}' for item in request_dict] request_str = '&'.join(request_str) - url = base_url + request_str + return base_url + request_str + + @staticmethod + def _do_search(query): + """ + Query the SOAR server with a single query. + + Parameters + ---------- + query : list[str] + List of query items. + + Returns + ------- + astropy.table.QTable + Query results. + """ + url = SOARClient._construct_url(query) log.debug(f'Getting request from URL: {url}') # Get request info r = requests.get(url) @@ -113,7 +125,7 @@ class SOARClient(BaseClient): for row in query_results: url = base_url + row['Data item ID'] - filepath = str(path).format(file=row['Filename']) + filepath = str(path).format(file=row['Filename'], **row.response_block_map) log.debug(f'Queing URL: {url}') downloader.enqueue_file(url, filename=filepath)
sunpy/sunpy-soar
fc28b4201b90f6e1a3c99b9cee0f8a3c8b7e6d07
diff --git a/sunpy_soar/tests/test_sunpy_soar.py b/sunpy_soar/tests/test_sunpy_soar.py index 45e87f9..a93fef7 100644 --- a/sunpy_soar/tests/test_sunpy_soar.py +++ b/sunpy_soar/tests/test_sunpy_soar.py @@ -70,3 +70,16 @@ def test_no_instrument(): time = a.Time('2020-04-16', '2020-04-17') res = SOARClient().search(time) assert len(res) == 50 + + +def test_download_path(tmp_path): + # Check that we can download things to a custom path using + # the search parameters + id = a.Instrument('EUI') + time = a.Time('2021-02-01', '2021-02-02') + level = a.Level(1) + res = Fido.search(id & time & level) + files = Fido.fetch(res[0, 0], path=tmp_path / '{instrument}') + assert len(files) == 1 + for f in files: + assert 'EUI' in f
SOAR client does not correctly handle string interpolation in `Fido.fetch` When using the `path=...` keyword argument in `Fido.fetch`, string interpolation can be used to direct certain files to certain directories. However, when used with the SOAR client, this throws an exception. This is demonstrated with the following code example: ```python import sunpy_soar from sunpy_soar.attrs import Product from sunpy.net import Fido, attrs as a result = Fido.search(a.Time("2021-02-12 16:0", "2021-02-13 02:00") & a.Level(2) & a.Instrument('EUI') & Product('EUI-FSI174-IMAGE')) files = Fido.fetch(result, path='{instrument}') ``` throws the following exception ```python traceback --------------------------------------------------------------------------- KeyError Traceback (most recent call last) Input In [16], in <cell line: 1>() ----> 1 files = Fido.fetch(result[0][:1], path='data/{instrument}') File ~/anaconda/envs/pyhc-summer-school/lib/python3.9/site-packages/sunpy/net/fido_factory.py:430, in UnifiedDownloaderFactory.fetch(self, path, max_conn, progress, overwrite, downloader, *query_results, **kwargs) 427 raise ValueError(f"Query result has an unrecognized type: {type(query_result)} " 428 "Allowed types are QueryResponseRow, QueryResponseTable or UnifiedResponse.") 429 for block in responses: --> 430 result = block.client.fetch(block, path=path, 431 downloader=downloader, 432 wait=False, **kwargs) 433 if result not in (NotImplemented, None): 434 reslist.append(result) File ~/anaconda/envs/pyhc-summer-school/lib/python3.9/site-packages/sunpy_soar/client.py:118, in SOARClient.fetch(self, query_results, path, downloader, **kwargs) 116 for row in query_results: 117 url = base_url + row['Data item ID'] --> 118 filepath = str(path).format(file=row['Filename']) 119 log.debug(f'Queing URL: {url}') 120 downloader.enqueue_file(url, filename=filepath) KeyError: 'instrument' ```
0.0
fc28b4201b90f6e1a3c99b9cee0f8a3c8b7e6d07
[ "sunpy_soar/tests/test_sunpy_soar.py::test_download_path" ]
[ "sunpy_soar/tests/test_sunpy_soar.py::test_deprecated_identifier", "sunpy_soar/tests/test_sunpy_soar.py::test_no_results" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2022-05-12 19:46:18+00:00
bsd-2-clause
5,807
supakeen__pinnwand-234
diff --git a/requirements.txt b/requirements.txt index 232a10f..639a635 100644 --- a/requirements.txt +++ b/requirements.txt @@ -428,9 +428,9 @@ iniconfig==2.0.0 \ isort==5.13.2 \ --hash=sha256:48fdfcb9face5d58a4f6dde2e72a1fb8dcaf8ab26f95ab49fab84c2ddefb0109 \ --hash=sha256:8ca5e72a8d85860d5a3fa69b8745237f2939afe12dbf656afbcb47fe72d947a6 -jinja2==3.1.2 \ - --hash=sha256:31351a702a408a9e7595a8fc6150fc3f43bb6bf7e319770cbc0db9df9437e852 \ - --hash=sha256:6088930bfe239f0e6710546ab9c19c9ef35e29792895fed6e6e31a023a182a61 +jinja2==3.1.3 \ + --hash=sha256:7d6d50dd97d52cbc355597bd845fabfbac3f551e1f99619e39a35ce8c370b5fa \ + --hash=sha256:ac8bd6544d4bb2c9792bf3a159e80bba8fda7f07e81bc3aed565432d5925ba90 license-expression==30.1.1 \ --hash=sha256:42375df653ad85e6f5b4b0385138b2dbea1f5d66360783d8625c3e4f97f11f0c \ --hash=sha256:8d7e5e2de0d04fc104a4f952c440e8f08a5ba63480a0dad015b294770b7e58ec diff --git a/src/pinnwand/http.py b/src/pinnwand/app.py similarity index 100% rename from src/pinnwand/http.py rename to src/pinnwand/app.py diff --git a/src/pinnwand/command.py b/src/pinnwand/command.py index 969056a..dc9ec9a 100644 --- a/src/pinnwand/command.py +++ b/src/pinnwand/command.py @@ -82,7 +82,7 @@ def main(verbose: int, configuration_path: Optional[str]) -> None: def http(port: int, debug: bool) -> None: """Run pinnwand's HTTP server.""" from pinnwand import utility - from pinnwand.http import make_application + from pinnwand.app import make_application # Reap expired pastes on startup (we might've been shut down for a while) utility.reap()
supakeen/pinnwand
9c5049e1a9ff5f5998917dac2d5ff1ea0cff9200
diff --git a/test/conftest.py b/test/conftest.py index e79684f..9c4ed31 100644 --- a/test/conftest.py +++ b/test/conftest.py @@ -36,7 +36,7 @@ def pytest_runtest_makereport(item, call): outcome = yield screen_file = str(screenshot_dir / f"{slugify(item.nodeid)}.png") report = outcome.get_result() - extra = getattr(report, "extra", []) + extras = getattr(report, "extras", []) if report.when == "call": if report.failed: if "page" in item.funcargs: @@ -44,8 +44,8 @@ def pytest_runtest_makereport(item, call): make_screenshot(item, page) xfail = hasattr(report, "wasxfail") if (report.skipped and xfail) or (report.failed and not xfail): - extra.append(pytest_html.extras.png(re.sub("test\W*e2e\W*report\W*", "", screen_file))) - report.extra = extra + extras.append(pytest_html.extras.png(re.sub(r"test\W*e2e\W*report\W*", "", screen_file))) + report.extras = extras def make_screenshot(item, page): diff --git a/test/integration/test_http_api.py b/test/integration/test_http_api.py index 9b8df48..0f03f81 100644 --- a/test/integration/test_http_api.py +++ b/test/integration/test_http_api.py @@ -10,7 +10,7 @@ configuration.ratelimit["read"]["capacity"] = 2**64 - 1 configuration.ratelimit["create"]["capacity"] = 2**64 - 1 configuration.ratelimit["delete"]["capacity"] = 2**64 - 1 -from pinnwand import configuration, database, http, utility +from pinnwand import configuration, database, app, utility class DeprecatedAPITestCase(tornado.testing.AsyncHTTPTestCase): @@ -19,7 +19,7 @@ class DeprecatedAPITestCase(tornado.testing.AsyncHTTPTestCase): database.Base.metadata.create_all(database._engine) def get_app(self) -> tornado.web.Application: - return http.make_application() + return app.make_application() def test_api_new(self) -> None: response = self.fetch( @@ -291,7 +291,7 @@ class APIv1TestCase(tornado.testing.AsyncHTTPTestCase): database.Base.metadata.create_all(database._engine) def get_app(self) -> tornado.web.Application: - return http.make_application() + return app.make_application() def test_api_new(self) -> None: response = self.fetch( diff --git a/test/integration/test_http_curl.py b/test/integration/test_http_curl.py index 08d0707..514fc08 100644 --- a/test/integration/test_http_curl.py +++ b/test/integration/test_http_curl.py @@ -10,7 +10,7 @@ configuration.ratelimit["read"]["capacity"] = 2**64 - 1 configuration.ratelimit["create"]["capacity"] = 2**64 - 1 configuration.ratelimit["delete"]["capacity"] = 2**64 - 1 -from pinnwand import database, http +from pinnwand import database, app class CurlTestCase(tornado.testing.AsyncHTTPTestCase): @@ -19,7 +19,7 @@ class CurlTestCase(tornado.testing.AsyncHTTPTestCase): database.Base.metadata.create_all(database._engine) def get_app(self) -> tornado.web.Application: - return http.make_application() + return app.make_application() def test_curl_post_no_lexer(self) -> None: response = self.fetch( diff --git a/test/integration/test_http_website.py b/test/integration/test_http_website.py index ffb2460..82cfb0e 100644 --- a/test/integration/test_http_website.py +++ b/test/integration/test_http_website.py @@ -9,7 +9,7 @@ configuration.ratelimit["read"]["capacity"] = 2**64 - 1 configuration.ratelimit["create"]["capacity"] = 2**64 - 1 configuration.ratelimit["delete"]["capacity"] = 2**64 - 1 -from pinnwand import database, http +from pinnwand import database, app class WebsiteTestCase(tornado.testing.AsyncHTTPTestCase): @@ -18,7 +18,7 @@ class WebsiteTestCase(tornado.testing.AsyncHTTPTestCase): database.Base.metadata.create_all(database._engine) def get_app(self) -> tornado.web.Application: - return http.make_application() + return app.make_application() def test_website_index(self) -> None: response = self.fetch( @@ -402,7 +402,7 @@ class DeprecatedWebsiteTestCase(tornado.testing.AsyncHTTPTestCase): database.Base.metadata.create_all(database._engine) def get_app(self) -> tornado.web.Application: - return http.make_application() + return app.make_application() def test_website_index_post_no_lexer(self) -> None: response = self.fetch(
ModuleNotFoundError: No module named 'http.cookies'; 'http' is not a package This error seems to happen particulary in `Pycharm` when I try to make a new config to run the `pinnwand` package with speciefic attributes to target the different CLI commands. It first drove me crazy, but the issue is coming from a name conflict with the built-in Python `http` library . Debugging is alot easier with `Pycharm`, at least to me. Would you be up to renaming the `http` module to `app`, since what it does eventually is make the app instance that'll later be ran.
0.0
9c5049e1a9ff5f5998917dac2d5ff1ea0cff9200
[ "test/integration/test_http_api.py::DeprecatedAPITestCase::test_api_get_expiries", "test/integration/test_http_api.py::DeprecatedAPITestCase::test_api_get_lexers", "test/integration/test_http_api.py::DeprecatedAPITestCase::test_api_new", "test/integration/test_http_api.py::DeprecatedAPITestCase::test_api_new_empty_code", "test/integration/test_http_api.py::DeprecatedAPITestCase::test_api_new_invalid_lexer", "test/integration/test_http_api.py::DeprecatedAPITestCase::test_api_new_large_file", "test/integration/test_http_api.py::DeprecatedAPITestCase::test_api_new_no_code", "test/integration/test_http_api.py::DeprecatedAPITestCase::test_api_new_no_expiry", "test/integration/test_http_api.py::DeprecatedAPITestCase::test_api_new_no_lexer", "test/integration/test_http_api.py::DeprecatedAPITestCase::test_api_new_small_file", "test/integration/test_http_api.py::DeprecatedAPITestCase::test_api_new_space_code", "test/integration/test_http_api.py::DeprecatedAPITestCase::test_api_new_wrong_method", "test/integration/test_http_api.py::DeprecatedAPITestCase::test_api_remove", "test/integration/test_http_api.py::DeprecatedAPITestCase::test_api_return_filename", "test/integration/test_http_api.py::DeprecatedAPITestCase::test_api_show", "test/integration/test_http_api.py::DeprecatedAPITestCase::test_api_show_nonexistent", "test/integration/test_http_api.py::DeprecatedAPITestCase::test_api_show_spaced", "test/integration/test_http_api.py::DeprecatedAPITestCase::test_api_show_web", "test/integration/test_http_api.py::APIv1TestCase::test_api_detail_many_files", "test/integration/test_http_api.py::APIv1TestCase::test_api_new", "test/integration/test_http_api.py::APIv1TestCase::test_api_new_invalid_body", "test/integration/test_http_api.py::APIv1TestCase::test_api_new_invalid_lexer", "test/integration/test_http_api.py::APIv1TestCase::test_api_new_large_file", "test/integration/test_http_api.py::APIv1TestCase::test_api_new_many_file", "test/integration/test_http_api.py::APIv1TestCase::test_api_new_many_file_large", "test/integration/test_http_api.py::APIv1TestCase::test_api_new_no_content", "test/integration/test_http_api.py::APIv1TestCase::test_api_new_no_expiry", "test/integration/test_http_api.py::APIv1TestCase::test_api_new_no_files", "test/integration/test_http_api.py::APIv1TestCase::test_api_new_no_lexer", "test/integration/test_http_api.py::APIv1TestCase::test_api_new_small_file", "test/integration/test_http_api.py::APIv1TestCase::test_api_new_wrong_method", "test/integration/test_http_curl.py::CurlTestCase::test_curl_post", "test/integration/test_http_curl.py::CurlTestCase::test_curl_post_empty_raw", "test/integration/test_http_curl.py::CurlTestCase::test_curl_post_no_expiry", "test/integration/test_http_curl.py::CurlTestCase::test_curl_post_no_lexer", "test/integration/test_http_curl.py::CurlTestCase::test_curl_post_no_raw", "test/integration/test_http_curl.py::CurlTestCase::test_curl_post_nonexistent_expiry", "test/integration/test_http_curl.py::CurlTestCase::test_curl_post_nonexistent_lexer", "test/integration/test_http_curl.py::CurlTestCase::test_curl_post_spaced_raw", "test/integration/test_http_curl.py::CurlTestCase::test_curl_raw", "test/integration/test_http_curl.py::CurlTestCase::test_curl_raw_spaced", "test/integration/test_http_curl.py::CurlTestCase::test_curl_remove", "test/integration/test_http_curl.py::CurlTestCase::test_curl_show", "test/integration/test_http_website.py::WebsiteTestCase::test_website_about", "test/integration/test_http_website.py::WebsiteTestCase::test_website_create_post_empty_filenames", "test/integration/test_http_website.py::WebsiteTestCase::test_website_create_post_empty_lexers", "test/integration/test_http_website.py::WebsiteTestCase::test_website_create_post_empty_raws", "test/integration/test_http_website.py::WebsiteTestCase::test_website_create_post_many", "test/integration/test_http_website.py::WebsiteTestCase::test_website_create_post_many_too_large", "test/integration/test_http_website.py::WebsiteTestCase::test_website_create_post_mismatched", "test/integration/test_http_website.py::WebsiteTestCase::test_website_create_post_multiple", "test/integration/test_http_website.py::WebsiteTestCase::test_website_create_post_nonexistent_expiry", "test/integration/test_http_website.py::WebsiteTestCase::test_website_create_post_nonexistent_lexer", "test/integration/test_http_website.py::WebsiteTestCase::test_website_create_post_nothing", "test/integration/test_http_website.py::WebsiteTestCase::test_website_create_post_only_filenames", "test/integration/test_http_website.py::WebsiteTestCase::test_website_create_post_only_lexers", "test/integration/test_http_website.py::WebsiteTestCase::test_website_create_post_only_raws", "test/integration/test_http_website.py::WebsiteTestCase::test_website_create_post_only_xsrf", "test/integration/test_http_website.py::WebsiteTestCase::test_website_create_post_raw_only_space", "test/integration/test_http_website.py::WebsiteTestCase::test_website_create_post_single", "test/integration/test_http_website.py::WebsiteTestCase::test_website_create_post_too_large", "test/integration/test_http_website.py::WebsiteTestCase::test_website_expiry", "test/integration/test_http_website.py::WebsiteTestCase::test_website_hex_nonexistent_paste", "test/integration/test_http_website.py::WebsiteTestCase::test_website_index", "test/integration/test_http_website.py::WebsiteTestCase::test_website_index_with_lexer", "test/integration/test_http_website.py::WebsiteTestCase::test_website_index_with_nonexistent_lexer", "test/integration/test_http_website.py::WebsiteTestCase::test_website_nonexistent_page", "test/integration/test_http_website.py::WebsiteTestCase::test_website_raw_nonexistent_paste", "test/integration/test_http_website.py::WebsiteTestCase::test_website_removal", "test/integration/test_http_website.py::WebsiteTestCase::test_website_show_nonexistent_paste", "test/integration/test_http_website.py::DeprecatedWebsiteTestCase::test_website_download", "test/integration/test_http_website.py::DeprecatedWebsiteTestCase::test_website_download_nonexistent_paste", "test/integration/test_http_website.py::DeprecatedWebsiteTestCase::test_website_hex", "test/integration/test_http_website.py::DeprecatedWebsiteTestCase::test_website_hex_nonexistent_paste", "test/integration/test_http_website.py::DeprecatedWebsiteTestCase::test_website_index_post", "test/integration/test_http_website.py::DeprecatedWebsiteTestCase::test_website_index_post_empty_code", "test/integration/test_http_website.py::DeprecatedWebsiteTestCase::test_website_index_post_no_code", "test/integration/test_http_website.py::DeprecatedWebsiteTestCase::test_website_index_post_no_expiry", "test/integration/test_http_website.py::DeprecatedWebsiteTestCase::test_website_index_post_no_lexer", "test/integration/test_http_website.py::DeprecatedWebsiteTestCase::test_website_index_post_nonexistent_expiry", "test/integration/test_http_website.py::DeprecatedWebsiteTestCase::test_website_index_post_nonexistent_lexer", "test/integration/test_http_website.py::DeprecatedWebsiteTestCase::test_website_logo", "test/integration/test_http_website.py::DeprecatedWebsiteTestCase::test_website_raw", "test/integration/test_http_website.py::DeprecatedWebsiteTestCase::test_website_remove", "test/integration/test_http_website.py::DeprecatedWebsiteTestCase::test_website_remove_nonexistent_paste", "test/integration/test_http_website.py::DeprecatedWebsiteTestCase::test_website_repaste", "test/integration/test_http_website.py::DeprecatedWebsiteTestCase::test_website_repaste_nonexistent_paste", "test/integration/test_http_website.py::DeprecatedWebsiteTestCase::test_website_show" ]
[]
{ "failed_lite_validators": [ "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2024-01-11 13:33:42+00:00
mit
5,808
supakeen__pinnwand-261
diff --git a/pdm.lock b/pdm.lock index 8dd8de3..75291bf 100644 --- a/pdm.lock +++ b/pdm.lock @@ -5,7 +5,7 @@ groups = ["default", "dev"] strategy = ["cross_platform"] lock_version = "4.4.1" -content_hash = "sha256:a1d2e245c8350af379963adad03a3a7d34992b3baf4f5302faf3588b6dc977fc" +content_hash = "sha256:ed8c7d415898ea8f15e65023b6c8d43be31aef16a0536d278f33bfa43911c699" [[package]] name = "bandit" @@ -25,7 +25,7 @@ files = [ [[package]] name = "black" -version = "24.2.0" +version = "24.3.0" requires_python = ">=3.8" summary = "The uncompromising code formatter." dependencies = [ @@ -38,28 +38,28 @@ dependencies = [ "typing-extensions>=4.0.1; python_version < \"3.11\"", ] files = [ - {file = "black-24.2.0-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:6981eae48b3b33399c8757036c7f5d48a535b962a7c2310d19361edeef64ce29"}, - {file = "black-24.2.0-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:d533d5e3259720fdbc1b37444491b024003e012c5173f7d06825a77508085430"}, - {file = "black-24.2.0-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:61a0391772490ddfb8a693c067df1ef5227257e72b0e4108482b8d41b5aee13f"}, - {file = "black-24.2.0-cp310-cp310-win_amd64.whl", hash = "sha256:992e451b04667116680cb88f63449267c13e1ad134f30087dec8527242e9862a"}, - {file = "black-24.2.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:163baf4ef40e6897a2a9b83890e59141cc8c2a98f2dda5080dc15c00ee1e62cd"}, - {file = "black-24.2.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:e37c99f89929af50ffaf912454b3e3b47fd64109659026b678c091a4cd450fb2"}, - {file = "black-24.2.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:4f9de21bafcba9683853f6c96c2d515e364aee631b178eaa5145fc1c61a3cc92"}, - {file = "black-24.2.0-cp311-cp311-win_amd64.whl", hash = "sha256:9db528bccb9e8e20c08e716b3b09c6bdd64da0dd129b11e160bf082d4642ac23"}, - {file = "black-24.2.0-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:d84f29eb3ee44859052073b7636533ec995bd0f64e2fb43aeceefc70090e752b"}, - {file = "black-24.2.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:1e08fb9a15c914b81dd734ddd7fb10513016e5ce7e6704bdd5e1251ceee51ac9"}, - {file = "black-24.2.0-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:810d445ae6069ce64030c78ff6127cd9cd178a9ac3361435708b907d8a04c693"}, - {file = "black-24.2.0-cp312-cp312-win_amd64.whl", hash = "sha256:ba15742a13de85e9b8f3239c8f807723991fbfae24bad92d34a2b12e81904982"}, - {file = "black-24.2.0-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:7e53a8c630f71db01b28cd9602a1ada68c937cbf2c333e6ed041390d6968faf4"}, - {file = "black-24.2.0-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:93601c2deb321b4bad8f95df408e3fb3943d85012dddb6121336b8e24a0d1218"}, - {file = "black-24.2.0-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a0057f800de6acc4407fe75bb147b0c2b5cbb7c3ed110d3e5999cd01184d53b0"}, - {file = "black-24.2.0-cp38-cp38-win_amd64.whl", hash = "sha256:faf2ee02e6612577ba0181f4347bcbcf591eb122f7841ae5ba233d12c39dcb4d"}, - {file = "black-24.2.0-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:057c3dc602eaa6fdc451069bd027a1b2635028b575a6c3acfd63193ced20d9c8"}, - {file = "black-24.2.0-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:08654d0797e65f2423f850fc8e16a0ce50925f9337fb4a4a176a7aa4026e63f8"}, - {file = "black-24.2.0-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:ca610d29415ee1a30a3f30fab7a8f4144e9d34c89a235d81292a1edb2b55f540"}, - {file = "black-24.2.0-cp39-cp39-win_amd64.whl", hash = "sha256:4dd76e9468d5536abd40ffbc7a247f83b2324f0c050556d9c371c2b9a9a95e31"}, - {file = "black-24.2.0-py3-none-any.whl", hash = "sha256:e8a6ae970537e67830776488bca52000eaa37fa63b9988e8c487458d9cd5ace6"}, - {file = "black-24.2.0.tar.gz", hash = "sha256:bce4f25c27c3435e4dace4815bcb2008b87e167e3bf4ee47ccdc5ce906eb4894"}, + {file = "black-24.3.0-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:7d5e026f8da0322b5662fa7a8e752b3fa2dac1c1cbc213c3d7ff9bdd0ab12395"}, + {file = "black-24.3.0-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:9f50ea1132e2189d8dff0115ab75b65590a3e97de1e143795adb4ce317934995"}, + {file = "black-24.3.0-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:e2af80566f43c85f5797365077fb64a393861a3730bd110971ab7a0c94e873e7"}, + {file = "black-24.3.0-cp310-cp310-win_amd64.whl", hash = "sha256:4be5bb28e090456adfc1255e03967fb67ca846a03be7aadf6249096100ee32d0"}, + {file = "black-24.3.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:4f1373a7808a8f135b774039f61d59e4be7eb56b2513d3d2f02a8b9365b8a8a9"}, + {file = "black-24.3.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:aadf7a02d947936ee418777e0247ea114f78aff0d0959461057cae8a04f20597"}, + {file = "black-24.3.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:65c02e4ea2ae09d16314d30912a58ada9a5c4fdfedf9512d23326128ac08ac3d"}, + {file = "black-24.3.0-cp311-cp311-win_amd64.whl", hash = "sha256:bf21b7b230718a5f08bd32d5e4f1db7fc8788345c8aea1d155fc17852b3410f5"}, + {file = "black-24.3.0-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:2818cf72dfd5d289e48f37ccfa08b460bf469e67fb7c4abb07edc2e9f16fb63f"}, + {file = "black-24.3.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:4acf672def7eb1725f41f38bf6bf425c8237248bb0804faa3965c036f7672d11"}, + {file = "black-24.3.0-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:c7ed6668cbbfcd231fa0dc1b137d3e40c04c7f786e626b405c62bcd5db5857e4"}, + {file = "black-24.3.0-cp312-cp312-win_amd64.whl", hash = "sha256:56f52cfbd3dabe2798d76dbdd299faa046a901041faf2cf33288bc4e6dae57b5"}, + {file = "black-24.3.0-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:79dcf34b33e38ed1b17434693763301d7ccbd1c5860674a8f871bd15139e7837"}, + {file = "black-24.3.0-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:e19cb1c6365fd6dc38a6eae2dcb691d7d83935c10215aef8e6c38edee3f77abd"}, + {file = "black-24.3.0-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:65b76c275e4c1c5ce6e9870911384bff5ca31ab63d19c76811cb1fb162678213"}, + {file = "black-24.3.0-cp38-cp38-win_amd64.whl", hash = "sha256:b5991d523eee14756f3c8d5df5231550ae8993e2286b8014e2fdea7156ed0959"}, + {file = "black-24.3.0-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:c45f8dff244b3c431b36e3224b6be4a127c6aca780853574c00faf99258041eb"}, + {file = "black-24.3.0-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:6905238a754ceb7788a73f02b45637d820b2f5478b20fec82ea865e4f5d4d9f7"}, + {file = "black-24.3.0-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:d7de8d330763c66663661a1ffd432274a2f92f07feeddd89ffd085b5744f85e7"}, + {file = "black-24.3.0-cp39-cp39-win_amd64.whl", hash = "sha256:7bb041dca0d784697af4646d3b62ba4a6b028276ae878e53f6b4f74ddd6db99f"}, + {file = "black-24.3.0-py3-none-any.whl", hash = "sha256:41622020d7120e01d377f74249e677039d20e6344ff5851de8a10f11f513bf93"}, + {file = "black-24.3.0.tar.gz", hash = "sha256:a0c9c4a0771afc6919578cec71ce82a3e31e054904e7197deacbc9382671c41f"}, ] [[package]] @@ -1160,6 +1160,7 @@ files = [ {file = "PyYAML-6.0.1-cp311-cp311-win_amd64.whl", hash = "sha256:bf07ee2fef7014951eeb99f56f39c9bb4af143d8aa3c21b1677805985307da34"}, {file = "PyYAML-6.0.1-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:855fb52b0dc35af121542a76b9a84f8d1cd886ea97c84703eaa6d88e37a2ad28"}, {file = "PyYAML-6.0.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:40df9b996c2b73138957fe23a16a4f0ba614f4c0efce1e9406a184b6d07fa3a9"}, + {file = "PyYAML-6.0.1-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:a08c6f0fe150303c1c6b71ebcd7213c2858041a7e01975da3a99aed1e7a378ef"}, {file = "PyYAML-6.0.1-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:6c22bec3fbe2524cde73d7ada88f6566758a8f7227bfbf93a408a9d86bcc12a0"}, {file = "PyYAML-6.0.1-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:8d4e9c88387b0f5c7d5f281e55304de64cf7f9c0021a3525bd3b1c542da3b0e4"}, {file = "PyYAML-6.0.1-cp312-cp312-win32.whl", hash = "sha256:d483d2cdf104e7c9fa60c544d92981f12ad66a457afae824d146093b8c294c54"}, diff --git a/pyproject.toml b/pyproject.toml index 49d15cd..071a2d4 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -29,7 +29,7 @@ license = {text = "MIT"} dev = [ "pytest>=7.3.1", "coverage>=7.2.7", - "black>=23.3.0", + "black>=24.3.0", "pytest-cov>=4.1.0", "pre-commit>=3.3.2", "mypy>=1.3.0", diff --git a/requirements.txt b/requirements.txt index da92629..533f74b 100644 --- a/requirements.txt +++ b/requirements.txt @@ -4,29 +4,29 @@ bandit==1.7.8 \ --hash=sha256:36de50f720856ab24a24dbaa5fee2c66050ed97c1477e0a1159deab1775eab6b \ --hash=sha256:509f7af645bc0cd8fd4587abc1a038fc795636671ee8204d502b933aee44f381 -black==24.2.0 \ - --hash=sha256:057c3dc602eaa6fdc451069bd027a1b2635028b575a6c3acfd63193ced20d9c8 \ - --hash=sha256:08654d0797e65f2423f850fc8e16a0ce50925f9337fb4a4a176a7aa4026e63f8 \ - --hash=sha256:163baf4ef40e6897a2a9b83890e59141cc8c2a98f2dda5080dc15c00ee1e62cd \ - --hash=sha256:1e08fb9a15c914b81dd734ddd7fb10513016e5ce7e6704bdd5e1251ceee51ac9 \ - --hash=sha256:4dd76e9468d5536abd40ffbc7a247f83b2324f0c050556d9c371c2b9a9a95e31 \ - --hash=sha256:4f9de21bafcba9683853f6c96c2d515e364aee631b178eaa5145fc1c61a3cc92 \ - --hash=sha256:61a0391772490ddfb8a693c067df1ef5227257e72b0e4108482b8d41b5aee13f \ - --hash=sha256:6981eae48b3b33399c8757036c7f5d48a535b962a7c2310d19361edeef64ce29 \ - --hash=sha256:7e53a8c630f71db01b28cd9602a1ada68c937cbf2c333e6ed041390d6968faf4 \ - --hash=sha256:810d445ae6069ce64030c78ff6127cd9cd178a9ac3361435708b907d8a04c693 \ - --hash=sha256:93601c2deb321b4bad8f95df408e3fb3943d85012dddb6121336b8e24a0d1218 \ - --hash=sha256:992e451b04667116680cb88f63449267c13e1ad134f30087dec8527242e9862a \ - --hash=sha256:9db528bccb9e8e20c08e716b3b09c6bdd64da0dd129b11e160bf082d4642ac23 \ - --hash=sha256:a0057f800de6acc4407fe75bb147b0c2b5cbb7c3ed110d3e5999cd01184d53b0 \ - --hash=sha256:ba15742a13de85e9b8f3239c8f807723991fbfae24bad92d34a2b12e81904982 \ - --hash=sha256:bce4f25c27c3435e4dace4815bcb2008b87e167e3bf4ee47ccdc5ce906eb4894 \ - --hash=sha256:ca610d29415ee1a30a3f30fab7a8f4144e9d34c89a235d81292a1edb2b55f540 \ - --hash=sha256:d533d5e3259720fdbc1b37444491b024003e012c5173f7d06825a77508085430 \ - --hash=sha256:d84f29eb3ee44859052073b7636533ec995bd0f64e2fb43aeceefc70090e752b \ - --hash=sha256:e37c99f89929af50ffaf912454b3e3b47fd64109659026b678c091a4cd450fb2 \ - --hash=sha256:e8a6ae970537e67830776488bca52000eaa37fa63b9988e8c487458d9cd5ace6 \ - --hash=sha256:faf2ee02e6612577ba0181f4347bcbcf591eb122f7841ae5ba233d12c39dcb4d +black==24.3.0 \ + --hash=sha256:2818cf72dfd5d289e48f37ccfa08b460bf469e67fb7c4abb07edc2e9f16fb63f \ + --hash=sha256:41622020d7120e01d377f74249e677039d20e6344ff5851de8a10f11f513bf93 \ + --hash=sha256:4acf672def7eb1725f41f38bf6bf425c8237248bb0804faa3965c036f7672d11 \ + --hash=sha256:4be5bb28e090456adfc1255e03967fb67ca846a03be7aadf6249096100ee32d0 \ + --hash=sha256:4f1373a7808a8f135b774039f61d59e4be7eb56b2513d3d2f02a8b9365b8a8a9 \ + --hash=sha256:56f52cfbd3dabe2798d76dbdd299faa046a901041faf2cf33288bc4e6dae57b5 \ + --hash=sha256:65b76c275e4c1c5ce6e9870911384bff5ca31ab63d19c76811cb1fb162678213 \ + --hash=sha256:65c02e4ea2ae09d16314d30912a58ada9a5c4fdfedf9512d23326128ac08ac3d \ + --hash=sha256:6905238a754ceb7788a73f02b45637d820b2f5478b20fec82ea865e4f5d4d9f7 \ + --hash=sha256:79dcf34b33e38ed1b17434693763301d7ccbd1c5860674a8f871bd15139e7837 \ + --hash=sha256:7bb041dca0d784697af4646d3b62ba4a6b028276ae878e53f6b4f74ddd6db99f \ + --hash=sha256:7d5e026f8da0322b5662fa7a8e752b3fa2dac1c1cbc213c3d7ff9bdd0ab12395 \ + --hash=sha256:9f50ea1132e2189d8dff0115ab75b65590a3e97de1e143795adb4ce317934995 \ + --hash=sha256:a0c9c4a0771afc6919578cec71ce82a3e31e054904e7197deacbc9382671c41f \ + --hash=sha256:aadf7a02d947936ee418777e0247ea114f78aff0d0959461057cae8a04f20597 \ + --hash=sha256:b5991d523eee14756f3c8d5df5231550ae8993e2286b8014e2fdea7156ed0959 \ + --hash=sha256:bf21b7b230718a5f08bd32d5e4f1db7fc8788345c8aea1d155fc17852b3410f5 \ + --hash=sha256:c45f8dff244b3c431b36e3224b6be4a127c6aca780853574c00faf99258041eb \ + --hash=sha256:c7ed6668cbbfcd231fa0dc1b137d3e40c04c7f786e626b405c62bcd5db5857e4 \ + --hash=sha256:d7de8d330763c66663661a1ffd432274a2f92f07feeddd89ffd085b5744f85e7 \ + --hash=sha256:e19cb1c6365fd6dc38a6eae2dcb691d7d83935c10215aef8e6c38edee3f77abd \ + --hash=sha256:e2af80566f43c85f5797365077fb64a393861a3730bd110971ab7a0c94e873e7 boolean-py==4.0 \ --hash=sha256:17b9a181630e43dde1851d42bef546d616d5d9b4480357514597e78b203d06e4 \ --hash=sha256:2876f2051d7d6394a531d82dc6eb407faa0b01a0a0b3083817ccd7323b8d96bd diff --git a/src/pinnwand/defensive.py b/src/pinnwand/defensive.py index 0b64d53..4a5ebd5 100644 --- a/src/pinnwand/defensive.py +++ b/src/pinnwand/defensive.py @@ -1,6 +1,5 @@ -import ipaddress import re -from typing import Dict, Union +from typing import Dict from functools import wraps import token_bucket @@ -13,18 +12,10 @@ from pinnwand.configuration import Configuration, ConfigurationProvider log = logger.get_logger(__name__) -ratelimit_area: Dict[ - str, - Dict[ - Union[ipaddress.IPv4Address, ipaddress.IPv6Address], - token_bucket.Limiter, - ], -] = {} +ratelimit_area: Dict[str, token_bucket.Limiter] = {} -def should_be_ratelimited( - request: HTTPServerRequest, area: str = "global" -) -> bool: +def should_be_ratelimited(ip_address: str, area: str = "global") -> bool: """Test if a requesting IP is ratelimited for a certain area. Areas are different functionalities of the website, for example 'view' or 'input' to differentiate between creating new pastes (low volume) or high volume @@ -38,20 +29,17 @@ def should_be_ratelimited( configuration: Configuration = ConfigurationProvider.get_config() if area not in ratelimit_area: - ratelimit_area[area] = {} - - # TODO handle valueerror as validationerror? - address = ipaddress.ip_address(str(request.remote_ip)) - - if address not in ratelimit_area[area]: - ratelimit_area[area][address] = token_bucket.Limiter( + ratelimit_area[area] = token_bucket.Limiter( configuration.ratelimit[area]["refill"], configuration.ratelimit[area]["capacity"], token_bucket.MemoryStorage(), ) - if not ratelimit_area[area][address].consume(1): - log.warning("%s hit rate limit for %r", address, area) + if not ratelimit_area[area].consume( + ip_address.encode("utf-8"), + configuration.ratelimit[area]["consume"], + ): + log.warning("%s hit rate limit for %r", ip_address, area) return True return False @@ -63,7 +51,7 @@ def ratelimit(area: str): def wrapper(func): @wraps(func) def inner(request_handler: RequestHandler, *args, **kwargs): - if should_be_ratelimited(request_handler.request, area): + if should_be_ratelimited(request_handler.request.remote_ip, area): raise error.RatelimitError() return func(request_handler, *args, **kwargs) diff --git a/src/pinnwand/handler/api_curl.py b/src/pinnwand/handler/api_curl.py index 1fca553..1cf569e 100644 --- a/src/pinnwand/handler/api_curl.py +++ b/src/pinnwand/handler/api_curl.py @@ -31,7 +31,6 @@ class Create(tornado.web.RequestHandler): @defensive.ratelimit(area="create") def post(self) -> None: - configuration: Configuration = ConfigurationProvider.get_config() lexer = self.get_body_argument("lexer", "text") raw = self.get_body_argument("raw", "", strip=False)
supakeen/pinnwand
97525e394f263dd6aaa56da6ba090e262d536631
diff --git a/test/integration/test_http_api.py b/test/integration/test_http_api.py index 47b6dd5..672e8ac 100644 --- a/test/integration/test_http_api.py +++ b/test/integration/test_http_api.py @@ -1,20 +1,23 @@ import json +import copy import urllib.parse - +import unittest.mock import tornado.testing import tornado.web from pinnwand.configuration import Configuration, ConfigurationProvider +from pinnwand import app, utility +from pinnwand.database import manager, utils as database_utils + configuration: Configuration = ConfigurationProvider.get_config() -configuration._ratelimit["read"]["capacity"] = 2**64 - 1 -configuration._ratelimit["create"]["capacity"] = 2**64 - 1 -configuration._ratelimit["delete"]["capacity"] = 2**64 - 1 -from pinnwand import app, utility -from pinnwand.database import manager, utils as database_utils +ratelimit_copy = copy.deepcopy(configuration._ratelimit) +for area in ("read", "create", "delete"): + ratelimit_copy[area]["capacity"] = 2**64 - 1 [email protected](configuration._ratelimit, ratelimit_copy) class DeprecatedAPITestCase(tornado.testing.AsyncHTTPTestCase): def setUp(self) -> None: super().setUp() @@ -117,7 +120,6 @@ class DeprecatedAPITestCase(tornado.testing.AsyncHTTPTestCase): ), ) - print(response.body) assert response.code == 200 def test_api_new_large_file(self) -> None: diff --git a/test/integration/test_http_curl.py b/test/integration/test_http_curl.py index d648b74..489e23d 100644 --- a/test/integration/test_http_curl.py +++ b/test/integration/test_http_curl.py @@ -1,20 +1,22 @@ import re import urllib.parse - +import unittest.mock import tornado.testing import tornado.web - +import copy from pinnwand.configuration import Configuration, ConfigurationProvider -configuration: Configuration = ConfigurationProvider.get_config() - -configuration._ratelimit["read"]["capacity"] = 2**64 - 1 -configuration._ratelimit["create"]["capacity"] = 2**64 - 1 -configuration._ratelimit["delete"]["capacity"] = 2**64 - 1 from pinnwand import app from pinnwand.database import manager, utils as database_utils +configuration: Configuration = ConfigurationProvider.get_config() +ratelimit_copy = copy.deepcopy(configuration._ratelimit) +for area in ("read", "create", "delete"): + ratelimit_copy[area]["capacity"] = 2**64 - 1 + + [email protected](configuration._ratelimit, ratelimit_copy) class CurlTestCase(tornado.testing.AsyncHTTPTestCase): def setUp(self) -> None: super().setUp() @@ -131,7 +133,6 @@ class CurlTestCase(tornado.testing.AsyncHTTPTestCase): .group(1) # type: ignore .decode("ascii") ) - print(paste) paste = urllib.parse.urlparse(paste).path response = self.fetch( @@ -157,8 +158,6 @@ class CurlTestCase(tornado.testing.AsyncHTTPTestCase): ) paste = urllib.parse.urlparse(paste).path - print(repr(paste)) - response = self.fetch( paste, method="GET", @@ -262,8 +261,6 @@ class CurlTestCase(tornado.testing.AsyncHTTPTestCase): follow_redirects=False, ) - print(response.body) - paste = ( re.search(b"Paste URL: (.*)", response.body) .group(1) # type: ignore diff --git a/test/integration/test_http_ratelimit.py b/test/integration/test_http_ratelimit.py new file mode 100644 index 0000000..ce3e60b --- /dev/null +++ b/test/integration/test_http_ratelimit.py @@ -0,0 +1,90 @@ +import copy +import time +import unittest.mock + +import tornado.testing +import tornado.web + +from pinnwand import app, configuration, defensive + + +class RateLimitTestCase(tornado.testing.AsyncHTTPTestCase): + + def get_app(self) -> tornado.web.Application: + return app.make_application() + + def test_ratelimit_verification_on_endpoints(self): + with unittest.mock.patch("pinnwand.defensive.should_be_ratelimited") as patch: + patch.return_value = False + + self.fetch( + "/", + method="GET", + ) + + patch.assert_called() + patch.reset_mock() + + def test_ratelimit_application_on_one_client(self): + config = configuration.ConfigurationProvider.get_config() + ratelimlit_copy = copy.deepcopy(config._ratelimit) + ratelimlit_copy["read"]["capacity"] = 2 + ratelimlit_copy["read"]["consume"] = 2 + ratelimlit_copy["read"]["refill"] = 1 + + with unittest.mock.patch.dict("pinnwand.defensive.ConfigurationProvider._config._ratelimit", ratelimlit_copy): + with unittest.mock.patch.dict("pinnwand.defensive.ratelimit_area", clear=True): + response = self.fetch( + "/", + method="GET", + ) + + assert response.code == 200 + + response = self.fetch( + "/", + method="GET", + ) + + assert response.code == 429 + + def test_ratelimit_application_on_multiple_clients(self): + config = configuration.ConfigurationProvider.get_config() + ratelimlit_copy = copy.deepcopy(config._ratelimit) + area = "read" + ratelimlit_copy[area]["capacity"] = 10 + ratelimlit_copy[area]["consume"] = 7 + ratelimlit_copy[area]["refill"] = 1 + + ip1 = "192.168.15.32" + ip2 = "10.45.134.23" + + with unittest.mock.patch.dict("pinnwand.defensive.ConfigurationProvider._config._ratelimit", ratelimlit_copy): + with unittest.mock.patch.dict("pinnwand.defensive.ratelimit_area", clear=True): + assert defensive.should_be_ratelimited(ip1, area) is False + assert defensive.should_be_ratelimited(ip1, area) is True + assert defensive.should_be_ratelimited(ip2, area) is False + assert defensive.should_be_ratelimited(ip2, area) is True + assert defensive.should_be_ratelimited(ip2, area) is True + time.sleep(10) # Give it enough time to replenish + assert defensive.should_be_ratelimited(ip1, area) is False + assert defensive.should_be_ratelimited(ip2, area) is False + + def test_bucket_tokens_consumption(self): + config = configuration.ConfigurationProvider.get_config() + ratelimlit_copy = copy.deepcopy(config._ratelimit) + area = "read" + consumption = 7 + capacity = 10 + ratelimlit_copy[area]["capacity"] = capacity + ratelimlit_copy[area]["consume"] = consumption + ratelimlit_copy[area]["refill"] = 1 + + ip = "192.168.15.32" + with unittest.mock.patch.dict("pinnwand.defensive.ConfigurationProvider._config._ratelimit", ratelimlit_copy): + with unittest.mock.patch.dict("pinnwand.defensive.ratelimit_area", clear=True): + defensive.should_be_ratelimited(ip, area) + limiter = defensive.ratelimit_area[area] + tokens_remaining = limiter._storage.get_token_count(ip.encode("utf-8")) + assert tokens_remaining == capacity - consumption + diff --git a/test/integration/test_http_website.py b/test/integration/test_http_website.py index cbe19ea..630bd26 100644 --- a/test/integration/test_http_website.py +++ b/test/integration/test_http_website.py @@ -1,20 +1,22 @@ import urllib.parse - +import unittest.mock import tornado.testing import tornado.web - +import copy from pinnwand.configuration import Configuration, ConfigurationProvider +from pinnwand import app +from pinnwand.database import manager, utils as database_utils + configuration: Configuration = ConfigurationProvider.get_config() -configuration._ratelimit["read"]["capacity"] = 2**64 - 1 -configuration._ratelimit["create"]["capacity"] = 2**64 - 1 -configuration._ratelimit["delete"]["capacity"] = 2**64 - 1 -from pinnwand import app -from pinnwand.database import manager, utils as database_utils +ratelimit_copy = copy.deepcopy(configuration._ratelimit) +for area in ("read", "create", "delete"): + ratelimit_copy[area]["capacity"] = 2**64 - 1 [email protected](configuration._ratelimit, ratelimit_copy) class WebsiteTestCase(tornado.testing.AsyncHTTPTestCase): def setUp(self) -> None: super().setUp()
Fix consume ratelimit config Configuration for rate limits lets you set the consume rate: https://github.com/supakeen/pinnwand/blob/e737aba402548f83bc458c62ac6e10e69419f2b1/src/pinnwand/configuration.py#L12-L26 However, this configuration is not used, instead the consume value is always 1: https://github.com/supakeen/pinnwand/blob/e737aba402548f83bc458c62ac6e10e69419f2b1/src/pinnwand/defensive.py#L46
0.0
97525e394f263dd6aaa56da6ba090e262d536631
[ "test/integration/test_http_ratelimit.py::RateLimitTestCase::test_bucket_tokens_consumption", "test/integration/test_http_ratelimit.py::RateLimitTestCase::test_ratelimit_application_on_multiple_clients", "test/integration/test_http_ratelimit.py::RateLimitTestCase::test_ratelimit_application_on_one_client" ]
[ "test/integration/test_http_api.py::DeprecatedAPITestCase::test_api_get_expiries", "test/integration/test_http_api.py::DeprecatedAPITestCase::test_api_get_lexers", "test/integration/test_http_api.py::DeprecatedAPITestCase::test_api_new", "test/integration/test_http_api.py::DeprecatedAPITestCase::test_api_new_empty_code", "test/integration/test_http_api.py::DeprecatedAPITestCase::test_api_new_invalid_lexer", "test/integration/test_http_api.py::DeprecatedAPITestCase::test_api_new_large_file", "test/integration/test_http_api.py::DeprecatedAPITestCase::test_api_new_no_code", "test/integration/test_http_api.py::DeprecatedAPITestCase::test_api_new_no_expiry", "test/integration/test_http_api.py::DeprecatedAPITestCase::test_api_new_no_lexer", "test/integration/test_http_api.py::DeprecatedAPITestCase::test_api_new_small_file", "test/integration/test_http_api.py::DeprecatedAPITestCase::test_api_new_space_code", "test/integration/test_http_api.py::DeprecatedAPITestCase::test_api_new_wrong_method", "test/integration/test_http_api.py::DeprecatedAPITestCase::test_api_remove", "test/integration/test_http_api.py::DeprecatedAPITestCase::test_api_return_filename", "test/integration/test_http_api.py::DeprecatedAPITestCase::test_api_show", "test/integration/test_http_api.py::DeprecatedAPITestCase::test_api_show_nonexistent", "test/integration/test_http_api.py::DeprecatedAPITestCase::test_api_show_spaced", "test/integration/test_http_api.py::DeprecatedAPITestCase::test_api_show_web", "test/integration/test_http_api.py::APIv1TestCase::test_api_detail_many_files", "test/integration/test_http_api.py::APIv1TestCase::test_api_new", "test/integration/test_http_api.py::APIv1TestCase::test_api_new_invalid_body", "test/integration/test_http_api.py::APIv1TestCase::test_api_new_invalid_lexer", "test/integration/test_http_api.py::APIv1TestCase::test_api_new_large_file", "test/integration/test_http_api.py::APIv1TestCase::test_api_new_many_file", "test/integration/test_http_api.py::APIv1TestCase::test_api_new_many_file_large", "test/integration/test_http_api.py::APIv1TestCase::test_api_new_no_content", "test/integration/test_http_api.py::APIv1TestCase::test_api_new_no_expiry", "test/integration/test_http_api.py::APIv1TestCase::test_api_new_no_files", "test/integration/test_http_api.py::APIv1TestCase::test_api_new_no_lexer", "test/integration/test_http_api.py::APIv1TestCase::test_api_new_small_file", "test/integration/test_http_api.py::APIv1TestCase::test_api_new_wrong_method", "test/integration/test_http_curl.py::CurlTestCase::test_curl_post", "test/integration/test_http_curl.py::CurlTestCase::test_curl_post_empty_raw", "test/integration/test_http_curl.py::CurlTestCase::test_curl_post_no_expiry", "test/integration/test_http_curl.py::CurlTestCase::test_curl_post_no_lexer", "test/integration/test_http_curl.py::CurlTestCase::test_curl_post_no_raw", "test/integration/test_http_curl.py::CurlTestCase::test_curl_post_nonexistent_expiry", "test/integration/test_http_curl.py::CurlTestCase::test_curl_post_nonexistent_lexer", "test/integration/test_http_curl.py::CurlTestCase::test_curl_post_spaced_raw", "test/integration/test_http_curl.py::CurlTestCase::test_curl_raw", "test/integration/test_http_curl.py::CurlTestCase::test_curl_raw_spaced", "test/integration/test_http_curl.py::CurlTestCase::test_curl_remove", "test/integration/test_http_curl.py::CurlTestCase::test_curl_show", "test/integration/test_http_ratelimit.py::RateLimitTestCase::test_ratelimit_verification_on_endpoints", "test/integration/test_http_website.py::WebsiteTestCase::test_website_about", "test/integration/test_http_website.py::WebsiteTestCase::test_website_create_post_empty_filenames", "test/integration/test_http_website.py::WebsiteTestCase::test_website_create_post_empty_lexers", "test/integration/test_http_website.py::WebsiteTestCase::test_website_create_post_empty_raws", "test/integration/test_http_website.py::WebsiteTestCase::test_website_create_post_many", "test/integration/test_http_website.py::WebsiteTestCase::test_website_create_post_many_too_large", "test/integration/test_http_website.py::WebsiteTestCase::test_website_create_post_mismatched", "test/integration/test_http_website.py::WebsiteTestCase::test_website_create_post_multiple", "test/integration/test_http_website.py::WebsiteTestCase::test_website_create_post_nonexistent_expiry", "test/integration/test_http_website.py::WebsiteTestCase::test_website_create_post_nonexistent_lexer", "test/integration/test_http_website.py::WebsiteTestCase::test_website_create_post_nothing", "test/integration/test_http_website.py::WebsiteTestCase::test_website_create_post_only_filenames", "test/integration/test_http_website.py::WebsiteTestCase::test_website_create_post_only_lexers", "test/integration/test_http_website.py::WebsiteTestCase::test_website_create_post_only_raws", "test/integration/test_http_website.py::WebsiteTestCase::test_website_create_post_only_xsrf", "test/integration/test_http_website.py::WebsiteTestCase::test_website_create_post_raw_only_space", "test/integration/test_http_website.py::WebsiteTestCase::test_website_create_post_single", "test/integration/test_http_website.py::WebsiteTestCase::test_website_create_post_too_large", "test/integration/test_http_website.py::WebsiteTestCase::test_website_expiry", "test/integration/test_http_website.py::WebsiteTestCase::test_website_hex_nonexistent_paste", "test/integration/test_http_website.py::WebsiteTestCase::test_website_index", "test/integration/test_http_website.py::WebsiteTestCase::test_website_index_with_lexer", "test/integration/test_http_website.py::WebsiteTestCase::test_website_index_with_nonexistent_lexer", "test/integration/test_http_website.py::WebsiteTestCase::test_website_nonexistent_page", "test/integration/test_http_website.py::WebsiteTestCase::test_website_raw_nonexistent_paste", "test/integration/test_http_website.py::WebsiteTestCase::test_website_removal", "test/integration/test_http_website.py::WebsiteTestCase::test_website_show_nonexistent_paste", "test/integration/test_http_website.py::DeprecatedWebsiteTestCase::test_website_download", "test/integration/test_http_website.py::DeprecatedWebsiteTestCase::test_website_download_nonexistent_paste", "test/integration/test_http_website.py::DeprecatedWebsiteTestCase::test_website_hex", "test/integration/test_http_website.py::DeprecatedWebsiteTestCase::test_website_hex_nonexistent_paste", "test/integration/test_http_website.py::DeprecatedWebsiteTestCase::test_website_index_post", "test/integration/test_http_website.py::DeprecatedWebsiteTestCase::test_website_index_post_empty_code", "test/integration/test_http_website.py::DeprecatedWebsiteTestCase::test_website_index_post_no_code", "test/integration/test_http_website.py::DeprecatedWebsiteTestCase::test_website_index_post_no_expiry", "test/integration/test_http_website.py::DeprecatedWebsiteTestCase::test_website_index_post_no_lexer", "test/integration/test_http_website.py::DeprecatedWebsiteTestCase::test_website_index_post_nonexistent_expiry", "test/integration/test_http_website.py::DeprecatedWebsiteTestCase::test_website_index_post_nonexistent_lexer", "test/integration/test_http_website.py::DeprecatedWebsiteTestCase::test_website_logo", "test/integration/test_http_website.py::DeprecatedWebsiteTestCase::test_website_raw", "test/integration/test_http_website.py::DeprecatedWebsiteTestCase::test_website_remove", "test/integration/test_http_website.py::DeprecatedWebsiteTestCase::test_website_remove_nonexistent_paste", "test/integration/test_http_website.py::DeprecatedWebsiteTestCase::test_website_repaste", "test/integration/test_http_website.py::DeprecatedWebsiteTestCase::test_website_repaste_nonexistent_paste", "test/integration/test_http_website.py::DeprecatedWebsiteTestCase::test_website_show" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2024-03-20 10:07:41+00:00
mit
5,809
svenevs__ci_exec-29
diff --git a/ci_exec/parsers/cmake_parser.py b/ci_exec/parsers/cmake_parser.py index 5fa9cd8..267904f 100644 --- a/ci_exec/parsers/cmake_parser.py +++ b/ci_exec/parsers/cmake_parser.py @@ -261,6 +261,13 @@ class CMakeParser(argparse.ArgumentParser): __ https://cmake.org/cmake/help/latest/generator/Ninja.html """ + ninja_multi_generator = {"Ninja Multi-Config"} + """ + The `Ninja Multi-Config Generator`__. + + __ https://cmake.org/cmake/help/latest/generator/Ninja%20Multi-Config.html + """ + visual_studio_generators = { "Visual Studio 9 2008", "Visual Studio 10 2010", @@ -268,7 +275,8 @@ class CMakeParser(argparse.ArgumentParser): "Visual Studio 12 2013", "Visual Studio 14 2015", "Visual Studio 15 2017", - "Visual Studio 16 2019" + "Visual Studio 16 2019", + "Visual Studio 17 2022" } """ The `Visual Studio Generators`__. @@ -286,7 +294,8 @@ class CMakeParser(argparse.ArgumentParser): @classmethod def is_multi_config_generator(cls, generator: str) -> bool: """Whether or not string ``generator`` is a multi-config generator.""" - return generator in (cls.visual_studio_generators | cls.other_generators) + return generator in (cls.visual_studio_generators | cls.other_generators | + cls.ninja_multi_generator) @classmethod def is_single_config_generator(cls, generator: str) -> bool: @@ -310,7 +319,8 @@ class CMakeParser(argparse.ArgumentParser): help="Generator to use (CMake -G flag).", choices=sorted( self.makefile_generators | self.ninja_generator | - self.visual_studio_generators | self.other_generators + self.ninja_multi_generator | self.visual_studio_generators | + self.other_generators ) )
svenevs/ci_exec
1b513bfc2720334c7eda4a49519013fa644a8a9d
diff --git a/tests/parsers/cmake_parser.py b/tests/parsers/cmake_parser.py index 3b60354..10308f0 100644 --- a/tests/parsers/cmake_parser.py +++ b/tests/parsers/cmake_parser.py @@ -53,7 +53,8 @@ def test_cmake_parser_is_x_config_generator(): assert CMakeParser.is_single_config_generator(g) assert not CMakeParser.is_multi_config_generator(g) - for g in chain(CMakeParser.visual_studio_generators, CMakeParser.other_generators): + for g in chain(CMakeParser.visual_studio_generators, CMakeParser.other_generators, + CMakeParser.ninja_multi_generator): assert not CMakeParser.is_single_config_generator(g) assert CMakeParser.is_multi_config_generator(g) @@ -492,3 +493,9 @@ def test_cmake_parser_single_vs_multi_configure_build_args(): ]) assert "-DCMAKE_BUILD_TYPE=Debug" not in args.cmake_configure_args assert args.cmake_build_args == ["--config", "Debug"] + + args = parser.parse_args([ + "-G", "Ninja Multi-Config", "--build-type", "Debug" + ]) + assert "-DCMAKE_BUILD_TYPE=Debug" not in args.cmake_configure_args + assert args.cmake_build_args == ["--config", "Debug"]
add ninja multi config generator https://cmake.org/cmake/help/latest/generator/Ninja%20Multi-Config.html Wait until 3.17 comes out to make it easier to test :smirk:
0.0
1b513bfc2720334c7eda4a49519013fa644a8a9d
[ "tests/parsers/cmake_parser.py::test_cmake_parser_is_x_config_generator", "tests/parsers/cmake_parser.py::test_cmake_parser_single_vs_multi_configure_build_args" ]
[ "tests/parsers/cmake_parser.py::test_cmake_parser_defaults", "tests/parsers/cmake_parser.py::test_cmake_parser_add_argument_failues", "tests/parsers/cmake_parser.py::test_cmake_parser_get_argument", "tests/parsers/cmake_parser.py::test_cmake_parser_remove", "tests/parsers/cmake_parser.py::test_cmake_parser_set_argument", "tests/parsers/cmake_parser.py::test_cmake_parser_extra_args", "tests/parsers/cmake_parser.py::test_cmake_parser_shared_or_static", "tests/parsers/cmake_parser.py::test_cmake_parser_parse_args_cmake_configure_args" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_hyperlinks", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2021-08-21 01:14:14+00:00
apache-2.0
5,810
swar__nba_api-286
diff --git a/src/nba_api/stats/library/data.py b/src/nba_api/stats/library/data.py index 9bfb241..daf40e2 100644 --- a/src/nba_api/stats/library/data.py +++ b/src/nba_api/stats/library/data.py @@ -4848,36 +4848,37 @@ team_index_year_founded = 3 team_index_city = 4 team_index_full_name = 5 team_index_state = 6 +team_index_championship_year = 7 teams = [ - [1610612737, 'ATL', 'Hawks', 1949, 'Atlanta', 'Atlanta Hawks', 'Atlanta'], - [1610612738, 'BOS', 'Celtics', 1946, 'Boston', 'Boston Celtics', 'Massachusetts'], - [1610612739, 'CLE', 'Cavaliers', 1970, 'Cleveland', 'Cleveland Cavaliers', 'Ohio'], - [1610612740, 'NOP', 'Pelicans', 2002, 'New Orleans', 'New Orleans Pelicans', 'Louisiana'], - [1610612741, 'CHI', 'Bulls', 1966, 'Chicago', 'Chicago Bulls', 'Illinois'], - [1610612742, 'DAL', 'Mavericks', 1980, 'Dallas', 'Dallas Mavericks', 'Texas'], - [1610612743, 'DEN', 'Nuggets', 1976, 'Denver', 'Denver Nuggets', 'Colorado'], - [1610612744, 'GSW', 'Warriors', 1946, 'Golden State', 'Golden State Warriors', 'California'], - [1610612745, 'HOU', 'Rockets', 1967, 'Houston', 'Houston Rockets', 'Texas'], - [1610612746, 'LAC', 'Clippers', 1970, 'Los Angeles', 'Los Angeles Clippers', 'California'], - [1610612747, 'LAL', 'Lakers', 1948, 'Los Angeles', 'Los Angeles Lakers', 'California'], - [1610612748, 'MIA', 'Heat', 1988, 'Miami', 'Miami Heat', 'Florida'], - [1610612749, 'MIL', 'Bucks', 1968, 'Milwaukee', 'Milwaukee Bucks', 'Wisconsin'], - [1610612750, 'MIN', 'Timberwolves', 1989, 'Minnesota', 'Minnesota Timberwolves', 'Minnesota'], - [1610612751, 'BKN', 'Nets', 1976, 'Brooklyn', 'Brooklyn Nets', 'New York'], - [1610612752, 'NYK', 'Knicks', 1946, 'New York', 'New York Knicks', 'New York'], - [1610612753, 'ORL', 'Magic', 1989, 'Orlando', 'Orlando Magic', 'Florida'], - [1610612754, 'IND', 'Pacers', 1976, 'Indiana', 'Indiana Pacers', 'Indiana'], - [1610612755, 'PHI', '76ers', 1949, 'Philadelphia', 'Philadelphia 76ers', 'Pennsylvania'], - [1610612756, 'PHX', 'Suns', 1968, 'Phoenix', 'Phoenix Suns', 'Arizona'], - [1610612757, 'POR', 'Trail Blazers', 1970, 'Portland', 'Portland Trail Blazers', 'Oregon'], - [1610612758, 'SAC', 'Kings', 1948, 'Sacramento', 'Sacramento Kings', 'California'], - [1610612759, 'SAS', 'Spurs', 1976, 'San Antonio', 'San Antonio Spurs', 'Texas'], - [1610612760, 'OKC', 'Thunder', 1967, 'Oklahoma City', 'Oklahoma City Thunder', 'Oklahoma'], - [1610612761, 'TOR', 'Raptors', 1995, 'Toronto', 'Toronto Raptors', 'Ontario'], - [1610612762, 'UTA', 'Jazz', 1974, 'Utah', 'Utah Jazz', 'Utah'], - [1610612763, 'MEM', 'Grizzlies', 1995, 'Memphis', 'Memphis Grizzlies', 'Tennessee'], - [1610612764, 'WAS', 'Wizards', 1961, 'Washington', 'Washington Wizards', 'District of Columbia'], - [1610612765, 'DET', 'Pistons', 1948, 'Detroit', 'Detroit Pistons', 'Michigan'], - [1610612766, 'CHA', 'Hornets', 1988, 'Charlotte', 'Charlotte Hornets', 'North Carolina'] + [1610612737, 'ATL', 'Hawks', 1949, 'Atlanta', 'Atlanta Hawks', 'Atlanta', [1958]], + [1610612738, 'BOS', 'Celtics', 1946, 'Boston', 'Boston Celtics', 'Massachusetts', [1957, 1959, 1960, 1961, 1962, 1963, 1964, 1965, 1966, 1968, 1969, 1974, 1976, 1981, 1984, 1986, 2008]], + [1610612739, 'CLE', 'Cavaliers', 1970, 'Cleveland', 'Cleveland Cavaliers', 'Ohio', [2016]], + [1610612740, 'NOP', 'Pelicans', 2002, 'New Orleans', 'New Orleans Pelicans', 'Louisiana', []], + [1610612741, 'CHI', 'Bulls', 1966, 'Chicago', 'Chicago Bulls', 'Illinois', [1991, 1992, 1993, 1996, 1997, 1998]], + [1610612742, 'DAL', 'Mavericks', 1980, 'Dallas', 'Dallas Mavericks', 'Texas', [2011]], + [1610612743, 'DEN', 'Nuggets', 1976, 'Denver', 'Denver Nuggets', 'Colorado', []], + [1610612744, 'GSW', 'Warriors', 1946, 'Golden State', 'Golden State Warriors', 'California', [1947, 1956, 1975, 2015, 2017, 2018, 2022]], + [1610612745, 'HOU', 'Rockets', 1967, 'Houston', 'Houston Rockets', 'Texas', [1994, 1995]], + [1610612746, 'LAC', 'Clippers', 1970, 'Los Angeles', 'Los Angeles Clippers', 'California', []], + [1610612747, 'LAL', 'Lakers', 1948, 'Los Angeles', 'Los Angeles Lakers', 'California', [1949, 1950, 1952, 1953, 1954, 1972, 1980, 1982, 1985, 1987, 1988, 2000, 2001, 2002, 2009, 2010, 2020]], + [1610612748, 'MIA', 'Heat', 1988, 'Miami', 'Miami Heat', 'Florida', [2006, 2012, 2013]], + [1610612749, 'MIL', 'Bucks', 1968, 'Milwaukee', 'Milwaukee Bucks', 'Wisconsin', [1971, 2021]], + [1610612750, 'MIN', 'Timberwolves', 1989, 'Minnesota', 'Minnesota Timberwolves', 'Minnesota', []], + [1610612751, 'BKN', 'Nets', 1976, 'Brooklyn', 'Brooklyn Nets', 'New York', []], + [1610612752, 'NYK', 'Knicks', 1946, 'New York', 'New York Knicks', 'New York', [1970, 1973]], + [1610612753, 'ORL', 'Magic', 1989, 'Orlando', 'Orlando Magic', 'Florida', []], + [1610612754, 'IND', 'Pacers', 1976, 'Indiana', 'Indiana Pacers', 'Indiana', []], + [1610612755, 'PHI', '76ers', 1949, 'Philadelphia', 'Philadelphia 76ers', 'Pennsylvania', [1955, 1967, 1983]], + [1610612756, 'PHX', 'Suns', 1968, 'Phoenix', 'Phoenix Suns', 'Arizona', []], + [1610612757, 'POR', 'Trail Blazers', 1970, 'Portland', 'Portland Trail Blazers', 'Oregon', [1977]], + [1610612758, 'SAC', 'Kings', 1948, 'Sacramento', 'Sacramento Kings', 'California', [1951]], + [1610612759, 'SAS', 'Spurs', 1976, 'San Antonio', 'San Antonio Spurs', 'Texas', [1999, 2003, 2005, 2007, 2014]], + [1610612760, 'OKC', 'Thunder', 1967, 'Oklahoma City', 'Oklahoma City Thunder', 'Oklahoma', [1979]], + [1610612761, 'TOR', 'Raptors', 1995, 'Toronto', 'Toronto Raptors', 'Ontario', [2019]], + [1610612762, 'UTA', 'Jazz', 1974, 'Utah', 'Utah Jazz', 'Utah', []], + [1610612763, 'MEM', 'Grizzlies', 1995, 'Memphis', 'Memphis Grizzlies', 'Tennessee', []], + [1610612764, 'WAS', 'Wizards', 1961, 'Washington', 'Washington Wizards', 'District of Columbia', [1978]], + [1610612765, 'DET', 'Pistons', 1948, 'Detroit', 'Detroit Pistons', 'Michigan', [1989, 1990, 2004]], + [1610612766, 'CHA', 'Hornets', 1988, 'Charlotte', 'Charlotte Hornets', 'North Carolina', []] ] diff --git a/tools/stats/static_players_update/template.py b/tools/stats/static_players_update/template.py index 448fe24..7c3f5f0 100644 --- a/tools/stats/static_players_update/template.py +++ b/tools/stats/static_players_update/template.py @@ -18,38 +18,39 @@ team_index_year_founded = 3 team_index_city = 4 team_index_full_name = 5 team_index_state = 6 +team_index_championship_year = 7 teams = [ - [1610612737, 'ATL', 'Hawks', 1949, 'Atlanta', 'Atlanta Hawks', 'Atlanta'], - [1610612738, 'BOS', 'Celtics', 1946, 'Boston', 'Boston Celtics', 'Massachusetts'], - [1610612739, 'CLE', 'Cavaliers', 1970, 'Cleveland', 'Cleveland Cavaliers', 'Ohio'], - [1610612740, 'NOP', 'Pelicans', 2002, 'New Orleans', 'New Orleans Pelicans', 'Louisiana'], - [1610612741, 'CHI', 'Bulls', 1966, 'Chicago', 'Chicago Bulls', 'Illinois'], - [1610612742, 'DAL', 'Mavericks', 1980, 'Dallas', 'Dallas Mavericks', 'Texas'], - [1610612743, 'DEN', 'Nuggets', 1976, 'Denver', 'Denver Nuggets', 'Colorado'], - [1610612744, 'GSW', 'Warriors', 1946, 'Golden State', 'Golden State Warriors', 'California'], - [1610612745, 'HOU', 'Rockets', 1967, 'Houston', 'Houston Rockets', 'Texas'], - [1610612746, 'LAC', 'Clippers', 1970, 'Los Angeles', 'Los Angeles Clippers', 'California'], - [1610612747, 'LAL', 'Lakers', 1948, 'Los Angeles', 'Los Angeles Lakers', 'California'], - [1610612748, 'MIA', 'Heat', 1988, 'Miami', 'Miami Heat', 'Florida'], - [1610612749, 'MIL', 'Bucks', 1968, 'Milwaukee', 'Milwaukee Bucks', 'Wisconsin'], - [1610612750, 'MIN', 'Timberwolves', 1989, 'Minnesota', 'Minnesota Timberwolves', 'Minnesota'], - [1610612751, 'BKN', 'Nets', 1976, 'Brooklyn', 'Brooklyn Nets', 'New York'], - [1610612752, 'NYK', 'Knicks', 1946, 'New York', 'New York Knicks', 'New York'], - [1610612753, 'ORL', 'Magic', 1989, 'Orlando', 'Orlando Magic', 'Florida'], - [1610612754, 'IND', 'Pacers', 1976, 'Indiana', 'Indiana Pacers', 'Indiana'], - [1610612755, 'PHI', '76ers', 1949, 'Philadelphia', 'Philadelphia 76ers', 'Pennsylvania'], - [1610612756, 'PHX', 'Suns', 1968, 'Phoenix', 'Phoenix Suns', 'Arizona'], - [1610612757, 'POR', 'Trail Blazers', 1970, 'Portland', 'Portland Trail Blazers', 'Oregon'], - [1610612758, 'SAC', 'Kings', 1948, 'Sacramento', 'Sacramento Kings', 'California'], - [1610612759, 'SAS', 'Spurs', 1976, 'San Antonio', 'San Antonio Spurs', 'Texas'], - [1610612760, 'OKC', 'Thunder', 1967, 'Oklahoma City', 'Oklahoma City Thunder', 'Oklahoma'], - [1610612761, 'TOR', 'Raptors', 1995, 'Toronto', 'Toronto Raptors', 'Ontario'], - [1610612762, 'UTA', 'Jazz', 1974, 'Utah', 'Utah Jazz', 'Utah'], - [1610612763, 'MEM', 'Grizzlies', 1995, 'Memphis', 'Memphis Grizzlies', 'Tennessee'], - [1610612764, 'WAS', 'Wizards', 1961, 'Washington', 'Washington Wizards', 'District of Columbia'], - [1610612765, 'DET', 'Pistons', 1948, 'Detroit', 'Detroit Pistons', 'Michigan'], - [1610612766, 'CHA', 'Hornets', 1988, 'Charlotte', 'Charlotte Hornets', 'North Carolina'] + [1610612737, 'ATL', 'Hawks', 1949, 'Atlanta', 'Atlanta Hawks', 'Atlanta', [1958]], + [1610612738, 'BOS', 'Celtics', 1946, 'Boston', 'Boston Celtics', 'Massachusetts', [1957, 1959, 1960, 1961, 1962, 1963, 1964, 1965, 1966, 1968, 1969, 1974, 1976, 1981, 1984, 1986, 2008]], + [1610612739, 'CLE', 'Cavaliers', 1970, 'Cleveland', 'Cleveland Cavaliers', 'Ohio', [2016]], + [1610612740, 'NOP', 'Pelicans', 2002, 'New Orleans', 'New Orleans Pelicans', 'Louisiana', []], + [1610612741, 'CHI', 'Bulls', 1966, 'Chicago', 'Chicago Bulls', 'Illinois', [1991, 1992, 1993, 1996, 1997, 1998]], + [1610612742, 'DAL', 'Mavericks', 1980, 'Dallas', 'Dallas Mavericks', 'Texas', [2011]], + [1610612743, 'DEN', 'Nuggets', 1976, 'Denver', 'Denver Nuggets', 'Colorado', []], + [1610612744, 'GSW', 'Warriors', 1946, 'Golden State', 'Golden State Warriors', 'California', [1947, 1956, 1975, 2015, 2017, 2018, 2022]], + [1610612745, 'HOU', 'Rockets', 1967, 'Houston', 'Houston Rockets', 'Texas', [1994, 1995]], + [1610612746, 'LAC', 'Clippers', 1970, 'Los Angeles', 'Los Angeles Clippers', 'California', []], + [1610612747, 'LAL', 'Lakers', 1948, 'Los Angeles', 'Los Angeles Lakers', 'California', [1949, 1950, 1952, 1953, 1954, 1972, 1980, 1982, 1985, 1987, 1988, 2000, 2001, 2002, 2009, 2010, 2020]], + [1610612748, 'MIA', 'Heat', 1988, 'Miami', 'Miami Heat', 'Florida', [2006, 2012, 2013]], + [1610612749, 'MIL', 'Bucks', 1968, 'Milwaukee', 'Milwaukee Bucks', 'Wisconsin', [1971, 2021]], + [1610612750, 'MIN', 'Timberwolves', 1989, 'Minnesota', 'Minnesota Timberwolves', 'Minnesota', []], + [1610612751, 'BKN', 'Nets', 1976, 'Brooklyn', 'Brooklyn Nets', 'New York', []], + [1610612752, 'NYK', 'Knicks', 1946, 'New York', 'New York Knicks', 'New York', [1970, 1973]], + [1610612753, 'ORL', 'Magic', 1989, 'Orlando', 'Orlando Magic', 'Florida', []], + [1610612754, 'IND', 'Pacers', 1976, 'Indiana', 'Indiana Pacers', 'Indiana', []], + [1610612755, 'PHI', '76ers', 1949, 'Philadelphia', 'Philadelphia 76ers', 'Pennsylvania', [1955, 1967, 1983]], + [1610612756, 'PHX', 'Suns', 1968, 'Phoenix', 'Phoenix Suns', 'Arizona', []], + [1610612757, 'POR', 'Trail Blazers', 1970, 'Portland', 'Portland Trail Blazers', 'Oregon', [1977]], + [1610612758, 'SAC', 'Kings', 1948, 'Sacramento', 'Sacramento Kings', 'California', [1951]], + [1610612759, 'SAS', 'Spurs', 1976, 'San Antonio', 'San Antonio Spurs', 'Texas', [1999, 2003, 2005, 2007, 2014]], + [1610612760, 'OKC', 'Thunder', 1967, 'Oklahoma City', 'Oklahoma City Thunder', 'Oklahoma', [1979]], + [1610612761, 'TOR', 'Raptors', 1995, 'Toronto', 'Toronto Raptors', 'Ontario', [2019]], + [1610612762, 'UTA', 'Jazz', 1974, 'Utah', 'Utah Jazz', 'Utah', []], + [1610612763, 'MEM', 'Grizzlies', 1995, 'Memphis', 'Memphis Grizzlies', 'Tennessee', []], + [1610612764, 'WAS', 'Wizards', 1961, 'Washington', 'Washington Wizards', 'District of Columbia', [1978]], + [1610612765, 'DET', 'Pistons', 1948, 'Detroit', 'Detroit Pistons', 'Michigan', [1989, 1990, 2004]], + [1610612766, 'CHA', 'Hornets', 1988, 'Charlotte', 'Charlotte Hornets', 'North Carolina', []] ] '''
swar/nba_api
cd721a79a50b8c18e5846122e08a23666a4e1a08
diff --git a/tests/unit/test_static_data.py b/tests/unit/test_static_data.py new file mode 100644 index 0000000..de88a88 --- /dev/null +++ b/tests/unit/test_static_data.py @@ -0,0 +1,5 @@ +from nba_api.stats.static import teams + + +def test_get_request_url(): + assert len(teams.teams) == 30
[Bug]: cannot import name 'team_index_championship_year' from 'nba_api.stats.library.data' ### NBA API Version V1.1.12 ### Issue Working on Linux Ubuntu 22.04 LTS Installed nba_api using (!pip install) in a jupyter notebook cell. Getting an ImportError when I try to import (teams) using 'from nba_api.stats.static import teams' ### Code ``` In [ 66 ] : !pip install nba_api ``` ``` In [ 67 ] : from nba_api.stats.static import teams ```
0.0
cd721a79a50b8c18e5846122e08a23666a4e1a08
[ "tests/unit/test_static_data.py::test_get_request_url" ]
[]
{ "failed_lite_validators": [ "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2022-10-16 00:18:06+00:00
mit
5,811
swaroopch__edn_format-36
diff --git a/edn_format/edn_lex.py b/edn_format/edn_lex.py index 42fdea7..e3b729e 100644 --- a/edn_format/edn_lex.py +++ b/edn_format/edn_lex.py @@ -193,13 +193,13 @@ def t_BOOLEAN(t): def t_FLOAT(t): - r"""[+-]?\d+\.\d+[M]?([eE][+-]?\d+)?""" + r"""[+-]?\d+(?:\.\d+([eE][+-]?\d+)?|([eE][+-]?\d+))M?""" e_value = 0 if 'e' in t.value or 'E' in t.value: - matches = re.search('[eE]([+-]?\d+)$', t.value) + matches = re.search('[eE]([+-]?\d+)M?$', t.value) if matches is None: raise SyntaxError('Invalid float : {}'.format(t.value)) - e_value = int(matches.group()[1:]) + e_value = int(matches.group(1)) if t.value.endswith('M'): t.value = decimal.Decimal(t.value[:-1]) * pow(1, e_value) else:
swaroopch/edn_format
0616eb18781cd9d9394683b806b0b3033b47f371
diff --git a/tests.py b/tests.py index c77c273..437c2fd 100644 --- a/tests.py +++ b/tests.py @@ -143,7 +143,8 @@ class EdnTest(unittest.TestCase): ["+123N", "123"], ["123.2", "123.2"], ["+32.23M", "32.23M"], - ["3.23e10", "32300000000.0"] + ["3.23e10", "32300000000.0"], + ["3e10", "30000000000.0"], ] for literal in EDN_LITERALS: @@ -195,6 +196,8 @@ class EdnTest(unittest.TestCase): "32.23M", "-32.23M", "3.23e-10", + "3e+20", + "3E+20M", '["abc"]', '[1]', '[1 "abc"]',
issue parsing big numbers specifically `45e+43` and `45.4e+43M`
0.0
0616eb18781cd9d9394683b806b0b3033b47f371
[ "tests.py::EdnTest::test_round_trip_conversion", "tests.py::EdnTest::test_round_trip_same" ]
[ "tests.py::ConsoleTest::test_dumping", "tests.py::EdnTest::test_dump", "tests.py::EdnTest::test_keyword_keys", "tests.py::EdnTest::test_lexer", "tests.py::EdnTest::test_parser", "tests.py::EdnTest::test_proper_unicode_escape", "tests.py::EdnTest::test_round_trip_inst_short", "tests.py::EdnTest::test_round_trip_sets", "tests.py::EdnInstanceTest::test_equality", "tests.py::EdnInstanceTest::test_hashing" ]
{ "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false }
2017-02-14 10:07:46+00:00
apache-2.0
5,812
swaroopch__edn_format-43
diff --git a/edn_format/edn_lex.py b/edn_format/edn_lex.py index ac0a3af..fc2026e 100644 --- a/edn_format/edn_lex.py +++ b/edn_format/edn_lex.py @@ -102,7 +102,8 @@ tokens = ('WHITESPACE', 'MAP_START', 'SET_START', 'MAP_OR_SET_END', - 'TAG') + 'TAG', + 'DISCARD_TAG') PARTS = {} PARTS["non_nums"] = r"\w.*+!\-_?$%&=:#<>@" @@ -138,7 +139,7 @@ KEYWORD = (":" "[{all}]+" ")").format(**PARTS) TAG = (r"\#" - r"\w" + r"[a-zA-Z]" # https://github.com/edn-format/edn/issues/30#issuecomment-8540641 "(" "[{all}]*" r"\/" @@ -147,6 +148,8 @@ TAG = (r"\#" "[{all}]*" ")").format(**PARTS) +DISCARD_TAG = r"\#\_" + t_VECTOR_START = r'\[' t_VECTOR_END = r'\]' t_LIST_START = r'\(' @@ -228,9 +231,10 @@ def t_COMMENT(t): pass # ignore -def t_DISCARD(t): - r'\#_\S+\b' - pass # ignore [email protected](DISCARD_TAG) +def t_DISCARD_TAG(t): + t.value = t.value[1:] + return t @ply.lex.TOKEN(TAG) diff --git a/edn_format/edn_parse.py b/edn_format/edn_parse.py index c2be09d..329584e 100644 --- a/edn_format/edn_parse.py +++ b/edn_format/edn_parse.py @@ -56,41 +56,21 @@ def p_term_leaf(p): p[0] = p[1] -def p_empty_vector(p): - """vector : VECTOR_START VECTOR_END""" - p[0] = ImmutableList([]) - - def p_vector(p): """vector : VECTOR_START expressions VECTOR_END""" p[0] = ImmutableList(p[2]) -def p_empty_list(p): - """list : LIST_START LIST_END""" - p[0] = tuple() - - def p_list(p): """list : LIST_START expressions LIST_END""" p[0] = tuple(p[2]) -def p_empty_set(p): - """set : SET_START MAP_OR_SET_END""" - p[0] = frozenset() - - def p_set(p): """set : SET_START expressions MAP_OR_SET_END""" p[0] = frozenset(p[2]) -def p_empty_map(p): - """map : MAP_START MAP_OR_SET_END""" - p[0] = ImmutableDict({}) - - def p_map(p): """map : MAP_START expressions MAP_OR_SET_END""" terms = p[2] @@ -100,14 +80,20 @@ def p_map(p): p[0] = ImmutableDict(dict([terms[i:i + 2] for i in range(0, len(terms), 2)])) -def p_expressions_expressions_expression(p): - """expressions : expressions expression""" - p[0] = p[1] + [p[2]] +def p_discarded_expressions(p): + """discarded_expressions : DISCARD_TAG expression discarded_expressions + |""" + p[0] = [] + +def p_expressions_expression_expressions(p): + """expressions : expression expressions""" + p[0] = [p[1]] + p[2] -def p_expressions_expression(p): - """expressions : expression""" - p[0] = [p[1]] + +def p_expressions_empty(p): + """expressions : discarded_expressions""" + p[0] = [] def p_expression(p): @@ -119,6 +105,11 @@ def p_expression(p): p[0] = p[1] +def p_expression_discard_expression_expression(p): + """expression : DISCARD_TAG expression expression""" + p[0] = p[3] + + def p_expression_tagged_element(p): """expression : TAG expression""" tag = p[1] @@ -144,9 +135,13 @@ def p_expression_tagged_element(p): p[0] = output +def eof(): + raise EDNDecodeError('EOF Reached') + + def p_error(p): if p is None: - raise EDNDecodeError('EOF Reached') + eof() else: raise EDNDecodeError(p)
swaroopch/edn_format
7a3865c6d7ddc1a8d2d8ecb4114f11ed8b96fda8
diff --git a/tests.py b/tests.py index 8f7fcc1..29562d5 100644 --- a/tests.py +++ b/tests.py @@ -133,6 +133,12 @@ class EdnTest(unittest.TestCase): def check_roundtrip(self, data_input, **kw): self.assertEqual(data_input, loads(dumps(data_input, **kw))) + def check_eof(self, data_input, **kw): + with self.assertRaises(EDNDecodeError) as ctx: + loads(data_input, **kw) + + self.assertEqual('EOF Reached', str(ctx.exception)) + def test_dump(self): self.check_roundtrip({1, 2, 3}) self.check_roundtrip({1, 2, 3}, sort_sets=True) @@ -339,6 +345,57 @@ class EdnTest(unittest.TestCase): set(seq), sort_sets=True) + def test_discard(self): + for expected, edn_data in ( + ('[x]', '[x #_ z]'), + ('[z]', '[#_ x z]'), + ('[x z]', '[x #_ y z]'), + ('{1 4}', '{1 #_ 2 #_ 3 4}'), + ('[1 2]', '[1 #_ [ #_ [ #_ [ #_ [ #_ 42 ] ] ] ] 2 ]'), + ('[1 2 11]', '[1 2 #_ #_ #_ #_ 4 5 6 #_ 7 #_ #_ 8 9 10 11]'), + ('()', '(#_(((((((1))))))))'), + ('[6]', '[#_ #_ #_ #_ #_ 1 2 3 4 5 6]'), + ('[4]', '[#_ #_ 1 #_ 2 3 4]'), + ('{:a 1}', '{:a #_:b 1}'), + ('[42]', '[42 #_ {:a [1 2 3 4] true false 1 #inst "2017"}]'), + ('#{1}', '#{1 #_foo}'), + ('"#_ foo"', '"#_ foo"'), + ('["#" _]', '[\#_]'), + ('[_]', '[#_\#_]'), + ('[1]', '[1 #_\n\n42]'), + ('{}', '{#_ 1}'), + ): + self.assertEqual(expected, dumps(loads(edn_data)), edn_data) + + def test_discard_syntax_errors(self): + for edn_data in ('#_', '#_ #_ 1', '#inst #_ 2017', '[#_]'): + with self.assertRaises(EDNDecodeError): + loads(edn_data) + + def test_discard_all(self): + for edn_data in ( + '42', '-1', 'nil', 'true', 'false', '"foo"', '\\space', '\\a', + ':foo', ':foo/bar', '[]', '{}', '#{}', '()', '(a)', '(a b)', + '[a [[[b] c]] 2]', '#inst "2017"', + ): + self.assertEqual([1], loads('[1 #_ {}]'.format(edn_data)), edn_data) + self.assertEqual([1], loads('[#_ {} 1]'.format(edn_data)), edn_data) + + self.check_eof('#_ {}'.format(edn_data)) + + for coll in ('[%s]', '(%s)', '{%s}', '#{%s}'): + expected = coll % "" + edn_data = coll % '#_ {}'.format(edn_data) + self.assertEqual(expected, dumps(loads(edn_data)), edn_data) + + def test_chained_discards(self): + for expected, edn_data in ( + ('[]', '[#_ 1 #_ 2 #_ 3]'), + ('[]', '[#_ #_ 1 2 #_ 3]'), + ('[]', '[#_ #_ #_ 1 2 3]'), + ): + self.assertEqual(expected, dumps(loads(edn_data)), edn_data) + class EdnInstanceTest(unittest.TestCase): def test_hashing(self):
not handling discard as expected `[x #_ y z]` should yield `[Symbol(x), Symbol(z)]` but instead it is failing saying: "Don't know how to handle tag _"
0.0
7a3865c6d7ddc1a8d2d8ecb4114f11ed8b96fda8
[ "tests.py::EdnTest::test_chained_discards", "tests.py::EdnTest::test_discard", "tests.py::EdnTest::test_discard_all", "tests.py::EdnTest::test_discard_syntax_errors" ]
[ "tests.py::ConsoleTest::test_dumping", "tests.py::EdnTest::test_chars", "tests.py::EdnTest::test_dump", "tests.py::EdnTest::test_exceptions", "tests.py::EdnTest::test_keyword_keys", "tests.py::EdnTest::test_lexer", "tests.py::EdnTest::test_parser", "tests.py::EdnTest::test_proper_unicode_escape", "tests.py::EdnTest::test_round_trip_conversion", "tests.py::EdnTest::test_round_trip_inst_short", "tests.py::EdnTest::test_round_trip_same", "tests.py::EdnTest::test_round_trip_sets", "tests.py::EdnTest::test_sort_keys", "tests.py::EdnTest::test_sort_sets", "tests.py::EdnInstanceTest::test_equality", "tests.py::EdnInstanceTest::test_hashing", "tests.py::ImmutableListTest::test_list" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2018-08-04 10:41:01+00:00
apache-2.0
5,813
swen128__twitter-text-python-7
diff --git a/twitter_text/parse_tweet.py b/twitter_text/parse_tweet.py index ffa4f3e..db0d7cb 100644 --- a/twitter_text/parse_tweet.py +++ b/twitter_text/parse_tweet.py @@ -1,3 +1,4 @@ +import re import unicodedata from math import floor from typing import List, Dict @@ -25,6 +26,10 @@ class ParsedResult: return attr.asdict(self) +def convert_line_ending(string, to="\n"): + return re.sub(r'\r\n|\r|\n', to, string) + + def parse_tweet(text: str, options: dict = config['defaults']) -> ParsedResult: """ Parse a Twitter text according to https://developer.twitter.com/en/docs/developer-utilities/twitter-text @@ -106,7 +111,7 @@ def parse_tweet(text: str, options: dict = config['defaults']) -> ParsedResult: emoji_parsing_enabled = options['emoji_parsing_enabled'] max_weighted_tweet_length = options['max_weighted_tweet_length'] - normalized_text = unicodedata.normalize('NFC', text) + normalized_text = convert_line_ending(unicodedata.normalize('NFC', text)) url_entities_map = transform_entities_to_hash(extract_urls_with_indices(normalized_text)) emoji_entities_map = transform_entities_to_hash(extract_emojis_with_indices(normalized_text))
swen128/twitter-text-python
ff20ed9def7773695e875257cf59783aa5d20001
diff --git a/tests/cases/added.yml b/tests/cases/added.yml index b20b36d..1391e2f 100644 --- a/tests/cases/added.yml +++ b/tests/cases/added.yml @@ -6,6 +6,16 @@ tests: - url: "https://t.co/slug" indices: [0, 17] ParseTweet: + - description: "CRLF character" + text: "a\r\nb" + expected: + weightedLength: 3 + valid: true + permillage: 10 + displayRangeStart: 0 + displayRangeEnd: 3 + validRangeStart: 0 + validRangeEnd: 3 - description: "A URL containing emojis" text: "https://😷😷😷😷😷😷😷😷😷😷😷😷😷😷😷😷😷😷😷😷😷😷😷😷😷😷.jp" expected:
[Bug] "\r\n" を2文字としてカウントするバグ Tweet API を使用していて、ツイッターをブラウザで開いてツイートできる文字数なのに、parse_tweet関数を使用すると文字数オーバーとなる奇妙な現象に遭遇・・・。 おそらく"\r" を改行として取得できていません。 以下のテストコードを見て下さい。 ``` from twitter_text import parse_tweet text1 = '''abc def ghi''' print(text1) print(parse_tweet(text1)) print() text2 = 'abc\ndef\nghi' print(text2) print(parse_tweet(text2)) print() text3 = 'abc\rdef\rghi' print(text3) print(parse_tweet(text3)) print() text4 = 'abc\r\ndef\r\nghi' print(text4) print(parse_tweet(text4)) ``` 結果は次のようになります。 ``` abc def ghi ParsedResult(valid=True, weightedLength=11, permillage=39, validRangeStart=0, validRangeEnd=10, displayRangeStart=0, displayRangeEnd=10) abc def ghi ParsedResult(valid=True, weightedLength=11, permillage=39, validRangeStart=0, validRangeEnd=10, displayRangeStart=0, displayRangeEnd=10) ghi ParsedResult(valid=True, weightedLength=11, permillage=39, validRangeStart=0, validRangeEnd=10, displayRangeStart=0, displayRangeEnd=10) abc def ghi ParsedResult(valid=True, weightedLength=13, permillage=46, validRangeStart=0, validRangeEnd=12, displayRangeStart=0, displayRangeEnd=12) ``` 改行文字を1文字として取得しているならば、 "weightedLength=11"が正しく、それ以外は間違っています。 修正して下さい。
0.0
ff20ed9def7773695e875257cf59783aa5d20001
[ "tests/test_added.py::test_added_parse_tweet[CRLF" ]
[ "tests/test_conformance.py::test_extract_urls[DO", "tests/test_conformance.py::test_extract_urls[Extract", "tests/test_conformance.py::test_tlds_country[bb", "tests/test_conformance.py::test_extract_urls_with_directional_markers[Extract", "tests/test_conformance.py::test_tlds_country[cl", "tests/test_conformance.py::test_tlds_country[uy", "tests/test_conformance.py::test_tlds_country[ee", "tests/test_conformance.py::test_tlds_country[ru", "tests/test_conformance.py::test_tlds_country[ai", "tests/test_conformance.py::test_tlds_country[nz", "tests/test_conformance.py::test_tlds_country[nf", "tests/test_conformance.py::test_tlds_country[la", "tests/test_conformance.py::test_tlds_country[cx", "tests/test_conformance.py::test_tlds_country[\\u0639\\u0645\\u0627\\u0646", "tests/test_conformance.py::test_extract_urls_with_indices[Extract", "tests/test_conformance.py::test_tlds_country[mz", "tests/test_conformance.py::test_tlds_country[bv", "tests/test_conformance.py::test_tlds_country[fo", "tests/test_conformance.py::test_tlds_country[pe", "tests/test_conformance.py::test_tlds_country[mt", "tests/test_conformance.py::test_tlds_country[ws", "tests/test_conformance.py::test_tlds_country[ca", "tests/test_conformance.py::test_tlds_country[gy", "tests/test_conformance.py::test_tlds_country[fk", "tests/test_conformance.py::test_tlds_country[lb", "tests/test_conformance.py::test_tlds_country[mr", "tests/test_conformance.py::test_tlds_country[ua", "tests/test_conformance.py::test_tlds_country[cc", "tests/test_conformance.py::test_tlds_country[ne", "tests/test_conformance.py::test_tlds_country[cr", "tests/test_conformance.py::test_tlds_country[\\u0633\\u0648\\u062f\\u0627\\u0646", "tests/test_conformance.py::test_tlds_country[\\u0b87\\u0bb2\\u0b99\\u0bcd\\u0b95\\u0bc8", "tests/test_conformance.py::test_validate_weighted_tweets_with_discounted_emoji_counter_test[Unicode", "tests/test_conformance.py::test_tlds_country[tg", "tests/test_conformance.py::test_tlds_country[py", "tests/test_conformance.py::test_tlds_country[ly", "tests/test_conformance.py::test_tlds_country[\\u067e\\u0627\\u06a9\\u0633\\u062a\\u0627\\u0646", "tests/test_conformance.py::test_tlds_country[fj", "tests/test_conformance.py::test_tlds_country[nl", "tests/test_conformance.py::test_tlds_country[br", "tests/test_conformance.py::test_tlds_country[\\u0440\\u0444", "tests/test_conformance.py::test_tlds_country[sn", "tests/test_conformance.py::test_tlds_country[hu", "tests/test_conformance.py::test_tlds_country[za", "tests/test_conformance.py::test_validate_weighted_tweets_with_discounted_emoji_counter_test[10", "tests/test_conformance.py::test_tlds_country[ht", "tests/test_conformance.py::test_tlds_country[bj", "tests/test_conformance.py::test_tlds_country[kp", "tests/test_conformance.py::test_tlds_country[ug", "tests/test_conformance.py::test_tlds_country[al", "tests/test_conformance.py::test_tlds_country[gp", "tests/test_conformance.py::test_tlds_country[gf", "tests/test_conformance.py::test_validate_unicode_directional_marker_counter_test[Tweet", "tests/test_conformance.py::test_tlds_country[\\u4e2d\\u570b", "tests/test_conformance.py::test_tlds_country[tv", "tests/test_conformance.py::test_tlds_country[\\u0d2d\\u0d3e\\u0d30\\u0d24\\u0d02", "tests/test_conformance.py::test_tlds_country[bg", "tests/test_conformance.py::test_tlds_country[bw", "tests/test_conformance.py::test_tlds_country[re", "tests/test_conformance.py::test_tlds_country[bn", "tests/test_conformance.py::test_tlds_country[\\u0627\\u0644\\u0633\\u0639\\u0648\\u062f\\u064a\\u0629", "tests/test_conformance.py::test_tlds_country[ac", "tests/test_conformance.py::test_tlds_country[kn", "tests/test_conformance.py::test_tlds_country[vc", "tests/test_conformance.py::test_validate_weighted_tweets_with_discounted_emoji_counter_test[Count", "tests/test_conformance.py::test_tlds_country[\\ud55c\\uad6d", "tests/test_conformance.py::test_tlds_country[gi", "tests/test_conformance.py::test_tlds_country[cv", "tests/test_conformance.py::test_tlds_country[ni", "tests/test_conformance.py::test_tlds_country[pf", "tests/test_conformance.py::test_tlds_country[ki", "tests/test_conformance.py::test_tlds_country[ms", "tests/test_conformance.py::test_tlds_country[\\u0431\\u0433", "tests/test_conformance.py::test_tlds_country[km", "tests/test_conformance.py::test_tlds_country[np", "tests/test_conformance.py::test_tlds_country[\\u0b87\\u0ba8\\u0bcd\\u0ba4\\u0bbf\\u0baf\\u0bbe", "tests/test_conformance.py::test_tlds_country[ar", "tests/test_conformance.py::test_tlds_country[sm", "tests/test_conformance.py::test_tlds_country[vg", "tests/test_conformance.py::test_tlds_country[yt", "tests/test_conformance.py::test_extract_tco_urls_with_params[Extract", "tests/test_conformance.py::test_tlds_country[cy", "tests/test_conformance.py::test_tlds_country[eh", "tests/test_conformance.py::test_tlds_country[ng", "tests/test_conformance.py::test_tlds_country[sr", "tests/test_conformance.py::test_tlds_country[mh", "tests/test_conformance.py::test_tlds_country[lc", "tests/test_conformance.py::test_tlds_country[\\u6fb3\\u9580", "tests/test_conformance.py::test_tlds_country[na", "tests/test_conformance.py::test_tlds_country[me", "tests/test_conformance.py::test_tlds_country[pw", "tests/test_conformance.py::test_tlds_country[\\u043c\\u043a\\u0434", "tests/test_conformance.py::test_tlds_country[\\u049b\\u0430\\u0437", "tests/test_conformance.py::test_tlds_country[\\u0e44\\u0e17\\u0e22", "tests/test_conformance.py::test_tlds_country[ag", "tests/test_conformance.py::test_tlds_country[tf", "tests/test_conformance.py::test_tlds_country[gw", "tests/test_conformance.py::test_tlds_country[mf", "tests/test_conformance.py::test_tlds_country[sy", "tests/test_conformance.py::test_validate_weighted_tweets_with_discounted_emoji_counter_test[Handle", "tests/test_conformance.py::test_tlds_country[au", "tests/test_conformance.py::test_tlds_country[pg", "tests/test_conformance.py::test_tlds_country[\\u09ac\\u09be\\u0982\\u09b2\\u09be", "tests/test_conformance.py::test_tlds_country[\\u043c\\u043e\\u043d", "tests/test_conformance.py::test_tlds_country[kh", "tests/test_conformance.py::test_tlds_country[gn", "tests/test_conformance.py::test_tlds_country[no", "tests/test_conformance.py::test_tlds_country[de", "tests/test_conformance.py::test_tlds_country[tm", "tests/test_conformance.py::test_validate_weighted_tweets_with_discounted_emoji_counter_test[282", "tests/test_conformance.py::test_tlds_country[mu", "tests/test_conformance.py::test_tlds_country[bo", "tests/test_conformance.py::test_tlds_country[\\u092d\\u093e\\u0930\\u0924", "tests/test_conformance.py::test_tlds_country[\\u0441\\u0440\\u0431", "tests/test_conformance.py::test_tlds_country[bq", "tests/test_conformance.py::test_tlds_country[by", "tests/test_conformance.py::test_tlds_country[iq", "tests/test_conformance.py::test_tlds_country[aq", "tests/test_conformance.py::test_validate_weighted_tweets_with_discounted_emoji_counter_test[Do", "tests/test_conformance.py::test_tlds_country[\\u0dbd\\u0d82\\u0d9a\\u0dcf", "tests/test_conformance.py::test_tlds_country[eg", "tests/test_conformance.py::test_tlds_country[be", "tests/test_conformance.py::test_tlds_country[io", "tests/test_conformance.py::test_tlds_country[mw", "tests/test_conformance.py::test_tlds_country[pl", "tests/test_conformance.py::test_tlds_country[in", "tests/test_conformance.py::test_tlds_country[nu", "tests/test_conformance.py::test_tlds_country[\\u0b9a\\u0bbf\\u0b99\\u0bcd\\u0b95\\u0baa\\u0bcd\\u0baa\\u0bc2\\u0bb0\\u0bcd", "tests/test_conformance.py::test_tlds_country[mm", "tests/test_conformance.py::test_tlds_country[cd", "tests/test_conformance.py::test_tlds_country[ad", "tests/test_conformance.py::test_tlds_country[sz", "tests/test_conformance.py::test_tlds_country[li", "tests/test_conformance.py::test_tlds_country[\\u9999\\u6e2f", "tests/test_conformance.py::test_tlds_country[dm", "tests/test_conformance.py::test_tlds_country[\\u0633\\u0648\\u0631\\u064a\\u0629", "tests/test_conformance.py::test_tlds_country[cf", "tests/test_conformance.py::test_tlds_country[ps", "tests/test_conformance.py::test_tlds_country[\\u0b2d\\u0b3e\\u0b30\\u0b24", "tests/test_conformance.py::test_tlds_country[md", "tests/test_conformance.py::test_tlds_country[it", "tests/test_conformance.py::test_tlds_country[sb", "tests/test_conformance.py::test_tlds_country[\\u0641\\u0644\\u0633\\u0637\\u064a\\u0646", "tests/test_conformance.py::test_tlds_country[sh", "tests/test_conformance.py::test_tlds_country[\\u0627\\u0644\\u0627\\u0631\\u062f\\u0646", "tests/test_conformance.py::test_tlds_country[rs", "tests/test_conformance.py::test_tlds_country[sv", "tests/test_conformance.py::test_tlds_country[vu", "tests/test_conformance.py::test_tlds_country[at", "tests/test_conformance.py::test_tlds_country[tw", "tests/test_conformance.py::test_tlds_country[jm", "tests/test_conformance.py::test_tlds_country[mn", "tests/test_conformance.py::test_tlds_country[tt", "tests/test_conformance.py::test_tlds_country[tc", "tests/test_conformance.py::test_tlds_country[\\u0435\\u044e", "tests/test_conformance.py::test_tlds_country[va", "tests/test_conformance.py::test_tlds_country[ml", "tests/test_conformance.py::test_tlds_country[mc", "tests/test_conformance.py::test_tlds_country[\\u0680\\u0627\\u0631\\u062a", "tests/test_conformance.py::test_tlds_country[rw", "tests/test_conformance.py::test_validate_unicode_directional_marker_counter_test[Handle", "tests/test_conformance.py::test_tlds_country[eu", "tests/test_conformance.py::test_tlds_country[ge", "tests/test_conformance.py::test_tlds_country[\\u092d\\u093e\\u0930\\u094b\\u0924", "tests/test_conformance.py::test_tlds_country[uk", "tests/test_conformance.py::test_tlds_country[\\u4e2d\\u56fd", "tests/test_conformance.py::test_tlds_country[pr", "tests/test_conformance.py::test_tlds_country[cn", "tests/test_conformance.py::test_validate_weighted_tweets_with_discounted_emoji_counter_test[160", "tests/test_conformance.py::test_tlds_country[\\u0cad\\u0cbe\\u0cb0\\u0ca4", "tests/test_conformance.py::test_tlds_country[\\u0431\\u0435\\u043b", "tests/test_conformance.py::test_tlds_country[bi", "tests/test_conformance.py::test_tlds_country[ga", "tests/test_conformance.py::test_tlds_country[bl", "tests/test_conformance.py::test_tlds_country[hk", "tests/test_conformance.py::test_tlds_country[kz", "tests/test_conformance.py::test_tlds_country[gq", "tests/test_conformance.py::test_tlds_country[gb", "tests/test_conformance.py::test_tlds_country[ec", "tests/test_conformance.py::test_tlds_country[do", "tests/test_conformance.py::test_tlds_country[\\u0627\\u0644\\u062c\\u0632\\u0627\\u0626\\u0631", "tests/test_conformance.py::test_tlds_country[cu", "tests/test_conformance.py::test_tlds_country[bd", "tests/test_conformance.py::test_tlds_country[bs", "tests/test_conformance.py::test_tlds_country[az", "tests/test_conformance.py::test_tlds_country[qa", "tests/test_conformance.py::test_tlds_country[\\u0627\\u06cc\\u0631\\u0627\\u0646", "tests/test_conformance.py::test_tlds_country[je", "tests/test_conformance.py::test_tlds_country[fi", "tests/test_conformance.py::test_tlds_country[fm", "tests/test_conformance.py::test_tlds_country[aw", "tests/test_conformance.py::test_tlds_country[tp", "tests/test_conformance.py::test_tlds_country[gl", "tests/test_conformance.py::test_tlds_country[\\u0628\\u06be\\u0627\\u0631\\u062a", "tests/test_conformance.py::test_tlds_country[\\u0a2d\\u0a3e\\u0a30\\u0a24", "tests/test_conformance.py::test_tlds_country[am", "tests/test_conformance.py::test_tlds_country[mx", "tests/test_conformance.py::test_validate_weighted_tweets_with_discounted_emoji_counter_test[Allow", "tests/test_conformance.py::test_tlds_country[\\u0639\\u0631\\u0627\\u0642", "tests/test_conformance.py::test_tlds_country[mo", "tests/test_conformance.py::test_tlds_country[tk", "tests/test_conformance.py::test_tlds_country[gd", "tests/test_conformance.py::test_tlds_country[kw", "tests/test_conformance.py::test_tlds_country[\\u0627\\u0645\\u0627\\u0631\\u0627\\u062a", "tests/test_conformance.py::test_tlds_country[\\u0aad\\u0abe\\u0ab0\\u0aa4", "tests/test_conformance.py::test_tlds_country[so", "tests/test_conformance.py::test_tlds_country[\\u0642\\u0637\\u0631", "tests/test_conformance.py::test_tlds_country[hr", "tests/test_conformance.py::test_tlds_country[tl", "tests/test_conformance.py::test_tlds_country[ci", "tests/test_conformance.py::test_tlds_country[dk", "tests/test_conformance.py::test_tlds_country[pt", "tests/test_conformance.py::test_tlds_country[vn", "tests/test_conformance.py::test_tlds_country[gg", "tests/test_conformance.py::test_tlds_country[zm", "tests/test_conformance.py::test_tlds_country[lv", "tests/test_conformance.py::test_extract_urls_with_indices[Properly", "tests/test_conformance.py::test_tlds_country[sg", "tests/test_conformance.py::test_tlds_country[ck", "tests/test_conformance.py::test_tlds_country[my", "tests/test_conformance.py::test_validate_weighted_tweets_with_discounted_emoji_counter_test[Long", "tests/test_conformance.py::test_tlds_country[sc", "tests/test_conformance.py::test_tlds_country[bh", "tests/test_conformance.py::test_tlds_country[lk", "tests/test_conformance.py::test_tlds_country[lr", "tests/test_conformance.py::test_tlds_country[ls", "tests/test_conformance.py::test_tlds_country[ma", "tests/test_conformance.py::test_tlds_country[\\u0c2d\\u0c3e\\u0c30\\u0c24\\u0c4d", "tests/test_conformance.py::test_tlds_country[nc", "tests/test_conformance.py::test_tlds_country[ph", "tests/test_conformance.py::test_tlds_country[gh", "tests/test_conformance.py::test_tlds_country[es", "tests/test_conformance.py::test_tlds_country[nr", "tests/test_conformance.py::test_validate_weighted_tweets_with_discounted_emoji_counter_test[Just", "tests/test_conformance.py::test_tlds_country[ye", "tests/test_conformance.py::test_tlds_country[gu", "tests/test_conformance.py::test_tlds_country[jp", "tests/test_conformance.py::test_tlds_country[\\u0627\\u0644\\u0645\\u063a\\u0631\\u0628", "tests/test_conformance.py::test_tlds_country[mq", "tests/test_conformance.py::test_tlds_country[cw", "tests/test_conformance.py::test_tlds_country[co", "tests/test_conformance.py::test_tlds_country[\\u09ad\\u09be\\u09b0\\u09a4", "tests/test_conformance.py::test_tlds_country[pn", "tests/test_conformance.py::test_tlds_country[tj", "tests/test_conformance.py::test_tlds_country[hm", "tests/test_conformance.py::test_tlds_country[as", "tests/test_conformance.py::test_tlds_country[cz", "tests/test_conformance.py::test_tlds_country[\\u53f0\\u7063", "tests/test_conformance.py::test_tlds_country[ve", "tests/test_conformance.py::test_tlds_country[sx", "tests/test_conformance.py::test_tlds_country[ss", "tests/test_conformance.py::test_tlds_country[si", "tests/test_conformance.py::test_tlds_country[sl", "tests/test_conformance.py::test_tlds_country[\\u0628\\u0627\\u0631\\u062a", "tests/test_conformance.py::test_validate_weighted_tweets_with_discounted_emoji_counter_test[140", "tests/test_conformance.py::test_tlds_country[et", "tests/test_conformance.py::test_tlds_country[om", "tests/test_conformance.py::test_tlds_country[su", "tests/test_conformance.py::test_tlds_country[ch", "tests/test_conformance.py::test_tlds_country[pm", "tests/test_conformance.py::test_tlds_country[sa", "tests/test_conformance.py::test_tlds_country[tz", "tests/test_conformance.py::test_tlds_country[\\u09ad\\u09be\\u09f0\\u09a4", "tests/test_conformance.py::test_tlds_country[\\u0645\\u0635\\u0631", "tests/test_conformance.py::test_tlds_country[bz", "tests/test_conformance.py::test_tlds_country[ke", "tests/test_conformance.py::test_tlds_country[\\u03b5\\u03bb", "tests/test_conformance.py::test_tlds_country[fr", "tests/test_conformance.py::test_tlds_country[um", "tests/test_conformance.py::test_tlds_country[an", "tests/test_conformance.py::test_validate_weighted_tweets_with_discounted_emoji_counter_test[Regular", "tests/test_conformance.py::test_tlds_country[kg", "tests/test_conformance.py::test_tlds_country[tn", "tests/test_conformance.py::test_tlds_country[\\u65b0\\u52a0\\u5761", "tests/test_conformance.py::test_tlds_country[im", "tests/test_conformance.py::test_tlds_country[lu", "tests/test_conformance.py::test_tlds_country[er", "tests/test_conformance.py::test_tlds_country[sj", "tests/test_conformance.py::test_tlds_country[ao", "tests/test_conformance.py::test_tlds_country[\\u53f0\\u6e7e", "tests/test_conformance.py::test_tlds_country[mp", "tests/test_conformance.py::test_tlds_country[sd", "tests/test_conformance.py::test_tlds_country[gs", "tests/test_conformance.py::test_tlds_country[jo", "tests/test_conformance.py::test_tlds_country[tr", "tests/test_conformance.py::test_tlds_country[pk", "tests/test_conformance.py::test_tlds_country[mg", "tests/test_conformance.py::test_tlds_country[cm", "tests/test_conformance.py::test_tlds_country[se", "tests/test_conformance.py::test_tlds_country[gt", "tests/test_conformance.py::test_tlds_country[\\u062a\\u0648\\u0646\\u0633", "tests/test_conformance.py::test_tlds_country[td", "tests/test_conformance.py::test_tlds_country[vi", "tests/test_conformance.py::test_tlds_country[th", "tests/test_conformance.py::test_tlds_country[af", "tests/test_conformance.py::test_tlds_country[bm", "tests/test_conformance.py::test_tlds_country[ir", "tests/test_conformance.py::test_tlds_country[uz", "tests/test_conformance.py::test_tlds_country[\\u0645\\u0644\\u064a\\u0633\\u064a\\u0627", "tests/test_conformance.py::test_tlds_country[zw", "tests/test_conformance.py::test_tlds_country[il", "tests/test_conformance.py::test_tlds_country[sk", "tests/test_conformance.py::test_validate_weighted_tweets_with_discounted_emoji_counter_test[3", "tests/test_conformance.py::test_tlds_country[to", "tests/test_conformance.py::test_tlds_country[mv", "tests/test_conformance.py::test_tlds_country[ro", "tests/test_conformance.py::test_tlds_country[st", "tests/test_conformance.py::test_tlds_country[\\u0443\\u043a\\u0440", "tests/test_conformance.py::test_tlds_country[dj", "tests/test_conformance.py::test_tlds_country[gr", "tests/test_conformance.py::test_tlds_country[ax", "tests/test_conformance.py::test_tlds_country[ie", "tests/test_conformance.py::test_tlds_country[wf", "tests/test_conformance.py::test_tlds_country[\\u092d\\u093e\\u0930\\u0924\\u092e\\u094d", "tests/test_conformance.py::test_tlds_country[ky", "tests/test_conformance.py::test_tlds_country[lt", "tests/test_conformance.py::test_tlds_country[bt", "tests/test_conformance.py::test_tlds_country[id", "tests/test_conformance.py::test_tlds_country[cg", "tests/test_conformance.py::test_tlds_country[us", "tests/test_conformance.py::test_tlds_country[dz", "tests/test_conformance.py::test_tlds_country[\\u0570\\u0561\\u0575", "tests/test_conformance.py::test_tlds_country[mk", "tests/test_conformance.py::test_tlds_country[is", "tests/test_conformance.py::test_tlds_country[kr", "tests/test_conformance.py::test_tlds_country[bf", "tests/test_conformance.py::test_tlds_country[ba", "tests/test_conformance.py::test_tlds_country[pa", "tests/test_conformance.py::test_tlds_country[\\u10d2\\u10d4", "tests/test_conformance.py::test_tlds_country[gm", "tests/test_conformance.py::test_tlds_country[hn", "tests/test_conformance.py::test_tlds_country[ae", "tests/test_added.py::test_added_parse_tweet[A", "tests/test_added.py::test_added_parse_tweet[Hangul", "tests/test_added.py::test_added_parse_tweet[One", "tests/test_added.py::test_added_extract_urls_with_indices[t.co" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2020-05-24 01:56:24+00:00
mit
5,814
sybila__eBCSgen-105
diff --git a/eBCSgen/Parsing/ParseBCSL.py b/eBCSgen/Parsing/ParseBCSL.py index 1fc448f..4bb2843 100644 --- a/eBCSgen/Parsing/ParseBCSL.py +++ b/eBCSgen/Parsing/ParseBCSL.py @@ -362,6 +362,10 @@ class TransformAbstractSyntax(Transformer): self.complex_defns = complex_defns def cmplx_name(self, matches): + if str(matches[0]) not in self.complex_defns: + raise ComplexParsingError( + f"Complex alias {matches[0]} not found in defined complexes: {list(self.complex_defns.keys())}", matches + ) return deepcopy(self.complex_defns[str(matches[0])]) def abstract_sequence(self, matches): @@ -544,11 +548,19 @@ class TreeToComplex(Transformer): def structure(self, matches): name = str(matches[0].children[0]) - if len(matches) > 1: - composition = set(matches[1].children) - return StructureAgent(name, composition) - else: + if len(matches) <= 1: return StructureAgent(name, set()) + atomic_names = set() + composition = set() + for atomic in matches[1].children: + if atomic.name in atomic_names: + raise ComplexParsingError( + f"Duplicate atomic agent in structure: {atomic.name}", matches + ) + atomic_names.add(atomic.name) + composition.add(atomic) + + return StructureAgent(name, composition) def rate_complex(self, matches): sequence = []
sybila/eBCSgen
2e3b30105b1b1760a997bbacfc7e8487eb625961
diff --git a/Testing/objects_testing.py b/Testing/objects_testing.py index 71742b5..a324d26 100644 --- a/Testing/objects_testing.py +++ b/Testing/objects_testing.py @@ -58,7 +58,7 @@ u2_c1_u = AtomicAgent("U", "u") # structure s1 = StructureAgent("B", {a1}) s2 = StructureAgent("D", set()) -s3 = StructureAgent("K", {a1, a3, a5}) +s3 = StructureAgent("K", {a1, a3, a11}) s4 = StructureAgent("B", {a4}) s5 = StructureAgent("D", {a5, a6}) s6 = StructureAgent("K", set()) diff --git a/Testing/parsing/test_complex.py b/Testing/parsing/test_complex.py index 77d5d35..e16dfb3 100644 --- a/Testing/parsing/test_complex.py +++ b/Testing/parsing/test_complex.py @@ -6,12 +6,12 @@ def test_parser(): assert ret.success assert ret.data.children[0] == objects.c1 - ret = objects.rate_complex_parser.parse("B(T{s}).D().K(T{s},S{s},S{_})::cell") + ret = objects.rate_complex_parser.parse("B(T{s}).D().K(T{s},S{s},U{a})::cell") assert ret.success assert ret.data.children[0] == objects.c2 ret = objects.rate_complex_parser.parse( - "B(T{s}).K(T{s}, S{s}, S{_}).D(S{_},T{p})::cyt" + "B(T{s}).K(T{s}, S{s}, U{a}).D(S{_},T{p})::cyt" ) assert ret.success assert ret.data.children[0] == objects.c3 @@ -58,3 +58,12 @@ def test_parser(): ret = objects.rate_complex_parser.parse("B(T{s})::") assert not ret.success + + ret = objects.rate_complex_parser.parse("B(T{s}, T{_})::cell") + assert not ret.success + + ret = objects.rate_complex_parser.parse("B(T{s}, T{s})::cell") + assert not ret.success + + ret = objects.rate_complex_parser.parse("B(T{s}, T{a})::cell") + assert not ret.success diff --git a/Testing/parsing/test_side.py b/Testing/parsing/test_side.py index 6034958..908aa9b 100644 --- a/Testing/parsing/test_side.py +++ b/Testing/parsing/test_side.py @@ -13,13 +13,13 @@ def test_parser(): assert ret.data.to_side() == objects.side2 ret = objects.side_parser.parse( - "B(T{s})::cell + B(T{s}).D().K(T{s},S{s},S{_})::cell + B(T{s}).D().K(T{s},S{s},S{_})::cell" + "B(T{s})::cell + B(T{s}).D().K(T{s},S{s},U{a})::cell + B(T{s}).D().K(T{s},S{s},U{a})::cell" ) assert ret.success assert ret.data.to_side() == objects.side3 ret = objects.side_parser.parse( - "B(T{s})::cell + 2 B(T{s}).D().K(T{s},S{s},S{_})::cell" + "B(T{s})::cell + 2 B(T{s}).D().K(T{s},S{s},U{a})::cell" ) assert ret.success assert ret.data.to_side() == objects.side3 @@ -48,3 +48,9 @@ def test_parser(): ret = objects.side_parser.parse("B(T{s}") assert not ret.success + + # not unique atomics in structure + ret = objects.side_parser.parse( + "B(T{s})::cell + B(T{s}).D().K(T{s},S{s},S{_})::cell + B(T{s}).D().K(T{s},S{s},S{_})::cell" + ) + assert not ret.success diff --git a/Testing/parsing/test_structure.py b/Testing/parsing/test_structure.py index bed18af..a7fbfd4 100644 --- a/Testing/parsing/test_structure.py +++ b/Testing/parsing/test_structure.py @@ -4,7 +4,7 @@ import Testing.objects_testing as objects def test_parser(): assert objects.structure_parser.parse("B(T{s})").data == objects.s1 assert objects.structure_parser.parse("D()").data == objects.s2 - assert objects.structure_parser.parse("K(T{s}, S{s}, S{_})").data == objects.s3 + assert objects.structure_parser.parse("K(T{s}, S{s}, U{a})").data == objects.s3 assert objects.structure_parser.parse("B(T{_})").data == objects.s4 assert objects.structure_parser.parse("D(S{_},T{p})").data == objects.s5 assert objects.structure_parser.parse("K()").data == objects.s6 @@ -18,3 +18,6 @@ def test_parser(): assert not objects.structure_parser.parse("[B(T{s})]").success assert not objects.structure_parser.parse("").success assert not objects.structure_parser.parse("B({s})").success + assert not objects.structure_parser.parse("B(S{s}, S{a})").success + assert not objects.structure_parser.parse("B(S{a}, S{a})").success + assert not objects.structure_parser.parse("B(S{_}, S{a})").success
raise error when an undefined complex alias is used in a rule Raise `ComplexParsingError` when the alias is not defined.
0.0
2e3b30105b1b1760a997bbacfc7e8487eb625961
[ "Testing/parsing/test_complex.py::test_parser", "Testing/parsing/test_side.py::test_parser", "Testing/parsing/test_structure.py::test_parser" ]
[]
{ "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false }
2024-03-21 14:35:33+00:00
mit
5,815
sybila__eBCSgen-107
diff --git a/eBCSgen/Parsing/ParseBCSL.py b/eBCSgen/Parsing/ParseBCSL.py index 4bb2843..480317f 100644 --- a/eBCSgen/Parsing/ParseBCSL.py +++ b/eBCSgen/Parsing/ParseBCSL.py @@ -3,7 +3,7 @@ import json import numpy as np from numpy import inf from copy import deepcopy -from lark import Lark, Token, Transformer, Tree +from lark import Lark, Transformer, Tree from lark import UnexpectedCharacters, UnexpectedToken, UnexpectedEOF from lark.load_grammar import _TERMINAL_NAMES import regex @@ -116,7 +116,7 @@ GRAMMAR = r""" init: const? rate_complex definition: def_param "=" number - rule: ((label)? side ARROW side ("@" rate)? (";" variable)?) | ((label)? side BI_ARROW side ("@" rate "|" rate )? (";" variable)?) + rule: ((label)? side arrow side ("@" rate)? (";" variable)?) | ((label)? side BI_ARROW side ("@" rate "|" rate )? (";" variable)?) cmplx_dfn: cmplx_name "=" value side: (const? complex "+")* (const? complex)? @@ -131,8 +131,10 @@ GRAMMAR = r""" COM: "//" POW: "**" - ARROW: "=>" + arrow: SINGLE_ARROW | REPLICATION_ARROW + SINGLE_ARROW: "=>" BI_ARROW: "<=>" + REPLICATION_ARROW: "=*>" RULES_START: "#! rules" INITS_START: "#! inits" DEFNS_START: "#! definitions" @@ -647,18 +649,21 @@ class TreeToObjects(Transformer): ) ) pairs = [(i, i + lhs.counter) for i in range(min(lhs.counter, rhs.counter))] - if lhs.counter > rhs.counter: + if type(arrow) is Tree and arrow.children[0].value == "=*>": + if lhs.counter >= rhs.counter or lhs.counter != 1 or rhs.counter <= 1: + raise UnspecifiedParsingError("Rule does not contain replication") + + for i in range(lhs.counter, rhs.counter): + if lhs.seq[pairs[-1][0]] == rhs.seq[pairs[-1][1] - lhs.counter]: + if rhs.seq[pairs[-1][1] - lhs.counter] == rhs.seq[i]: + pairs += [(pairs[-1][0], i + lhs.counter)] + else: + raise UnspecifiedParsingError("Rule does not contain replication") + + elif lhs.counter > rhs.counter: pairs += [(i, None) for i in range(rhs.counter, lhs.counter)] elif lhs.counter < rhs.counter: - for i in range(lhs.counter, rhs.counter): - replication = False - if lhs.counter == 1 and rhs.counter > 1: - if lhs.seq[pairs[-1][0]] == rhs.seq[pairs[-1][1] - lhs.counter]: - if rhs.seq[pairs[-1][1] - lhs.counter] == rhs.seq[i]: - pairs += [(pairs[-1][0], i + lhs.counter)] - replication = True - if not replication: - pairs += [(None, i + lhs.counter)] + pairs += [(None, i + lhs.counter) for i in range(lhs.counter, rhs.counter)] reversible = False if arrow == "<=>":
sybila/eBCSgen
902a02bc29b7e7da70ba34b5f96bf592832c63cd
diff --git a/Testing/objects_testing.py b/Testing/objects_testing.py index a324d26..a39e1fc 100644 --- a/Testing/objects_testing.py +++ b/Testing/objects_testing.py @@ -352,6 +352,35 @@ rule_no_change = Rule( sequence_no_change, mid_c1, compartments_c1, complexes_c1, pairs_c1, rate_c1 ) +sequence_repl1 = (s31, s31, s31) +mid_repl1 = 1 +compartments_repl1 = ["rep"] * 3 +complexes_repl1 = [(0, 0), (1, 1), (2, 2)] +pairs_repl1 = [(0, 1), (0, 2)] +rate_repl1 = Rate("3.0*[X()::rep]/2.0*v_1") + +rule_repl1 = Rule( + sequence_repl1, mid_repl1, compartments_repl1, complexes_repl1, pairs_repl1, None +) +rule_repl1_rate = Rule( + sequence_repl1, + mid_repl1, + compartments_repl1, + complexes_repl1, + pairs_repl1, + rate_repl1, +) + +repl_sequence2 = (s31, s31, s31, s31) +mid_repl2 = 1 +compartments_repl2 = ["rep"] * 4 +complexes_repl2 = [(0, 0), (1, 1), (2, 2), (3, 3)] +pairs_repl2 = [(0, 1), (0, 2), (0, 3)] + +rule_repl2 = Rule( + repl_sequence2, mid_repl2, compartments_repl2, complexes_repl2, pairs_repl2, None +) + # reactions reaction1 = Reaction(lhs, rhs, rate_5) diff --git a/Testing/parsing/test_rule.py b/Testing/parsing/test_rule.py index e3294e4..3ce55df 100644 --- a/Testing/parsing/test_rule.py +++ b/Testing/parsing/test_rule.py @@ -1,6 +1,7 @@ import pytest import Testing.objects_testing as objects +from eBCSgen.Core.Rate import Rate def test_parser(): @@ -70,3 +71,27 @@ def test_bidirectional(): rule_expr = "#! rules\nK(S{u}).B()::cyt => K(S{p})::cyt + B()::cyt @ 3*[K()::cyt]/2*v_1 | 2*[K()::cyt]/3*v_1" assert not objects.rules_parser.parse(rule_expr).success + + +def test_replication(): + rule_expr = "X()::rep =*> X()::rep + X()::rep" + result = objects.rule_parser.parse(rule_expr) + assert result.success + assert result.data[1] == objects.rule_repl1 + + rule_expr = "X()::rep =*> X()::rep + X()::rep @ 3*[X()::rep]/2*v_1" + result = objects.rule_parser.parse(rule_expr) + assert result.success + rate_repl1 = Rate("3.0*[X()::rep]/2*v_1") + assert result.data[1] == objects.rule_repl1_rate + + rule_expr = "X()::rep =*> X()::rep + X()::rep + X()::rep" + result = objects.rule_parser.parse(rule_expr) + assert result.success + assert result.data[1] == objects.rule_repl2 + + rule_expr = "X()::rep + Y()::rep =*> X()::rep + X()::rep" + assert not objects.rule_parser.parse(rule_expr).success + + rule_expr = "X()::rep =*> X()::rep + X()::rep + Y()::rep" + assert not objects.rule_parser.parse(rule_expr).success
replication rules replication rules - this feature is quite hardcoded, the first question is whether we want to support it at all, then how to do it in a robust way
0.0
902a02bc29b7e7da70ba34b5f96bf592832c63cd
[ "Testing/parsing/test_rule.py::test_replication" ]
[ "Testing/parsing/test_rule.py::test_parser", "Testing/parsing/test_rule.py::test_bidirectional" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2024-04-15 12:01:00+00:00
mit
5,816
sybila__eBCSgen-109
diff --git a/eBCSgen/Parsing/ParseBCSL.py b/eBCSgen/Parsing/ParseBCSL.py index 4bb2843..8368f44 100644 --- a/eBCSgen/Parsing/ParseBCSL.py +++ b/eBCSgen/Parsing/ParseBCSL.py @@ -3,7 +3,7 @@ import json import numpy as np from numpy import inf from copy import deepcopy -from lark import Lark, Token, Transformer, Tree +from lark import Lark, Transformer, Tree from lark import UnexpectedCharacters, UnexpectedToken, UnexpectedEOF from lark.load_grammar import _TERMINAL_NAMES import regex @@ -106,17 +106,18 @@ class SideHelper: GRAMMAR = r""" model: (sections)* rules (sections | rules)* - sections: inits | definitions | complexes | regulation + sections: inits | definitions | complexes | regulation | observables rules: RULES_START _NL+ (rule _NL+)* rule _NL* inits: INITS_START _NL+ (init _NL+)* init _NL* definitions: DEFNS_START _NL+ (definition _NL+)* definition _NL* complexes: COMPLEXES_START _NL+ (cmplx_dfn _NL+)* cmplx_dfn _NL* regulation: REGULATION_START _NL+ regulation_def _NL* + observables: OBSERVABLES_START _NL+ (observable _NL+)* observable _NL* init: const? rate_complex definition: def_param "=" number - rule: ((label)? side ARROW side ("@" rate)? (";" variable)?) | ((label)? side BI_ARROW side ("@" rate "|" rate )? (";" variable)?) + rule: ((label)? side arrow side ("@" rate)? (";" variable)?) | ((label)? side BI_ARROW side ("@" rate "|" rate )? (";" variable)?) cmplx_dfn: cmplx_name "=" value side: (const? complex "+")* (const? complex)? @@ -131,13 +132,16 @@ GRAMMAR = r""" COM: "//" POW: "**" - ARROW: "=>" + arrow: SINGLE_ARROW | REPLICATION_ARROW + SINGLE_ARROW: "=>" BI_ARROW: "<=>" + REPLICATION_ARROW: "=*>" RULES_START: "#! rules" INITS_START: "#! inits" DEFNS_START: "#! definitions" COMPLEXES_START: "#! complexes" REGULATION_START: "#! regulation" + OBSERVABLES_START: "#! observables" _NL: /(\r?\n[\t ]*)+/ !label: CNAME "~" @@ -239,6 +243,11 @@ REGEX_GRAMMAR = r""" REGEX_CHAR: /[^\\^$().*+?{}\[\]|]/ """ +OBSERVABLES_GRAMMAR = """ + observable: CNAME ":" observable_pattern + !observable_pattern: const | complex | observable_pattern "+" observable_pattern | observable_pattern "-" observable_pattern | observable_pattern "*" observable_pattern | observable_pattern "/" observable_pattern | observable_pattern POW const | "(" observable_pattern ")" +""" + class TransformRegulations(Transformer): def regulation(self, matches): @@ -647,31 +656,38 @@ class TreeToObjects(Transformer): ) ) pairs = [(i, i + lhs.counter) for i in range(min(lhs.counter, rhs.counter))] - if lhs.counter > rhs.counter: + if type(arrow) is Tree and arrow.children[0].value == "=*>": + if lhs.counter >= rhs.counter or lhs.counter != 1 or rhs.counter <= 1: + raise UnspecifiedParsingError("Rule does not contain replication") + + for i in range(lhs.counter, rhs.counter): + if lhs.seq[pairs[-1][0]] == rhs.seq[pairs[-1][1] - lhs.counter]: + if rhs.seq[pairs[-1][1] - lhs.counter] == rhs.seq[i]: + pairs += [(pairs[-1][0], i + lhs.counter)] + else: + raise UnspecifiedParsingError("Rule does not contain replication") + + elif lhs.counter > rhs.counter: pairs += [(i, None) for i in range(rhs.counter, lhs.counter)] elif lhs.counter < rhs.counter: - for i in range(lhs.counter, rhs.counter): - replication = False - if lhs.counter == 1 and rhs.counter > 1: - if lhs.seq[pairs[-1][0]] == rhs.seq[pairs[-1][1] - lhs.counter]: - if rhs.seq[pairs[-1][1] - lhs.counter] == rhs.seq[i]: - pairs += [(pairs[-1][0], i + lhs.counter)] - replication = True - if not replication: - pairs += [(None, i + lhs.counter)] + pairs += [(None, i + lhs.counter) for i in range(lhs.counter, rhs.counter)] reversible = False if arrow == "<=>": reversible = True - return reversible, Rule( - agents, - mid, - compartments, - complexes, - pairs, - Rate(rate1) if rate1 else None, - label, - ), Rate(rate2) if rate2 else None + return ( + reversible, + Rule( + agents, + mid, + compartments, + complexes, + pairs, + Rate(rate1) if rate1 else None, + label, + ), + Rate(rate2) if rate2 else None, + ) def rules(self, matches): rules = [] @@ -703,6 +719,15 @@ class TreeToObjects(Transformer): result[init[0].children[0]] = 1 return {"inits": result} + def observable(self, matches): + return {str(matches[0]): matches[1].children} + + def observables(self, matches): + result = dict() + for observable in matches[1:]: + result.update(observable) + return {"observables": result} + def param(self, matches): self.params.add(str(matches[0])) return Tree("param", matches) @@ -712,6 +737,7 @@ class TreeToObjects(Transformer): definitions = dict() regulation = None inits = collections.Counter() + observables = dict() for match in matches: if type(match) == dict: key, value = list(match.items())[0] @@ -728,6 +754,8 @@ class TreeToObjects(Transformer): inits.update(value) elif key == "definitions": definitions.update(value) + elif key == "observables": + observables.update(value) elif key == "regulation": if regulation: raise UnspecifiedParsingError("Multiple regulations") @@ -749,9 +777,13 @@ class Parser: + EXTENDED_GRAMMAR + REGULATIONS_GRAMMAR + REGEX_GRAMMAR + + OBSERVABLES_GRAMMAR ) self.parser = Lark( - grammar, parser="earley", propagate_positions=False, maybe_placeholders=False + grammar, + parser="earley", + propagate_positions=False, + maybe_placeholders=False, ) self.terminals = dict((v, k) for k, v in _TERMINAL_NAMES.items()) @@ -856,7 +888,7 @@ class Parser: return Result( False, { - "unexpected": str(u.token), + "unexpected": str(u.token), "expected": self.replace(u.expected), "line": u.line, "column": u.column,
sybila/eBCSgen
902a02bc29b7e7da70ba34b5f96bf592832c63cd
diff --git a/Testing/objects_testing.py b/Testing/objects_testing.py index a324d26..171ba58 100644 --- a/Testing/objects_testing.py +++ b/Testing/objects_testing.py @@ -22,6 +22,8 @@ rate_complex_parser = Parser("rate_complex") rule_parser = Parser("rule") rules_parser = Parser("rules") model_parser = Parser("model") +observables_parser = Parser("observables") +observable_parser = Parser("observable") # atomic a1 = AtomicAgent("T", "s") @@ -352,6 +354,35 @@ rule_no_change = Rule( sequence_no_change, mid_c1, compartments_c1, complexes_c1, pairs_c1, rate_c1 ) +sequence_repl1 = (s31, s31, s31) +mid_repl1 = 1 +compartments_repl1 = ["rep"] * 3 +complexes_repl1 = [(0, 0), (1, 1), (2, 2)] +pairs_repl1 = [(0, 1), (0, 2)] +rate_repl1 = Rate("3.0*[X()::rep]/2.0*v_1") + +rule_repl1 = Rule( + sequence_repl1, mid_repl1, compartments_repl1, complexes_repl1, pairs_repl1, None +) +rule_repl1_rate = Rule( + sequence_repl1, + mid_repl1, + compartments_repl1, + complexes_repl1, + pairs_repl1, + rate_repl1, +) + +repl_sequence2 = (s31, s31, s31, s31) +mid_repl2 = 1 +compartments_repl2 = ["rep"] * 4 +complexes_repl2 = [(0, 0), (1, 1), (2, 2), (3, 3)] +pairs_repl2 = [(0, 1), (0, 2), (0, 3)] + +rule_repl2 = Rule( + repl_sequence2, mid_repl2, compartments_repl2, complexes_repl2, pairs_repl2, None +) + # reactions reaction1 = Reaction(lhs, rhs, rate_5) diff --git a/Testing/parsing/test_observables.py b/Testing/parsing/test_observables.py new file mode 100644 index 0000000..75340a9 --- /dev/null +++ b/Testing/parsing/test_observables.py @@ -0,0 +1,67 @@ +import pytest + +import Testing.objects_testing as objects + + +def test_parser(): + observable_expr1 = "abc: A()::cell" + assert objects.observable_parser.parse(observable_expr1) + + observable_expr2 = "efg: E(F{_})::cell" + assert objects.observable_parser.parse(observable_expr2) + + observable_expr3 = "hij: H()::cell" + assert objects.observable_parser.parse(observable_expr3) + + observable_expr4 = "klm: K()::cyt * L()::cell + M()::cell" + assert objects.observable_parser.parse(observable_expr4) + + observable_expr5 = "nop: N()::cell" + assert objects.observable_parser.parse(observable_expr5).success + + observable_expr6 = "qrs: Q().R().S()::cell" + assert objects.observable_parser.parse(observable_expr6).success + + observable_expr7 = "tuv: T(U{v})::cell " + assert objects.observable_parser.parse(observable_expr7).success + + observable_expr8 = "wx: 2 * W{x}::cell" + assert objects.observable_parser.parse(observable_expr8).success + + observable_expr9 = "z: Y{z}::cyt + Z{y}::ext" + assert objects.observable_parser.parse(observable_expr9).success + + observable_expr10 = "z: 2 * Y{z}::cyt + Z{y}::ext ** 2" + assert objects.observable_parser.parse(observable_expr10).success + + observable_expr10 = "z: (Y{z}::cell + Z{y}::cyt) / 2.1 ** 10" + assert objects.observable_parser.parse(observable_expr10).success + + observable_expr11 = "scaled_A: 1000 * A{i}::cell" + assert objects.observable_parser.parse(observable_expr11).success + + observable_expr12 = "obs_A_all: A{i}::cell + A{a}::cell" + assert objects.observable_parser.parse(observable_expr12).success + + observables_expr = ( + "#! observables\n" + + observable_expr1 + + "\n" + + observable_expr2 + + "\n" + + observable_expr3 + + "\n" + + observable_expr4 + + "\n" + + observable_expr5 + + "\n" + + observable_expr6 + ) + assert objects.observables_parser.parse(observables_expr).success + + assert not objects.observable_parser.parse("A()::cell > 2").success + assert not objects.observable_parser.parse("a: A(::cell").success + assert not objects.observable_parser.parse("a: b: A():cell > 2").success + assert not objects.observable_parser.parse("a: 2 > A():cell").success + assert not objects.observable_parser.parse("a: A()::cell$").success + assert not objects.observable_parser.parse("a: A{}::cell").success diff --git a/Testing/parsing/test_rule.py b/Testing/parsing/test_rule.py index e3294e4..3ce55df 100644 --- a/Testing/parsing/test_rule.py +++ b/Testing/parsing/test_rule.py @@ -1,6 +1,7 @@ import pytest import Testing.objects_testing as objects +from eBCSgen.Core.Rate import Rate def test_parser(): @@ -70,3 +71,27 @@ def test_bidirectional(): rule_expr = "#! rules\nK(S{u}).B()::cyt => K(S{p})::cyt + B()::cyt @ 3*[K()::cyt]/2*v_1 | 2*[K()::cyt]/3*v_1" assert not objects.rules_parser.parse(rule_expr).success + + +def test_replication(): + rule_expr = "X()::rep =*> X()::rep + X()::rep" + result = objects.rule_parser.parse(rule_expr) + assert result.success + assert result.data[1] == objects.rule_repl1 + + rule_expr = "X()::rep =*> X()::rep + X()::rep @ 3*[X()::rep]/2*v_1" + result = objects.rule_parser.parse(rule_expr) + assert result.success + rate_repl1 = Rate("3.0*[X()::rep]/2*v_1") + assert result.data[1] == objects.rule_repl1_rate + + rule_expr = "X()::rep =*> X()::rep + X()::rep + X()::rep" + result = objects.rule_parser.parse(rule_expr) + assert result.success + assert result.data[1] == objects.rule_repl2 + + rule_expr = "X()::rep + Y()::rep =*> X()::rep + X()::rep" + assert not objects.rule_parser.parse(rule_expr).success + + rule_expr = "X()::rep =*> X()::rep + X()::rep + Y()::rep" + assert not objects.rule_parser.parse(rule_expr).success
define observables define observables - pools, scaling (basic arithmetics).
0.0
902a02bc29b7e7da70ba34b5f96bf592832c63cd
[ "Testing/parsing/test_observables.py::test_parser", "Testing/parsing/test_rule.py::test_parser", "Testing/parsing/test_rule.py::test_bidirectional", "Testing/parsing/test_rule.py::test_replication" ]
[]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2024-04-16 14:38:35+00:00
mit
5,817
sybila__eBCSgen-92
diff --git a/eBCSgen/Parsing/ParseBCSL.py b/eBCSgen/Parsing/ParseBCSL.py index a9ac674..e70646c 100644 --- a/eBCSgen/Parsing/ParseBCSL.py +++ b/eBCSgen/Parsing/ParseBCSL.py @@ -156,9 +156,9 @@ GRAMMAR = r""" EXTENDED_GRAMMAR = """ abstract_sequence: atomic_complex | atomic_structure_complex | structure_complex - atomic_complex: atomic ":" (cmplx_name|VAR) - atomic_structure_complex: atomic ":" structure ":" (cmplx_name|VAR) - structure_complex: structure ":" (cmplx_name|VAR) + atomic_complex: atomic ":" (VAR | value) + atomic_structure_complex: atomic ":" structure ":" (VAR | value) + structure_complex: structure ":" (VAR | value) variable: VAR "=" "{" cmplx_name ("," cmplx_name)+ "}" VAR: "?" @@ -401,18 +401,23 @@ class TransformAbstractSyntax(Transformer): Raises: ComplexParsingError: If no matching struct is found in the complex. """ - for i in range(len(complex.children)): - if self.get_name(struct) == self.get_name(complex.children[i].children[0]): + if isinstance(complex.children[0].children[0].children[0].children[0], Tree): + search = complex.children[0] + else: + search = complex + + for i in range(len(search.children)): + if self.get_name(struct) == self.get_name(search.children[i].children[0]): struct_found = True # search same name structs - if they contain atomics with matching names, they are considered incompatible for j in range(len(struct.children[1].children)): for k in range( - len(complex.children[i].children[0].children[1].children) + len(search.children[i].children[0].children[1].children) ): if self.get_name( struct.children[1].children[j] ) == self.get_name( - complex.children[i].children[0].children[1].children[k] + search.children[i].children[0].children[1].children[k] ): struct_found = False break @@ -422,13 +427,11 @@ class TransformAbstractSyntax(Transformer): if struct_found: # if the complex's struct is empty, replace it with the struct - if self.is_empty(complex.children[i]): - complex.children[i] = Tree("agent", [struct]) + if self.is_empty(search.children[i]): + search.children[i] = Tree("agent", [struct]) else: # if the complex's struct is not empty merge the struct's children into the complex's struct - complex.children[i].children[0].children[ - 1 - ].children += struct.children[1].children + search.children[i].children[0].children[1].children += struct.children[1].children return complex raise ComplexParsingError( @@ -450,10 +453,15 @@ class TransformAbstractSyntax(Transformer): Raises: ComplexParsingError: If an atomic with the same name is already present in the complex. """ - for i in range(len(complex.children)): - if self.get_name(atomic) == self.get_name(complex.children[i].children[0]): - if self.is_empty(complex.children[i].children[0]): - complex.children[i] = Tree("agent", [atomic]) + if isinstance(complex.children[0].children[0].children[0].children[0], Tree): + search = complex.children[0] + else: + search = complex + + for i in range(len(search.children)): + if self.get_name(atomic) == self.get_name(search.children[i].children[0]): + if self.is_empty(search.children[i].children[0]): + search.children[i] = Tree("agent", [atomic]) return complex raise ComplexParsingError( f"Illegal atomic nesting or duplication: {atomic}:{complex}", complex
sybila/eBCSgen
230b3745b6ffaf930f9f30907925041856fb4cdd
diff --git a/Testing/models/model_cmplx_in_abstr_seq1.txt b/Testing/models/model_cmplx_in_abstr_seq1.txt new file mode 100644 index 0000000..f03c61d --- /dev/null +++ b/Testing/models/model_cmplx_in_abstr_seq1.txt @@ -0,0 +1,5 @@ +#! rules +S{i}:A():A2::cell => A()::cell + +#! complexes +A2 = A().A() diff --git a/Testing/models/model_cmplx_in_abstr_seq2.txt b/Testing/models/model_cmplx_in_abstr_seq2.txt new file mode 100644 index 0000000..801026b --- /dev/null +++ b/Testing/models/model_cmplx_in_abstr_seq2.txt @@ -0,0 +1,2 @@ +#! rules +S{i}:A():A().A()::cell => A()::cell diff --git a/Testing/parsing/test_cmplx_in_abstr_seq.py b/Testing/parsing/test_cmplx_in_abstr_seq.py new file mode 100644 index 0000000..068f47d --- /dev/null +++ b/Testing/parsing/test_cmplx_in_abstr_seq.py @@ -0,0 +1,17 @@ +import pytest + +from Testing.models.get_model_str import get_model_str +import Testing.objects_testing as objects + + +def test_complexes_in_abstract_sequence(): + # is allowed + model = get_model_str("model_cmplx_in_abstr_seq1") + ret1 = objects.model_parser.parse(model) + assert ret1.success + + # should be allowed + model = get_model_str("model_cmplx_in_abstr_seq2") + ret2 = objects.model_parser.parse(model) + assert ret2.success + assert ret1.data == ret2.data
Use complexes directly in `abstract_sequence` Allow usage of complexes directly in abstract_sequence - currently only aliases in place of complex are allowed
0.0
230b3745b6ffaf930f9f30907925041856fb4cdd
[ "Testing/parsing/test_cmplx_in_abstr_seq.py::test_complexes_in_abstract_sequence" ]
[]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2024-01-31 09:00:55+00:00
mit
5,818
sybila__eBCSgen-96
diff --git a/eBCSgen/Core/Rule.py b/eBCSgen/Core/Rule.py index 9faa67f..2bd5932 100644 --- a/eBCSgen/Core/Rule.py +++ b/eBCSgen/Core/Rule.py @@ -15,7 +15,16 @@ def column(lst, index): class Rule: - def __init__(self, agents: tuple, mid: int, compartments: list, complexes: list, pairs: list, rate: Rate, label=None): + def __init__( + self, + agents: tuple, + mid: int, + compartments: list, + complexes: list, + pairs: list, + rate: Rate, + label=None, + ): """ Class to represent BCSL rule @@ -35,9 +44,15 @@ class Rule: self.label = label self.comment = (False, []) - def __eq__(self, other: 'Rule'): - return self.agents == other.agents and self.mid == other.mid and self.compartments == other.compartments and \ - self.complexes == other.complexes and self.pairs == other.pairs and str(self.rate) == str(other.rate) + def __eq__(self, other: "Rule"): + return ( + self.agents == other.agents + and self.mid == other.mid + and self.compartments == other.compartments + and self.complexes == other.complexes + and self.pairs == other.pairs + and str(self.rate) == str(other.rate) + ) def __repr__(self): return str(self) @@ -47,14 +62,23 @@ class Rule: rate = " @ " + str(self.rate) if self.rate else "" pre_comment, post_comment = "", "" if self.comment[1]: - comment = "// redundant #{" + ", ".join(list(map(str, self.comment[1]))) + "} " + comment = ( + "// redundant #{" + ", ".join(list(map(str, self.comment[1]))) + "} " + ) pre_comment = comment + "// " if self.comment[0] else "" post_comment = " " + comment if not self.comment[0] else "" label = str(self.label) + " ~ " if self.label else "" - return label + pre_comment + " + ".join(lhs.to_list_of_strings()) + \ - " => " + " + ".join(rhs.to_list_of_strings()) + rate + post_comment + return ( + label + + pre_comment + + " + ".join(lhs.to_list_of_strings()) + + " => " + + " + ".join(rhs.to_list_of_strings()) + + rate + + post_comment + ) def __lt__(self, other): return str(self) < str(other) @@ -70,10 +94,12 @@ class Rule: :return: dict of {Complexes:{SBML codes of all isomorphisms in set}} """ unique_complexes_from_rule = dict() - for (f, t) in self.complexes: - c = Complex(self.agents[f:t + 1], self.compartments[f]) - double = (c, c.to_SBML_species_code()) - unique_complexes_from_rule[c] = unique_complexes_from_rule.get(c, set()) | {double} + for f, t in self.complexes: + c = Complex(self.agents[f : t + 1], self.compartments[f]) + double = (c, c.to_SBML_species_code()) + unique_complexes_from_rule[c] = unique_complexes_from_rule.get(c, set()) | { + double + } return unique_complexes_from_rule def create_complexes(self): @@ -83,8 +109,8 @@ class Rule: :return: two multisets of Complexes represented as object Side """ lhs, rhs = [], [] - for (f, t) in self.complexes: - c = Complex(self.agents[f:t + 1], self.compartments[f]) + for f, t in self.complexes: + c = Complex(self.agents[f : t + 1], self.compartments[f]) lhs.append(c) if t < self.mid else rhs.append(c) return Side(lhs), Side(rhs) @@ -108,7 +134,9 @@ class Rule: if self.rate: self.rate.vectorize(ordering, definitions) - def create_reactions(self, atomic_signature: dict, structure_signature: dict) -> set: + def create_reactions( + self, atomic_signature: dict, structure_signature: dict + ) -> set: """ Create all possible reactions. Decide if rule is of replication type and call corresponding lower level method. @@ -118,13 +146,21 @@ class Rule: :return: set of created reactions """ unique_lhs_indices = set(column(self.pairs, 0)) - if len(self.pairs) > 1 and len(unique_lhs_indices) == 1 and None not in unique_lhs_indices: + if ( + len(self.pairs) > 1 + and len(unique_lhs_indices) == 1 + and None not in unique_lhs_indices + ): # should be the replication rule - return self._create_replication_reactions(atomic_signature, structure_signature) + return self._create_replication_reactions( + atomic_signature, structure_signature + ) else: return self._create_normal_reactions(atomic_signature, structure_signature) - def _create_replication_reactions(self, atomic_signature: dict, structure_signature: dict) -> set: + def _create_replication_reactions( + self, atomic_signature: dict, structure_signature: dict + ) -> set: """ Create reaction from rule of special form for replication (A -> 2 A) @@ -144,13 +180,22 @@ class Rule: # replicate RHS agent n times for _ in range(len(self.pairs)): new_agents.append(deepcopy(new_agents[-1])) - new_rule = Rule(tuple(new_agents), self.mid, self.compartments, - self.complexes, self.pairs, self.rate, self.label) + new_rule = Rule( + tuple(new_agents), + self.mid, + self.compartments, + self.complexes, + self.pairs, + self.rate, + self.label, + ) reactions.add(new_rule.to_reaction()) return reactions - def _create_normal_reactions(self, atomic_signature: dict, structure_signature: dict) -> set: + def _create_normal_reactions( + self, atomic_signature: dict, structure_signature: dict + ) -> set: """ Adds context to all agents and generated all possible combinations. Then, new rules with these enhances agents are generated and converted to Reactions. @@ -160,7 +205,7 @@ class Rule: :return: set of created reactions """ results = [] - for (l, r) in self.pairs: + for l, r in self.pairs: if l is None: right = -1 left = self.agents[r] @@ -170,17 +215,27 @@ class Rule: else: left = self.agents[l] right = self.agents[r] - results.append(left.add_context(right, atomic_signature, structure_signature)) + results.append( + left.add_context(right, atomic_signature, structure_signature) + ) reactions = set() for result in itertools.product(*results): new_agents = tuple(filter(None, column(result, 0) + column(result, 1))) - new_rule = Rule(new_agents, self.mid, self.compartments, self.complexes, self.pairs, self.rate, self.label) + new_rule = Rule( + new_agents, + self.mid, + self.compartments, + self.complexes, + self.pairs, + self.rate, + self.label, + ) reactions.add(new_rule.to_reaction()) return reactions - def compatible(self, other: 'Rule') -> bool: + def compatible(self, other: "Rule") -> bool: """ Checks whether Rule is compatible (position-wise) with the other Rule. Is done by formaly translating to Reactions (just a better object handling). @@ -201,7 +256,14 @@ class Rule: """ new_agents = tuple([agent.reduce_context() for agent in self.agents]) new_rate = self.rate.reduce_context() if self.rate else None - return Rule(new_agents, self.mid, self.compartments, self.complexes, self.pairs, new_rate) + return Rule( + new_agents, + self.mid, + self.compartments, + self.complexes, + self.pairs, + new_rate, + ) def is_meaningful(self) -> bool: """ @@ -231,7 +293,9 @@ class Rule: :param structure_signature: given structure signature :return: set of all created Complexes """ - return self.to_reaction().create_all_compatible(atomic_signature, structure_signature) + return self.to_reaction().create_all_compatible( + atomic_signature, structure_signature + ) def evaluate_rate(self, state, params): """ @@ -242,7 +306,7 @@ class Rule: :return: a real number of the rate """ values = dict() - for (state_complex, count) in state.content.value.items(): + for state_complex, count in state.content.value.items(): for agent in self.rate_agents: if agent.compatible(state_complex): values[agent] = values.get(agent, 0) + count @@ -277,16 +341,24 @@ class Rule: # replace respective agents unique_lhs_indices = set(column(self.pairs, 0)) - if len(self.pairs) > 1 and len(unique_lhs_indices) == 1 and \ - None not in unique_lhs_indices and len(aligned_match) == 1: + if ( + len(self.pairs) > 1 + and len(unique_lhs_indices) == 1 + and None not in unique_lhs_indices + and len(aligned_match) == 1 + ): resulting_rhs = self._replace_replicated_rhs(aligned_match[0]) else: resulting_rhs = self._replace_normal_rhs(aligned_match) # construct resulting complexes output_complexes = [] - for (f, t) in list(filter(lambda item: item[0] >= self.mid, self.complexes)): - output_complexes.append(Complex(resulting_rhs[f - self.mid:t - self.mid + 1], self.compartments[f])) + for f, t in list(filter(lambda item: item[0] >= self.mid, self.complexes)): + output_complexes.append( + Complex( + resulting_rhs[f - self.mid : t - self.mid + 1], self.compartments[f] + ) + ) return Multiset(collections.Counter(output_complexes)) @@ -298,7 +370,7 @@ class Rule: :return: RHS with replaced agents """ resulting_rhs = [] - for i, rhs_agent in enumerate(self.agents[self.mid:]): + for i, rhs_agent in enumerate(self.agents[self.mid :]): if len(aligned_match) <= i: resulting_rhs.append(rhs_agent) else: @@ -329,11 +401,11 @@ class Rule: :return: multiset of constructed agents """ output_complexes = [] - for (f, t) in list(filter(lambda item: item[1] < self.mid, self.complexes)): - output_complexes.append(Complex(match[f:t + 1], self.compartments[f])) + for f, t in list(filter(lambda item: item[1] < self.mid, self.complexes)): + output_complexes.append(Complex(match[f : t + 1], self.compartments[f])) return Multiset(collections.Counter(output_complexes)) - def create_reversible(self): + def create_reversible(self, rate: Rate = None): """ Create a reversible version of the rule with _bw label. @@ -343,19 +415,22 @@ class Rule: :return: reversed Rule """ - agents = self.agents[self.mid:] + self.agents[:self.mid] + agents = self.agents[self.mid :] + self.agents[: self.mid] mid = len(self.agents) - self.mid - compartments = self.compartments[self.mid:] + self.compartments[:self.mid] - complexes = sorted([((f - self.mid) % len(self.agents), - (t - self.mid) % len(self.agents)) for (f, t) in self.complexes]) + compartments = self.compartments[self.mid :] + self.compartments[: self.mid] + complexes = sorted( + [ + ((f - self.mid) % len(self.agents), (t - self.mid) % len(self.agents)) + for (f, t) in self.complexes + ] + ) pairs = [] - for (l, r) in self.pairs: + for l, r in self.pairs: if l is None or r is None: pairs.append((r, l)) else: pairs.append((l, r)) - rate = self.rate label = None if self.label: label = self.label + "_bw" diff --git a/eBCSgen/Parsing/ParseBCSL.py b/eBCSgen/Parsing/ParseBCSL.py index e70646c..990fe7a 100644 --- a/eBCSgen/Parsing/ParseBCSL.py +++ b/eBCSgen/Parsing/ParseBCSL.py @@ -114,7 +114,7 @@ GRAMMAR = r""" init: const? rate_complex (COMMENT)? definition: def_param "=" number (COMMENT)? - rule: (label)? side ARROW side ("@" rate)? (";" variable)? (COMMENT)? + rule: ((label)? side ARROW side ("@" rate)? (";" variable)? (COMMENT)?) | ((label)? side BI_ARROW side ("@" rate "|" rate)? (";" variable)? (COMMENT)?) cmplx_dfn: cmplx_name "=" value (COMMENT)? side: (const? complex "+")* (const? complex)? @@ -129,7 +129,8 @@ GRAMMAR = r""" COM: "//" POW: "**" - ARROW: "=>" | "<=>" + ARROW: "=>" + BI_ARROW: "<=>" RULES_START: "#! rules" INITS_START: "#! inits" DEFNS_START: "#! definitions" @@ -567,14 +568,20 @@ class TreeToObjects(Transformer): def rule(self, matches): label = None # TODO create implicit label - rate = None + rate1 = None + rate2 = None + if len(matches) == 6: + label, lhs, arrow, rhs, rate1, rate2 = matches if len(matches) == 5: - label, lhs, arrow, rhs, rate = matches + if type(matches[0]) == str: + label, lhs, arrow, rhs, rate1 = matches + else: + lhs, arrow, rhs, rate1, rate2 = matches elif len(matches) == 4: if type(matches[0]) == str: label, lhs, arrow, rhs = matches else: - lhs, arrow, rhs, rate = matches + lhs, arrow, rhs, rate1 = matches else: lhs, arrow, rhs = matches agents = tuple(lhs.seq + rhs.seq) @@ -609,15 +616,15 @@ class TreeToObjects(Transformer): compartments, complexes, pairs, - Rate(rate) if rate else None, + Rate(rate1) if rate1 else None, label, - ) + ), Rate(rate2) if rate2 else None def rules(self, matches): rules = [] - for reversible, rule in matches[1:]: + for reversible, rule, new_rate in matches[1:]: if reversible: - reversible_rule = rule.create_reversible() + reversible_rule = rule.create_reversible(new_rate) rules.append(rule) rules.append(reversible_rule) else: @@ -695,7 +702,8 @@ class Parser: self.terminals.update( { "COM": "//", - "ARROW": "=>, <=>", + "ARROW": "=>", + "BI_ARROW": "<=>", "POW": "**", "DOUBLE_COLON": "::", "RULES_START": "#! rules",
sybila/eBCSgen
52f30b5211bc9d71314595159c46d65ecce2f400
diff --git a/Testing/objects_testing.py b/Testing/objects_testing.py index 5debd74..71742b5 100644 --- a/Testing/objects_testing.py +++ b/Testing/objects_testing.py @@ -20,6 +20,7 @@ state_parser = Parser("state") side_parser = Parser("side") rate_complex_parser = Parser("rate_complex") rule_parser = Parser("rule") +rules_parser = Parser("rules") model_parser = Parser("model") # atomic @@ -246,13 +247,75 @@ rate_3 = Rate("1.0/(1.0+([X()::rep])**4.0)") r3 = Rule(sequence_3, mid_3, compartments_3, complexes_3, pairs_3, rate_3) sequence_4 = (s34, s35, s36, s37) +reversed_sequence_4 = (s36, s37, s34, s35) mid_4 = 2 compartments_4 = ["cyt"] * 4 complexes_4 = [(0, 1), (2, 2), (3, 3)] +reversed_complexes_4 = [(0, 0), (1, 1), (2, 3)] pairs_4 = [(0, 2), (1, 3)] rate_4 = Rate("3.0*[K()::cyt]/2.0*v_1") +reversed_rate_4 = Rate("2.0*[K()::cyt]/3.0*v_1") r4 = Rule(sequence_4, mid_4, compartments_4, complexes_4, pairs_4, rate_4) +reversed_r4a = Rule( + reversed_sequence_4, mid_4, compartments_4, reversed_complexes_4, pairs_4, rate_4 +) +reversed_r4b = Rule( + reversed_sequence_4, + mid_4, + compartments_4, + reversed_complexes_4, + pairs_4, + reversed_rate_4, +) +sequence_one_side_bidirectional = (s36, s37) +mid_one_side_bidirectional_a = 2 +mid_one_side_bidirectional_b = 0 +compartments_one_side_bidirectional = ["cyt"] * 2 +complexes_one_side_bidirectional = [(0, 0), (1, 1)] +pairs_one_side_bidirectional_a = [(0, None), (1, None)] +pairs_one_side_bidirectional_b = [(None, 0), (None, 1)] +one_side_bidirectional_a = Rule( + sequence_one_side_bidirectional, + mid_one_side_bidirectional_a, + compartments_one_side_bidirectional, + complexes_one_side_bidirectional, + pairs_one_side_bidirectional_a, + rate_4, +) +one_side_bidirectional_b = Rule( + sequence_one_side_bidirectional, + mid_one_side_bidirectional_b, + compartments_one_side_bidirectional, + complexes_one_side_bidirectional, + pairs_one_side_bidirectional_b, + rate_4, +) +one_side_bidirectional_b_reversed_rate = Rule( + sequence_one_side_bidirectional, + mid_one_side_bidirectional_b, + compartments_one_side_bidirectional, + complexes_one_side_bidirectional, + pairs_one_side_bidirectional_b, + reversed_rate_4, +) +one_side_bidirectional_a_no_rate = Rule( + sequence_one_side_bidirectional, + mid_one_side_bidirectional_a, + compartments_one_side_bidirectional, + complexes_one_side_bidirectional, + pairs_one_side_bidirectional_a, + None, +) +one_side_bidirectional_b_no_rate = Rule( + sequence_one_side_bidirectional, + mid_one_side_bidirectional_b, + compartments_one_side_bidirectional, + complexes_one_side_bidirectional, + pairs_one_side_bidirectional_b, + None, +) + sequence_5 = (s34, s35, s36, s37, s38) mid_5 = 2 @@ -272,6 +335,9 @@ rate_6 = Rate("3.0*[K(T{3+})::cyt]/2.0*v_1") r6 = Rule(sequence_6, mid_6, compartments_6, complexes_6, pairs_6, rate_6) rule_no_rate = Rule(sequence_4, mid_4, compartments_4, complexes_4, pairs_4, None) +reversed_no_rate = Rule( + reversed_sequence_4, mid_4, compartments_4, reversed_complexes_4, pairs_4, None +) sequence_c1 = (s34, s35, s36, s37, s2) mid_c1 = 2 diff --git a/Testing/parsing/test_rule.py b/Testing/parsing/test_rule.py index a44b056..e3294e4 100644 --- a/Testing/parsing/test_rule.py +++ b/Testing/parsing/test_rule.py @@ -1,10 +1,8 @@ import pytest -from eBCSgen.Core.Rule import Rule -from eBCSgen.Core.Rate import Rate - import Testing.objects_testing as objects + def test_parser(): rule_expr = "K(S{u}).B()::cyt => K(S{p})::cyt + B()::cyt + D(B{_})::cell @ 3*[K()::cyt]/2*v_1" assert objects.rule_parser.parse(rule_expr).data[1] == objects.r5 @@ -20,3 +18,55 @@ def test_parser(): rule_expr = "K(S{u}).B()::cyt => K(S{p})::cyt + B()::cyt" assert objects.rule_parser.parse(rule_expr).data[1] == objects.rule_no_rate + + +def test_bidirectional(): + rule_expr = "#! rules\nK(S{u}).B()::cyt <=> K(S{p})::cyt + B()::cyt" + parsed = objects.rules_parser.parse(rule_expr) + assert parsed.success + assert objects.rule_no_rate in parsed.data["rules"] + assert objects.reversed_no_rate in parsed.data["rules"] + + rule_expr = "#! rules\nK(S{u}).B()::cyt <=> K(S{p})::cyt + B()::cyt @ 3*[K()::cyt]/2*v_1 | 3*[K()::cyt]/2*v_1" + parsed = objects.rules_parser.parse(rule_expr) + assert parsed.success + assert objects.r4 in parsed.data["rules"] + assert objects.reversed_r4a in parsed.data["rules"] + + rule_expr = "#! rules\nK(S{u}).B()::cyt <=> K(S{p})::cyt + B()::cyt @ 3*[K()::cyt]/2*v_1 | 2*[K()::cyt]/3*v_1" + parsed = objects.rules_parser.parse(rule_expr) + assert parsed.success + assert objects.r4 in parsed.data["rules"] + assert objects.reversed_r4b in parsed.data["rules"] + + rule_expr = "#! rules\n <=> K(S{p})::cyt + B()::cyt @ 3*[K()::cyt]/2*v_1 | 3*[K()::cyt]/2*v_1" + parsed = objects.rules_parser.parse(rule_expr) + assert parsed.success + assert objects.one_side_bidirectional_a in parsed.data["rules"] + assert objects.one_side_bidirectional_b in parsed.data["rules"] + + rule_expr = "#! rules\n K(S{p})::cyt + B()::cyt <=> @ 3*[K()::cyt]/2*v_1 | 3*[K()::cyt]/2*v_1" + parsed = objects.rules_parser.parse(rule_expr) + assert parsed.success + assert objects.one_side_bidirectional_a in parsed.data["rules"] + assert objects.one_side_bidirectional_b in parsed.data["rules"] + + rule_expr = "#! rules\n K(S{p})::cyt + B()::cyt <=> @ 3*[K()::cyt]/2*v_1 | 2*[K()::cyt]/3*v_1" + parsed = objects.rules_parser.parse(rule_expr) + assert parsed.success + assert objects.one_side_bidirectional_a in parsed.data["rules"] + assert objects.one_side_bidirectional_b_reversed_rate in parsed.data["rules"] + + rule_expr = "#! rules\n K(S{p})::cyt + B()::cyt <=>" + parsed = objects.rules_parser.parse(rule_expr) + assert parsed.success + assert objects.one_side_bidirectional_a_no_rate in parsed.data["rules"] + assert objects.one_side_bidirectional_b_no_rate in parsed.data["rules"] + + rule_expr = ( + "#! rules\nK(S{u}).B()::cyt <=> K(S{p})::cyt + B()::cyt @ 3*[K()::cyt]/2*v_1" + ) + assert not objects.rules_parser.parse(rule_expr).success + + rule_expr = "#! rules\nK(S{u}).B()::cyt => K(S{p})::cyt + B()::cyt @ 3*[K()::cyt]/2*v_1 | 2*[K()::cyt]/3*v_1" + assert not objects.rules_parser.parse(rule_expr).success
Allow bidirectional rules In current version, bidirectional rules are not supported at all.
0.0
52f30b5211bc9d71314595159c46d65ecce2f400
[ "Testing/parsing/test_rule.py::test_bidirectional" ]
[ "Testing/parsing/test_rule.py::test_parser" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2024-02-27 11:48:24+00:00
mit
5,819
symerio__pgeocode-46
diff --git a/README.rst b/README.rst index b1b279c..a3af1ab 100644 --- a/README.rst +++ b/README.rst @@ -103,6 +103,27 @@ Defaults to ``~/pgeocode_data``, it is the directory where data is downloaded for later consumption. It can be changed using the environment variable ``PGEOCODE_DATA_DIR``, i.e. ``export PGEOCODE_DATA_DIR=/tmp/pgeocode_data``. +**Data sources** + +The data sources are provided as a list in the ``pgeocode.DOWNLOAD_URL`` variable. +The default value is, + +.. code:: + + DOWNLOAD_URL = [ + "https://download.geonames.org/export/zip/{country}.zip", + "https://symerio.github.io/postal-codes-data/data/geonames/{country}.txt", + ] + +Data sources are tried from first to last until one works. Here the second link is a mirror +of the first. + +It is also possible to extend this variable with third party data sources, as +long as they follow the same format. See for instance +[postal-codes-data](https://github.com/symerio/postal-codes-data/tree/master/data/geonames) +repository for examples of data files. + + License ------- diff --git a/doc/contributing.rst b/doc/contributing.rst index 914ab51..35f3408 100644 --- a/doc/contributing.rst +++ b/doc/contributing.rst @@ -9,6 +9,10 @@ Testing Unit tests can be run with, +.. code:: + + pip install pytest pytest-httpserver + .. code:: pytest diff --git a/pgeocode.py b/pgeocode.py index 191a37d..fe6a6d9 100644 --- a/pgeocode.py +++ b/pgeocode.py @@ -2,11 +2,13 @@ # # Authors: Roman Yurchak <[email protected]> +import contextlib import os import urllib.request import warnings from io import BytesIO -from typing import Any, Tuple +from typing import Any, Tuple, List +from zipfile import ZipFile import numpy as np import pandas as pd @@ -17,7 +19,13 @@ STORAGE_DIR = os.environ.get( "PGEOCODE_DATA_DIR", os.path.join(os.path.expanduser("~"), "pgeocode_data") ) -DOWNLOAD_URL = "https://download.geonames.org/export/zip/{country}.zip" +# A list of download locations. If the first URL fails, following ones will +# be used. +DOWNLOAD_URL = [ + "https://download.geonames.org/export/zip/{country}.zip", + "https://symerio.github.io/postal-codes-data/data/geonames/{country}.txt", +] + DATA_FIELDS = [ "country_code", @@ -121,11 +129,51 @@ COUNTRIES_VALID = [ ] -def _open_url(url: str) -> Tuple[BytesIO, Any]: - """Download contents for a URL""" [email protected] +def _open_extract_url(url: str, country: str) -> Any: + """Download contents for a URL + + If the file has a .zip extension, open it and extract the country + + Returns the opened file object. + """ with urllib.request.urlopen(url) as res: - reader = BytesIO(res.read()) - return reader, res.headers + with BytesIO(res.read()) as reader: + if url.endswith(".zip"): + with ZipFile(reader) as fh_zip: + with fh_zip.open(country.upper() + ".txt") as fh: + yield fh + else: + yield reader + + [email protected] +def _open_extract_cycle_url(urls: List[str], country: str) -> Any: + """Same as _open_extract_url but cycle through URLs until one works + + We start by opening the first URL in the list, and if fails + move to the next, until one works or the end of list is reached. + """ + if not isinstance(urls, list) or not len(urls): + raise ValueError(f"urls={urls} must be a list with at least one URL") + + err_msg = f"Provided download URLs failed {{err}}: {urls}" + for idx, val in enumerate(urls): + try: + with _open_extract_url(val, country) as fh: + yield fh + # Found a working URL, exit the loop. + break + except urllib.error.HTTPError as err: # type: ignore + if idx == len(urls) - 1: + raise + warnings.warn( + f"Download from {val} failed with: {err}. " + "Trying next URL in DOWNLOAD_URL list.", + UserWarning, + ) + else: + raise ValueError(err_msg) class Nominatim: @@ -168,23 +216,22 @@ class Nominatim: @staticmethod def _get_data(country: str) -> Tuple[str, pd.DataFrame]: """Load the data from disk; otherwise download and save it""" - from zipfile import ZipFile data_path = os.path.join(STORAGE_DIR, country.upper() + ".txt") if os.path.exists(data_path): data = pd.read_csv(data_path, dtype={"postal_code": str}) else: - url = DOWNLOAD_URL.format(country=country) - reader, headers = _open_url(url) - with ZipFile(reader) as fh_zip: - with fh_zip.open(country.upper() + ".txt") as fh: - data = pd.read_csv( - fh, - sep="\t", - header=None, - names=DATA_FIELDS, - dtype={"postal_code": str}, - ) + download_urls = [ + val.format(country=country) for val in DOWNLOAD_URL + ] + with _open_extract_cycle_url(download_urls, country) as fh: + data = pd.read_csv( + fh, + sep="\t", + header=None, + names=DATA_FIELDS, + dtype={"postal_code": str}, + ) if not os.path.exists(STORAGE_DIR): os.mkdir(STORAGE_DIR) data.to_csv(data_path, index=None)
symerio/pgeocode
e4aeceb647e28abe9ab21edaf943993385f6cb82
diff --git a/.github/workflows/python-tests.yml b/.github/workflows/python-tests.yml index c52c3b3..d7259f8 100644 --- a/.github/workflows/python-tests.yml +++ b/.github/workflows/python-tests.yml @@ -38,5 +38,5 @@ jobs: pip install flake8 - name: Test with pytest run: | - pip install pytest + pip install pytest pytest-httpserver pytest diff --git a/test_pgeocode.py b/test_pgeocode.py index d8c966a..fe64c6a 100644 --- a/test_pgeocode.py +++ b/test_pgeocode.py @@ -2,8 +2,10 @@ # # Authors: Roman Yurchak <[email protected]> import os -import shutil -import tempfile +import urllib +import json +from zipfile import ZipFile +from io import BytesIO import numpy as np import pandas as pd @@ -12,16 +14,13 @@ from numpy.testing import assert_allclose, assert_array_equal import pgeocode from pgeocode import GeoDistance, Nominatim, haversine_distance +from pgeocode import _open_extract_url @pytest.fixture -def temp_dir(): - path_save = pgeocode.STORAGE_DIR - path = tempfile.mkdtemp() - pgeocode.STORAGE_DIR = path - yield path - pgeocode.STORAGE_DIR = path_save - shutil.rmtree(path) +def temp_dir(tmpdir, monkeypatch): + monkeypatch.setattr(pgeocode, "STORAGE_DIR", str(tmpdir)) + yield str(tmpdir) def _normalize_str(x): @@ -179,3 +178,82 @@ def test_haversine_distance(): d_pred = haversine_distance(x, y) # same distance +/- 3 km assert_allclose(d_ref, d_pred, atol=3) + + +def test_open_extract_url(httpserver): + download_url = "/fr.txt" + + # check download of uncompressed files + httpserver.expect_oneshot_request(download_url).respond_with_json({"a": 1}) + with _open_extract_url(httpserver.url_for(download_url), "fr") as fh: + assert json.loads(fh.read()) == {"a": 1} + httpserver.check_assertions() + + # check download of zipped files + # Create an in-memory zip file + answer = b"a=1" + with BytesIO() as fh: + with ZipFile(fh, "w") as fh_zip: + with fh_zip.open("FR.txt", "w") as fh_inner: + fh_inner.write(answer) + fh.seek(0) + res = fh.read() + + download_url = "/fr.zip" + httpserver.expect_oneshot_request(download_url).respond_with_data(res) + + with _open_extract_url(httpserver.url_for(download_url), "fr") as fh: + assert fh.read() == answer + + [email protected]( + "download_url", + [ + "https://download.geonames.org/export/zip/{country}.zip", + "https://symerio.github.io/postal-codes-data/data/" + "geonames/{country}.txt", + ], + ids=["geonames", "gitlab-pages"], +) +def test_cdn(temp_dir, monkeypatch, download_url): + monkeypatch.setattr(pgeocode, "DOWNLOAD_URL", [download_url]) + assert not os.path.exists(os.path.join(temp_dir, "IE.txt")) + Nominatim("IE") + # the data file was downloaded + assert os.path.exists(os.path.join(temp_dir, "IE.txt")) + + +def test_url_returns_404(httpserver, monkeypatch, temp_dir): + download_url = "/fr.gzip" + httpserver.expect_oneshot_request(download_url).respond_with_data( + "", status=404 + ) + + monkeypatch.setattr( + pgeocode, "DOWNLOAD_URL", [httpserver.url_for(download_url)] + ) + # Nominatim("fr") + with pytest.raises(urllib.error.HTTPError, match="HTTP Error 404"): + Nominatim("fr") + httpserver.check_assertions() + + +def test_first_url_fails(httpserver, monkeypatch, temp_dir): + download_url = "/IE.txt" + httpserver.expect_oneshot_request(download_url).respond_with_data( + "", status=404 + ) + + monkeypatch.setattr( + pgeocode, + "DOWNLOAD_URL", + [ + httpserver.url_for(download_url), + "https://symerio.github.io/postal-codes-data/data/" + "geonames/{country}.txt", + ], + ) + msg = "IE.txt failed with: HTTP Error 404.*Trying next URL" + with pytest.warns(UserWarning, match=msg): + Nominatim("ie") + httpserver.check_assertions()
Support alternate download locations It might be useful to support alternate download locations in case GeoNames website goes down. This would also help reproducibility (I'm not sure how often GeoNames database is updated and if that is tracked somewhere). This would require storing the data somewhere. One possibility for free hosting could be to attach it to Github releases. For instance, maybe @zaro's implementation in https://github.com/zaro/pgeocode/commit/6a3c743bee8fd67ae6ec82c87e0d6cbfefa62110 could be adapted.
0.0
e4aeceb647e28abe9ab21edaf943993385f6cb82
[ "test_pgeocode.py::test_countries[FR-91120-Palaiseau-67000-Strasbourg-400]", "test_pgeocode.py::test_countries[GB-WC2N", "test_pgeocode.py::test_countries[AU-6837-Perth-3000-melbourne-2722]", "test_pgeocode.py::test_countries[AU-6837-Perth-0221-Barton-3089]", "test_pgeocode.py::test_countries[US-60605-Chicago-94103-San", "test_pgeocode.py::test_countries[CA-M5R", "test_pgeocode.py::test_download_dataset", "test_pgeocode.py::test_nominatim_query_postal_code", "test_pgeocode.py::test_nominatim_query_postal_code_multiple", "test_pgeocode.py::test_nominatim_distance_postal_code", "test_pgeocode.py::test_cdn[geonames]", "test_pgeocode.py::test_cdn[gitlab-pages]" ]
[]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2020-10-23 22:01:54+00:00
bsd-3-clause
5,820
symerio__pgeocode-62
diff --git a/CHANGELOG.md b/CHANGELOG.md index 683a3c0..088341d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,12 @@ - The minimum supported Python version is updated to Python 3.8 [#65](https://github.com/symerio/pgeocode/pull/65) + - Fix error in latitude grouping when creating a unique postcode index. + With this fix `Nominatim(.., unique=True)` correctly computes the average + latitude for each postcode (if multiple localities share the same postcode), + instead of taking the first latitude value. + [#62](https://github.com/symerio/pgeocode/pull/62) + - The default folder to store downloaded data is changed to `~/.cache/pgeocode/`. This default can still be changed by setting the `PGEOCODE_DATA_DIR` environment variable. [#51](https://github.com/symerio/pgeocode/pull/51) diff --git a/pgeocode.py b/pgeocode.py index 65f8ffd..4f9aab3 100644 --- a/pgeocode.py +++ b/pgeocode.py @@ -252,7 +252,7 @@ class Nominatim: df_unique_cp_group = self._data.groupby("postal_code") data_unique = df_unique_cp_group[["latitude", "longitude"]].mean() valid_keys = set(DATA_FIELDS).difference( - ["place_name", "lattitude", "longitude", "postal_code"] + ["place_name", "latitude", "longitude", "postal_code"] ) data_unique["place_name"] = df_unique_cp_group["place_name"].apply( lambda x: ", ".join([str(el) for el in x])
symerio/pgeocode
fda231859ae17c7282a9d90c0e2b5b3cde1eb01d
diff --git a/test_pgeocode.py b/test_pgeocode.py index b6fe453..1bfdcbf 100644 --- a/test_pgeocode.py +++ b/test_pgeocode.py @@ -261,3 +261,60 @@ def test_first_url_fails(httpserver, monkeypatch, temp_dir): with pytest.warns(UserWarning, match=msg): Nominatim("ie") httpserver.check_assertions() + + +def test_unique_index_pcode(tmp_path): + """Check that a centroid is computed both for latitude and longitude + + Regression test for https://github.com/symerio/pgeocode/pull/62 + """ + + class MockNominatim(Nominatim): + def __init__(self): + pass + + data = pd.DataFrame( + { + "postal_code": ["1", "1", "2", "2"], + "latitude": [1.0, 2.0, 3.0, 4], + "longitude": [5.0, 6.0, 7.0, 8], + "place_name": ["a", "b", "c", "d"], + "state_name": ["a", "b", "c", "d"], + "country_name": ["a", "b", "c", "d"], + "county_name": ["a", "b", "c", "d"], + "community_name": ["a", "b", "c", "d"], + "accuracy": [1, 2, 3, 4], + "country_code": [1, 2, 3, 4], + "county_code": [1, 2, 3, 4], + "state_code": [1, 2, 3, 4], + "community_code": [1, 2, 3, 4], + } + ) + + nominatim = MockNominatim() + data_path = tmp_path / "a.txt" + nominatim._data_path = str(data_path) + nominatim._data = data + data_unique = nominatim._index_postal_codes() + + data_unique_expected = pd.DataFrame( + { + "postal_code": ["1", "2"], + "latitude": [1.5, 3.5], + "longitude": [5.5, 7.5], + "place_name": ["a, b", "c, d"], + "state_name": ["a", "c"], + # We don't include the country_name for some reason? + # 'country_name': ['a', 'c'], + "county_name": ["a", "c"], + "community_name": ["a", "c"], + "accuracy": [1, 3], + "country_code": [1, 3], + "county_code": [1, 3], + "state_code": [1, 3], + "community_code": [1, 3], + } + ) + pd.testing.assert_frame_equal( + data_unique.sort_index(axis=1), data_unique_expected.sort_index(axis=1) + )
incorrect centroid in query_postal_code for duplicate postal code entries query_postal_code sums the longitude. nomi.query_postal_code("41-800") Thats from GEOName file: 41-800 will return you 2 locations: PL, 41-800, 50.2817, 18.6745 PL,41-800, 50.3055, 18.778 After running: nomi.query_postal_code("41-800") postal_code 41-800 place_name Gliwice, Zabrze latitude 50.2817 longitude 18.7263 and the longitude = SUM of the locations from file / number of results.
0.0
fda231859ae17c7282a9d90c0e2b5b3cde1eb01d
[ "test_pgeocode.py::test_unique_index_pcode" ]
[ "test_pgeocode.py::test_countries[FR-91120-Palaiseau-67000-Strasbourg-400]", "test_pgeocode.py::test_countries[GB-WC2N", "test_pgeocode.py::test_countries[AU-6837-Perth-3000-melbourne-2722]", "test_pgeocode.py::test_countries[AU-6837-Perth-0221-Barton-3089]", "test_pgeocode.py::test_countries[US-60605-Chicago-94103-San", "test_pgeocode.py::test_countries[CA-M5R", "test_pgeocode.py::test_download_dataset", "test_pgeocode.py::test_nominatim_query_postal_code", "test_pgeocode.py::test_nominatim_query_postal_code_multiple", "test_pgeocode.py::test_nominatim_distance_postal_code", "test_pgeocode.py::test_cdn[geonames]", "test_pgeocode.py::test_cdn[gitlab-pages]" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2022-06-16 08:54:33+00:00
bsd-3-clause
5,821
syrusakbary__snapshottest-133
diff --git a/.travis.yml b/.travis.yml index 9494339..578c891 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,8 +1,6 @@ language: python sudo: false python: -- 2.7 -- 3.4 - 3.5 - 3.6 - 3.7 diff --git a/setup.py b/setup.py index 1229d68..a18b9b0 100644 --- a/setup.py +++ b/setup.py @@ -5,7 +5,7 @@ from setuptools import setup, find_packages with open("README.md") as f: readme = f.read() -tests_require = ["six", "pytest>=4.6", "pytest-cov", "nose", "django>=1.10.6"] +tests_require = ["pytest>=4.6", "pytest-cov", "nose", "django>=1.10.6"] setup( name="snapshottest", @@ -23,7 +23,7 @@ setup( ], "nose.plugins.0.10": ["snapshottest = snapshottest.nose:SnapshotTestPlugin"], }, - install_requires=["six>=1.10.0", "termcolor", "fastdiff>=0.1.4,<1"], + install_requires=["termcolor", "fastdiff>=0.1.4,<1"], tests_require=tests_require, extras_require={ "test": tests_require, @@ -34,21 +34,16 @@ setup( "nose", ], }, + requires_python=">=3.5", classifiers=[ "Development Status :: 5 - Production/Stable", + "Framework :: Django", "Framework :: Pytest", "Intended Audience :: Developers", "Operating System :: OS Independent", - "Programming Language :: Python", - "Programming Language :: Python :: 2", - "Programming Language :: Python :: 2.7", - "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.4", - "Programming Language :: Python :: 3.5", - "Programming Language :: Python :: 3.6", - "Programming Language :: Python :: 3.7", - "Programming Language :: Python :: 3.8", "Topic :: Software Development :: Libraries", + "Topic :: Software Development :: Testing", + "Topic :: Software Development :: Testing :: Unit", ], license="MIT", packages=find_packages(exclude=("tests",)),
syrusakbary/snapshottest
9818a7678b3998fcc67634fc86a427d68692c091
diff --git a/snapshottest/django.py b/snapshottest/django.py index 298fd5f..9d20b9c 100644 --- a/snapshottest/django.py +++ b/snapshottest/django.py @@ -1,4 +1,3 @@ -from __future__ import absolute_import from django.test import TestCase as dTestCase from django.test import SimpleTestCase as dSimpleTestCase from django.test.runner import DiscoverRunner diff --git a/snapshottest/error.py b/snapshottest/error.py index 5cd1fd7..da0ff8a 100644 --- a/snapshottest/error.py +++ b/snapshottest/error.py @@ -1,6 +1,3 @@ -from __future__ import unicode_literals - - class SnapshotError(Exception): pass diff --git a/snapshottest/formatters.py b/snapshottest/formatters.py index 089209f..39a0644 100644 --- a/snapshottest/formatters.py +++ b/snapshottest/formatters.py @@ -1,5 +1,4 @@ import math -import six from collections import defaultdict from .sorted_dict import SortedDict @@ -168,7 +167,7 @@ def default_formatters(): CollectionFormatter(list, format_list), CollectionFormatter(set, format_set), CollectionFormatter(frozenset, format_frozenset), - TypeFormatter(six.string_types, format_str), + TypeFormatter((str,), format_str), TypeFormatter((float,), format_float), TypeFormatter((int, complex, bool, bytes), format_std_type), GenericFormatter(), diff --git a/snapshottest/nose.py b/snapshottest/nose.py index 371734d..9d0e6b4 100644 --- a/snapshottest/nose.py +++ b/snapshottest/nose.py @@ -1,4 +1,3 @@ -from __future__ import absolute_import import logging import os diff --git a/snapshottest/pytest.py b/snapshottest/pytest.py index 2d40ca6..5b28898 100644 --- a/snapshottest/pytest.py +++ b/snapshottest/pytest.py @@ -1,4 +1,3 @@ -from __future__ import absolute_import import pytest import re diff --git a/snapshottest/unittest.py b/snapshottest/unittest.py index b68fce7..535b24a 100644 --- a/snapshottest/unittest.py +++ b/snapshottest/unittest.py @@ -1,4 +1,3 @@ -from __future__ import absolute_import import unittest import inspect diff --git a/tests/test_formatter.py b/tests/test_formatter.py index 8c53056..2b43f0a 100644 --- a/tests/test_formatter.py +++ b/tests/test_formatter.py @@ -1,14 +1,10 @@ # -*- coding: utf-8 -*- -from __future__ import unicode_literals - import pytest -import six from math import isnan from snapshottest.formatter import Formatter -if not six.PY2: - import unittest.mock +import unittest.mock @pytest.mark.parametrize( @@ -33,45 +29,33 @@ def test_text_formatting(text_value, expected): formatted = formatter(text_value) assert formatted == expected - if six.PY2: - # Also check that Python 2 str value formats the same as the unicode value. - # (If a test case raises UnicodeEncodeError in here, it should be moved to - # the non_ascii verson of this test, below.) - py2_str_value = text_value.encode("ASCII") - py2_str_formatted = formatter(py2_str_value) - assert py2_str_formatted == expected - -# When unicode snapshots are saved in Python 2, there's no easy way to generate -# a clean unicode_literals repr that doesn't use escape sequences. But the -# resulting snapshots are still valid on Python 3 (and vice versa). @pytest.mark.parametrize( - "text_value, expected_py3, expected_py2", + "text_value, expected", [ - ("encodage précis", "'encodage précis'", "'encodage pr\\xe9cis'"), - ("精确的编码", "'精确的编码'", "'\\u7cbe\\u786e\\u7684\\u7f16\\u7801'"), + ("encodage précis", "'encodage précis'"), + ("精确的编码", "'精确的编码'"), # backslash [unicode repr can't just be `"u'{}'".format(value)`] - ("omvänt\\snedstreck", "'omvänt\\\\snedstreck'", "'omv\\xe4nt\\\\snedstreck'"), + ("omvänt\\snedstreck", "'omvänt\\\\snedstreck'"), # multiline - ("ett\ntvå\n", "'''ett\ntvå\n'''", "'''ett\ntv\\xe5\n'''"), + ("ett\ntvå\n", "'''ett\ntvå\n'''"), ], ) -def test_non_ascii_text_formatting(text_value, expected_py3, expected_py2): - expected = expected_py2 if six.PY2 else expected_py3 +def test_non_ascii_text_formatting(text_value, expected): formatter = Formatter() formatted = formatter(text_value) assert formatted == expected -if not six.PY2: - # https://github.com/syrusakbary/snapshottest/issues/115 - def test_can_normalize_unittest_mock_call_object(): - formatter = Formatter() - print(formatter.normalize(unittest.mock.call(1, 2, 3))) +# https://github.com/syrusakbary/snapshottest/issues/115 +def test_can_normalize_unittest_mock_call_object(): + formatter = Formatter() + print(formatter.normalize(unittest.mock.call(1, 2, 3))) + - def test_can_normalize_iterator_objects(): - formatter = Formatter() - print(formatter.normalize(x for x in range(3))) +def test_can_normalize_iterator_objects(): + formatter = Formatter() + print(formatter.normalize(x for x in range(3))) @pytest.mark.parametrize( diff --git a/tests/test_module.py b/tests/test_module.py index cef2207..5ad2758 100644 --- a/tests/test_module.py +++ b/tests/test_module.py @@ -1,5 +1,3 @@ -from __future__ import unicode_literals - import pytest from snapshottest import Snapshot diff --git a/tests/test_snapshot_test.py b/tests/test_snapshot_test.py index 9249478..9084f87 100644 --- a/tests/test_snapshot_test.py +++ b/tests/test_snapshot_test.py @@ -1,5 +1,3 @@ -from __future__ import unicode_literals - import pytest from collections import OrderedDict diff --git a/tests/test_sorted_dict.py b/tests/test_sorted_dict.py index b8217d8..41ff194 100644 --- a/tests/test_sorted_dict.py +++ b/tests/test_sorted_dict.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- -from __future__ import unicode_literals import enum import pytest
Require Python 3 Since Python 2 has been deprecated, I suggest we drop support for it the next major release. Many libraries, including developer tools, have done so… pip, pytest, etc. IMO it is not worth spending the limited volunteer development efforts we have to keep this working on an obsolete platform.
0.0
9818a7678b3998fcc67634fc86a427d68692c091
[ "tests/test_snapshot_test.py::test_snapshot_matches_itself[{'a'," ]
[ "tests/test_formatter.py::test_text_formatting[abc-'abc']", "tests/test_formatter.py::test_text_formatting[-'']", "tests/test_formatter.py::test_text_formatting[back\\\\slash-'back\\\\\\\\slash']", "tests/test_formatter.py::test_text_formatting[it", "tests/test_formatter.py::test_text_formatting[it's", "tests/test_formatter.py::test_text_formatting[one\\ntwo\\n-'''one\\ntwo\\n''']", "tests/test_formatter.py::test_text_formatting[three\\n'''quotes-\"\"\"three\\n'''quotes\"\"\"]", "tests/test_formatter.py::test_text_formatting[so", "tests/test_formatter.py::test_non_ascii_text_formatting[encodage", "tests/test_formatter.py::test_non_ascii_text_formatting[\\u7cbe\\u786e\\u7684\\u7f16\\u7801-'\\u7cbe\\u786e\\u7684\\u7f16\\u7801']", "tests/test_formatter.py::test_non_ascii_text_formatting[omv\\xe4nt\\\\snedstreck-'omv\\xe4nt\\\\\\\\snedstreck']", "tests/test_formatter.py::test_non_ascii_text_formatting[ett\\ntv\\xe5\\n-'''ett\\ntv\\xe5\\n''']", "tests/test_formatter.py::test_can_normalize_unittest_mock_call_object", "tests/test_formatter.py::test_can_normalize_iterator_objects", "tests/test_formatter.py::test_basic_formatting_parsing[0]", "tests/test_formatter.py::test_basic_formatting_parsing[12.7]", "tests/test_formatter.py::test_basic_formatting_parsing[True]", "tests/test_formatter.py::test_basic_formatting_parsing[False]", "tests/test_formatter.py::test_basic_formatting_parsing[None]", "tests/test_formatter.py::test_basic_formatting_parsing[-inf]", "tests/test_formatter.py::test_basic_formatting_parsing[inf]", "tests/test_formatter.py::test_formatting_parsing_nan", "tests/test_module.py::TestSnapshotModuleLoading::test_load_not_yet_saved", "tests/test_module.py::TestSnapshotModuleLoading::test_load_missing_package", "tests/test_module.py::TestSnapshotModuleLoading::test_load_corrupted_snapshot", "tests/test_snapshot_test.py::test_snapshot_matches_itself['abc']", "tests/test_snapshot_test.py::test_snapshot_matches_itself[b'abc']", "tests/test_snapshot_test.py::test_snapshot_matches_itself[123]", "tests/test_snapshot_test.py::test_snapshot_matches_itself[123.456]", "tests/test_snapshot_test.py::test_snapshot_matches_itself[{'a':", "tests/test_snapshot_test.py::test_snapshot_matches_itself[['a',", "tests/test_snapshot_test.py::test_snapshot_matches_itself[('a',", "tests/test_snapshot_test.py::test_snapshot_matches_itself[('a',)]", "tests/test_snapshot_test.py::test_snapshot_matches_itself[None]", "tests/test_snapshot_test.py::test_snapshot_matches_itself[False]", "tests/test_snapshot_test.py::test_snapshot_matches_itself['']", "tests/test_snapshot_test.py::test_snapshot_matches_itself[b'']", "tests/test_snapshot_test.py::test_snapshot_matches_itself[{}]", "tests/test_snapshot_test.py::test_snapshot_matches_itself[[]]", "tests/test_snapshot_test.py::test_snapshot_matches_itself[set()]", "tests/test_snapshot_test.py::test_snapshot_matches_itself[()]", "tests/test_snapshot_test.py::test_snapshot_matches_itself[0]", "tests/test_snapshot_test.py::test_snapshot_matches_itself[0.0]", "tests/test_snapshot_test.py::test_snapshot_matches_itself[OrderedDict([('a',", "tests/test_snapshot_test.py::test_snapshot_matches_itself[OrderedDict([('c',", "tests/test_snapshot_test.py::test_snapshot_does_not_match_other_values[snapshot", "tests/test_sorted_dict.py::test_sorted_dict[key1-value]", "tests/test_sorted_dict.py::test_sorted_dict[key2-42]", "tests/test_sorted_dict.py::test_sorted_dict[key3-value2]", "tests/test_sorted_dict.py::test_sorted_dict[key4-value3]", "tests/test_sorted_dict.py::test_sorted_dict[key5-value4]", "tests/test_sorted_dict.py::test_sorted_dict[key6-value5]", "tests/test_sorted_dict.py::test_sorted_dict[key7-value6]", "tests/test_sorted_dict.py::test_sorted_dict[key8-value7]", "tests/test_sorted_dict.py::test_sorted_dict_string_key", "tests/test_sorted_dict.py::test_sorted_dict_int_key", "tests/test_sorted_dict.py::test_sorted_dict_intenum", "tests/test_sorted_dict.py::test_sorted_dict_enum", "tests/test_sorted_dict.py::test_sorted_dict_enum_value", "tests/test_sorted_dict.py::test_sorted_dict_enum_key" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2020-09-29 23:35:10+00:00
mit
5,822
tableau__document-api-python-15
diff --git a/tableaudocumentapi/datasource.py b/tableaudocumentapi/datasource.py index 93ebe55..617004a 100644 --- a/tableaudocumentapi/datasource.py +++ b/tableaudocumentapi/datasource.py @@ -72,7 +72,7 @@ class Datasource(object): """ # save the file - self._datasourceTree.write(self._filename) + self._datasourceTree.write(self._filename, encoding="utf-8", xml_declaration=True) def save_as(self, new_filename): """ @@ -85,7 +85,7 @@ class Datasource(object): Nothing. """ - self._datasourceTree.write(new_filename) + self._datasourceTree.write(new_filename, encoding="utf-8", xml_declaration=True) ########### # name diff --git a/tableaudocumentapi/workbook.py b/tableaudocumentapi/workbook.py index 67dbc32..889f746 100644 --- a/tableaudocumentapi/workbook.py +++ b/tableaudocumentapi/workbook.py @@ -76,7 +76,7 @@ class Workbook(object): """ # save the file - self._workbookTree.write(self._filename) + self._workbookTree.write(self._filename, encoding="utf-8", xml_declaration=True) def save_as(self, new_filename): """ @@ -90,7 +90,7 @@ class Workbook(object): """ - self._workbookTree.write(new_filename) + self._workbookTree.write(new_filename, encoding="utf-8", xml_declaration=True) ########################################################################### #
tableau/document-api-python
07aad9550d3d36a4d74c4751832c50fe81882a01
diff --git a/test.py b/test.py index fd7d1bd..5606005 100644 --- a/test.py +++ b/test.py @@ -17,6 +17,7 @@ TABLEAU_10_WORKBOOK = '''<?xml version='1.0' encoding='utf-8' ?><workbook source TABLEAU_CONNECTION_XML = ET.fromstring( '''<connection authentication='sspi' class='sqlserver' dbname='TestV1' odbc-native-protocol='yes' one-time-sql='' server='mssql2012.test.tsi.lan' username=''></connection>''') + class HelperMethodTests(unittest.TestCase): def test_is_valid_file_with_valid_inputs(self): @@ -39,7 +40,6 @@ class ConnectionParserTests(unittest.TestCase): self.assertIsInstance(connections[0], Connection) self.assertEqual(connections[0].dbname, 'TestV1') - def test_can_extract_federated_connections(self): parser = ConnectionParser(ET.fromstring(TABLEAU_10_TDS), '10.0') connections = parser.get_connections() @@ -97,6 +97,17 @@ class DatasourceModelTests(unittest.TestCase): new_tds = Datasource.from_file(self.tds_file.name) self.assertEqual(new_tds.connections[0].dbname, 'newdb.test.tsi.lan') + def test_save_has_xml_declaration(self): + original_tds = Datasource.from_file(self.tds_file.name) + original_tds.connections[0].dbname = 'newdb.test.tsi.lan' + + original_tds.save() + + with open(self.tds_file.name) as f: + first_line = f.readline().strip() # first line should be xml tag + self.assertEqual( + first_line, "<?xml version='1.0' encoding='utf-8'?>") + class WorkbookModelTests(unittest.TestCase): @@ -122,7 +133,8 @@ class WorkbookModelTests(unittest.TestCase): original_wb.save() new_wb = Workbook(self.workbook_file.name) - self.assertEqual(new_wb.datasources[0].connections[0].dbname, 'newdb.test.tsi.lan') + self.assertEqual(new_wb.datasources[0].connections[ + 0].dbname, 'newdb.test.tsi.lan') class WorkbookModelV10Tests(unittest.TestCase): @@ -152,7 +164,19 @@ class WorkbookModelV10Tests(unittest.TestCase): original_wb.save() new_wb = Workbook(self.workbook_file.name) - self.assertEqual(new_wb.datasources[0].connections[0].dbname, 'newdb.test.tsi.lan') + self.assertEqual(new_wb.datasources[0].connections[ + 0].dbname, 'newdb.test.tsi.lan') + + def test_save_has_xml_declaration(self): + original_wb = Workbook(self.workbook_file.name) + original_wb.datasources[0].connections[0].dbname = 'newdb.test.tsi.lan' + + original_wb.save() + + with open(self.workbook_file.name) as f: + first_line = f.readline().strip() # first line should be xml tag + self.assertEqual( + first_line, "<?xml version='1.0' encoding='utf-8'?>") if __name__ == '__main__': unittest.main()
Tabcmd publish with .twb created via Document API I can successfully create a .twb file via the Document API, but attempting to publish it to my Tableau Server via Tabcmd results in an unexpected error: **Bad request unexpected error occurred opening the packaged workbook.** Attached is the template workbook created in Tableau Desktop (superstore_sales.twb) and one of the workbooks created from that template via the Document API (superstore_sales_arizona.twb) [superstore_twbs.zip](https://github.com/tableau/document-api-python/files/285303/superstore_twbs.zip)
0.0
07aad9550d3d36a4d74c4751832c50fe81882a01
[ "test.py::DatasourceModelTests::test_save_has_xml_declaration", "test.py::WorkbookModelV10Tests::test_save_has_xml_declaration" ]
[ "test.py::HelperMethodTests::test_is_valid_file_with_invalid_inputs", "test.py::HelperMethodTests::test_is_valid_file_with_valid_inputs", "test.py::ConnectionParserTests::test_can_extract_federated_connections", "test.py::ConnectionParserTests::test_can_extract_legacy_connection", "test.py::ConnectionModelTests::test_can_read_attributes_from_connection", "test.py::ConnectionModelTests::test_can_write_attributes_to_connection", "test.py::DatasourceModelTests::test_can_extract_connection", "test.py::DatasourceModelTests::test_can_extract_datasource_from_file", "test.py::DatasourceModelTests::test_can_save_tds", "test.py::WorkbookModelTests::test_can_extract_datasource", "test.py::WorkbookModelTests::test_can_update_datasource_connection_and_save", "test.py::WorkbookModelV10Tests::test_can_extract_datasourceV10", "test.py::WorkbookModelV10Tests::test_can_update_datasource_connection_and_saveV10" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2016-06-02 00:21:16+00:00
mit
5,823
tableau__server-client-python-109
diff --git a/tableauserverclient/models/user_item.py b/tableauserverclient/models/user_item.py index 1e4f54a..2df6764 100644 --- a/tableauserverclient/models/user_item.py +++ b/tableauserverclient/models/user_item.py @@ -119,7 +119,7 @@ class UserItem(object): @classmethod def from_response(cls, resp): - all_user_items = set() + all_user_items = [] parsed_response = ET.fromstring(resp) all_user_xml = parsed_response.findall('.//t:user', namespaces=NAMESPACE) for user_xml in all_user_xml: @@ -128,7 +128,7 @@ class UserItem(object): user_item = cls(name, site_role) user_item._set_values(id, name, site_role, last_login, external_auth_user_id, fullname, email, auth_setting, domain_name) - all_user_items.add(user_item) + all_user_items.append(user_item) return all_user_items @staticmethod
tableau/server-client-python
e853d7c79f54f232c9f1da07f6c085db399e598a
diff --git a/test/test_user.py b/test/test_user.py index 556cd62..fa83443 100644 --- a/test/test_user.py +++ b/test/test_user.py @@ -54,7 +54,7 @@ class UserTests(unittest.TestCase): all_users, pagination_item = self.server.users.get() self.assertEqual(0, pagination_item.total_available) - self.assertEqual(set(), all_users) + self.assertEqual([], all_users) def test_get_before_signin(self): self.server._auth_token = None
Pager with users throws TypeError I am trying to extract the list of users using the Pager: `print(*TSC.Pager(tableau.users))` I get the following error: ` File "metalab_users.py", line 74, in <module> print(*tableau_users) File "C:\Program Files\Python35\lib\site-packages\tableauserverclient\server\pager.py", line 30, in __iter__ yield current_item_list.pop(0) TypeError: pop() takes no arguments (1 given)` When calling projects with the same code, I get no such error: `print(*TSC.Pager(tableau.projects))`
0.0
e853d7c79f54f232c9f1da07f6c085db399e598a
[ "test/test_user.py::UserTests::test_get_empty" ]
[ "test/test_user.py::UserTests::test_update_missing_id", "test/test_user.py::UserTests::test_get_by_id_missing_id", "test/test_user.py::UserTests::test_get_before_signin", "test/test_user.py::UserTests::test_update", "test/test_user.py::UserTests::test_add", "test/test_user.py::UserTests::test_populate_workbooks_missing_id", "test/test_user.py::UserTests::test_get_by_id", "test/test_user.py::UserTests::test_remove", "test/test_user.py::UserTests::test_get", "test/test_user.py::UserTests::test_populate_workbooks", "test/test_user.py::UserTests::test_remove_missing_id" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2016-12-02 04:38:26+00:00
mit
5,824
tableau__server-client-python-1117
diff --git a/samples/create_group.py b/samples/create_group.py index 50d84a1..d5cf712 100644 --- a/samples/create_group.py +++ b/samples/create_group.py @@ -46,7 +46,7 @@ def main(): logging.basicConfig(level=logging_level) tableau_auth = TSC.PersonalAccessTokenAuth(args.token_name, args.token_value, site_id=args.site) - server = TSC.Server(args.server, use_server_version=True) + server = TSC.Server(args.server, use_server_version=True, http_options={"verify": False}) with server.auth.sign_in(tableau_auth): # this code shows 3 different error codes that mean "resource is already in collection" # 409009: group already exists on server diff --git a/tableauserverclient/server/endpoint/endpoint.py b/tableauserverclient/server/endpoint/endpoint.py index 378c847..a7b3306 100644 --- a/tableauserverclient/server/endpoint/endpoint.py +++ b/tableauserverclient/server/endpoint/endpoint.py @@ -11,9 +11,12 @@ from .exceptions import ( NonXMLResponseError, EndpointUnavailableError, ) -from .. import endpoint from ..query import QuerySet from ... import helpers +from ..._version import get_versions + +__TSC_VERSION__ = get_versions()["version"] +del get_versions logger = logging.getLogger("tableau.endpoint") @@ -22,34 +25,25 @@ Success_codes = [200, 201, 202, 204] XML_CONTENT_TYPE = "text/xml" JSON_CONTENT_TYPE = "application/json" +USERAGENT_HEADER = "User-Agent" + if TYPE_CHECKING: from ..server import Server from requests import Response -_version_header: Optional[str] = None - - class Endpoint(object): def __init__(self, parent_srv: "Server"): - global _version_header self.parent_srv = parent_srv @staticmethod def _make_common_headers(auth_token, content_type): - global _version_header - - if not _version_header: - from ..server import __TSC_VERSION__ - - _version_header = __TSC_VERSION__ - headers = {} if auth_token is not None: headers["x-tableau-auth"] = auth_token if content_type is not None: headers["content-type"] = content_type - headers["User-Agent"] = "Tableau Server Client/{}".format(_version_header) + headers["User-Agent"] = "Tableau Server Client/{}".format(__TSC_VERSION__) return headers def _make_request( @@ -62,9 +56,9 @@ class Endpoint(object): parameters: Optional[Dict[str, Any]] = None, ) -> "Response": parameters = parameters or {} - parameters.update(self.parent_srv.http_options) if "headers" not in parameters: parameters["headers"] = {} + parameters.update(self.parent_srv.http_options) parameters["headers"].update(Endpoint._make_common_headers(auth_token, content_type)) if content is not None: diff --git a/tableauserverclient/server/server.py b/tableauserverclient/server/server.py index c82f4a6..18f5834 100644 --- a/tableauserverclient/server/server.py +++ b/tableauserverclient/server/server.py @@ -37,11 +37,6 @@ from .exceptions import NotSignedInError from ..namespace import Namespace -from .._version import get_versions - -__TSC_VERSION__ = get_versions()["version"] -del get_versions - _PRODUCT_TO_REST_VERSION = { "10.0": "2.3", "9.3": "2.2", @@ -51,7 +46,6 @@ _PRODUCT_TO_REST_VERSION = { } minimum_supported_server_version = "2.3" default_server_version = "2.3" -client_version_header = "X-TableauServerClient-Version" class Server(object): @@ -98,23 +92,29 @@ class Server(object): # must set this before calling use_server_version, because that's a server call if http_options: self.add_http_options(http_options) - self.add_http_version_header() if use_server_version: self.use_server_version() - def add_http_options(self, options_dict): - self._http_options.update(options_dict) - if options_dict.get("verify") == False: + def add_http_options(self, option_pair: dict): + if not option_pair: + # log debug message + return + if len(option_pair) != 1: + raise ValueError( + "Update headers one at a time. Expected type: ", + {"key": 12}.__class__, + "Actual type: ", + option_pair, + option_pair.__class__, + ) + self._http_options.update(option_pair) + if "verify" in option_pair.keys() and self._http_options.get("verify") is False: urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) - - def add_http_version_header(self): - if not self._http_options[client_version_header]: - self._http_options.update({client_version_header: __TSC_VERSION__}) + # would be nice if you could turn them back on def clear_http_options(self): self._http_options = dict() - self.add_http_version_header() def _clear_auth(self): self._site_id = None
tableau/server-client-python
f653e15b582ae2ea7fc76f423f178d430e2a30ed
diff --git a/test/http/test_http_requests.py b/test/http/test_http_requests.py new file mode 100644 index 0000000..5759b1c --- /dev/null +++ b/test/http/test_http_requests.py @@ -0,0 +1,56 @@ +import tableauserverclient as TSC +import unittest +from requests.exceptions import MissingSchema + + +class ServerTests(unittest.TestCase): + def test_init_server_model_empty_throws(self): + with self.assertRaises(TypeError): + server = TSC.Server() + + def test_init_server_model_bad_server_name_complains(self): + # by default, it will just set the version to 2.3 + server = TSC.Server("fake-url") + + def test_init_server_model_valid_server_name_works(self): + # by default, it will just set the version to 2.3 + server = TSC.Server("http://fake-url") + + def test_init_server_model_valid_https_server_name_works(self): + # by default, it will just set the version to 2.3 + server = TSC.Server("https://fake-url") + + def test_init_server_model_bad_server_name_not_version_check(self): + # by default, it will just set the version to 2.3 + server = TSC.Server("fake-url", use_server_version=False) + + def test_init_server_model_bad_server_name_do_version_check(self): + with self.assertRaises(MissingSchema): + server = TSC.Server("fake-url", use_server_version=True) + + def test_init_server_model_bad_server_name_not_version_check_random_options(self): + # by default, it will just set the version to 2.3 + server = TSC.Server("fake-url", use_server_version=False, http_options={"foo": 1}) + + def test_init_server_model_bad_server_name_not_version_check_real_options(self): + # by default, it will attempt to contact the server to check it's version + server = TSC.Server("fake-url", use_server_version=False, http_options={"verify": False}) + + def test_http_options_skip_ssl_works(self): + http_options = {"verify": False} + server = TSC.Server("http://fake-url") + server.add_http_options(http_options) + + # ValueError: dictionary update sequence element #0 has length 1; 2 is required + def test_http_options_multiple_options_fails(self): + http_options_1 = {"verify": False} + http_options_2 = {"birdname": "Parrot"} + server = TSC.Server("http://fake-url") + with self.assertRaises(ValueError): + server.add_http_options([http_options_1, http_options_2]) + + # TypeError: cannot convert dictionary update sequence element #0 to a sequence + def test_http_options_not_sequence_fails(self): + server = TSC.Server("http://fake-url") + with self.assertRaises(ValueError): + server.add_http_options({1, 2, 3})
Sign in with http_options set will fail **Describe the bug** Signing in to a server when any http_options have been set in the TSC.Server object will result in an exception: KeyError: 'X-TableauServerClient-Version' **Versions** TSC library versions v0.21 and v0.22 have the issue. Version v0.19.1 works correctly. **To Reproduce** Include any http_options while creating the TSC.Server object: ````py server = TSC.Server('https://10ax.online.tableau.com', use_server_version=True, http_options={"verify": False}) server.auth.sign_in(tableau_auth) ```` Workaround: use TSC v0.19.1 instead. **Results** ````py Traceback (most recent call last): File "/Users/brian/github/server-client-python/pat-login.py", line 17, in <module> server = TSC.Server('https://10ax.online.tableau.com', use_server_version=True, http_options={"verify": False}) File "/Users/brian/github/server-client-python/tableauserverclient/server/server.py", line 101, in __init__ self.add_http_version_header() File "/Users/brian/github/server-client-python/tableauserverclient/server/server.py", line 112, in add_http_version_header if not self._http_options[client_version_header]: KeyError: 'X-TableauServerClient-Version' ````
0.0
f653e15b582ae2ea7fc76f423f178d430e2a30ed
[ "test/http/test_http_requests.py::ServerTests::test_http_options_not_sequence_fails", "test/http/test_http_requests.py::ServerTests::test_init_server_model_bad_server_name_not_version_check_random_options", "test/http/test_http_requests.py::ServerTests::test_init_server_model_bad_server_name_not_version_check_real_options" ]
[ "test/http/test_http_requests.py::ServerTests::test_http_options_multiple_options_fails", "test/http/test_http_requests.py::ServerTests::test_http_options_skip_ssl_works", "test/http/test_http_requests.py::ServerTests::test_init_server_model_bad_server_name_complains", "test/http/test_http_requests.py::ServerTests::test_init_server_model_bad_server_name_do_version_check", "test/http/test_http_requests.py::ServerTests::test_init_server_model_bad_server_name_not_version_check", "test/http/test_http_requests.py::ServerTests::test_init_server_model_empty_throws", "test/http/test_http_requests.py::ServerTests::test_init_server_model_valid_https_server_name_works", "test/http/test_http_requests.py::ServerTests::test_init_server_model_valid_server_name_works" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2022-09-22 06:57:51+00:00
mit
5,825
tableau__server-client-python-1345
diff --git a/.gitignore b/.gitignore index e9bd2b4..92778cd 100644 --- a/.gitignore +++ b/.gitignore @@ -155,3 +155,4 @@ $RECYCLE.BIN/ docs/_site/ docs/.jekyll-metadata docs/Gemfile.lock +samples/credentials diff --git a/contributing.md b/contributing.md index 41c339c..6404611 100644 --- a/contributing.md +++ b/contributing.md @@ -10,8 +10,7 @@ Contribution can include, but are not limited to, any of the following: * Fix an Issue/Bug * Add/Fix documentation -Contributions must follow the guidelines outlined on the [Tableau Organization](http://tableau.github.io/) page, though filing an issue or requesting -a feature do not require the CLA. +Contributions must follow the guidelines outlined on the [Tableau Organization](http://tableau.github.io/) page, though filing an issue or requesting a feature do not require the CLA. ## Issues and Feature Requests diff --git a/samples/getting_started/3_hello_universe.py b/samples/getting_started/3_hello_universe.py index 3ed39fd..21de978 100644 --- a/samples/getting_started/3_hello_universe.py +++ b/samples/getting_started/3_hello_universe.py @@ -62,11 +62,6 @@ def main(): print("{} jobs".format(pagination.total_available)) print(jobs[0]) - metrics, pagination = server.metrics.get() - if metrics: - print("{} metrics".format(pagination.total_available)) - print(metrics[0]) - schedules, pagination = server.schedules.get() if schedules: print("{} schedules".format(pagination.total_available)) @@ -82,7 +77,7 @@ def main(): print("{} webhooks".format(pagination.total_available)) print(webhooks[0]) - users, pagination = server.metrics.get() + users, pagination = server.users.get() if users: print("{} users".format(pagination.total_available)) print(users[0]) @@ -92,5 +87,6 @@ def main(): print("{} groups".format(pagination.total_available)) print(groups[0]) - if __name__ == "__main__": - main() + +if __name__ == "__main__": + main() diff --git a/tableauserverclient/models/interval_item.py b/tableauserverclient/models/interval_item.py index f2f1596..537e6c1 100644 --- a/tableauserverclient/models/interval_item.py +++ b/tableauserverclient/models/interval_item.py @@ -69,7 +69,7 @@ class HourlyInterval(object): @interval.setter def interval(self, intervals): - VALID_INTERVALS = {0.25, 0.5, 1, 2, 4, 6, 8, 12} + VALID_INTERVALS = {0.25, 0.5, 1, 2, 4, 6, 8, 12, 24} for interval in intervals: # if an hourly interval is a string, then it is a weekDay interval if isinstance(interval, str) and not interval.isnumeric() and not hasattr(IntervalItem.Day, interval): diff --git a/tableauserverclient/server/endpoint/endpoint.py b/tableauserverclient/server/endpoint/endpoint.py index 77a7712..2b7f570 100644 --- a/tableauserverclient/server/endpoint/endpoint.py +++ b/tableauserverclient/server/endpoint/endpoint.py @@ -1,5 +1,3 @@ -from threading import Thread -from time import sleep from tableauserverclient import datetime_helpers as datetime from packaging.version import Version @@ -76,55 +74,20 @@ class Endpoint(object): return parameters def _blocking_request(self, method, url, parameters={}) -> Optional[Union["Response", Exception]]: - self.async_response = None response = None logger.debug("[{}] Begin blocking request to {}".format(datetime.timestamp(), url)) try: response = method(url, **parameters) - self.async_response = response logger.debug("[{}] Call finished".format(datetime.timestamp())) except Exception as e: logger.debug("Error making request to server: {}".format(e)) - self.async_response = e - finally: - if response and not self.async_response: - logger.debug("Request response not saved") - return None - logger.debug("[{}] Request complete".format(datetime.timestamp())) - return self.async_response + raise e + return response def send_request_while_show_progress_threaded( self, method, url, parameters={}, request_timeout=None ) -> Optional[Union["Response", Exception]]: - try: - request_thread = Thread(target=self._blocking_request, args=(method, url, parameters)) - request_thread.start() - except Exception as e: - logger.debug("Error starting server request on separate thread: {}".format(e)) - return None - seconds = 0.05 - minutes = 0 - last_log_minute = 0 - sleep(seconds) - if self.async_response is not None: - # a quick return for any immediate responses - return self.async_response - timed_out: bool = request_timeout is not None and seconds > request_timeout - while (self.async_response is None) and not timed_out: - sleep(DELAY_SLEEP_SECONDS) - seconds = seconds + DELAY_SLEEP_SECONDS - minutes = int(seconds / 60) - last_log_minute = self.log_wait_time(minutes, last_log_minute, url) - return self.async_response - - def log_wait_time(self, minutes, last_log_minute, url) -> int: - logger.debug("{} Waiting....".format(datetime.timestamp())) - if minutes > last_log_minute: # detailed log message ~every minute - logger.info("[{}] Waiting ({} minutes so far) for request to {}".format(datetime.timestamp(), minutes, url)) - last_log_minute = minutes - else: - logger.debug("[{}] Waiting for request to {}".format(datetime.timestamp(), url)) - return last_log_minute + return self._blocking_request(method, url, parameters) def _make_request( self,
tableau/server-client-python
00c767786f84509bb9aaa6bc2d35b669dd6a2c4b
diff --git a/test/test_endpoint.py b/test/test_endpoint.py index 3d2d1c9..8635af9 100644 --- a/test/test_endpoint.py +++ b/test/test_endpoint.py @@ -1,4 +1,6 @@ from pathlib import Path +import pytest +import requests import unittest import tableauserverclient as TSC @@ -35,11 +37,12 @@ class TestEndpoint(unittest.TestCase): ) self.assertIsNotNone(response) - def test_blocking_request_returns(self) -> None: - url = "http://test/" - endpoint = TSC.server.Endpoint(self.server) - response = endpoint._blocking_request(endpoint.parent_srv.session.get, url=url) - self.assertIsNotNone(response) + def test_blocking_request_raises_request_error(self) -> None: + with pytest.raises(requests.exceptions.ConnectionError): + url = "http://test/" + endpoint = TSC.server.Endpoint(self.server) + response = endpoint._blocking_request(endpoint.parent_srv.session.get, url=url) + self.assertIsNotNone(response) def test_get_request_stream(self) -> None: url = "http://test/"
Unauthorized Access error when signing out (either explicitly or at the end of a `with` block) Starting with v0.29 I notice many of my test scripts failing with an exception. It seems like a general problem rather than specific to one endpoint. Here's an example: ```py import tableauserverclient as TSC tableau_auth = TSC.PersonalAccessTokenAuth( "xxxxx", "xxxxxxxxxx", "", ) server = TSC.Server("https://devplat.tableautest.com", use_server_version=True) with server.auth.sign_in(tableau_auth): all_wb, pagination_item = server.workbooks.get() print("\nThere are {} workbooks: ".format(pagination_item.total_available)) for wb in all_wb: print(wb.id, wb.name, wb.tags) ``` The script succeeds (printing workbooks), but ends with an exception like this: ``` Traceback (most recent call last): File "/Users/bcantoni/github/server-client-python/getdatasources.py", line 14, in <module> with server.auth.sign_in(tableau_auth): File "/Users/bcantoni/github/server-client-python/tableauserverclient/server/endpoint/auth_endpoint.py", line 27, in __exit__ self._callback() File "/Users/bcantoni/github/server-client-python/tableauserverclient/server/endpoint/endpoint.py", line 291, in wrapper return func(self, *args, **kwargs) File "/Users/bcantoni/github/server-client-python/tableauserverclient/server/endpoint/auth_endpoint.py", line 85, in sign_out self.post_request(url, "") File "/Users/bcantoni/github/server-client-python/tableauserverclient/server/endpoint/endpoint.py", line 248, in post_request return self._make_request( File "/Users/bcantoni/github/server-client-python/tableauserverclient/server/endpoint/endpoint.py", line 165, in _make_request self._check_status(server_response, url) File "/Users/bcantoni/github/server-client-python/tableauserverclient/server/endpoint/endpoint.py", line 186, in _check_status raise NotSignedInError(server_response.content, url) tableauserverclient.server.endpoint.exceptions.NotSignedInError: (b'<?xml version=\'1.0\' encoding=\'UTF-8\'?><tsResponse xmlns="http://tableau.com/api" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://tableau.com/api https://help.tableau.com/samples/en-us/rest_api/ts-api_3_22.xsd"><error code="401002"><summary>Unauthorized Access</summary><detail>Invalid authentication credentials were provided.</detail></error></tsResponse>', 'https://10ax.online.tableau.com/api/3.22/auth/signout') ``` If I switch from using the `with` statement to the older style, it works fine: ```py import tableauserverclient as TSC tableau_auth = TSC.PersonalAccessTokenAuth( "xxxx", "xxxxxxx", "", ) server = TSC.Server("https://devplat.tableautest.com", use_server_version=True) server.auth.sign_in(tableau_auth) all_wb, pagination_item = server.workbooks.get() print("\nThere are {} workbooks: ".format(pagination_item.total_available)) for wb in all_wb: print(wb.id, wb.name, wb.tags) ``` Testing notes: - I tested with same results on both Tableau Cloud and Server. - This seems new to 0.29; switching back to 0.28 solves the issue. - Git bisect points to https://github.com/tableau/server-client-python/pull/1300 as the point this was introduced - In server/endpoint/endpoint.py, changing `seconds = 0.05` back to `seconds = 0` seems to fix it (but I'll admit I don't totally follow the changes in that PR)
0.0
00c767786f84509bb9aaa6bc2d35b669dd6a2c4b
[ "test/test_endpoint.py::TestEndpoint::test_blocking_request_raises_request_error" ]
[ "test/test_endpoint.py::TestEndpoint::test_binary_log_truncated", "test/test_endpoint.py::TestEndpoint::test_fallback_request_logic", "test/test_endpoint.py::TestEndpoint::test_get_request_stream", "test/test_endpoint.py::TestEndpoint::test_set_user_agent_from_options", "test/test_endpoint.py::TestEndpoint::test_set_user_agent_from_options_headers", "test/test_endpoint.py::TestEndpoint::test_set_user_agent_when_blank", "test/test_endpoint.py::TestEndpoint::test_user_friendly_request_returns" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2024-01-19 09:14:30+00:00
mit
5,826
tableau__server-client-python-274
diff --git a/samples/download_view_image.py b/samples/download_view_image.py index 2da2320..b95a862 100644 --- a/samples/download_view_image.py +++ b/samples/download_view_image.py @@ -43,7 +43,7 @@ def main(): tableau_auth = TSC.TableauAuth(args.username, password, site_id=site_id) server = TSC.Server(args.server) # The new endpoint was introduced in Version 2.5 - server.version = 2.5 + server.version = "2.5" with server.auth.sign_in(tableau_auth): # Step 2: Query for the view that we want an image of diff --git a/tableauserverclient/server/endpoint/endpoint.py b/tableauserverclient/server/endpoint/endpoint.py index deaa94a..e78b2e0 100644 --- a/tableauserverclient/server/endpoint/endpoint.py +++ b/tableauserverclient/server/endpoint/endpoint.py @@ -27,6 +27,17 @@ class Endpoint(object): return headers + @staticmethod + def _safe_to_log(server_response): + '''Checks if the server_response content is not xml (eg binary image or zip) + and and replaces it with a constant + ''' + ALLOWED_CONTENT_TYPES = ('application/xml',) + if server_response.headers.get('Content-Type', None) not in ALLOWED_CONTENT_TYPES: + return '[Truncated File Contents]' + else: + return server_response.content + def _make_request(self, method, url, content=None, request_object=None, auth_token=None, content_type=None, parameters=None): if request_object is not None: @@ -50,7 +61,7 @@ class Endpoint(object): return server_response def _check_status(self, server_response): - logger.debug(server_response.content) + logger.debug(self._safe_to_log(server_response)) if server_response.status_code not in Success_codes: raise ServerResponseError.from_response(server_response.content, self.parent_srv.namespace)
tableau/server-client-python
86e463810be80c2b562845f7c14b775d604f2a86
diff --git a/test/test_regression_tests.py b/test/test_regression_tests.py index 95bdcea..8958c3c 100644 --- a/test/test_regression_tests.py +++ b/test/test_regression_tests.py @@ -1,8 +1,23 @@ import unittest import tableauserverclient.server.request_factory as factory +from tableauserverclient.server.endpoint import Endpoint class BugFix257(unittest.TestCase): def test_empty_request_works(self): result = factory.EmptyRequest().empty_req() self.assertEqual(b'<tsRequest />', result) + + +class BugFix273(unittest.TestCase): + def test_binary_log_truncated(self): + + class FakeResponse(object): + + headers = {'Content-Type': 'application/octet-stream'} + content = b'\x1337' * 1000 + status_code = 200 + + server_response = FakeResponse() + + self.assertEqual(Endpoint._safe_to_log(server_response), '[Truncated File Contents]')
This log line is overly chatty https://github.com/tableau/server-client-python/blob/608aa7694d0560ea3c8c37b10127b11207e56e8d/tableauserverclient/server/endpoint/endpoint.py#L53 When using server client python to download workbooks or data sources and you've got log_level=Debug, this log line ends up blowing up your logs. It outputs the hexadecimal representation of the entire file you're downloading, which is not very helpful and explodes your log size. Can we remove this line, or only log out the response contents when you're not using the endpoint to download a file?
0.0
86e463810be80c2b562845f7c14b775d604f2a86
[ "test/test_regression_tests.py::BugFix273::test_binary_log_truncated" ]
[ "test/test_regression_tests.py::BugFix257::test_empty_request_works" ]
{ "failed_lite_validators": [ "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2018-03-09 02:04:54+00:00
mit
5,827
tacitvenom__genomics_algo-37
diff --git a/genomics_algo/miscellaneous_algorithms/misc_algos.py b/genomics_algo/miscellaneous_algorithms/misc_algos.py index 0b937b1..9703fcc 100644 --- a/genomics_algo/miscellaneous_algorithms/misc_algos.py +++ b/genomics_algo/miscellaneous_algorithms/misc_algos.py @@ -1,8 +1,13 @@ +from itertools import product import numpy as np -from typing import List, Tuple +from typing import List, Set, Tuple -from genomics_algo.utilities.misc_utilities import get_frequency_map +from genomics_algo.utilities.misc_utilities import ( + get_frequency_map, + validate_bases_in_genome, +) +from genomics_algo.utilities.string_cmp import find_hamming_distance def find_most_freq_k_substring( @@ -56,3 +61,57 @@ def find_minimum_gc_skew_location(genome: str) -> int: gc_skew[index + 1] += genome[index] == "G" gc_skew[index + 1] -= genome[index] == "C" return np.where(gc_skew == gc_skew.min())[0] - 1 + + +def find_frequent_kmers_with_mismatches(genome: str, k: int, d: int) -> Set[str]: + """Determine most frequent k-mers with at most `d` mismatches. + A most frequent k-mer with up to `d` mismatches in `genome` is simply a string pattern maximising + the total number of occurrences of said pattern in `genome` with at most `d` mismatches. + Note that the pattern does not need to actually appear as a substring of `genome`. + >>> find_frequent_kmers_with_mismatches('ACGTTGCATGTCGCATGATGCATGAGAGCT', 4, 1)-{'ATGC', 'GATG', 'ATGT'} + set() + + Parameters + ---------- + genome : str + String representation of genome. + k: int + Length of kmers to find. + d: int + Number of allowed mismatches in kmers. + + Returns + ------- + Set[str] + Set of most frequent kmers with up to d mismatches + """ + + n = len(genome) + chars = {"A", "C", "G", "T"} + # input validation: + validate_bases_in_genome(genome) + if n < k or k < d or d < 0: + raise ValueError( + f"The input values for genome, k and d don't make sense. It must hold: len(genome)>=k, k>=d, d>=0. Received: len(genome)={n}, k={k}, d={d}." + ) + if k > 12 or d > 3: + raise Warning( + f"The large input values k={k} and/or d={d} might cause long run times." + ) + + frequency_map = {} + # FIXME here ALL possible patterns of length k are created -> should be optimised + possible_patterns = ["".join(p) for p in product(chars, repeat=k)] + for i in range(n - k + 1): + pattern = genome[i : i + k] + for kmer in possible_patterns: + if find_hamming_distance(pattern, kmer) <= d: + if kmer in frequency_map.keys(): + frequency_map[kmer] += 1 + else: + frequency_map[kmer] = 1 + + most_frequent = max(frequency_map.values()) + return { + kmer for kmer, frequency in frequency_map.items() if frequency == most_frequent + } diff --git a/genomics_algo/utilities/misc_utilities.py b/genomics_algo/utilities/misc_utilities.py index 4fa1603..c737773 100644 --- a/genomics_algo/utilities/misc_utilities.py +++ b/genomics_algo/utilities/misc_utilities.py @@ -70,3 +70,11 @@ def get_frequency_map(text: str, substring_length: int) -> Dict[str, int]: else: freq_map[substr] = 1 return freq_map + + +def validate_bases_in_genome(genome: str) -> bool: + """Validates a genome string for existing bases. + Raises ``ValueError`` if ``genome`` contains bases other than defined in ``Bases`` class.""" + set_diff = set(genome).difference({Bases.A, Bases.C, Bases.G, Bases.T}) + if not set_diff == set(): + raise ValueError(f"Genome contains invalid bases: {set_diff}")
tacitvenom/genomics_algo
3174c1e9e685db12c5849ce5c7e3411f1922a4be
diff --git a/genomics_algo/tests/miscellaneous_algorithms/test_misc_algos.py b/genomics_algo/tests/miscellaneous_algorithms/test_misc_algos.py index 85c96b7..f1f14a8 100644 --- a/genomics_algo/tests/miscellaneous_algorithms/test_misc_algos.py +++ b/genomics_algo/tests/miscellaneous_algorithms/test_misc_algos.py @@ -5,6 +5,7 @@ from genomics_algo.utilities.read_files import read_genome from genomics_algo.miscellaneous_algorithms.misc_algos import ( find_pattern_clumps, find_minimum_gc_skew_location, + find_frequent_kmers_with_mismatches, ) @@ -53,3 +54,100 @@ def test_find_minimum_gc_skew_location_in_genome(): genome = read_genome("genomics_algo/tests/test_data/e_coli.txt") result = find_minimum_gc_skew_location(genome) np.testing.assert_array_equal([3923619, 3923620, 3923621, 3923622], result) + + +def test_find_frequent_kmers_with_mismatches_raises(): + with pytest.raises(Warning): + find_frequent_kmers_with_mismatches("ACGTTGCAACGTTGCA", 13, 3) + with pytest.raises(Warning): + find_frequent_kmers_with_mismatches("ACGTTGCAACGTTGCA", 12, 4) + with pytest.raises(ValueError) as e: + find_frequent_kmers_with_mismatches("ACGT", 6, -1) + assert "Received: len(genome)=4, k=6, d=-1." in str(e.value) + + [email protected](reason="Takes around 2 minutes to execute") +def test_find_frequent_kmers_with_mismatches_benchmark(): + res = find_frequent_kmers_with_mismatches("ACGTTGCAACGTTGCA", 12, 3) + assert len(res) == 32855 + + +def test_find_frequent_kmers_with_mismatches(): + """Some debug datasets taken from: + http://bioinformaticsalgorithms.com/data/debugdatasets/replication/FrequentWordsWithMismatchesProblem.pdf + """ + + """ Dataset 1 + This dataset checks that the implementation includes k-mers that do not actually appear in Text. + Notice here that, although none of the output k-mers except for AA actually appear in Text, they + are all valid because they appear in Text with up to 1 mismatch (i.e. 0 or 1 mismatch). + """ + genome1 = "AAAAAAAAAA" + k1 = 2 + d1 = 1 + expected1 = {"AA", "AC", "AG", "CA", "AT", "GA", "TA"} + result1 = find_frequent_kmers_with_mismatches(genome1, k1, d1) + assert result1 == expected1 + + """ Dataset 2 + This dataset makes sure that the implementation is not accidentally swapping k and d. + """ + genome2 = "AGTCAGTC" + k2 = 4 + d2 = 2 + expected2 = { + "TCTC", + "CGGC", + "AAGC", + "TGTG", + "GGCC", + "AGGT", + "ATCC", + "ACTG", + "ACAC", + "AGAG", + "ATTA", + "TGAC", + "AATT", + "CGTT", + "GTTC", + "GGTA", + "AGCA", + "CATC", + } + result2 = find_frequent_kmers_with_mismatches(genome2, k2, d2) + assert result2 == expected2 + + """ Dataset 3 + This dataset makes sure you are not finding patterns in the Reverse Complement of genome + """ + genome3 = "AATTAATTGGTAGGTAGGTA" + k3 = 4 + d3 = 0 + expected3 = {"GGTA"} + result3 = find_frequent_kmers_with_mismatches(genome3, k3, d3) + assert result3 == expected3 + + """ Dataset 4 + This dataset first checks that k-mers with exactly d mismatches are being found. Then, it + checks that k-mers with less than d mismatches are being allowed (i.e. you are not only allowing + k-mers with exactly d mismatches). Next, it checks that you are not returning too few k-mers. + Last, it checks that you are not returning too many k-mers. + """ + genome4 = "ATA" + k4 = 3 + d4 = 1 + expected4 = {"GTA", "ACA", "AAA", "ATC", "ATA", "AGA", "ATT", "CTA", "TTA", "ATG"} + result4 = find_frequent_kmers_with_mismatches(genome4, k4, d4) + assert result4 == expected4 + + """ Dataset 5 + This dataset checks that your code is not looking for k-mers in the Reverse Complement + of genome. + """ + genome5 = "AAT" + k5 = 3 + d5 = 0 + expected5 = {"AAT"} + result5 = find_frequent_kmers_with_mismatches(genome5, k5, d5) + assert result5 == expected5
Frequent Words with Mismatches Find the most frequent k-mers with mismatches in a string. Input: A string Text as well as integers k and d. (You may assume k ≤ 12 and d ≤ 3.) Output: All most frequent k-mers with up to d mismatches in Text.
0.0
3174c1e9e685db12c5849ce5c7e3411f1922a4be
[ "genomics_algo/tests/miscellaneous_algorithms/test_misc_algos.py::test_find_pattern_clumps_short", "genomics_algo/tests/miscellaneous_algorithms/test_misc_algos.py::test_find_minimum_gc_skew_location", "genomics_algo/tests/miscellaneous_algorithms/test_misc_algos.py::test_find_frequent_kmers_with_mismatches_raises", "genomics_algo/tests/miscellaneous_algorithms/test_misc_algos.py::test_find_frequent_kmers_with_mismatches" ]
[]
{ "failed_lite_validators": [ "has_many_modified_files", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2021-02-02 23:48:56+00:00
mit
5,828
takahi-i__hideout-36
diff --git a/hideout/file.py b/hideout/file.py index 395e5d0..f204a37 100644 --- a/hideout/file.py +++ b/hideout/file.py @@ -66,11 +66,21 @@ def _generate_file_path_from_label(label): def _generate_file_path_from_func(func, func_args={}): - label = func.__name__ + class_name = _get_class_that_defined_method(func) + label = "{}".format(class_name) for arg_name in func_args: arg_value = str(func_args[arg_name]) if len(arg_value) > 10: arg_value = hashlib.md5(arg_value.encode("utf-8")).hexdigest()[0:10] - print("hashed_value: " + arg_value) label += "-{}-{}".format(arg_name, arg_value) return _generate_file_path_from_label(label) + + +def _get_class_that_defined_method(method): + class_name = "" + names = method.__qualname__.split('.') + for i, attr in enumerate(names): + class_name += "{}".format(attr) + if i != len(names) - 1: + class_name += "-" + return class_name
takahi-i/hideout
e024334f3f124b8df0a9617c3bc8fe8ab7c909aa
diff --git a/tests/test_file.py b/tests/test_file.py index 9e1d842..31ddb08 100644 --- a/tests/test_file.py +++ b/tests/test_file.py @@ -13,24 +13,40 @@ class Generator2: return {"foobar": baz} +class Generator3: + class InnerGenerator: + def generate(self, baz): + return {"foobar": baz} + + def __init__(self) -> None: + self.inner = Generator3.InnerGenerator() + + class TestFile(unittest.TestCase): def test_generate_file_name_with_label(self): self.assertEquals("large_object.pickle", os.path.basename(generate_path( - func=generate, - func_args={"baz": [0, 1, 2, 3, 4, 5, 7, 6, 8, 9, 10]}, - label="large_object"))) + func=generate, + func_args={"baz": [0, 1, 2, 3, 4, 5, 7, 6, 8, 9, 10]}, + label="large_object"))) def test_generate_file_name_from_hash(self): self.assertEquals("generate-baz-6979983cbc.pickle", os.path.basename(generate_path( - func=generate, - func_args={"baz": [0, 1, 2, 3, 4, 5, 7, 6, 8, 9, 10]}))) + func=generate, + func_args={"baz": [0, 1, 2, 3, 4, 5, 7, 6, 8, 9, 10]}))) def test_generate_file_name_from_hash_with_instance(self): generator = Generator2() - self.assertEquals("generate-baz-6979983cbc.pickle", + self.assertEquals("Generator2-generate-baz-6979983cbc.pickle", os.path.basename(generate_path( func=generator.generate, func_args={"baz": [0, 1, 2, 3, 4, 5, 7, 6, 8, 9, 10]}))) + + def test_generate_file_name_from_hash_with_instance_of_inner_class(self): + generator = Generator3() + self.assertEquals("Generator3-InnerGenerator-generate-baz-6979983cbc.pickle", + os.path.basename(generate_path( + func=generator.inner.generate, + func_args={"baz": [0, 1, 2, 3, 4, 5, 7, 6, 8, 9, 10]})))
Get class name for bind method for cache file
0.0
e024334f3f124b8df0a9617c3bc8fe8ab7c909aa
[ "tests/test_file.py::TestFile::test_generate_file_name_from_hash_with_instance", "tests/test_file.py::TestFile::test_generate_file_name_from_hash_with_instance_of_inner_class" ]
[ "tests/test_file.py::TestFile::test_generate_file_name_from_hash", "tests/test_file.py::TestFile::test_generate_file_name_with_label" ]
{ "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false }
2019-08-12 05:22:56+00:00
mit
5,829
takahi-i__pfm-27
diff --git a/pf_manager/pf_command/add.py b/pf_manager/pf_command/add.py index 31abddf..978a2d3 100644 --- a/pf_manager/pf_command/add.py +++ b/pf_manager/pf_command/add.py @@ -20,11 +20,13 @@ def check_fields(target): def check_local_port_is_used(local_port, targets): + print("local_port: " + local_port); + + for target_name in targets: target = targets[target_name] if local_port == target["local_port"]: - raise RuntimeError("local port " + str(local_port) + " is already used in " + target_name) - + logger.warn("local port {} is already used in {}".format(str(local_port), target_name)) def check_remote_port_is_used(new_target, targets): remote_port = new_target["remote_port"] @@ -35,9 +37,7 @@ def check_remote_port_is_used(new_target, targets): target_remote_host = get_remote_host(target) if target_remote_host == remote_host and target["remote_port"] == remote_port: - raise RuntimeError( - "remote port " + str(remote_port) + " in host " + remote_host + "is already used in " + target_name) - + logger.warn("remote port {} in host {} is already used in {} ".format(str(remote_port), remote_host, target_name)) def get_remote_host(target): target_remote_host = target["remote_host"]
takahi-i/pfm
28ad611a179c3e0c463e197ce23e81d1d8968eb1
diff --git a/tests/pf_command/test_add.py b/tests/pf_command/test_add.py index 6f1b0d4..18b86b1 100644 --- a/tests/pf_command/test_add.py +++ b/tests/pf_command/test_add.py @@ -27,7 +27,7 @@ class TestPfm(unittest.TestCase): None) self.assertRaises(RuntimeError, lambda: add_command.generate_consistent_target({})) - def test_fail_to_add_same_local_port(self): + def test_add_same_local_port(self): targets = {'food-nonfood': { 'name': 'text-classification', @@ -37,7 +37,7 @@ class TestPfm(unittest.TestCase): } add_command = AddCommand("image-processing", None, "L", "localhost", "8888", "8888", "my.aws.com", None, None, None) - self.assertRaises(RuntimeError, lambda: add_command.generate_consistent_target(targets)) + self.assertEqual("8888", add_command.generate_consistent_target(targets)["local_port"]) def test_add_target_without_local_port(self): targets = {'food-nonfood': @@ -49,6 +49,7 @@ class TestPfm(unittest.TestCase): } add_command = AddCommand("image-processing", None, "L", "localhost", "8888", None, "my.aws.com", None, None, None) + self.assertEqual("49152", add_command.generate_consistent_target(targets)["local_port"]) def test_add_target_without_remote_port(self): targets = {'food-nonfood': @@ -85,7 +86,7 @@ class TestPfm(unittest.TestCase): add_command = AddCommand("image-processing", None, "L", "my-ml-instance.ml.aws.com", "9999", "7777", "ssh-server-instance.ml.aws.com", None, None, None) - self.assertRaises(RuntimeError, lambda: add_command.generate_consistent_target(targets)) + self.assertEqual("9999", add_command.generate_consistent_target(targets)["remote_port"]) def test_fail_to_add_same_remote_port_in_same_host2(self): targets = {'food-nonfood': @@ -98,4 +99,4 @@ class TestPfm(unittest.TestCase): add_command = AddCommand("image-processing", None, 'L', 'localhost', '9999', '7777', 'my-ml-instance.ml.aws.com', None, None, None) - self.assertRaises(RuntimeError, lambda: add_command.generate_consistent_target(targets)) + self.assertEqual("9999", add_command.generate_consistent_target(targets)["remote_port"])
Cannot add new stuff with the same local port * pfm version:0.3.0 * Python version:pyton:3.5.2 * Operating System:mac OS 10.13 ### Description I cannot add a new element using a local port that was used before. ### What I Did ``` $ pfm list +----------------------+------------+------------+--------------------------------+------------+-----------------+--------------------------------+--------------+ | name | type | local_port | remote_host | remote_por | login_user | ssh_server | server_port | | | | | | t | | | | +======================+============+============+================================+============+=================+================================+==============+ | test1 | L | 8888 | localhost | 10003 | None | test-server | | | | | | | | | | None | +----------------------+------------+------------+--------------------------------+------------+-----------------+--------------------------------+--------------+ ``` Then ``` $ pfm add --name test2 --local-port 8888 --ssh-server test-server local_port is not specified allocating remote_port for test2... remote_port of test2 is set to 49152 Failed to register... local port 8888 is already used in test1 ```
0.0
28ad611a179c3e0c463e197ce23e81d1d8968eb1
[ "tests/pf_command/test_add.py::TestPfm::test_add_same_local_port", "tests/pf_command/test_add.py::TestPfm::test_fail_to_add_same_remote_port_in_same_host", "tests/pf_command/test_add.py::TestPfm::test_fail_to_add_same_remote_port_in_same_host2" ]
[ "tests/pf_command/test_add.py::TestPfm::test_add_same_remote_port_in_different_host", "tests/pf_command/test_add.py::TestPfm::test_add_target_without_local_port", "tests/pf_command/test_add.py::TestPfm::test_add_target_without_remote_port", "tests/pf_command/test_add.py::TestPfm::test_generate_target_with_argument", "tests/pf_command/test_add.py::TestPfm::test_generate_target_with_options", "tests/pf_command/test_add.py::TestPfm::test_raise_exception_with_inadiquate_parameters" ]
{ "failed_lite_validators": [ "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2018-02-03 15:31:44+00:00
mit
5,830
tantale__deprecated-69
diff --git a/CHANGELOG.rst b/CHANGELOG.rst index ec2f685..1e43f51 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -28,6 +28,8 @@ Fix - Resolve Python 2.7 support issue introduced in v1.2.14 in ``sphinx.py``. +- Fix #69: Add ``extra_stacklevel`` argument for interoperating with other wrapper functions (refer to #68 for a concrete use case). + Other ----- diff --git a/deprecated/classic.py b/deprecated/classic.py index 6ca3f27..84f683c 100644 --- a/deprecated/classic.py +++ b/deprecated/classic.py @@ -17,7 +17,7 @@ import wrapt try: # If the C extension for wrapt was compiled and wrapt/_wrappers.pyd exists, then the # stack level that should be passed to warnings.warn should be 2. However, if using - # a pure python wrapt, a extra stacklevel is required. + # a pure python wrapt, an extra stacklevel is required. import wrapt._wrappers _routine_stacklevel = 2 @@ -83,7 +83,7 @@ class ClassicAdapter(wrapt.AdapterFactory): return x + y """ - def __init__(self, reason="", version="", action=None, category=DeprecationWarning): + def __init__(self, reason="", version="", action=None, category=DeprecationWarning, extra_stacklevel=0): """ Construct a wrapper adapter. @@ -97,23 +97,33 @@ class ClassicAdapter(wrapt.AdapterFactory): If you follow the `Semantic Versioning <https://semver.org/>`_, the version number has the format "MAJOR.MINOR.PATCH". - :type action: str + :type action: Literal["default", "error", "ignore", "always", "module", "once"] :param action: A warning filter used to activate or not the deprecation warning. Can be one of "error", "ignore", "always", "default", "module", or "once". - If ``None`` or empty, the the global filtering mechanism is used. + If ``None`` or empty, the global filtering mechanism is used. See: `The Warnings Filter`_ in the Python documentation. - :type category: type + :type category: Type[Warning] :param category: The warning category to use for the deprecation warning. By default, the category class is :class:`~DeprecationWarning`, you can inherit this class to define your own deprecation warning category. + + :type extra_stacklevel: int + :param extra_stacklevel: + Number of additional stack levels to consider instrumentation rather than user code. + With the default value of 0, the warning refers to where the class was instantiated + or the function was called. + + .. versionchanged:: 1.2.15 + Add the *extra_stacklevel* parameter. """ self.reason = reason or "" self.version = version or "" self.action = action self.category = category + self.extra_stacklevel = extra_stacklevel super(ClassicAdapter, self).__init__() def get_deprecated_msg(self, wrapped, instance): @@ -161,12 +171,13 @@ class ClassicAdapter(wrapt.AdapterFactory): def wrapped_cls(cls, *args, **kwargs): msg = self.get_deprecated_msg(wrapped, None) + stacklevel = _class_stacklevel + self.extra_stacklevel if self.action: with warnings.catch_warnings(): warnings.simplefilter(self.action, self.category) - warnings.warn(msg, category=self.category, stacklevel=_class_stacklevel) + warnings.warn(msg, category=self.category, stacklevel=stacklevel) else: - warnings.warn(msg, category=self.category, stacklevel=_class_stacklevel) + warnings.warn(msg, category=self.category, stacklevel=stacklevel) if old_new1 is object.__new__: return old_new1(cls) # actually, we don't know the real signature of *old_new1* @@ -174,6 +185,24 @@ class ClassicAdapter(wrapt.AdapterFactory): wrapped.__new__ = staticmethod(wrapped_cls) + elif inspect.isroutine(wrapped): + @wrapt.decorator + def wrapper_function(wrapped_, instance_, args_, kwargs_): + msg = self.get_deprecated_msg(wrapped_, instance_) + stacklevel = _routine_stacklevel + self.extra_stacklevel + if self.action: + with warnings.catch_warnings(): + warnings.simplefilter(self.action, self.category) + warnings.warn(msg, category=self.category, stacklevel=stacklevel) + else: + warnings.warn(msg, category=self.category, stacklevel=stacklevel) + return wrapped_(*args_, **kwargs_) + + return wrapper_function(wrapped) + + else: + raise TypeError(repr(type(wrapped))) + return wrapped @@ -226,7 +255,7 @@ def deprecated(*args, **kwargs): return x + y The *category* keyword argument allow you to specify the deprecation warning class of your choice. - By default, :exc:`DeprecationWarning` is used but you can choose :exc:`FutureWarning`, + By default, :exc:`DeprecationWarning` is used, but you can choose :exc:`FutureWarning`, :exc:`PendingDeprecationWarning` or a custom subclass. .. code-block:: python @@ -240,7 +269,7 @@ def deprecated(*args, **kwargs): The *action* keyword argument allow you to locally change the warning filtering. *action* can be one of "error", "ignore", "always", "default", "module", or "once". - If ``None``, empty or missing, the the global filtering mechanism is used. + If ``None``, empty or missing, the global filtering mechanism is used. See: `The Warnings Filter`_ in the Python documentation. .. code-block:: python @@ -252,6 +281,9 @@ def deprecated(*args, **kwargs): def some_old_function(x, y): return x + y + The *extra_stacklevel* keyword argument allows you to specify additional stack levels + to consider instrumentation rather than user code. With the default value of 0, the + warning refers to where the class was instantiated or the function was called. """ if args and isinstance(args[0], string_types): kwargs['reason'] = args[0] @@ -261,32 +293,9 @@ def deprecated(*args, **kwargs): raise TypeError(repr(type(args[0]))) if args: - action = kwargs.get('action') - category = kwargs.get('category', DeprecationWarning) adapter_cls = kwargs.pop('adapter_cls', ClassicAdapter) adapter = adapter_cls(**kwargs) - wrapped = args[0] - if inspect.isclass(wrapped): - wrapped = adapter(wrapped) - return wrapped - - elif inspect.isroutine(wrapped): - - @wrapt.decorator(adapter=adapter) - def wrapper_function(wrapped_, instance_, args_, kwargs_): - msg = adapter.get_deprecated_msg(wrapped_, instance_) - if action: - with warnings.catch_warnings(): - warnings.simplefilter(action, category) - warnings.warn(msg, category=category, stacklevel=_routine_stacklevel) - else: - warnings.warn(msg, category=category, stacklevel=_routine_stacklevel) - return wrapped_(*args_, **kwargs_) - - return wrapper_function(wrapped) - - else: - raise TypeError(repr(type(wrapped))) + return adapter(wrapped) return functools.partial(deprecated, **kwargs) diff --git a/deprecated/sphinx.py b/deprecated/sphinx.py index be6dce9..70ef050 100644 --- a/deprecated/sphinx.py +++ b/deprecated/sphinx.py @@ -22,8 +22,6 @@ when the function/method is called or the class is constructed. import re import textwrap -import wrapt - from deprecated.classic import ClassicAdapter from deprecated.classic import deprecated as _classic_deprecated @@ -48,6 +46,7 @@ class SphinxAdapter(ClassicAdapter): version="", action=None, category=DeprecationWarning, + extra_stacklevel=0, line_length=70, ): """ @@ -67,29 +66,40 @@ class SphinxAdapter(ClassicAdapter): If you follow the `Semantic Versioning <https://semver.org/>`_, the version number has the format "MAJOR.MINOR.PATCH". - :type action: str + :type action: Literal["default", "error", "ignore", "always", "module", "once"] :param action: A warning filter used to activate or not the deprecation warning. Can be one of "error", "ignore", "always", "default", "module", or "once". - If ``None`` or empty, the the global filtering mechanism is used. + If ``None`` or empty, the global filtering mechanism is used. See: `The Warnings Filter`_ in the Python documentation. - :type category: type + :type category: Type[Warning] :param category: The warning category to use for the deprecation warning. By default, the category class is :class:`~DeprecationWarning`, you can inherit this class to define your own deprecation warning category. + :type extra_stacklevel: int + :param extra_stacklevel: + Number of additional stack levels to consider instrumentation rather than user code. + With the default value of 0, the warning refers to where the class was instantiated + or the function was called. + :type line_length: int :param line_length: Max line length of the directive text. If non nul, a long text is wrapped in several lines. + + .. versionchanged:: 1.2.15 + Add the *extra_stacklevel* parameter. """ if not version: # https://github.com/tantale/deprecated/issues/40 raise ValueError("'version' argument is required in Sphinx directives") self.directive = directive self.line_length = line_length - super(SphinxAdapter, self).__init__(reason=reason, version=version, action=action, category=category) + super(SphinxAdapter, self).__init__( + reason=reason, version=version, action=action, category=category, extra_stacklevel=extra_stacklevel + ) def __call__(self, wrapped): """ @@ -102,7 +112,7 @@ class SphinxAdapter(ClassicAdapter): # -- build the directive division fmt = ".. {directive}:: {version}" if self.version else ".. {directive}::" div_lines = [fmt.format(directive=self.directive, version=self.version)] - width = self.line_length - 3 if self.line_length > 3 else 2 ** 16 + width = self.line_length - 3 if self.line_length > 3 else 2**16 reason = textwrap.dedent(self.reason).strip() for paragraph in reason.splitlines(): if paragraph: @@ -153,7 +163,7 @@ class SphinxAdapter(ClassicAdapter): """ msg = super(SphinxAdapter, self).get_deprecated_msg(wrapped, instance) - # Strip Sphinx cross reference syntax (like ":function:", ":py:func:" and ":py:meth:") + # Strip Sphinx cross-reference syntax (like ":function:", ":py:func:" and ":py:meth:") # Possible values are ":role:`foo`", ":domain:role:`foo`" # where ``role`` and ``domain`` should match "[a-zA-Z]+" msg = re.sub(r"(?: : [a-zA-Z]+ )? : [a-zA-Z]+ : (`[^`]*`)", r"\1", msg, flags=re.X) @@ -163,7 +173,7 @@ class SphinxAdapter(ClassicAdapter): def versionadded(reason="", version="", line_length=70): """ This decorator can be used to insert a "versionadded" directive - in your function/class docstring in order to documents the + in your function/class docstring in order to document the version of the project which adds this new functionality in your library. :param str reason: @@ -193,7 +203,7 @@ def versionadded(reason="", version="", line_length=70): def versionchanged(reason="", version="", line_length=70): """ This decorator can be used to insert a "versionchanged" directive - in your function/class docstring in order to documents the + in your function/class docstring in order to document the version of the project which modifies this functionality in your library. :param str reason: @@ -222,7 +232,7 @@ def versionchanged(reason="", version="", line_length=70): def deprecated(reason="", version="", line_length=70, **kwargs): """ This decorator can be used to insert a "deprecated" directive - in your function/class docstring in order to documents the + in your function/class docstring in order to document the version of the project which deprecates this functionality in your library. :param str reason: @@ -242,17 +252,26 @@ def deprecated(reason="", version="", line_length=70, **kwargs): - "action": A warning filter used to activate or not the deprecation warning. Can be one of "error", "ignore", "always", "default", "module", or "once". - If ``None``, empty or missing, the the global filtering mechanism is used. + If ``None``, empty or missing, the global filtering mechanism is used. - "category": The warning category to use for the deprecation warning. By default, the category class is :class:`~DeprecationWarning`, you can inherit this class to define your own deprecation warning category. + - "extra_stacklevel": + Number of additional stack levels to consider instrumentation rather than user code. + With the default value of 0, the warning refers to where the class was instantiated + or the function was called. + + :return: a decorator used to deprecate a function. .. versionchanged:: 1.2.13 Change the signature of the decorator to reflect the valid use cases. + + .. versionchanged:: 1.2.15 + Add the *extra_stacklevel* parameter. """ directive = kwargs.pop('directive', 'deprecated') adapter_cls = kwargs.pop('adapter_cls', SphinxAdapter) diff --git a/docs/source/tutorial.rst b/docs/source/tutorial.rst index 86cf056..00fb237 100644 --- a/docs/source/tutorial.rst +++ b/docs/source/tutorial.rst @@ -242,3 +242,28 @@ function will raise an exception because the *action* is set to "error". File "path/to/deprecated/classic.py", line 274, in wrapper_function warnings.warn(msg, category=category, stacklevel=_stacklevel) DeprecationWarning: Call to deprecated function (or staticmethod) foo. (do not call it) + + +Modifying the deprecated code reference +--------------------------------------- + +By default, when a deprecated function or class is called, the warning message indicates the location of the caller. + +The ``extra_stacklevel`` parameter allows customizing the stack level reference in the deprecation warning message. + +This parameter is particularly useful in scenarios where you have a factory or utility function that creates deprecated +objects or performs deprecated operations. By specifying an ``extra_stacklevel`` value, you can control the stack level +at which the deprecation warning is emitted, making it appear as if the calling function is the deprecated one, +rather than the actual deprecated entity. + +For example, if you have a factory function ``create_object()`` that creates deprecated objects, you can use +the ``extra_stacklevel`` parameter to emit the deprecation warning at the calling location. This provides clearer and +more actionable deprecation messages, allowing developers to identify and update the code that invokes the deprecated +functionality. + +For instance: + +.. literalinclude:: tutorial/warning_ctrl/extra_stacklevel_demo.py + +Please note that the ``extra_stacklevel`` value should be an integer indicating the number of stack levels to skip +when emitting the deprecation warning. diff --git a/docs/source/tutorial/warning_ctrl/extra_stacklevel_demo.py b/docs/source/tutorial/warning_ctrl/extra_stacklevel_demo.py new file mode 100644 index 0000000..3c0516c --- /dev/null +++ b/docs/source/tutorial/warning_ctrl/extra_stacklevel_demo.py @@ -0,0 +1,24 @@ +import warnings + +from deprecated import deprecated + + +@deprecated(version='1.0', extra_stacklevel=1) +class MyObject(object): + def __init__(self, name): + self.name = name + + def __str__(self): + return "object: {name}".format(name=self.name) + + +def create_object(name): + return MyObject(name) + + +if __name__ == '__main__': + warnings.filterwarnings("default", category=DeprecationWarning) + # warn here: + print(create_object("orange")) + # and also here: + print(create_object("banane"))
tantale/deprecated
1ebf9b89aa8a199d2d5b5d6634cd908eb80e1e7f
diff --git a/tests/test_deprecated.py b/tests/test_deprecated.py index e4c00ef..0e467ae 100644 --- a/tests/test_deprecated.py +++ b/tests/test_deprecated.py @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- +import inspect import sys import warnings @@ -11,6 +12,10 @@ class MyDeprecationWarning(DeprecationWarning): pass +class WrongStackLevelWarning(DeprecationWarning): + pass + + _PARAMS = [ None, ((), {}), @@ -19,6 +24,7 @@ _PARAMS = [ ((), {'version': '1.2.3'}), ((), {'action': 'once'}), ((), {'category': MyDeprecationWarning}), + ((), {'extra_stacklevel': 1, 'category': WrongStackLevelWarning}), ] @@ -136,7 +142,7 @@ def test_classic_deprecated_function__warns(classic_deprecated_function): warn = warns[0] assert issubclass(warn.category, DeprecationWarning) assert "deprecated function (or staticmethod)" in str(warn.message) - assert warn.filename == __file__, 'Incorrect warning stackLevel' + assert warn.filename == __file__ or warn.category is WrongStackLevelWarning, 'Incorrect warning stackLevel' # noinspection PyShadowingNames @@ -148,7 +154,7 @@ def test_classic_deprecated_class__warns(classic_deprecated_class): warn = warns[0] assert issubclass(warn.category, DeprecationWarning) assert "deprecated class" in str(warn.message) - assert warn.filename == __file__, 'Incorrect warning stackLevel' + assert warn.filename == __file__ or warn.category is WrongStackLevelWarning, 'Incorrect warning stackLevel' # noinspection PyShadowingNames @@ -161,7 +167,7 @@ def test_classic_deprecated_method__warns(classic_deprecated_method): warn = warns[0] assert issubclass(warn.category, DeprecationWarning) assert "deprecated method" in str(warn.message) - assert warn.filename == __file__, 'Incorrect warning stackLevel' + assert warn.filename == __file__ or warn.category is WrongStackLevelWarning, 'Incorrect warning stackLevel' # noinspection PyShadowingNames @@ -173,7 +179,7 @@ def test_classic_deprecated_static_method__warns(classic_deprecated_static_metho warn = warns[0] assert issubclass(warn.category, DeprecationWarning) assert "deprecated function (or staticmethod)" in str(warn.message) - assert warn.filename == __file__, 'Incorrect warning stackLevel' + assert warn.filename == __file__ or warn.category is WrongStackLevelWarning, 'Incorrect warning stackLevel' # noinspection PyShadowingNames @@ -189,7 +195,7 @@ def test_classic_deprecated_class_method__warns(classic_deprecated_class_method) assert "deprecated class method" in str(warn.message) else: assert "deprecated function (or staticmethod)" in str(warn.message) - assert warn.filename == __file__, 'Incorrect warning stackLevel' + assert warn.filename == __file__ or warn.category is WrongStackLevelWarning, 'Incorrect warning stackLevel' def test_should_raise_type_error(): @@ -258,3 +264,61 @@ def test_respect_global_filter(): fun() fun() assert len(warns) == 1 + + +def test_default_stacklevel(): + """ + The objective of this unit test is to ensure that the triggered warning message, + when invoking the 'use_foo' function, correctly indicates the line where the + deprecated 'foo' function is called. + """ + + @deprecated.classic.deprecated + def foo(): + pass + + def use_foo(): + foo() + + with warnings.catch_warnings(record=True) as warns: + warnings.simplefilter("always") + use_foo() + + # Check that the warning path matches the module path + warn = warns[0] + assert warn.filename == __file__ + + # Check that the line number points to the first line inside 'use_foo' + use_foo_lineno = inspect.getsourcelines(use_foo)[1] + assert warn.lineno == use_foo_lineno + 1 + + +def test_extra_stacklevel(): + """ + The unit test utilizes an 'extra_stacklevel' of 1 to ensure that the warning message + accurately identifies the caller of the deprecated function. It verifies that when + the 'use_foo' function is called, the warning message correctly indicates the line + where the call to 'use_foo' is made. + """ + + @deprecated.classic.deprecated(extra_stacklevel=1) + def foo(): + pass + + def use_foo(): + foo() + + def demo(): + use_foo() + + with warnings.catch_warnings(record=True) as warns: + warnings.simplefilter("always") + demo() + + # Check that the warning path matches the module path + warn = warns[0] + assert warn.filename == __file__ + + # Check that the line number points to the first line inside 'demo' + demo_lineno = inspect.getsourcelines(demo)[1] + assert warn.lineno == demo_lineno + 1
[ENH] Stacklevel offset Over at https://github.com/coroa/pandas-indexing/pull/27, I am about to deprecate a [pandas accessor](https://pandas.pydata.org/docs/development/extending.html#registering-custom-accessors), but since these accessors are classes, which are instantiated by pandas upon access the warning is not emitted since the `stacklevel` is too low. # MWE ```python import pandas as pd from deprecated import deprecated @pd.api.extensions.register_dataframe_accessor("idx") @deprecated class IdxAccessor: def __init__(self, pandas_obj): self._obj = pandas_obj df = pd.DataFrame() df.idx ``` will only emit with a ~`warnings.simplefilter("always")`~ `warnings.simplefilter("default")` (edit: changed to include "default" which was pointed out below), since the callstack looks like: ```python Cell In[4], line 11 df.idx File ~/.local/conda/envs/aneris2/lib/python3.10/site-packages/pandas/core/accessor.py:182 in __get__ accessor_obj = self._accessor(obj) File ~/.local/conda/envs/aneris2/lib/python3.10/site-packages/deprecated/classic.py:169 in wrapped_cls warnings.warn(msg, category=self.category, stacklevel=_class_stacklevel) ``` so that the last `stacklevel=2` setting points to the `pandas.core.accessor` module instead of the user code. # Proposal Would you accept a PR to add a `stacklevel_offset` or `stacklevel` argument to deprecated which would either be added like: ```python warnings.warn(msg, category=self.category, stacklevel=_class_stacklevel + stacklevel_offset) ``` or could be used to replace the default `stacklevel`, like: ```python warnings.warn(msg, category=self.category, stacklevel=_class_stacklevel if stacklevel is None else stacklevel) ```
0.0
1ebf9b89aa8a199d2d5b5d6634cd908eb80e1e7f
[ "tests/test_deprecated.py::test_classic_deprecated_function__warns[classic_deprecated_function7]", "tests/test_deprecated.py::test_classic_deprecated_class__warns[classic_deprecated_class7]", "tests/test_deprecated.py::test_classic_deprecated_method__warns[classic_deprecated_method7]", "tests/test_deprecated.py::test_classic_deprecated_static_method__warns[classic_deprecated_static_method7]", "tests/test_deprecated.py::test_classic_deprecated_class_method__warns[classic_deprecated_class_method7]", "tests/test_deprecated.py::test_extra_stacklevel" ]
[ "tests/test_deprecated.py::test_classic_deprecated_function__warns[None]", "tests/test_deprecated.py::test_classic_deprecated_function__warns[classic_deprecated_function1]", "tests/test_deprecated.py::test_classic_deprecated_function__warns[classic_deprecated_function2]", "tests/test_deprecated.py::test_classic_deprecated_function__warns[classic_deprecated_function3]", "tests/test_deprecated.py::test_classic_deprecated_function__warns[classic_deprecated_function4]", "tests/test_deprecated.py::test_classic_deprecated_function__warns[classic_deprecated_function5]", "tests/test_deprecated.py::test_classic_deprecated_function__warns[classic_deprecated_function6]", "tests/test_deprecated.py::test_classic_deprecated_class__warns[None]", "tests/test_deprecated.py::test_classic_deprecated_class__warns[classic_deprecated_class1]", "tests/test_deprecated.py::test_classic_deprecated_class__warns[classic_deprecated_class2]", "tests/test_deprecated.py::test_classic_deprecated_class__warns[classic_deprecated_class3]", "tests/test_deprecated.py::test_classic_deprecated_class__warns[classic_deprecated_class4]", "tests/test_deprecated.py::test_classic_deprecated_class__warns[classic_deprecated_class5]", "tests/test_deprecated.py::test_classic_deprecated_class__warns[classic_deprecated_class6]", "tests/test_deprecated.py::test_classic_deprecated_method__warns[None]", "tests/test_deprecated.py::test_classic_deprecated_method__warns[classic_deprecated_method1]", "tests/test_deprecated.py::test_classic_deprecated_method__warns[classic_deprecated_method2]", "tests/test_deprecated.py::test_classic_deprecated_method__warns[classic_deprecated_method3]", "tests/test_deprecated.py::test_classic_deprecated_method__warns[classic_deprecated_method4]", "tests/test_deprecated.py::test_classic_deprecated_method__warns[classic_deprecated_method5]", "tests/test_deprecated.py::test_classic_deprecated_method__warns[classic_deprecated_method6]", "tests/test_deprecated.py::test_classic_deprecated_static_method__warns[None]", "tests/test_deprecated.py::test_classic_deprecated_static_method__warns[classic_deprecated_static_method1]", "tests/test_deprecated.py::test_classic_deprecated_static_method__warns[classic_deprecated_static_method2]", "tests/test_deprecated.py::test_classic_deprecated_static_method__warns[classic_deprecated_static_method3]", "tests/test_deprecated.py::test_classic_deprecated_static_method__warns[classic_deprecated_static_method4]", "tests/test_deprecated.py::test_classic_deprecated_static_method__warns[classic_deprecated_static_method5]", "tests/test_deprecated.py::test_classic_deprecated_static_method__warns[classic_deprecated_static_method6]", "tests/test_deprecated.py::test_classic_deprecated_class_method__warns[None]", "tests/test_deprecated.py::test_classic_deprecated_class_method__warns[classic_deprecated_class_method1]", "tests/test_deprecated.py::test_classic_deprecated_class_method__warns[classic_deprecated_class_method2]", "tests/test_deprecated.py::test_classic_deprecated_class_method__warns[classic_deprecated_class_method3]", "tests/test_deprecated.py::test_classic_deprecated_class_method__warns[classic_deprecated_class_method4]", "tests/test_deprecated.py::test_classic_deprecated_class_method__warns[classic_deprecated_class_method5]", "tests/test_deprecated.py::test_classic_deprecated_class_method__warns[classic_deprecated_class_method6]", "tests/test_deprecated.py::test_should_raise_type_error", "tests/test_deprecated.py::test_warning_is_ignored", "tests/test_deprecated.py::test_respect_global_filter", "tests/test_deprecated.py::test_default_stacklevel" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2023-07-08 22:09:05+00:00
mit
5,831
tarioch__xirr-15
diff --git a/src/xirr/math.py b/src/xirr/math.py index 92ca4de..14bf286 100644 --- a/src/xirr/math.py +++ b/src/xirr/math.py @@ -50,7 +50,7 @@ def xirr(valuesPerDate): try: result = scipy.optimize.newton(lambda r: xnpv(valuesPerDate, r), 0) except (RuntimeError, OverflowError): # Failed to converge? - result = scipy.optimize.brentq(lambda r: xnpv(valuesPerDate, r), -0.999999999999999, 1e20) + result = scipy.optimize.brentq(lambda r: xnpv(valuesPerDate, r), -0.999999999999999, 1e20, maxiter=10**6) if not isinstance(result, complex): return result
tarioch/xirr
9d046ac2db139ed311fc146ff1a7feae22e549d1
diff --git a/tests/test_math.py b/tests/test_math.py index 0c78f3f..48b0a1f 100644 --- a/tests/test_math.py +++ b/tests/test_math.py @@ -21,6 +21,18 @@ from xirr.math import xirr, cleanXirr, xnpv ({'2011-01-01': 1, '2011-01-02': 0, '2012-01-01': 1}, float("inf")), ({'2011-07-01': -10000, '2014-07-01': 1}, -0.9535), ({'2011-07-01': 10000, '2014-07-01': -1}, -0.9535), + ({ + '2016-04-06': 18902.0, + '2016-05-04': 83600.0, + '2016-05-12': -5780.0, + '2017-05-08': -4080.0, + '2017-07-03': -56780.0, + '2018-05-07': -2210.0, + '2019-05-06': -2380.0, + '2019-10-01': 33975.0, + '2020-03-13': 23067.98, + '2020-05-07': -1619.57, + }, -1), ]) def test_xirr(valuesPerDateString, expected): valuesPerDate = {datetime.fromisoformat(k).date(): v for k, v in valuesPerDateString.items()}
Problematic example Here's an interesting example of numbers: Values: ``` [5046.0, 5037.299999999999, 4995.25, 5795.5, -1085.6, 4998.0, 4557.8, 4815.0, 4928.0, -2197.05, 5424.0, -2565.0, -2872.8, 10085.0, 9500.0, 9976.8, 14880.000000000002, -6094.7, 19522.359999999997, 18035.0, 10477.44] ``` Dates: ``` [Timestamp('2015-08-03 00:00:00+0000', tz='UTC'), Timestamp('2015-10-20 00:00:00+0000', tz='UTC'), Timestamp('2016-01-11 00:00:00+0000', tz='UTC'), Timestamp('2016-04-06 00:00:00+0000', tz='UTC'), Timestamp('2016-04-26 00:00:00+0000', tz='UTC'), Timestamp('2016-07-19 00:00:00+0000', tz='UTC'), Timestamp('2016-10-11 00:00:00+0000', tz='UTC'), Timestamp('2017-01-11 00:00:00+0000', tz='UTC'), Timestamp('2017-04-11 00:00:00+0000', tz='UTC'), Timestamp('2017-04-25 00:00:00+0000', tz='UTC'), Timestamp('2017-10-12 00:00:00+0000', tz='UTC'), Timestamp('2018-04-24 00:00:00+0000', tz='UTC'), Timestamp('2019-04-23 00:00:00+0000', tz='UTC'), Timestamp('2020-02-25 00:00:00+0000', tz='UTC'), Timestamp('2020-03-03 00:00:00+0000', tz='UTC'), Timestamp('2020-03-09 00:00:00+0000', tz='UTC'), Timestamp('2020-04-06 00:00:00+0000', tz='UTC'), Timestamp('2020-04-23 00:00:00+0000', tz='UTC'), Timestamp('2020-06-05 00:00:00+0000', tz='UTC'), Timestamp('2020-08-05 00:00:00+0000', tz='UTC'), Timestamp('2020-08-19 00:00:00+0000', tz='UTC')] ``` It produces an exception in xirr: `ValueError: f(a) and f(b) must have different signs` It also produces an error in Google Sheets. Excel, however, produces a result: ![image](https://user-images.githubusercontent.com/8012482/92327892-26b14d00-f05d-11ea-9bf9-d102c3ed394f.png) Any idea what is going on here?
0.0
9d046ac2db139ed311fc146ff1a7feae22e549d1
[ "tests/test_math.py::test_xirr[valuesPerDateString15--1]" ]
[ "tests/test_math.py::test_xirr[valuesPerDateString0--0.6454]", "tests/test_math.py::test_xirr[valuesPerDateString1--0.6454]", "tests/test_math.py::test_xirr[valuesPerDateString2--0.6581]", "tests/test_math.py::test_xirr[valuesPerDateString3-None]", "tests/test_math.py::test_xirr[valuesPerDateString4--inf]", "tests/test_math.py::test_xirr[valuesPerDateString5-inf]", "tests/test_math.py::test_xirr[valuesPerDateString6-0.0]", "tests/test_math.py::test_xirr[valuesPerDateString7-0.0]", "tests/test_math.py::test_xirr[valuesPerDateString8-412461.6383]", "tests/test_math.py::test_xirr[valuesPerDateString9-1.2238535289956518e+16]", "tests/test_math.py::test_xirr[valuesPerDateString10--0.8037]", "tests/test_math.py::test_xirr[valuesPerDateString11--inf]", "tests/test_math.py::test_xirr[valuesPerDateString12-inf]", "tests/test_math.py::test_xirr[valuesPerDateString13--0.9535]", "tests/test_math.py::test_xirr[valuesPerDateString14--0.9535]", "tests/test_math.py::test_cleanXirr[valuesPerDateString0--0.6454]", "tests/test_math.py::test_cleanXirr[valuesPerDateString1--0.6454]", "tests/test_math.py::test_cleanXirr[valuesPerDateString2--0.6581]", "tests/test_math.py::test_cleanXirr[valuesPerDateString3-None]", "tests/test_math.py::test_cleanXirr[valuesPerDateString4-None]", "tests/test_math.py::test_cleanXirr[valuesPerDateString5-None]", "tests/test_math.py::test_cleanXirr[valuesPerDateString6-None]", "tests/test_math.py::test_cleanXirr[valuesPerDateString7--0.8037]", "tests/test_math.py::test_cleanXirr[valuesPerDateString8-None]", "tests/test_math.py::test_xnpv[valuesPerDateString0--1.0-inf]", "tests/test_math.py::test_xnpv[valuesPerDateString1--0.1-22.2575]" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_media" ], "has_test_patch": true, "is_lite": false }
2020-09-15 16:30:22+00:00
mit
5,832
tarohi24__typedflow-16
diff --git a/typedflow/typedflow.py b/typedflow/typedflow.py index 8185bd6..b6dc426 100644 --- a/typedflow/typedflow.py +++ b/typedflow/typedflow.py @@ -19,6 +19,10 @@ T = TypeVar('T') # serializable K = TypeVar('K') # serializable +class BatchIsEmpty(Exception): + pass + + @dataclass class Batch(Generic[T]): batch_id: int @@ -31,8 +35,18 @@ class Task(Generic[T, K]): def process(self, batch: Batch[T]) -> Batch[K]: - lst: List[K] = [self.func(item) for item in batch.data] - return Batch(batch_id=batch.batch_id, data=lst) + products: List[K] = [] + for item in batch.data: + try: + products.append(self.func(item)) + except Exception as e: + logger.warn(repr(e)) + continue + if len(products) > 0: + return Batch[K](batch_id=batch.batch_id, + data=products) + else: + raise BatchIsEmpty() @dataclass @@ -97,7 +111,6 @@ class Pipeline: for batch in self.loader.load(): try: product: Batch = _run(batch, self.pipeline) - except Exception as e: - logger.warn(repr(e)) + except BatchIsEmpty: continue self.dumper.dump(product)
tarohi24/typedflow
885708ac898ab55f2cd467b54695ccf4c468edc8
diff --git a/typedflow/tests/typedflow/test_task.py b/typedflow/tests/typedflow/test_task.py index 3294062..93e6463 100644 --- a/typedflow/tests/typedflow/test_task.py +++ b/typedflow/tests/typedflow/test_task.py @@ -77,7 +77,7 @@ def test_process(pl, capsys): def test_except_batch(invalid_pl, capsys): invalid_pl.run() out, _ = capsys.readouterr() - assert out == '' + assert out == '15\n12\n' def test_multibatch_process(mutlibatch_pl, capsys):
Batch doesn't flow if any items in it has an error even if the majority isn't troublesome
0.0
885708ac898ab55f2cd467b54695ccf4c468edc8
[ "typedflow/tests/typedflow/test_task.py::test_except_batch" ]
[ "typedflow/tests/typedflow/test_task.py::test_process", "typedflow/tests/typedflow/test_task.py::test_multibatch_process", "typedflow/tests/typedflow/test_task.py::test_multibatch_ids" ]
{ "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false }
2019-11-02 10:00:52+00:00
mit
5,833
tarohi24__typedflow-68
diff --git a/typedflow/nodes/base.py b/typedflow/nodes/base.py index ece0895..b9853f9 100644 --- a/typedflow/nodes/base.py +++ b/typedflow/nodes/base.py @@ -113,7 +113,8 @@ class ConsumerNode: None """ assert len(self.precs) == 0, 'Some arguments have been already set' - self.precs: Dict[str, ProviderNode] = args + for name, prec in args.items(): + self.set_upstream_node(name, prec) return self
tarohi24/typedflow
2127e74314d2b97d596cfc12ed8fb257bb688d6f
diff --git a/typedflow/tests/flow/test_flow.py b/typedflow/tests/flow/test_flow.py index aa31917..7682475 100644 --- a/typedflow/tests/flow/test_flow.py +++ b/typedflow/tests/flow/test_flow.py @@ -209,3 +209,4 @@ def test_declare_inputs_when_definition_with_multiple_args(): node_dump = DumpNode(dump)({'a': node_task}) flow = Flow([node_dump, ]) flow.typecheck() + assert node_task.cache_table.life == 1
The new syntax doesn't work It doesn't accept args in the correct way. For instance, life of cache tables are never incremented.
0.0
2127e74314d2b97d596cfc12ed8fb257bb688d6f
[ "typedflow/tests/flow/test_flow.py::test_declare_inputs_when_definition_with_multiple_args" ]
[ "typedflow/tests/flow/test_flow.py::test_flow_run", "typedflow/tests/flow/test_flow.py::test_typecheck_success", "typedflow/tests/flow/test_flow.py::test_typecheck_failure", "typedflow/tests/flow/test_flow.py::test_incoming_multiple_node", "typedflow/tests/flow/test_flow.py::test_arg_inheritance", "typedflow/tests/flow/test_flow.py::test_declare_inputs_when_definition" ]
{ "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false }
2019-12-10 15:26:34+00:00
mit
5,834