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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
fetchai__tools-pocketbook-16
|
diff --git a/pocketbook/cli.py b/pocketbook/cli.py
index 27187da..6424598 100644
--- a/pocketbook/cli.py
+++ b/pocketbook/cli.py
@@ -11,7 +11,7 @@ from .commands.list import run_list
from .commands.transfer import run_transfer
from .commands.rename import run_rename
from .disclaimer import display_disclaimer
-from .utils import NetworkUnavailableError
+from .utils import NetworkUnavailableError, checked_address
def parse_commandline():
@@ -33,7 +33,7 @@ def parse_commandline():
parser_add = subparsers.add_parser('add', help='Adds an address to the address book')
parser_add.add_argument('name', help='The name of the key')
- parser_add.add_argument('address', type=Address, help='The account address')
+ parser_add.add_argument('address', type=checked_address, help='The account address')
parser_add.set_defaults(handler=run_add)
parser_transfer = subparsers.add_parser('transfer')
diff --git a/pocketbook/utils.py b/pocketbook/utils.py
index 7298c64..a46f608 100644
--- a/pocketbook/utils.py
+++ b/pocketbook/utils.py
@@ -1,3 +1,4 @@
+from fetchai.ledger.crypto import Address
class NetworkUnavailableError(Exception):
@@ -23,3 +24,11 @@ def create_api(name: str):
pass
raise NetworkUnavailableError()
+
+
+def checked_address(address):
+ try:
+ return Address(address)
+ except:
+ raise RuntimeError('Unable to convert {} into and address. The address needs to be a base58 encoded value'.format(address))
+
|
fetchai/tools-pocketbook
|
a2498677031f48b82f9e8a009cae26d46d2efba0
|
diff --git a/tests/test_utils.py b/tests/test_utils.py
index a0eee66..a752b53 100644
--- a/tests/test_utils.py
+++ b/tests/test_utils.py
@@ -1,7 +1,10 @@
import unittest
from unittest.mock import MagicMock, patch
-from pocketbook.utils import get_balance, get_stake, NetworkUnavailableError
+from fetchai.ledger.crypto import Address, Entity
+
+from pocketbook.utils import get_balance, get_stake, NetworkUnavailableError, checked_address
+
class UtilsTests(unittest.TestCase):
@@ -14,7 +17,6 @@ class UtilsTests(unittest.TestCase):
api.tokens.balance.assert_called_once_with('some address')
-
def test_get_stake(self):
api = MagicMock()
api.tokens.stake.return_value = 50000000000
@@ -26,7 +28,6 @@ class UtilsTests(unittest.TestCase):
@patch('fetchai.ledger.api.LedgerApi')
def test_create_api(self, MockLedgerApi):
-
# normal use
from pocketbook.utils import create_api
create_api('super-duper-net')
@@ -36,10 +37,23 @@ class UtilsTests(unittest.TestCase):
@patch('fetchai.ledger.api.LedgerApi', side_effect=[RuntimeError('Bad Error')])
def test_error_on_create_api(self, MockLedgerApi):
-
# internal error case
from pocketbook.utils import create_api
with self.assertRaises(NetworkUnavailableError):
create_api('super-duper-net')
- MockLedgerApi.assert_called_once_with(network='super-duper-net')
\ No newline at end of file
+ MockLedgerApi.assert_called_once_with(network='super-duper-net')
+
+ def test_valid_address(self):
+ entity = Entity()
+ address = Address(entity)
+
+ recovered_address = checked_address(str(address))
+
+ self.assertEqual(str(recovered_address), str(address))
+
+ def test_invalid_address_exception(self):
+ with self.assertRaises(RuntimeError) as ctx:
+ checked_address('foo-bar-baz')
+ self.assertEqual(str(ctx.exception),
+ 'Unable to convert foo-bar-baz into and address. The address needs to be a base58 encoded value')
|
Unknown address generates cryptic error
If you do a transfer to an address you do not have in the book, it generates this error:
```
Error: Unable to parse address, incorrect size
```
... instead of something like "Unknown address 'octopus'"
|
0.0
|
a2498677031f48b82f9e8a009cae26d46d2efba0
|
[
"tests/test_utils.py::UtilsTests::test_create_api",
"tests/test_utils.py::UtilsTests::test_error_on_create_api",
"tests/test_utils.py::UtilsTests::test_get_balance",
"tests/test_utils.py::UtilsTests::test_get_stake",
"tests/test_utils.py::UtilsTests::test_invalid_address_exception",
"tests/test_utils.py::UtilsTests::test_valid_address"
] |
[] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-01-08 15:35:09+00:00
|
apache-2.0
| 2,335 |
|
fetchai__tools-pocketbook-19
|
diff --git a/pocketbook/cli.py b/pocketbook/cli.py
index 19c0cd9..65bddfd 100644
--- a/pocketbook/cli.py
+++ b/pocketbook/cli.py
@@ -4,13 +4,13 @@ import sys
from . import __version__
from .commands.add import run_add
from .commands.create import run_create
+from .commands.delete import run_delete
from .commands.display import run_display
from .commands.list import run_list
from .commands.rename import run_rename
from .commands.transfer import run_transfer
-from .commands.delete import run_delete
from .disclaimer import display_disclaimer
-from .utils import NetworkUnavailableError, checked_address
+from .utils import NetworkUnavailableError, checked_address, to_canonical, MINIMUM_FRACTIONAL_FET
def parse_commandline():
@@ -38,8 +38,10 @@ def parse_commandline():
parser_transfer = subparsers.add_parser('transfer')
parser_transfer.add_argument('destination',
help='The destination address either a name in the address book or an address')
- parser_transfer.add_argument('amount', type=int, help='The amount in whole FET to be transferred')
+ parser_transfer.add_argument('amount', type=to_canonical, help='The amount of FET to be transferred')
parser_transfer.add_argument('--from', dest='from_address', help='The signing account, required for multi-sig')
+ parser_transfer.add_argument('-R', '--charge-rate', type=to_canonical, default=to_canonical(MINIMUM_FRACTIONAL_FET),
+ help='The charge rate associated with this transaction')
parser_transfer.add_argument('signers', nargs='+', help='The series of key names needed to sign the transaction')
parser_transfer.set_defaults(handler=run_transfer)
diff --git a/pocketbook/commands/transfer.py b/pocketbook/commands/transfer.py
index cc9dbcb..eadda8a 100644
--- a/pocketbook/commands/transfer.py
+++ b/pocketbook/commands/transfer.py
@@ -6,21 +6,25 @@ def run_transfer(args):
from pocketbook.address_book import AddressBook
from pocketbook.key_store import KeyStore
- from pocketbook.utils import create_api
+ from pocketbook.utils import create_api, from_canonical, token_amount
address_book = AddressBook()
key_store = KeyStore()
# choose the destination
+ destination_name = '{}:'.format(args.destination)
if args.destination in address_book.keys():
destination = address_book.lookup_address(args.destination)
else:
destination = key_store.lookup_address(args.destination)
if destination is None:
destination = Address(args.destination)
+ destination_name = ''
- # change the amount
- amount = args.amount * 10000000000
+ # convert the amount
+ amount = args.amount
+ charge_rate = args.charge_rate
+ computed_amount = from_canonical(amount)
# check all the signers make sense
for signer in args.signers:
@@ -39,11 +43,24 @@ def run_transfer(args):
else:
raise RuntimeError('Unable to determine from account')
+ required_ops = len(args.signers)
+ fee = required_ops * charge_rate
+ computed_fee = from_canonical(fee)
+ computed_total = computed_amount + computed_fee
+ computed_charge_rate = from_canonical(charge_rate)
+
print('Network....:', args.network)
print('From.......:', str(from_address_name))
- print('Signers....:', args.signers)
- print('Destination:', str(destination))
- print('Amount.....:', args.amount, 'FET')
+ print('Signer(s)..:', ','.join(args.signers))
+ print('Destination:', destination_name, str(destination))
+ print('Amount.....:', token_amount(computed_amount))
+ print('Fee........:', token_amount(computed_fee))
+
+ # only display extended fee information if something other than the default it selected
+ if charge_rate != 1:
+ print(' : {} ops @ {}'.format(required_ops, token_amount(computed_charge_rate)))
+
+ print('Total......:', token_amount(computed_total), '(Amount + Fee)')
print()
input('Press enter to continue')
@@ -62,7 +79,8 @@ def run_transfer(args):
from_address = Address(address_book.lookup_address(from_address_name))
# build up the basic transaction information
- tx = api.tokens._create_skeleton_tx(len(entities.values()))
+ tx = api.tokens._create_skeleton_tx(required_ops)
+ tx.charge_rate = charge_rate
tx.from_address = Address(from_address)
tx.add_transfer(destination, amount)
for entity in entities.values():
diff --git a/pocketbook/utils.py b/pocketbook/utils.py
index 37249bf..c9bc94e 100644
--- a/pocketbook/utils.py
+++ b/pocketbook/utils.py
@@ -1,18 +1,56 @@
+from typing import Union
+
from fetchai.ledger.crypto import Address
+CANONICAL_FET_UNIT = 1e10
+MINIMUM_FRACTIONAL_FET = 1 / CANONICAL_FET_UNIT
+
class NetworkUnavailableError(Exception):
pass
+class ConversionError(RuntimeError):
+ def __init__(self, msg):
+ super().__init__(msg)
+
+
+def to_canonical(value: Union[float, int]) -> int:
+ value = float(value)
+ if value < 0:
+ raise ConversionError('Unable to convert negative token amount: {}'.format(value))
+ if value < MINIMUM_FRACTIONAL_FET:
+ raise ConversionError(
+ 'Converted value {} is below minimum transfer value: {}'.format(value, MINIMUM_FRACTIONAL_FET))
+
+ return int(value * CANONICAL_FET_UNIT)
+
+
+def from_canonical(value: int) -> float:
+ value = int(value)
+ if value < 0:
+ raise ConversionError('Unable to convert negative token amount: {}'.format(value))
+
+ return value / int(CANONICAL_FET_UNIT)
+
+
+def token_amount(value: float) -> str:
+ """
+ Converts a token amount into a fixed precision string value
+ :param value: The input value to display
+ :return: The converted value
+ """
+ return '{:6.10f} FET'.format(float(value))
+
+
def get_balance(api, address):
balance = int(api.tokens.balance(address))
- return balance / 10000000000
+ return from_canonical(balance)
def get_stake(api, addresss):
stake = int(api.tokens.stake(addresss))
- return stake / 10000000000
+ return from_canonical(stake)
def create_api(name: str):
|
fetchai/tools-pocketbook
|
d7cc8a1bbc00aa0439fd1709b4425f1c1f33e9d0
|
diff --git a/tests/commands/test_transfer.py b/tests/commands/test_transfer.py
index 456e80f..5835785 100644
--- a/tests/commands/test_transfer.py
+++ b/tests/commands/test_transfer.py
@@ -1,5 +1,5 @@
import unittest
-from unittest.mock import patch, Mock, MagicMock
+from unittest.mock import patch, Mock, MagicMock, PropertyMock
from fetchai.ledger.crypto import Entity, Address
from fetchai.ledger.serialisation.transaction import encode_transaction
@@ -41,6 +41,7 @@ class TransferCommandUnitTests(unittest.TestCase):
mock_create_api.return_value = api
tx = MagicMock()
+ tx.charge_rate = PropertyMock()
api.tokens._create_skeleton_tx.return_value = tx
api.tokens._post_tx_json.return_value = '0xTransactionHexId'
@@ -49,7 +50,8 @@ class TransferCommandUnitTests(unittest.TestCase):
args = Mock()
args.destination = person2.name
- args.amount = 2
+ args.amount = 20000000000
+ args.charge_rate = 1
args.signers = [person1.name]
args.from_address = None
args.network = 'super-duper-net'
@@ -95,7 +97,8 @@ class TransferCommandUnitTests(unittest.TestCase):
args = Mock()
args.destination = person2.name
- args.amount = 2
+ args.amount = 20000000000
+ args.charge_rate = 1
args.signers = [person1.name]
args.from_address = None
args.network = 'super-duper-net'
@@ -103,14 +106,6 @@ class TransferCommandUnitTests(unittest.TestCase):
from pocketbook.commands.transfer import run_transfer
run_transfer(args)
- # mock_create_api.assert_called_once_with('super-duper-net')
- # key_store.load_key.assert_called_once_with(person1.name, 'weak-password')
- # api.tokens._create_skeleton_tx.assert_called_once_with(1) # single signature
- # tx.add_transfer.assert_called_once_with(person2.address, 20000000000)
- # mock_encode_transaction.assert_called_once_with(tx, [person1.entity])
- # api.tokens._post_tx_json.assert_called_once_with(encoded_tx, 'transfer')
- # api.sync.assert_called_once_with('0xTransactionHexId')
-
@patch('getpass.getpass', side_effect=['weak-password'])
@patch('builtins.input', return_value='')
@patch('fetchai.ledger.serialisation.transaction.encode_transaction', spec=encode_transaction)
@@ -141,7 +136,8 @@ class TransferCommandUnitTests(unittest.TestCase):
args = Mock()
args.destination = str(person2.address)
- args.amount = 2
+ args.amount = 20000000000
+ args.charge_rate = 1
args.signers = [person1.name]
args.from_address = None
args.network = 'super-duper-net'
@@ -189,7 +185,8 @@ class TransferCommandUnitTests(unittest.TestCase):
args = Mock()
args.destination = person2.name
- args.amount = 2
+ args.amount = 20000000000
+ args.charge_rate = 1
args.signers = [person1.name]
args.from_address = multisig.name
args.network = 'super-duper-net'
@@ -229,7 +226,8 @@ class TransferCommandUnitTests(unittest.TestCase):
args = Mock()
args.destination = person2.name
- args.amount = 2
+ args.amount = 20000000000
+ args.charge_rate = 1
args.signers = [person1.name]
args.from_address = person2.name
args.network = 'super-duper-net'
@@ -263,7 +261,8 @@ class TransferCommandUnitTests(unittest.TestCase):
args = Mock()
args.destination = person2.name
- args.amount = 2
+ args.amount = 20000000000
+ args.charge_rate = 1
args.signers = [person1.name]
args.from_address = 'some-one-missing'
args.network = 'super-duper-net'
@@ -297,7 +296,8 @@ class TransferCommandUnitTests(unittest.TestCase):
args = Mock()
args.destination = person2.name
- args.amount = 2
+ args.amount = 20000000000
+ args.charge_rate = 1
args.signers = []
args.from_address = 'some-one-missing'
args.network = 'super-duper-net'
diff --git a/tests/test_utils.py b/tests/test_utils.py
index a752b53..7b18a51 100644
--- a/tests/test_utils.py
+++ b/tests/test_utils.py
@@ -1,16 +1,18 @@
import unittest
+from typing import Union
from unittest.mock import MagicMock, patch
from fetchai.ledger.crypto import Address, Entity
-from pocketbook.utils import get_balance, get_stake, NetworkUnavailableError, checked_address
+from pocketbook.utils import get_balance, get_stake, NetworkUnavailableError, checked_address, to_canonical, \
+ from_canonical, token_amount, ConversionError
class UtilsTests(unittest.TestCase):
def test_get_balance(self):
api = MagicMock()
- api.tokens.balance.return_value = 100000000000
+ api.tokens.balance.return_value = to_canonical(10)
balance = get_balance(api, 'some address')
self.assertEqual(balance, 10)
@@ -19,7 +21,7 @@ class UtilsTests(unittest.TestCase):
def test_get_stake(self):
api = MagicMock()
- api.tokens.stake.return_value = 50000000000
+ api.tokens.stake.return_value = to_canonical(5)
stake = get_stake(api, 'some address')
self.assertEqual(stake, 5)
@@ -57,3 +59,54 @@ class UtilsTests(unittest.TestCase):
checked_address('foo-bar-baz')
self.assertEqual(str(ctx.exception),
'Unable to convert foo-bar-baz into and address. The address needs to be a base58 encoded value')
+
+
+class FetConversionTests(unittest.TestCase):
+ def assertIsConvertible(self, canonical: int, value: Union[int, float]):
+ converted_canonical = to_canonical(value)
+ self.assertEqual(canonical, converted_canonical)
+ self.assertEqual(float(value), from_canonical(converted_canonical))
+
+ def test_canonical_conversions(self):
+ self.assertIsConvertible(10000000000, 1)
+ self.assertIsConvertible(10000000000, 1.0)
+ self.assertIsConvertible(12000000000, 1.2)
+ self.assertIsConvertible(10020000000, 1.002)
+ self.assertIsConvertible(1, 1e-10)
+ self.assertIsConvertible(100, 1e-8)
+ self.assertIsConvertible(10000000, 1e-3)
+ self.assertIsConvertible(10000, 1e-6)
+ self.assertIsConvertible(10, 1e-9)
+ self.assertIsConvertible(10000000000000, 1e3)
+ self.assertIsConvertible(10000000000000000, 1e6)
+ self.assertIsConvertible(10000000000000000000, 1e9)
+
+ def test_token_amount_formatting(self):
+ self.assertEqual(token_amount(1), '1.0000000000 FET')
+ self.assertEqual(token_amount(1.0), '1.0000000000 FET')
+ self.assertEqual(token_amount(1.2), '1.2000000000 FET')
+ self.assertEqual(token_amount(1.002), '1.0020000000 FET')
+ self.assertEqual(token_amount(1e-10), '0.0000000001 FET')
+ self.assertEqual(token_amount(1e-8), '0.0000000100 FET')
+ self.assertEqual(token_amount(1e-3), '0.0010000000 FET')
+ self.assertEqual(token_amount(1e-6), '0.0000010000 FET')
+ self.assertEqual(token_amount(1e-9), '0.0000000010 FET')
+ self.assertEqual(token_amount(1e3), '1000.0000000000 FET')
+ self.assertEqual(token_amount(1e6), '1000000.0000000000 FET')
+ self.assertEqual(token_amount(1e9), '1000000000.0000000000 FET')
+
+ def test_invalid_negative_to_canonical(self):
+ with self.assertRaises(ConversionError):
+ to_canonical(-10)
+
+ def test_invalid_too_small_to_canonical(self):
+ with self.assertRaises(ConversionError):
+ to_canonical(1e-20)
+
+ def test_invalid_non_number_to_canonical(self):
+ with self.assertRaises(ValueError):
+ to_canonical('foo-bar')
+
+ def test_invalid_negative_from_canonical(self):
+ with self.assertRaises(ConversionError):
+ from_canonical(-10)
|
Pocketbook doesn't show fees
Fee paid, expected fee, and ability to raise that would be helpful.
|
0.0
|
d7cc8a1bbc00aa0439fd1709b4425f1c1f33e9d0
|
[
"tests/commands/test_transfer.py::TransferCommandUnitTests::test_error_case_with_bad_args",
"tests/commands/test_transfer.py::TransferCommandUnitTests::test_error_when_from_field_is_invalid",
"tests/commands/test_transfer.py::TransferCommandUnitTests::test_error_when_signer_not_present",
"tests/commands/test_transfer.py::TransferCommandUnitTests::test_multisig_transfer",
"tests/commands/test_transfer.py::TransferCommandUnitTests::test_transfer_to_addr_dest",
"tests/commands/test_transfer.py::TransferCommandUnitTests::test_transfer_to_key_dest",
"tests/commands/test_transfer.py::TransferCommandUnitTests::test_transfer_to_new_dest",
"tests/test_utils.py::UtilsTests::test_create_api",
"tests/test_utils.py::UtilsTests::test_error_on_create_api",
"tests/test_utils.py::UtilsTests::test_get_balance",
"tests/test_utils.py::UtilsTests::test_get_stake",
"tests/test_utils.py::UtilsTests::test_invalid_address_exception",
"tests/test_utils.py::UtilsTests::test_valid_address",
"tests/test_utils.py::FetConversionTests::test_canonical_conversions",
"tests/test_utils.py::FetConversionTests::test_invalid_negative_from_canonical",
"tests/test_utils.py::FetConversionTests::test_invalid_negative_to_canonical",
"tests/test_utils.py::FetConversionTests::test_invalid_non_number_to_canonical",
"tests/test_utils.py::FetConversionTests::test_invalid_too_small_to_canonical",
"tests/test_utils.py::FetConversionTests::test_token_amount_formatting"
] |
[] |
{
"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
}
|
2020-01-08 18:22:16+00:00
|
apache-2.0
| 2,336 |
|
fetchai__tools-pocketbook-28
|
diff --git a/pocketbook/commands/list.py b/pocketbook/commands/list.py
index 8a8d8c1..7db9d6e 100644
--- a/pocketbook/commands/list.py
+++ b/pocketbook/commands/list.py
@@ -1,5 +1,5 @@
from fnmatch import fnmatch
-
+import warnings
def _should_display(item, patterns):
return any([fnmatch(item, p) for p in patterns])
@@ -11,6 +11,9 @@ def run_list(args):
from pocketbook.table import Table
from pocketbook.utils import create_api, get_balance, get_stake, token_amount
+ # the latest version of SDK will generate warning because we are using the staking API
+ warnings.simplefilter('ignore')
+
address_book = AddressBook()
key_store = KeyStore()
keys = key_store.list_keys()
diff --git a/pocketbook/commands/transfer.py b/pocketbook/commands/transfer.py
index d88e64c..853afd5 100644
--- a/pocketbook/commands/transfer.py
+++ b/pocketbook/commands/transfer.py
@@ -85,10 +85,25 @@ def run_transfer(args):
tx = TokenTxFactory.transfer(Address(from_address), destination, amount, 0, signers)
tx.charge_rate = charge_rate
tx.charge_limit = required_ops
+ api.set_validity_period(tx)
for entity in signers:
tx.sign(entity)
+ tx_digest = api.submit_signed_tx(tx)
+ print('TX: 0x{} submitted'.format(tx_digest))
+
# submit the transaction
- print('Submitting TX...')
- api.sync(api.submit_signed_tx(tx))
- print('Submitting TX...complete')
+ print('Waiting for transaction to be confirmed...')
+ api.sync(tx_digest)
+ print('Waiting for transaction to be confirmed...complete')
+
+ # determine if there is a block explorer link to be printed
+ explorer_link = None
+ if args.network == 'mainnet':
+ explorer_link = 'https://explore.fetch.ai/transactions/0x{}'.format(tx_digest)
+ elif args.network == 'testnet':
+ explorer_link = 'https://explore-testnet.fetch.ai/transactions/0x{}'.format(tx_digest)
+
+ if explorer_link is not None:
+ print()
+ print('See {} for more details'.format(explorer_link))
\ No newline at end of file
diff --git a/setup.py b/setup.py
index ab98625..b457b8d 100644
--- a/setup.py
+++ b/setup.py
@@ -32,7 +32,7 @@ setup(
'Programming Language :: Python :: 3.7',
],
install_requires=[
- 'fetchai-ledger-api==1.0.0',
+ 'fetchai-ledger-api==1.0.1',
'toml',
'colored',
],
|
fetchai/tools-pocketbook
|
8dbcabfed3ace459251e0e91afaa9641a71087d4
|
diff --git a/tests/commands/test_transfer.py b/tests/commands/test_transfer.py
index 17dfc0f..88d8665 100644
--- a/tests/commands/test_transfer.py
+++ b/tests/commands/test_transfer.py
@@ -65,6 +65,7 @@ class TransferCommandUnitTests(unittest.TestCase):
[person1.entity])
self.assertEqual(tx.charge_rate, 1)
self.assertEqual(tx.charge_limit, 1)
+ api.set_validity_period.assert_called_once_with(tx)
tx.sign.assert_called_with(person1.entity)
# submission of the transaction
@@ -118,6 +119,7 @@ class TransferCommandUnitTests(unittest.TestCase):
[person1.entity])
self.assertEqual(tx.charge_rate, 2)
self.assertEqual(tx.charge_limit, 1)
+ api.set_validity_period.assert_called_once_with(tx)
tx.sign.assert_called_with(person1.entity)
# submission of the transaction
@@ -170,6 +172,7 @@ class TransferCommandUnitTests(unittest.TestCase):
[person1.entity])
self.assertEqual(tx.charge_rate, 1)
self.assertEqual(tx.charge_limit, 1)
+ api.set_validity_period.assert_called_once_with(tx)
tx.sign.assert_called_with(person1.entity)
# submission of the transaction
@@ -226,6 +229,7 @@ class TransferCommandUnitTests(unittest.TestCase):
[person1.entity])
self.assertEqual(tx.charge_rate, 1)
self.assertEqual(tx.charge_limit, 1)
+ api.set_validity_period.assert_called_once_with(tx)
tx.sign.assert_called_with(person1.entity)
# submission of the transaction
|
Pocketbook transfer to show transaction ID
It would be great if doing a transfer using pocketbook resulted in the transaction ID being posted so that it can be fed into the block-explorer, and also sent to people as "verification" of a transaction being sent.
|
0.0
|
8dbcabfed3ace459251e0e91afaa9641a71087d4
|
[
"tests/commands/test_transfer.py::TransferCommandUnitTests::test_multisig_transfer",
"tests/commands/test_transfer.py::TransferCommandUnitTests::test_transfer_to_addr_dest",
"tests/commands/test_transfer.py::TransferCommandUnitTests::test_transfer_to_key_dest",
"tests/commands/test_transfer.py::TransferCommandUnitTests::test_transfer_to_new_dest"
] |
[
"tests/commands/test_transfer.py::TransferCommandUnitTests::test_error_case_with_bad_args",
"tests/commands/test_transfer.py::TransferCommandUnitTests::test_error_when_from_field_is_invalid",
"tests/commands/test_transfer.py::TransferCommandUnitTests::test_error_when_signer_not_present"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-02-11 13:52:55+00:00
|
apache-2.0
| 2,337 |
|
fetzerch__kasserver-6
|
diff --git a/kasserver/__init__.py b/kasserver/__init__.py
index 7f1364a..86d55c5 100644
--- a/kasserver/__init__.py
+++ b/kasserver/__init__.py
@@ -51,11 +51,8 @@ class KasServer:
self._get_credentials()
def _get_credentials(self):
- def _sha1(string):
- return None if not string else hashlib.sha1(string.encode()).hexdigest()
-
self._username = os.environ.get("KASSERVER_USER", None)
- self._auth_sha1 = _sha1(os.environ.get("KASSERVER_PASSWORD", None))
+ self._password = os.environ.get("KASSERVER_PASSWORD", None)
if self._username:
return
@@ -63,7 +60,7 @@ class KasServer:
try:
info = netrc.netrc().authenticators(server)
self._username = info[0]
- self._auth_sha1 = _sha1(info[2])
+ self._password = info[2]
except (FileNotFoundError, netrc.NetrcParseError) as err:
LOGGER.warning(
"Cannot load credentials for %s from .netrc: %s", server, err
@@ -72,8 +69,8 @@ class KasServer:
def _request(self, request, params):
request = {
"KasUser": self._username,
- "KasAuthType": "sha1",
- "KasAuthData": self._auth_sha1,
+ "KasAuthType": "plain",
+ "KasAuthData": self._password,
"KasRequestType": request,
"KasRequestParams": params,
}
|
fetzerch/kasserver
|
bcf115dac60e5da2d03c172e9ad2786e708f773e
|
diff --git a/tests/test_kasserver.py b/tests/test_kasserver.py
index ca18a2f..b7be822 100644
--- a/tests/test_kasserver.py
+++ b/tests/test_kasserver.py
@@ -36,7 +36,6 @@ LOGGER = logging.getLogger(__name__)
USERNAME = "username"
PASSWORD = "password"
-PASSWORD_SHA1 = "5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8"
# pylint: disable=protected-access
# pylint: disable=attribute-defined-outside-init
@@ -56,7 +55,7 @@ class TestKasServerCredentials:
netrc.side_effect = FileNotFoundError("")
server = KasServer()
assert server._username == USERNAME
- assert server._auth_sha1 == PASSWORD_SHA1
+ assert server._password == PASSWORD
@staticmethod
@mock.patch.dict("os.environ", {})
@@ -66,7 +65,7 @@ class TestKasServerCredentials:
netrc.return_value.authenticators.return_value = (USERNAME, "", PASSWORD)
server = KasServer()
assert server._username == USERNAME
- assert server._auth_sha1 == PASSWORD_SHA1
+ assert server._password == PASSWORD
@staticmethod
@mock.patch.dict("os.environ", {})
@@ -76,7 +75,7 @@ class TestKasServerCredentials:
netrc.side_effect = FileNotFoundError("")
server = KasServer()
assert not server._username
- assert not server._auth_sha1
+ assert not server._password
class TestKasServer:
@@ -186,8 +185,8 @@ class TestKasServer:
kasserver._request(self.REQUEST_TYPE, self.REQUEST_PARAMS)
request = {
"KasUser": USERNAME,
- "KasAuthType": "sha1",
- "KasAuthData": PASSWORD_SHA1,
+ "KasAuthType": "plain",
+ "KasAuthData": PASSWORD,
"KasRequestType": self.REQUEST_TYPE,
"KasRequestParams": self.REQUEST_PARAMS,
}
|
Switch from 'sha1' to 'plain' authentication method
The following E-Mail from All-Inkl support reached me today:
> Our system has detected that you are using the KAS API, which means that your custom scripts gain access to several features of the technical administration panel (KAS). So please forward the following information to the developer of those custom scripts as appropriate.
>
> The authentication method "sha1" which is used by your custom scripts is deprecated and support for this authentication method will be gradually discontinued starting December 2022. In order to further use your custom scripts, an adjustment is necessary in the following accounts:
>
> account : date of last sha1 authentication
> XXXXXXXX : 2022-08-01 22:19:25
>
> Here's an example of how such a script code currently looks like:
>
> ```php
> $auth=array(
> 'kas_login' => 'XXXXXXXX',
> 'kas_auth_type' => 'sha1',
> 'kas_auth_data' => sha1('myPassword')
> )
> ```
>
> Please alter your scripts in a way so that they use the new authentication method "plain" instead. An example how it should look afterwards:
>
> ```php
> $auth=array(
> 'kas_login' => 'XXXXXXXX',
> 'kas_auth_type' => 'plain',
> 'kas_auth_data' => 'myPassword'
> )
> ```
>
> You can find a full documentation of the KAS API under:
>
> http://kasapi.kasserver.com/dokumentation/phpdoc/
|
0.0
|
bcf115dac60e5da2d03c172e9ad2786e708f773e
|
[
"tests/test_kasserver.py::TestKasServerCredentials::test_getcredentials_from_env",
"tests/test_kasserver.py::TestKasServerCredentials::test_getcredentials_from_netrc",
"tests/test_kasserver.py::TestKasServerCredentials::test_getcredentials_failed_netrc",
"tests/test_kasserver.py::TestKasServer::test_request"
] |
[
"tests/test_kasserver.py::TestKasServer::test_request_failed",
"tests/test_kasserver.py::TestKasServer::test_request_floodprotection",
"tests/test_kasserver.py::TestKasServer::test_getdnsrecords",
"tests/test_kasserver.py::TestKasServer::test_getdnsrecord",
"tests/test_kasserver.py::TestKasServer::test_getdnsrecord_notfound",
"tests/test_kasserver.py::TestKasServer::test_adddnsrecord",
"tests/test_kasserver.py::TestKasServer::test_updatednsrecord",
"tests/test_kasserver.py::TestKasServer::test_deletednsrecord",
"tests/test_kasserver.py::TestKasServer::test_deletedbsrecord_notfound",
"tests/test_kasserver.py::TestKasServerUtils::test_split_dqdn"
] |
{
"failed_lite_validators": [
"has_hyperlinks"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-08-03 22:05:00+00:00
|
mit
| 2,338 |
|
fgmacedo__python-statemachine-343
|
diff --git a/docs/releases/2.0.0.md b/docs/releases/2.0.0.md
index f20779c..67c375a 100644
--- a/docs/releases/2.0.0.md
+++ b/docs/releases/2.0.0.md
@@ -49,6 +49,12 @@ See {ref}`internal transition` for more details.
guards using decorators is now possible.
+## Bugfixes in 2.0
+
+- [#341](https://github.com/fgmacedo/python-statemachine/issues/341): Fix dynamic dispatch
+ on methods with default parameters.
+
+
## Backward incompatible changes in 2.0
- TODO
diff --git a/statemachine/dispatcher.py b/statemachine/dispatcher.py
index d3f2c42..29841a8 100644
--- a/statemachine/dispatcher.py
+++ b/statemachine/dispatcher.py
@@ -1,9 +1,9 @@
-import inspect
from collections import namedtuple
from functools import wraps
from operator import attrgetter
from .exceptions import AttrNotFound
+from .signature import SignatureAdapter
from .utils import ugettext as _
@@ -23,42 +23,6 @@ class ObjectConfig(namedtuple("ObjectConfig", "obj skip_attrs")):
return cls(obj, set())
-def methodcaller(method):
- """Build a wrapper that adapts the received arguments to the inner method signature"""
-
- # spec is a named tuple ArgSpec(args, varargs, keywords, defaults)
- # args is a list of the argument names (it may contain nested lists)
- # varargs and keywords are the names of the * and ** arguments or None
- # defaults is a tuple of default argument values or None if there are no default arguments
- spec = inspect.getfullargspec(method)
- keywords = spec.varkw
- expected_args = list(spec.args)
- expected_kwargs = spec.defaults or {}
-
- # discart "self" argument for bounded methods
- if hasattr(method, "__self__") and expected_args and expected_args[0] == "self":
- expected_args = expected_args[1:]
-
- @wraps(method)
- def wrapper(*args, **kwargs):
- if spec.varargs is not None:
- filtered_args = args
- else:
- filtered_args = [
- kwargs.get(k, (args[idx] if idx < len(args) else None))
- for idx, k in enumerate(expected_args)
- ]
-
- if keywords is not None:
- filtered_kwargs = kwargs
- else:
- filtered_kwargs = {k: v for k, v in kwargs.items() if k in expected_kwargs}
-
- return method(*filtered_args, **filtered_kwargs)
-
- return wrapper
-
-
def _get_func_by_attr(attr, *configs):
for config in configs:
if attr in config.skip_attrs:
@@ -84,7 +48,7 @@ def ensure_callable(attr, *objects):
has the given ``attr``.
"""
if callable(attr) or isinstance(attr, property):
- return methodcaller(attr)
+ return SignatureAdapter.wrap(attr)
# Setup configuration if not present to normalize the internal API
configs = [ObjectConfig.from_obj(obj) for obj in objects]
@@ -102,7 +66,7 @@ def ensure_callable(attr, *objects):
return wrapper
- return methodcaller(func)
+ return SignatureAdapter.wrap(func)
def resolver_factory(*objects):
diff --git a/statemachine/signature.py b/statemachine/signature.py
new file mode 100644
index 0000000..bef064b
--- /dev/null
+++ b/statemachine/signature.py
@@ -0,0 +1,148 @@
+import itertools
+from inspect import BoundArguments
+from inspect import Parameter
+from inspect import Signature
+from typing import Any
+from typing import Callable
+
+
+class SignatureAdapter(Signature):
+ method: Callable[..., Any]
+
+ @classmethod
+ def wrap(cls, method):
+ """Build a wrapper that adapts the received arguments to the inner ``method`` signature"""
+
+ sig = cls.from_callable(method)
+ sig.method = method
+ sig.__name__ = method.__name__
+ return sig
+
+ def __call__(self, *args: Any, **kwargs: Any) -> Any:
+ ba = self.bind_expected(*args, **kwargs)
+ return self.method(*ba.args, **ba.kwargs)
+
+ def bind_expected(self, *args: Any, **kwargs: Any) -> BoundArguments: # noqa: C901
+ """Get a BoundArguments object, that maps the passed `args`
+ and `kwargs` to the function's signature. It avoids to raise `TypeError`
+ trying to fill all the required arguments and ignoring the unknown ones.
+
+ Adapted from the internal `inspect.Signature._bind`.
+ """
+ arguments = {}
+
+ parameters = iter(self.parameters.values())
+ arg_vals = iter(args)
+ parameters_ex: Any = ()
+ kwargs_param = None
+
+ while True:
+ # Let's iterate through the positional arguments and corresponding
+ # parameters
+ try:
+ arg_val = next(arg_vals)
+ except StopIteration:
+ # No more positional arguments
+ try:
+ param = next(parameters)
+ except StopIteration:
+ # No more parameters. That's it. Just need to check that
+ # we have no `kwargs` after this while loop
+ break
+ else:
+ if param.kind == Parameter.VAR_POSITIONAL:
+ # That's OK, just empty *args. Let's start parsing
+ # kwargs
+ break
+ elif param.name in kwargs:
+ if param.kind == Parameter.POSITIONAL_ONLY:
+ msg = (
+ "{arg!r} parameter is positional only, "
+ "but was passed as a keyword"
+ )
+ msg = msg.format(arg=param.name)
+ raise TypeError(msg) from None
+ parameters_ex = (param,)
+ break
+ elif (
+ param.kind == Parameter.VAR_KEYWORD
+ or param.default is not Parameter.empty
+ ):
+ # That's fine too - we have a default value for this
+ # parameter. So, lets start parsing `kwargs`, starting
+ # with the current parameter
+ parameters_ex = (param,)
+ break
+ else:
+ # No default, not VAR_KEYWORD, not VAR_POSITIONAL,
+ # not in `kwargs`
+ parameters_ex = (param,)
+ break
+ else:
+ # We have a positional argument to process
+ try:
+ param = next(parameters)
+ except StopIteration:
+ # raise TypeError('too many positional arguments') from None
+ break
+ else:
+ if param.kind == Parameter.VAR_KEYWORD:
+ # Memorize that we have a '**kwargs'-like parameter
+ kwargs_param = param
+ break
+
+ if param.kind == Parameter.KEYWORD_ONLY:
+ # Looks like we have no parameter for this positional
+ # argument
+ # 'too many positional arguments' forgiven
+ break
+
+ if param.kind == Parameter.VAR_POSITIONAL:
+ # We have an '*args'-like argument, let's fill it with
+ # all positional arguments we have left and move on to
+ # the next phase
+ values = [arg_val]
+ values.extend(arg_vals)
+ arguments[param.name] = tuple(values)
+ break
+
+ if param.name in kwargs and param.kind != Parameter.POSITIONAL_ONLY:
+ arguments[param.name] = kwargs.pop(param.name)
+ else:
+ arguments[param.name] = arg_val
+
+ # Now, we iterate through the remaining parameters to process
+ # keyword arguments
+ for param in itertools.chain(parameters_ex, parameters):
+ if param.kind == Parameter.VAR_KEYWORD:
+ # Memorize that we have a '**kwargs'-like parameter
+ kwargs_param = param
+ continue
+
+ if param.kind == Parameter.VAR_POSITIONAL:
+ # Named arguments don't refer to '*args'-like parameters.
+ # We only arrive here if the positional arguments ended
+ # before reaching the last parameter before *args.
+ continue
+
+ param_name = param.name
+ try:
+ arg_val = kwargs.pop(param_name)
+ except KeyError:
+ # We have no value for this parameter. It's fine though,
+ # if it has a default value, or it is an '*args'-like
+ # parameter, left alone by the processing of positional
+ # arguments.
+ pass
+ else:
+ arguments[param_name] = arg_val #
+
+ if kwargs:
+ if kwargs_param is not None:
+ # Process our '**kwargs'-like parameter
+ arguments[kwargs_param.name] = kwargs # type: ignore [assignment]
+ else:
+ # 'ignoring we got an unexpected keyword argument'
+ pass
+
+ return BoundArguments(self, arguments) # type: ignore [arg-type]
|
fgmacedo/python-statemachine
|
f1afe5a28cdc8c54c1353a4cd2ca745e7051548d
|
diff --git a/tests/test_signature.py b/tests/test_signature.py
new file mode 100644
index 0000000..133e36d
--- /dev/null
+++ b/tests/test_signature.py
@@ -0,0 +1,187 @@
+import inspect
+import sys
+
+import pytest
+
+from statemachine.signature import SignatureAdapter
+
+
+def single_positional_param(a):
+ return a
+
+
+def single_default_keyword_param(a=42):
+ return a
+
+
+def args_param(*args):
+ return args
+
+
+def kwargs_param(**kwargs):
+ return kwargs
+
+
+def args_and_kwargs_param(*args, **kwargs):
+ return args, kwargs
+
+
+def positional_optional_catchall(a, b="ham", *args):
+ return a, b, args
+
+
+def ignored_param(a, b, *, c, d=10):
+ return a, b, c, d
+
+
+def positional_and_kw_arguments(source, target, event):
+ return source, target, event
+
+
+def default_kw_arguments(source: str = "A", target: str = "B", event: str = "go"):
+ return source, target, event
+
+
+class MyObject:
+ def __init__(self, value=42):
+ self.value = value
+
+ def method_no_argument(self):
+ return self.value
+
+
+class TestSignatureAdapter:
+ @pytest.mark.parametrize(
+ ("func", "args", "kwargs", "expected"),
+ [
+ (single_positional_param, [10], {}, 10),
+ (single_positional_param, [], {"a": 10}, 10),
+ pytest.param(single_positional_param, [], {}, TypeError),
+ (single_default_keyword_param, [10], {}, 10),
+ (single_default_keyword_param, [], {"a": 10}, 10),
+ pytest.param(single_default_keyword_param, [], {}, 42),
+ (MyObject().method_no_argument, [], {}, 42),
+ (MyObject().method_no_argument, ["ignored"], {"x": True}, 42),
+ (MyObject.method_no_argument, [MyObject()], {"x": True}, 42),
+ pytest.param(MyObject.method_no_argument, [], {}, TypeError),
+ (args_param, [], {}, ()),
+ (args_param, [42], {}, (42,)),
+ (args_param, [1, 1, 2, 3, 5, 8, 13], {}, (1, 1, 2, 3, 5, 8, 13)),
+ (
+ args_param,
+ [1, 1, 2, 3, 5, 8, 13],
+ {"x": True, "other": 42},
+ (1, 1, 2, 3, 5, 8, 13),
+ ),
+ (kwargs_param, [], {}, {}),
+ (kwargs_param, [1], {}, {}),
+ (kwargs_param, [1, 3, 5, 8, "x", True], {}, {}),
+ (kwargs_param, [], {"x": True}, {"x": True}),
+ (kwargs_param, [], {"x": True, "n": 42}, {"x": True, "n": 42}),
+ (
+ kwargs_param,
+ [10, "x", False],
+ {"x": True, "n": 42},
+ {"x": True, "n": 42},
+ ),
+ (args_and_kwargs_param, [], {}, ((), {})),
+ (args_and_kwargs_param, [1], {}, ((1,), {})),
+ (
+ args_and_kwargs_param,
+ [1, 3, 5, False, "n"],
+ {"x": True, "n": 42},
+ ((1, 3, 5, False, "n"), {"x": True, "n": 42}),
+ ),
+ (positional_optional_catchall, [], {}, TypeError),
+ (positional_optional_catchall, [42], {}, (42, "ham", ())),
+ pytest.param(
+ positional_optional_catchall,
+ [True],
+ {"b": "spam"},
+ (True, "spam", ()),
+ ),
+ pytest.param(
+ positional_optional_catchall,
+ ["a", "b"],
+ {"b": "spam"},
+ ("a", "spam", ()),
+ ),
+ (
+ positional_optional_catchall,
+ ["a", "b", "c"],
+ {"b": "spam"},
+ ("a", "spam", ("c",)),
+ ),
+ (
+ positional_optional_catchall,
+ ["a", "b", "c", False, 10],
+ {"other": 42},
+ ("a", "b", ("c", False, 10)),
+ ),
+ (ignored_param, [], {}, TypeError),
+ (ignored_param, [1, 2, 3], {}, TypeError),
+ pytest.param(
+ ignored_param,
+ [1, 2],
+ {"c": 42},
+ (1, 2, 42, 10),
+ ),
+ pytest.param(
+ ignored_param,
+ [1, 2],
+ {"c": 42, "d": 21},
+ (1, 2, 42, 21),
+ ),
+ pytest.param(positional_and_kw_arguments, [], {}, TypeError),
+ (positional_and_kw_arguments, [1, 2, 3], {}, (1, 2, 3)),
+ (positional_and_kw_arguments, [1, 2], {"event": "foo"}, (1, 2, "foo")),
+ (
+ positional_and_kw_arguments,
+ [],
+ {"source": "A", "target": "B", "event": "foo"},
+ ("A", "B", "foo"),
+ ),
+ pytest.param(default_kw_arguments, [], {}, ("A", "B", "go")),
+ (default_kw_arguments, [1, 2, 3], {}, (1, 2, 3)),
+ (default_kw_arguments, [1, 2], {"event": "wait"}, (1, 2, "wait")),
+ ],
+ )
+ def test_wrap_fn_single_positional_parameter(self, func, args, kwargs, expected):
+
+ wrapped_func = SignatureAdapter.wrap(func)
+
+ if inspect.isclass(expected) and issubclass(expected, Exception):
+ with pytest.raises(expected):
+ wrapped_func(*args, **kwargs)
+ else:
+ assert wrapped_func(*args, **kwargs) == expected
+
+ @pytest.mark.parametrize(
+ ("args", "kwargs", "expected"),
+ [
+ ([], {}, TypeError),
+ ([1, 2, 3], {}, TypeError),
+ ([1, 2], {"kw_only_param": 42}, (1, 2, 42)),
+ ([1], {"pos_or_kw_param": 21, "kw_only_param": 42}, (1, 21, 42)),
+ (
+ [],
+ {"pos_only": 10, "pos_or_kw_param": 21, "kw_only_param": 42},
+ TypeError,
+ ),
+ ],
+ )
+ @pytest.mark.skipif(
+ sys.version_info < (3, 8), reason="requires python3.8 or higher"
+ )
+ def test_positional_ony(self, args, kwargs, expected):
+ def func(pos_only, /, pos_or_kw_param, *, kw_only_param):
+ # https://peps.python.org/pep-0570/
+ return pos_only, pos_or_kw_param, kw_only_param
+
+ wrapped_func = SignatureAdapter.wrap(func)
+
+ if inspect.isclass(expected) and issubclass(expected, Exception):
+ with pytest.raises(expected):
+ wrapped_func(*args, **kwargs)
+ else:
+ assert wrapped_func(*args, **kwargs) == expected
|
bug: The dynamic dispatcher is not filling default values for parameters on callbacks.
* Python State Machine version: 1.0.3
* Python version: 3.11
* Operating System: Any
### Description
The dynamic dispatcher is not filling default values for parameters on callbacks.
``` py
from statemachine import State
from statemachine import StateMachine
class XMachine(StateMachine):
initial = State(initial=True, enter="enter_with_default_value")
test = initial.to.itself()
def enter_with_default_value(self, value: int = 42):
assert value == 42, value
XMachine()
```
Raises:
```py
assert value == 42, value
^^^^^^^^^^^
AssertionError: None
```
Development notes: Migrate `dispatcher.py` to [inspect.signature](https://docs.python.org/3/library/inspect.html#inspect.signature) that has a nicer API instead of the currently [inspect.getfullargspec](https://docs.python.org/3/library/inspect.html#inspect.getfullargspec).
|
0.0
|
f1afe5a28cdc8c54c1353a4cd2ca745e7051548d
|
[
"tests/test_signature.py::TestSignatureAdapter::test_wrap_fn_single_positional_parameter[single_positional_param-args0-kwargs0-10]",
"tests/test_signature.py::TestSignatureAdapter::test_wrap_fn_single_positional_parameter[single_positional_param-args1-kwargs1-10]",
"tests/test_signature.py::TestSignatureAdapter::test_wrap_fn_single_positional_parameter[single_positional_param-args2-kwargs2-TypeError]",
"tests/test_signature.py::TestSignatureAdapter::test_wrap_fn_single_positional_parameter[single_default_keyword_param-args3-kwargs3-10]",
"tests/test_signature.py::TestSignatureAdapter::test_wrap_fn_single_positional_parameter[single_default_keyword_param-args4-kwargs4-10]",
"tests/test_signature.py::TestSignatureAdapter::test_wrap_fn_single_positional_parameter[single_default_keyword_param-args5-kwargs5-42]",
"tests/test_signature.py::TestSignatureAdapter::test_wrap_fn_single_positional_parameter[method_no_argument-args6-kwargs6-42]",
"tests/test_signature.py::TestSignatureAdapter::test_wrap_fn_single_positional_parameter[method_no_argument-args7-kwargs7-42]",
"tests/test_signature.py::TestSignatureAdapter::test_wrap_fn_single_positional_parameter[method_no_argument-args8-kwargs8-42]",
"tests/test_signature.py::TestSignatureAdapter::test_wrap_fn_single_positional_parameter[method_no_argument-args9-kwargs9-TypeError]",
"tests/test_signature.py::TestSignatureAdapter::test_wrap_fn_single_positional_parameter[args_param-args10-kwargs10-expected10]",
"tests/test_signature.py::TestSignatureAdapter::test_wrap_fn_single_positional_parameter[args_param-args11-kwargs11-expected11]",
"tests/test_signature.py::TestSignatureAdapter::test_wrap_fn_single_positional_parameter[args_param-args12-kwargs12-expected12]",
"tests/test_signature.py::TestSignatureAdapter::test_wrap_fn_single_positional_parameter[args_param-args13-kwargs13-expected13]",
"tests/test_signature.py::TestSignatureAdapter::test_wrap_fn_single_positional_parameter[kwargs_param-args14-kwargs14-expected14]",
"tests/test_signature.py::TestSignatureAdapter::test_wrap_fn_single_positional_parameter[kwargs_param-args15-kwargs15-expected15]",
"tests/test_signature.py::TestSignatureAdapter::test_wrap_fn_single_positional_parameter[kwargs_param-args16-kwargs16-expected16]",
"tests/test_signature.py::TestSignatureAdapter::test_wrap_fn_single_positional_parameter[kwargs_param-args17-kwargs17-expected17]",
"tests/test_signature.py::TestSignatureAdapter::test_wrap_fn_single_positional_parameter[kwargs_param-args18-kwargs18-expected18]",
"tests/test_signature.py::TestSignatureAdapter::test_wrap_fn_single_positional_parameter[kwargs_param-args19-kwargs19-expected19]",
"tests/test_signature.py::TestSignatureAdapter::test_wrap_fn_single_positional_parameter[args_and_kwargs_param-args20-kwargs20-expected20]",
"tests/test_signature.py::TestSignatureAdapter::test_wrap_fn_single_positional_parameter[args_and_kwargs_param-args21-kwargs21-expected21]",
"tests/test_signature.py::TestSignatureAdapter::test_wrap_fn_single_positional_parameter[args_and_kwargs_param-args22-kwargs22-expected22]",
"tests/test_signature.py::TestSignatureAdapter::test_wrap_fn_single_positional_parameter[positional_optional_catchall-args23-kwargs23-TypeError]",
"tests/test_signature.py::TestSignatureAdapter::test_wrap_fn_single_positional_parameter[positional_optional_catchall-args24-kwargs24-expected24]",
"tests/test_signature.py::TestSignatureAdapter::test_wrap_fn_single_positional_parameter[positional_optional_catchall-args25-kwargs25-expected25]",
"tests/test_signature.py::TestSignatureAdapter::test_wrap_fn_single_positional_parameter[positional_optional_catchall-args26-kwargs26-expected26]",
"tests/test_signature.py::TestSignatureAdapter::test_wrap_fn_single_positional_parameter[positional_optional_catchall-args27-kwargs27-expected27]",
"tests/test_signature.py::TestSignatureAdapter::test_wrap_fn_single_positional_parameter[positional_optional_catchall-args28-kwargs28-expected28]",
"tests/test_signature.py::TestSignatureAdapter::test_wrap_fn_single_positional_parameter[ignored_param-args29-kwargs29-TypeError]",
"tests/test_signature.py::TestSignatureAdapter::test_wrap_fn_single_positional_parameter[ignored_param-args30-kwargs30-TypeError]",
"tests/test_signature.py::TestSignatureAdapter::test_wrap_fn_single_positional_parameter[ignored_param-args31-kwargs31-expected31]",
"tests/test_signature.py::TestSignatureAdapter::test_wrap_fn_single_positional_parameter[ignored_param-args32-kwargs32-expected32]",
"tests/test_signature.py::TestSignatureAdapter::test_wrap_fn_single_positional_parameter[positional_and_kw_arguments-args33-kwargs33-TypeError]",
"tests/test_signature.py::TestSignatureAdapter::test_wrap_fn_single_positional_parameter[positional_and_kw_arguments-args34-kwargs34-expected34]",
"tests/test_signature.py::TestSignatureAdapter::test_wrap_fn_single_positional_parameter[positional_and_kw_arguments-args35-kwargs35-expected35]",
"tests/test_signature.py::TestSignatureAdapter::test_wrap_fn_single_positional_parameter[positional_and_kw_arguments-args36-kwargs36-expected36]",
"tests/test_signature.py::TestSignatureAdapter::test_wrap_fn_single_positional_parameter[default_kw_arguments-args37-kwargs37-expected37]",
"tests/test_signature.py::TestSignatureAdapter::test_wrap_fn_single_positional_parameter[default_kw_arguments-args38-kwargs38-expected38]",
"tests/test_signature.py::TestSignatureAdapter::test_wrap_fn_single_positional_parameter[default_kw_arguments-args39-kwargs39-expected39]",
"tests/test_signature.py::TestSignatureAdapter::test_positional_ony[args0-kwargs0-TypeError]",
"tests/test_signature.py::TestSignatureAdapter::test_positional_ony[args1-kwargs1-TypeError]",
"tests/test_signature.py::TestSignatureAdapter::test_positional_ony[args2-kwargs2-expected2]",
"tests/test_signature.py::TestSignatureAdapter::test_positional_ony[args3-kwargs3-expected3]",
"tests/test_signature.py::TestSignatureAdapter::test_positional_ony[args4-kwargs4-TypeError]"
] |
[] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_added_files",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2023-01-29 03:19:35+00:00
|
mit
| 2,339 |
|
fgmacedo__python-statemachine-353
|
diff --git a/docs/releases/2.0.0.md b/docs/releases/2.0.0.md
index e5cd38b..7d3367e 100644
--- a/docs/releases/2.0.0.md
+++ b/docs/releases/2.0.0.md
@@ -47,6 +47,7 @@ See {ref}`internal transition` for more details.
- [#342](https://github.com/fgmacedo/python-statemachine/pull/342): Assignment of `Transition`
guards using decorators is now possible.
- [#331](https://github.com/fgmacedo/python-statemachine/pull/331): Added a way to generate diagrams using [QuickChart.io](https://quickchart.io) instead of GraphViz. See {ref}`diagrams` for more details.
+- [#353](https://github.com/fgmacedo/python-statemachine/pull/353): Support for abstract state machine classes, so you can subclass `StateMachine` to add behavior on your own base class. Abstract `StateMachine` cannot be instantiated.
## Bugfixes in 2.0
diff --git a/statemachine/factory.py b/statemachine/factory.py
index 186f28c..720196b 100644
--- a/statemachine/factory.py
+++ b/statemachine/factory.py
@@ -8,7 +8,6 @@ from .graph import visit_connected_states
from .state import State
from .transition import Transition
from .transition_list import TransitionList
-from .utils import qualname
from .utils import ugettext as _
@@ -57,18 +56,19 @@ class StateMachineMetaclass(type):
)
def _check(cls):
+ has_states = bool(cls.states)
+ has_events = bool(cls._events)
- # do not validate the base class
- name = qualname(cls)
- if name == "statemachine.statemachine.StateMachine":
- return
+ cls._abstract = not has_states and not has_events
- cls._abstract = False
+ # do not validate the base abstract classes
+ if cls._abstract:
+ return
- if not cls.states:
+ if not has_states:
raise InvalidDefinition(_("There are no states."))
- if not cls._events:
+ if not has_events:
raise InvalidDefinition(_("There are no events."))
cls._check_disconnected_state()
diff --git a/statemachine/statemachine.py b/statemachine/statemachine.py
index f9e3831..fa9f983 100644
--- a/statemachine/statemachine.py
+++ b/statemachine/statemachine.py
@@ -5,10 +5,12 @@ from .dispatcher import resolver_factory
from .event import Event
from .event_data import EventData
from .exceptions import InvalidStateValue
+from .exceptions import InvalidDefinition
from .exceptions import TransitionNotAllowed
from .factory import StateMachineMetaclass
from .model import Model
from .transition import Transition
+from .utils import ugettext as _
if TYPE_CHECKING:
@@ -28,6 +30,9 @@ class StateMachine(metaclass=StateMachineMetaclass):
self.state_field = state_field
self.start_value = start_value
+ if self._abstract:
+ raise InvalidDefinition(_("There are no states or transitions."))
+
initial_transition = Transition(
None, self._get_initial_state(), event="__initial__"
)
|
fgmacedo/python-statemachine
|
0a54b24fd195522c98db42d43ea6a75138750a2f
|
diff --git a/tests/test_statemachine.py b/tests/test_statemachine.py
index 095b44d..2d6d068 100644
--- a/tests/test_statemachine.py
+++ b/tests/test_statemachine.py
@@ -296,13 +296,21 @@ def test_state_machine_with_a_invalid_start_value(
machine_cls(model, start_value=start_value)
-def test_should_not_create_instance_of_machine_without_states():
+def test_should_not_create_instance_of_abstract_machine():
+ class EmptyMachine(StateMachine):
+ "An empty machine"
+ pass
+
+ with pytest.raises(exceptions.InvalidDefinition):
+ EmptyMachine()
+
+def test_should_not_create_instance_of_machine_without_states():
+ s1 = State("X")
with pytest.raises(exceptions.InvalidDefinition):
- class EmptyMachine(StateMachine):
- "An empty machine"
- pass
+ class OnlyTransitionMachine(StateMachine):
+ t1 = s1.to.itself()
def test_should_not_create_instance_of_machine_without_transitions():
|
Supporting abstract classes
### Discussed in https://github.com/fgmacedo/python-statemachine/discussions/344
<div type='discussions-op-text'>
<sup>Originally posted by **galhyt** January 30, 2023</sup>
I have a class that inherites statemachine and has no states and no transitions, all are defined in the children classes. The problem is that from version 1.0 it's mandatory to have transitions and states. Can you reverse it?</div>
|
0.0
|
0a54b24fd195522c98db42d43ea6a75138750a2f
|
[
"tests/test_statemachine.py::test_should_not_create_instance_of_abstract_machine"
] |
[
"tests/test_statemachine.py::test_machine_repr",
"tests/test_statemachine.py::test_machine_should_be_at_start_state",
"tests/test_statemachine.py::test_machine_should_only_allow_only_one_initial_state",
"tests/test_statemachine.py::test_machine_should_not_allow_transitions_from_final_state",
"tests/test_statemachine.py::test_should_change_state",
"tests/test_statemachine.py::test_should_run_a_transition_that_keeps_the_state",
"tests/test_statemachine.py::test_should_change_state_with_multiple_machine_instances",
"tests/test_statemachine.py::test_call_to_transition_that_is_not_in_the_current_state_should_raise_exception[draft-deliver]",
"tests/test_statemachine.py::test_call_to_transition_that_is_not_in_the_current_state_should_raise_exception[closed-add_job]",
"tests/test_statemachine.py::test_machine_should_list_allowed_events_in_the_current_state",
"tests/test_statemachine.py::test_machine_should_run_a_transition_by_his_key",
"tests/test_statemachine.py::test_machine_should_raise_an_exception_if_a_transition_by_his_key_is_not_found",
"tests/test_statemachine.py::test_machine_should_use_and_model_attr_other_than_state",
"tests/test_statemachine.py::test_cant_assign_an_invalid_state_directly",
"tests/test_statemachine.py::test_should_allow_validate_data_for_transition",
"tests/test_statemachine.py::test_should_check_if_is_in_status",
"tests/test_statemachine.py::test_defined_value_must_be_assigned_to_models",
"tests/test_statemachine.py::test_state_machine_without_model",
"tests/test_statemachine.py::test_state_machine_with_a_start_value[None-campaign_machine-producing]",
"tests/test_statemachine.py::test_state_machine_with_a_start_value[None-campaign_machine_with_values-2]",
"tests/test_statemachine.py::test_state_machine_with_a_start_value[model2-campaign_machine-producing]",
"tests/test_statemachine.py::test_state_machine_with_a_start_value[model3-campaign_machine_with_values-2]",
"tests/test_statemachine.py::test_state_machine_with_a_invalid_start_value[None-campaign_machine-tapioca]",
"tests/test_statemachine.py::test_state_machine_with_a_invalid_start_value[None-campaign_machine_with_values-99]",
"tests/test_statemachine.py::test_state_machine_with_a_invalid_start_value[model2-campaign_machine-tapioca]",
"tests/test_statemachine.py::test_state_machine_with_a_invalid_start_value[model3-campaign_machine_with_values-99]",
"tests/test_statemachine.py::test_should_not_create_instance_of_machine_without_states",
"tests/test_statemachine.py::test_should_not_create_instance_of_machine_without_transitions",
"tests/test_statemachine.py::test_should_not_create_disconnected_machine",
"tests/test_statemachine.py::test_should_not_create_big_disconnected_machine",
"tests/test_statemachine.py::test_state_value_is_correct",
"tests/test_statemachine.py::test_final_states",
"tests/test_statemachine.py::test_should_not_override_states_properties"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2023-02-22 18:18:00+00:00
|
mit
| 2,340 |
|
fgmacedo__python-statemachine-370
|
diff --git a/docs/releases/2.0.1.md b/docs/releases/2.0.1.md
new file mode 100644
index 0000000..fab6a72
--- /dev/null
+++ b/docs/releases/2.0.1.md
@@ -0,0 +1,12 @@
+# StateMachine 2.0.1
+
+*Not released yet*
+
+
+StateMachine 2.0.1 is a bugfix release.
+
+
+## Bugfixes
+
+- Fixes [#369](https://github.com/fgmacedo/python-statemachine/issues/336) adding support to wrap
+ methods used as {ref}`Actions` decorated with `functools.partial`.
diff --git a/docs/releases/index.md b/docs/releases/index.md
index e4a62da..2d8c6f5 100644
--- a/docs/releases/index.md
+++ b/docs/releases/index.md
@@ -15,6 +15,7 @@ Below are release notes through StateMachine and its patch releases.
```{toctree}
:maxdepth: 1
+2.0.1
2.0.0
```
diff --git a/statemachine/signature.py b/statemachine/signature.py
index bef064b..e3dca83 100644
--- a/statemachine/signature.py
+++ b/statemachine/signature.py
@@ -1,4 +1,5 @@
import itertools
+from functools import partial
from inspect import BoundArguments
from inspect import Parameter
from inspect import Signature
@@ -15,7 +16,9 @@ class SignatureAdapter(Signature):
sig = cls.from_callable(method)
sig.method = method
- sig.__name__ = method.__name__
+ sig.__name__ = (
+ method.func.__name__ if isinstance(method, partial) else method.__name__
+ )
return sig
def __call__(self, *args: Any, **kwargs: Any) -> Any:
|
fgmacedo/python-statemachine
|
5f6bf4cae29ab9e63d21ecdaa8b105ab2830b86d
|
diff --git a/tests/test_signature.py b/tests/test_signature.py
index fd9a891..175d2e2 100644
--- a/tests/test_signature.py
+++ b/tests/test_signature.py
@@ -1,4 +1,5 @@
import inspect
+from functools import partial
import pytest
@@ -148,9 +149,17 @@ class TestSignatureAdapter:
def test_wrap_fn_single_positional_parameter(self, func, args, kwargs, expected):
wrapped_func = SignatureAdapter.wrap(func)
+ assert wrapped_func.__name__ == func.__name__
if inspect.isclass(expected) and issubclass(expected, Exception):
with pytest.raises(expected):
wrapped_func(*args, **kwargs)
else:
assert wrapped_func(*args, **kwargs) == expected
+
+ def test_support_for_partial(self):
+ part = partial(positional_and_kw_arguments, event="activated")
+ wrapped_func = SignatureAdapter.wrap(part)
+
+ assert wrapped_func("A", "B") == ("A", "B", "activated")
+ assert wrapped_func.__name__ == positional_and_kw_arguments.__name__
|
SignatureAdapter wrap
* Python State Machine version: 2.0.0
* Python version: 3.7.16
* Operating System: MacBook
### Description
I have a decorator class for state machine child class's transitions methods.
The decorator has this function:
```
def __get__(self, instance, owner):
return partial(self.__call__, instance)
```
When partial is from functools package.
wrap function crashes on this line:
`sig.__name__ = method.__name__`
When method is functors.partial(decorator_class.__call__)
`AttributeError: 'functools.partial' object has no attribute '__name__'`
|
0.0
|
5f6bf4cae29ab9e63d21ecdaa8b105ab2830b86d
|
[
"tests/test_signature.py::TestSignatureAdapter::test_support_for_partial"
] |
[
"tests/test_signature.py::TestSignatureAdapter::test_wrap_fn_single_positional_parameter[single_positional_param-args0-kwargs0-10]",
"tests/test_signature.py::TestSignatureAdapter::test_wrap_fn_single_positional_parameter[single_positional_param-args1-kwargs1-10]",
"tests/test_signature.py::TestSignatureAdapter::test_wrap_fn_single_positional_parameter[single_positional_param-args2-kwargs2-TypeError]",
"tests/test_signature.py::TestSignatureAdapter::test_wrap_fn_single_positional_parameter[single_default_keyword_param-args3-kwargs3-10]",
"tests/test_signature.py::TestSignatureAdapter::test_wrap_fn_single_positional_parameter[single_default_keyword_param-args4-kwargs4-10]",
"tests/test_signature.py::TestSignatureAdapter::test_wrap_fn_single_positional_parameter[single_default_keyword_param-args5-kwargs5-42]",
"tests/test_signature.py::TestSignatureAdapter::test_wrap_fn_single_positional_parameter[method_no_argument-args6-kwargs6-42]",
"tests/test_signature.py::TestSignatureAdapter::test_wrap_fn_single_positional_parameter[method_no_argument-args7-kwargs7-42]",
"tests/test_signature.py::TestSignatureAdapter::test_wrap_fn_single_positional_parameter[method_no_argument-args8-kwargs8-42]",
"tests/test_signature.py::TestSignatureAdapter::test_wrap_fn_single_positional_parameter[method_no_argument-args9-kwargs9-TypeError]",
"tests/test_signature.py::TestSignatureAdapter::test_wrap_fn_single_positional_parameter[args_param-args10-kwargs10-expected10]",
"tests/test_signature.py::TestSignatureAdapter::test_wrap_fn_single_positional_parameter[args_param-args11-kwargs11-expected11]",
"tests/test_signature.py::TestSignatureAdapter::test_wrap_fn_single_positional_parameter[args_param-args12-kwargs12-expected12]",
"tests/test_signature.py::TestSignatureAdapter::test_wrap_fn_single_positional_parameter[args_param-args13-kwargs13-expected13]",
"tests/test_signature.py::TestSignatureAdapter::test_wrap_fn_single_positional_parameter[kwargs_param-args14-kwargs14-expected14]",
"tests/test_signature.py::TestSignatureAdapter::test_wrap_fn_single_positional_parameter[kwargs_param-args15-kwargs15-expected15]",
"tests/test_signature.py::TestSignatureAdapter::test_wrap_fn_single_positional_parameter[kwargs_param-args16-kwargs16-expected16]",
"tests/test_signature.py::TestSignatureAdapter::test_wrap_fn_single_positional_parameter[kwargs_param-args17-kwargs17-expected17]",
"tests/test_signature.py::TestSignatureAdapter::test_wrap_fn_single_positional_parameter[kwargs_param-args18-kwargs18-expected18]",
"tests/test_signature.py::TestSignatureAdapter::test_wrap_fn_single_positional_parameter[kwargs_param-args19-kwargs19-expected19]",
"tests/test_signature.py::TestSignatureAdapter::test_wrap_fn_single_positional_parameter[args_and_kwargs_param-args20-kwargs20-expected20]",
"tests/test_signature.py::TestSignatureAdapter::test_wrap_fn_single_positional_parameter[args_and_kwargs_param-args21-kwargs21-expected21]",
"tests/test_signature.py::TestSignatureAdapter::test_wrap_fn_single_positional_parameter[args_and_kwargs_param-args22-kwargs22-expected22]",
"tests/test_signature.py::TestSignatureAdapter::test_wrap_fn_single_positional_parameter[positional_optional_catchall-args23-kwargs23-TypeError]",
"tests/test_signature.py::TestSignatureAdapter::test_wrap_fn_single_positional_parameter[positional_optional_catchall-args24-kwargs24-expected24]",
"tests/test_signature.py::TestSignatureAdapter::test_wrap_fn_single_positional_parameter[positional_optional_catchall-args25-kwargs25-expected25]",
"tests/test_signature.py::TestSignatureAdapter::test_wrap_fn_single_positional_parameter[positional_optional_catchall-args26-kwargs26-expected26]",
"tests/test_signature.py::TestSignatureAdapter::test_wrap_fn_single_positional_parameter[positional_optional_catchall-args27-kwargs27-expected27]",
"tests/test_signature.py::TestSignatureAdapter::test_wrap_fn_single_positional_parameter[positional_optional_catchall-args28-kwargs28-expected28]",
"tests/test_signature.py::TestSignatureAdapter::test_wrap_fn_single_positional_parameter[ignored_param-args29-kwargs29-TypeError]",
"tests/test_signature.py::TestSignatureAdapter::test_wrap_fn_single_positional_parameter[ignored_param-args30-kwargs30-TypeError]",
"tests/test_signature.py::TestSignatureAdapter::test_wrap_fn_single_positional_parameter[ignored_param-args31-kwargs31-expected31]",
"tests/test_signature.py::TestSignatureAdapter::test_wrap_fn_single_positional_parameter[ignored_param-args32-kwargs32-expected32]",
"tests/test_signature.py::TestSignatureAdapter::test_wrap_fn_single_positional_parameter[positional_and_kw_arguments-args33-kwargs33-TypeError]",
"tests/test_signature.py::TestSignatureAdapter::test_wrap_fn_single_positional_parameter[positional_and_kw_arguments-args34-kwargs34-expected34]",
"tests/test_signature.py::TestSignatureAdapter::test_wrap_fn_single_positional_parameter[positional_and_kw_arguments-args35-kwargs35-expected35]",
"tests/test_signature.py::TestSignatureAdapter::test_wrap_fn_single_positional_parameter[positional_and_kw_arguments-args36-kwargs36-expected36]",
"tests/test_signature.py::TestSignatureAdapter::test_wrap_fn_single_positional_parameter[default_kw_arguments-args37-kwargs37-expected37]",
"tests/test_signature.py::TestSignatureAdapter::test_wrap_fn_single_positional_parameter[default_kw_arguments-args38-kwargs38-expected38]",
"tests/test_signature.py::TestSignatureAdapter::test_wrap_fn_single_positional_parameter[default_kw_arguments-args39-kwargs39-expected39]"
] |
{
"failed_lite_validators": [
"has_added_files",
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2023-03-10 23:15:00+00:00
|
mit
| 2,341 |
|
fgmacedo__python-statemachine-387
|
diff --git a/docs/releases/2.1.0.md b/docs/releases/2.1.0.md
index 5c3caf2..e182ca5 100644
--- a/docs/releases/2.1.0.md
+++ b/docs/releases/2.1.0.md
@@ -40,3 +40,4 @@ See {ref}`States from Enum types`.
- Fixes [#369](https://github.com/fgmacedo/python-statemachine/issues/369) adding support to wrap
methods used as {ref}`Actions` decorated with `functools.partial`.
+- Fixes [#384](https://github.com/fgmacedo/python-statemachine/issues/384) so multiple observers can watch the same callback.
diff --git a/statemachine/callbacks.py b/statemachine/callbacks.py
index 85a0e17..f10122b 100644
--- a/statemachine/callbacks.py
+++ b/statemachine/callbacks.py
@@ -19,6 +19,7 @@ class CallbackWrapper:
self.suppress_errors = suppress_errors
self.cond = Callbacks(factory=ConditionWrapper).add(cond)
self._callback = None
+ self._resolver_id = None
def __repr__(self):
return f"{type(self).__name__}({self.func!r})"
@@ -27,7 +28,7 @@ class CallbackWrapper:
return getattr(self.func, "__name__", self.func)
def __eq__(self, other):
- return self.func == getattr(other, "func", other)
+ return self.func == other.func and self._resolver_id == other._resolver_id
def __hash__(self):
return id(self)
@@ -45,6 +46,7 @@ class CallbackWrapper:
"""
self.cond.setup(resolver)
try:
+ self._resolver_id = getattr(resolver, "id", id(resolver))
self._callback = resolver(self.func)
return True
except AttrNotFound:
@@ -144,15 +146,15 @@ class Callbacks:
return all(condition(*args, **kwargs) for condition in self)
def _add(self, func, resolver=None, prepend=False, **kwargs):
- if func in self.items:
- return
-
resolver = resolver or self._resolver
callback = self.factory(func, **kwargs)
if resolver is not None and not callback.setup(resolver):
return
+ if callback in self.items:
+ return
+
if prepend:
self.items.insert(0, callback)
else:
diff --git a/statemachine/dispatcher.py b/statemachine/dispatcher.py
index d96a3f2..83c9b49 100644
--- a/statemachine/dispatcher.py
+++ b/statemachine/dispatcher.py
@@ -37,6 +37,28 @@ def _get_func_by_attr(attr, *configs):
return func, config.obj
+def _build_attr_wrapper(attr: str, obj):
+ # if `attr` is not callable, then it's an attribute or property,
+ # so `func` contains it's current value.
+ # we'll build a method that get's the fresh value for each call
+ getter = attrgetter(attr)
+
+ def wrapper(*args, **kwargs):
+ return getter(obj)
+
+ return wrapper
+
+
+def _build_sm_event_wrapper(func):
+ "Events already have the 'machine' parameter defined."
+
+ def wrapper(*args, **kwargs):
+ kwargs.pop("machine", None)
+ return func(*args, **kwargs)
+
+ return wrapper
+
+
def ensure_callable(attr, *objects):
"""Ensure that `attr` is a callable, if not, tries to retrieve one from any of the given
`objects`.
@@ -56,24 +78,10 @@ def ensure_callable(attr, *objects):
func, obj = _get_func_by_attr(attr, *configs)
if not callable(func):
- # if `attr` is not callable, then it's an attribute or property,
- # so `func` contains it's current value.
- # we'll build a method that get's the fresh value for each call
- getter = attrgetter(attr)
-
- def wrapper(*args, **kwargs):
- return getter(obj)
-
- return wrapper
+ return _build_attr_wrapper(attr, obj)
if getattr(func, "_is_sm_event", False):
- "Events already have the 'machine' parameter defined."
-
- def wrapper(*args, **kwargs):
- kwargs.pop("machine")
- return func(*args, **kwargs)
-
- return wrapper
+ return _build_sm_event_wrapper(func)
return SignatureAdapter.wrap(func)
@@ -81,8 +89,13 @@ def ensure_callable(attr, *objects):
def resolver_factory(*objects):
"""Factory that returns a configured resolver."""
+ objects = [ObjectConfig.from_obj(obj) for obj in objects]
+
@wraps(ensure_callable)
def wrapper(attr):
return ensure_callable(attr, *objects)
+ resolver_id = ".".join(str(id(obj.obj)) for obj in objects)
+ wrapper.id = resolver_id
+
return wrapper
|
fgmacedo/python-statemachine
|
c60f7febed5c176b5a45d5cf35d2f6474cc70370
|
diff --git a/tests/test_dispatcher.py b/tests/test_dispatcher.py
index c384f22..1c24228 100644
--- a/tests/test_dispatcher.py
+++ b/tests/test_dispatcher.py
@@ -112,3 +112,13 @@ class TestResolverFactory:
resolver = resolver_factory(org_config, person)
resolved_method = resolver(attr)
assert resolved_method() == expected_value
+
+ def test_should_generate_unique_ids(self):
+ person = Person("Frodo", "Bolseiro", "cpf")
+ org = Organization("The Lord fo the Rings", "cnpj")
+
+ resolver1 = resolver_factory(org, person)
+ resolver2 = resolver_factory(org, person)
+ resolver3 = resolver_factory(org, person)
+
+ assert resolver1.id == resolver2.id == resolver3.id
diff --git a/tests/testcases/issue384_multiple_observers.md b/tests/testcases/issue384_multiple_observers.md
new file mode 100644
index 0000000..83f252b
--- /dev/null
+++ b/tests/testcases/issue384_multiple_observers.md
@@ -0,0 +1,57 @@
+### Issue 384
+
+A StateMachine that exercises the example given on issue
+#[384](https://github.com/fgmacedo/python-statemachine/issues/384).
+
+In this example, we register multiple observers to the same named callback.
+
+This works also as a regression test.
+
+```py
+>>> from statemachine import State
+>>> from statemachine import StateMachine
+
+>>> class MyObs:
+... def on_move_car(self):
+... print("I observed moving from 1")
+
+>>> class MyObs2:
+... def on_move_car(self):
+... print("I observed moving from 2")
+...
+
+
+>>> class Car(StateMachine):
+... stopped = State(initial=True)
+... moving = State()
+...
+... move_car = stopped.to(moving)
+... stop_car = moving.to(stopped)
+...
+... def on_move_car(self):
+... print("I'm moving")
+
+```
+
+Running:
+
+```py
+>>> car = Car()
+>>> obs = MyObs()
+>>> obs2 = MyObs2()
+>>> car.add_observer(obs)
+Car(model=Model(state=stopped), state_field='state', current_state='stopped')
+
+>>> car.add_observer(obs2)
+Car(model=Model(state=stopped), state_field='state', current_state='stopped')
+
+>>> car.add_observer(obs2) # test to not register duplicated observer callbacks
+Car(model=Model(state=stopped), state_field='state', current_state='stopped')
+
+>>> car.move_car()
+I'm moving
+I observed moving from 1
+I observed moving from 2
+[None, None, None]
+
+```
|
Multiple Observers not working on singular State machine
* Python State Machine version:
* Python version:
* Operating System:
### Description
I would like to have multiple observers responding to an event from a statemachine.
### What I Did
```
from statemachine import StateMachine, State
class MyObs(object):
def __init__(self):
pass
def on_move_car(self):
print("I observed moving from 1")
return self
class MyObs2(object):
def __init__(self):
pass
def on_move_car(self):
print("I observed moving from 2")
return self
class Car(StateMachine):
def __init__(self):
super().__init__()
stopped = State(initial=True)
moving = State()
move_car = stopped.to(moving)
stop_car = moving.to(stopped)
@move_car.on
def on_move_car(self):
print("Im moving")
if __name__ == "__main__":
car = Car()
obs = MyObs()
obs2 = MyObs2()
car.add_observer(obs)
car.add_observer(obs2)
car.move_car()
```
I would expect to see both "I observed moving from 1" and "I observed moving from 2" but it seems the first observer to encounter the event will swallow the callback.
|
0.0
|
c60f7febed5c176b5a45d5cf35d2f6474cc70370
|
[
"tests/test_dispatcher.py::TestResolverFactory::test_should_generate_unique_ids"
] |
[
"tests/test_dispatcher.py::TestEnsureCallable::test_return_same_object_if_already_a_callable",
"tests/test_dispatcher.py::TestEnsureCallable::test_retrieve_a_method_from_its_name[no-args-no-kwargs]",
"tests/test_dispatcher.py::TestEnsureCallable::test_retrieve_a_method_from_its_name[no-args-with-kwargs]",
"tests/test_dispatcher.py::TestEnsureCallable::test_retrieve_a_method_from_its_name[with-args-no-kwargs]",
"tests/test_dispatcher.py::TestEnsureCallable::test_retrieve_a_method_from_its_name[with-args-with-kwargs]",
"tests/test_dispatcher.py::TestEnsureCallable::test_retrieve_a_callable_from_a_property_name[no-args-no-kwargs]",
"tests/test_dispatcher.py::TestEnsureCallable::test_retrieve_a_callable_from_a_property_name[no-args-with-kwargs]",
"tests/test_dispatcher.py::TestEnsureCallable::test_retrieve_a_callable_from_a_property_name[with-args-no-kwargs]",
"tests/test_dispatcher.py::TestEnsureCallable::test_retrieve_a_callable_from_a_property_name[with-args-with-kwargs]",
"tests/test_dispatcher.py::TestEnsureCallable::test_retrieve_callable_from_a_property_name_that_should_keep_reference[no-args-no-kwargs]",
"tests/test_dispatcher.py::TestEnsureCallable::test_retrieve_callable_from_a_property_name_that_should_keep_reference[no-args-with-kwargs]",
"tests/test_dispatcher.py::TestEnsureCallable::test_retrieve_callable_from_a_property_name_that_should_keep_reference[with-args-no-kwargs]",
"tests/test_dispatcher.py::TestEnsureCallable::test_retrieve_callable_from_a_property_name_that_should_keep_reference[with-args-with-kwargs]",
"tests/test_dispatcher.py::TestResolverFactory::test_should_chain_resolutions[first_name-Frodo]",
"tests/test_dispatcher.py::TestResolverFactory::test_should_chain_resolutions[last_name-Bolseiro]",
"tests/test_dispatcher.py::TestResolverFactory::test_should_chain_resolutions[legal_document-cnpj]",
"tests/test_dispatcher.py::TestResolverFactory::test_should_chain_resolutions[get_full_name-The",
"tests/test_dispatcher.py::TestResolverFactory::test_should_ignore_list_of_attrs[first_name-Frodo]",
"tests/test_dispatcher.py::TestResolverFactory::test_should_ignore_list_of_attrs[last_name-Bolseiro]",
"tests/test_dispatcher.py::TestResolverFactory::test_should_ignore_list_of_attrs[legal_document-cnpj]",
"tests/test_dispatcher.py::TestResolverFactory::test_should_ignore_list_of_attrs[get_full_name-Frodo"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2023-05-05 12:48:22+00:00
|
mit
| 2,342 |
|
fgmacedo__python-statemachine-425
|
diff --git a/statemachine/callbacks.py b/statemachine/callbacks.py
index 20d9126..3d8153d 100644
--- a/statemachine/callbacks.py
+++ b/statemachine/callbacks.py
@@ -240,6 +240,9 @@ class CallbacksRegistry:
executor_list.add(callbacks, resolver)
return executor_list
+ def clear(self):
+ self._registry.clear()
+
def __getitem__(self, callbacks: CallbackMetaList) -> CallbacksExecutor:
return self._registry[callbacks]
diff --git a/statemachine/statemachine.py b/statemachine/statemachine.py
index d0ccfae..855fdbe 100644
--- a/statemachine/statemachine.py
+++ b/statemachine/statemachine.py
@@ -1,4 +1,5 @@
from collections import deque
+from copy import deepcopy
from functools import partial
from typing import TYPE_CHECKING
from typing import Any
@@ -78,9 +79,9 @@ class StateMachine(metaclass=StateMachineMetaclass):
if self._abstract:
raise InvalidDefinition(_("There are no states or transitions."))
- initial_transition = Transition(None, self._get_initial_state(), event="__initial__")
- self._setup(initial_transition)
- self._activate_initial_state(initial_transition)
+ self._initial_transition = Transition(None, self._get_initial_state(), event="__initial__")
+ self._setup()
+ self._activate_initial_state()
def __init_subclass__(cls, strict_states: bool = False):
cls._strict_states = strict_states
@@ -98,6 +99,18 @@ class StateMachine(metaclass=StateMachineMetaclass):
f"current_state={current_state_id!r})"
)
+ def __deepcopy__(self, memo):
+ deepcopy_method = self.__deepcopy__
+ self.__deepcopy__ = None
+ try:
+ cp = deepcopy(self, memo)
+ finally:
+ self.__deepcopy__ = deepcopy_method
+ cp.__deepcopy__ = deepcopy_method
+ cp._callbacks_registry.clear()
+ cp._setup()
+ return cp
+
def _get_initial_state(self):
current_state_value = self.start_value if self.start_value else self.initial_state.value
try:
@@ -105,20 +118,20 @@ class StateMachine(metaclass=StateMachineMetaclass):
except KeyError as err:
raise InvalidStateValue(current_state_value) from err
- def _activate_initial_state(self, initial_transition):
+ def _activate_initial_state(self):
if self.current_state_value is None:
# send an one-time event `__initial__` to enter the current state.
# current_state = self.current_state
- initial_transition.before.clear()
- initial_transition.on.clear()
- initial_transition.after.clear()
+ self._initial_transition.before.clear()
+ self._initial_transition.on.clear()
+ self._initial_transition.after.clear()
event_data = EventData(
trigger_data=TriggerData(
machine=self,
- event=initial_transition.event,
+ event=self._initial_transition.event,
),
- transition=initial_transition,
+ transition=self._initial_transition,
)
self._activate(event_data)
@@ -142,12 +155,7 @@ class StateMachine(metaclass=StateMachineMetaclass):
for transition in state.transitions:
visitor(transition)
- def _setup(self, initial_transition: Transition):
- """
- Args:
- initial_transition: A special :ref:`transition` that triggers the enter on the
- `initial` :ref:`State`.
- """
+ def _setup(self):
machine = ObjectConfig.from_obj(self, skip_attrs=self._get_protected_attrs())
model = ObjectConfig.from_obj(self.model, skip_attrs={self.state_field})
default_resolver = resolver_factory(machine, model)
@@ -162,7 +170,7 @@ class StateMachine(metaclass=StateMachineMetaclass):
self._visit_states_and_transitions(setup_visitor)
- initial_transition._setup(register)
+ self._initial_transition._setup(register)
def _build_observers_visitor(self, *observers):
registry_callbacks = [
|
fgmacedo/python-statemachine
|
f236cad26f5aea3e25824973b19fe5c3519e1e60
|
diff --git a/tests/test_deepcopy.py b/tests/test_deepcopy.py
new file mode 100644
index 0000000..bbfdfc8
--- /dev/null
+++ b/tests/test_deepcopy.py
@@ -0,0 +1,25 @@
+from copy import deepcopy
+
+import pytest
+
+from statemachine import State
+from statemachine import StateMachine
+from statemachine.exceptions import TransitionNotAllowed
+
+
+def test_deepcopy():
+ class MySM(StateMachine):
+ draft = State("Draft", initial=True, value="draft")
+ published = State("Published", value="published")
+
+ publish = draft.to(published, cond="let_me_be_visible")
+
+ class MyModel:
+ let_me_be_visible = False
+
+ sm = MySM(MyModel())
+
+ sm2 = deepcopy(sm)
+
+ with pytest.raises(TransitionNotAllowed):
+ sm2.send("publish")
|
Models instantiated in Djangos setUpTestData seem to skip conditions
* Python State Machine version: 2.1.2
* Python version: 3.12
* Operating System: OsX 12.7.2
* Django: 5.0.3
### Description
The MachineMixin for Django seems to behave differently when models are used within django tests.
Oddly enough, any objects created during setUpTestData seem to cause transitions to bypass checks like
conditions.
### What I Did
This is a simple django application. Create migrations, run tests.
(I'm skipping some imports for stuff you probably know)
statemachines.py
```
class MySM(StateMachine):
draft = State("Draft", initial=True, value="draft")
published = State("Published", value="published")
publish = draft.to(published, cond="let_me_be_visible")
```
models.py
```
class MyContext(models.Model, MachineMixin):
state = models.CharField(max_length=30, blank=True, null=True)
state_machine_name = "myapp.statemachines.MySM"
state_machine_attr = "wf"
let_me_be_visible = False
```
tests.py
```
from django.test import TestCase
from statemachine.exceptions import TransitionNotAllowed
from myapp.models import MyContext
from myapp.statemachines import MySM
class WFTests(TestCase):
@classmethod
def setUpTestData(cls):
# Runs once
cls.one = MyContext.objects.create()
def setUp(self):
# Runs before every test
self.two = MyContext.objects.create()
def test_one(self):
# This test will fail
with self.assertRaises(TransitionNotAllowed):
self.one.wf.send("publish")
def test_two(self):
# This works as expected
with self.assertRaises(TransitionNotAllowed):
self.two.wf.send("publish")
def test_three(self):
# Managing this instance works if I call it like this instead.
# So this test works
wf = MySM(self.one)
with self.assertRaises(TransitionNotAllowed):
wf.send("publish")
```
The inner workings of the transitions are still a bit opaque to me, so sorry if there's something obvious I'm missing here.
Thanks for maintaining this great library!
|
0.0
|
f236cad26f5aea3e25824973b19fe5c3519e1e60
|
[
"tests/test_deepcopy.py::test_deepcopy"
] |
[] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2024-04-16 21:05:23+00:00
|
mit
| 2,343 |
|
fimion__wheniwork-api-py-3
|
diff --git a/wheniwork/__init__.py b/wheniwork/__init__.py
index 9eef3fd..04c6930 100644
--- a/wheniwork/__init__.py
+++ b/wheniwork/__init__.py
@@ -6,6 +6,16 @@ A Python Wrapper for WhenIWork.com
import requests
+def raise_for_status_with_message(resp):
+ try:
+ resp.raise_for_status()
+ except requests.exceptions.HTTPError as error:
+ if resp.text:
+ raise requests.exceptions.HTTPError('{} \nError message: {}'.format(str(error), resp.text))
+ else:
+ raise error
+
+
class WhenIWork(object):
""".. py:class: WhenIWork([:param token:=None, :param options:=dict()])
:param token: The user WhenIWork API token
@@ -134,7 +144,7 @@ class WhenIWork(object):
head = {'W-Key': key}
head.update(self.headers)
resp = requests.post(url, json=params, headers=head)
- assert resp.ok
+ raise_for_status_with_message(resp)
self.__api_resp = resp.json()
data = self.resp
if 'login' in data and 'token' in data['login']:
@@ -159,7 +169,7 @@ class WhenIWork(object):
if headers:
head.update(headers)
resp = requests.get(url, params, headers=head)
- assert resp.ok
+ raise_for_status_with_message(resp)
self.__api_resp = resp.json()
return self.resp
else:
@@ -184,7 +194,7 @@ class WhenIWork(object):
if headers:
head.update(headers)
resp = requests.post(url, json=params, headers=head)
- assert resp.ok
+ raise_for_status_with_message(resp)
self.__api_resp = resp.json()
return self.resp
else:
@@ -220,7 +230,7 @@ class WhenIWork(object):
if headers:
head.update(headers)
resp = requests.put(url, json=params, headers=head)
- assert resp.ok
+ raise_for_status_with_message(resp)
self.__api_resp = resp.json()
return self.resp
else:
@@ -244,10 +254,10 @@ class WhenIWork(object):
if headers:
head.update(headers)
resp = requests.delete(url, headers=head)
- assert resp.ok
+ raise_for_status_with_message(resp)
self.__api_resp = resp.json()
return self.resp
else:
return {'error': 'Token is not set!!'}
else:
- return {'error': 'Method is not str!!'}
\ No newline at end of file
+ return {'error': 'Method is not str!!'}
|
fimion/wheniwork-api-py
|
6563ab8da304442ecf103b9193b04f9f9bda5b16
|
diff --git a/tests/test_init.py b/tests/test_init.py
new file mode 100644
index 0000000..2f16b34
--- /dev/null
+++ b/tests/test_init.py
@@ -0,0 +1,23 @@
+from wheniwork import raise_for_status_with_message
+import pytest
+import requests
+
+
+def test_raise_for_status_with_message_no_error_on_successful_response():
+ successful_response = requests.models.Response()
+ successful_response.status_code = 200
+
+ raise_for_status_with_message(successful_response)
+
+
+def test_raise_for_status_with_message_shows_message_of_error():
+ TEST_ERROR_MESSAGE = 'this should be in error message'
+ EXPECTED_ERROR_MESSAGE = TEST_ERROR_MESSAGE
+ error_500_response = requests.models.Response()
+ error_500_response.status_code = 500
+ error_500_response._content = TEST_ERROR_MESSAGE.encode('utf8')
+
+ with pytest.raises(requests.exceptions.HTTPError) as excinfo:
+ raise_for_status_with_message(error_500_response)
+ assert EXPECTED_ERROR_MESSAGE in str(excinfo.value)
+
|
Error handling: make method to throw exceptions
Make this throw errors correctly
|
0.0
|
6563ab8da304442ecf103b9193b04f9f9bda5b16
|
[
"tests/test_init.py::test_raise_for_status_with_message_no_error_on_successful_response",
"tests/test_init.py::test_raise_for_status_with_message_shows_message_of_error"
] |
[] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2018-11-22 10:57:51+00:00
|
mit
| 2,344 |
|
firebase__firebase-admin-python-122
|
diff --git a/firebase_admin/__init__.py b/firebase_admin/__init__.py
index 0bf08cd..03471a6 100644
--- a/firebase_admin/__init__.py
+++ b/firebase_admin/__init__.py
@@ -218,15 +218,38 @@ class App(object):
self._options = _AppOptions(options)
self._lock = threading.RLock()
self._services = {}
- pid = self._options.get('projectId')
+ self._project_id = App._lookup_project_id(self._credential, self._options)
+
+ @classmethod
+ def _lookup_project_id(cls, credential, options):
+ """Looks up the Firebase project ID associated with an App.
+
+ This method first inspects the app options for a ``projectId`` entry. Then it attempts to
+ get the project ID from the credential used to initialize the app. If that also fails,
+ attempts to look up the ``GCLOUD_PROJECT`` environment variable.
+
+ Args:
+ credential: A Firebase credential instance.
+ options: A Firebase AppOptions instance.
+
+ Returns:
+ str: A project ID string or None.
+
+ Raises:
+ ValueError: If a non-string project ID value is specified.
+ """
+ pid = options.get('projectId')
if not pid:
try:
- pid = self._credential.project_id
+ pid = credential.project_id
except AttributeError:
pass
if not pid:
pid = os.environ.get('GCLOUD_PROJECT')
- self._project_id = pid
+ if pid is not None and not isinstance(pid, six.string_types):
+ raise ValueError(
+ 'Invalid project ID: "{0}". project ID must be a string.'.format(pid))
+ return pid
@property
def name(self):
diff --git a/firebase_admin/firestore.py b/firebase_admin/firestore.py
index 0191c00..1c32368 100644
--- a/firebase_admin/firestore.py
+++ b/firebase_admin/firestore.py
@@ -28,8 +28,6 @@ except ImportError:
raise ImportError('Failed to import the Cloud Firestore library for Python. Make sure '
'to install the "google-cloud-firestore" module.')
-import six
-
from firebase_admin import _utils
@@ -75,7 +73,4 @@ class _FirestoreClient(object):
'Project ID is required to access Firestore. Either set the projectId option, '
'or use service account credentials. Alternatively, set the GCLOUD_PROJECT '
'environment variable.')
- elif not isinstance(project, six.string_types):
- raise ValueError(
- 'Invalid project ID: "{0}". project ID must be a string.'.format(project))
return _FirestoreClient(credentials, project)
diff --git a/firebase_admin/instance_id.py b/firebase_admin/instance_id.py
index 5e4f5d4..70ace55 100644
--- a/firebase_admin/instance_id.py
+++ b/firebase_admin/instance_id.py
@@ -79,9 +79,6 @@ class _InstanceIdService(object):
'Project ID is required to access Instance ID service. Either set the projectId '
'option, or use service account credentials. Alternatively, set the '
'GCLOUD_PROJECT environment variable.')
- elif not isinstance(project_id, six.string_types):
- raise ValueError(
- 'Invalid project ID: "{0}". project ID must be a string.'.format(project_id))
self._project_id = project_id
self._client = _http_client.JsonHttpClient(
credential=app.credential.get_credential(), base_url=_IID_SERVICE_URL)
|
firebase/firebase-admin-python
|
d2d0060ec805f85a73b6b203d6df1d3c9e74cb8b
|
diff --git a/tests/test_app.py b/tests/test_app.py
index e4450eb..aaa3f0a 100644
--- a/tests/test_app.py
+++ b/tests/test_app.py
@@ -317,6 +317,11 @@ class TestFirebaseApp(object):
if project_id:
os.environ[GCLOUD_PROJECT] = project_id
+ def test_non_string_project_id(self):
+ options = {'projectId': {'key': 'not a string'}}
+ with pytest.raises(ValueError):
+ firebase_admin.initialize_app(CREDENTIAL, options=options)
+
def test_app_get(self, init_app):
assert init_app is firebase_admin.get_app(init_app.name)
|
Validate Project ID String Globally
We currently check if project_id is a string in each of the service modules. This can be done in one place -- namely when the project_id is first read in the `App.__init__()` method.
|
0.0
|
d2d0060ec805f85a73b6b203d6df1d3c9e74cb8b
|
[
"tests/test_app.py::TestFirebaseApp::test_non_string_project_id"
] |
[
"tests/test_app.py::TestFirebaseApp::test_default_app_init[cert]",
"tests/test_app.py::TestFirebaseApp::test_default_app_init[refreshtoken]",
"tests/test_app.py::TestFirebaseApp::test_default_app_init[explicit-appdefault]",
"tests/test_app.py::TestFirebaseApp::test_default_app_init[implicit-appdefault]",
"tests/test_app.py::TestFirebaseApp::test_non_default_app_init[cert]",
"tests/test_app.py::TestFirebaseApp::test_non_default_app_init[refreshtoken]",
"tests/test_app.py::TestFirebaseApp::test_non_default_app_init[explicit-appdefault]",
"tests/test_app.py::TestFirebaseApp::test_non_default_app_init[implicit-appdefault]",
"tests/test_app.py::TestFirebaseApp::test_app_init_with_invalid_credential[]",
"tests/test_app.py::TestFirebaseApp::test_app_init_with_invalid_credential[foo]",
"tests/test_app.py::TestFirebaseApp::test_app_init_with_invalid_credential[0]",
"tests/test_app.py::TestFirebaseApp::test_app_init_with_invalid_credential[1]",
"tests/test_app.py::TestFirebaseApp::test_app_init_with_invalid_credential[cred4]",
"tests/test_app.py::TestFirebaseApp::test_app_init_with_invalid_credential[cred5]",
"tests/test_app.py::TestFirebaseApp::test_app_init_with_invalid_credential[cred6]",
"tests/test_app.py::TestFirebaseApp::test_app_init_with_invalid_credential[True]",
"tests/test_app.py::TestFirebaseApp::test_app_init_with_invalid_credential[False]",
"tests/test_app.py::TestFirebaseApp::test_app_init_with_invalid_options[]",
"tests/test_app.py::TestFirebaseApp::test_app_init_with_invalid_options[0]",
"tests/test_app.py::TestFirebaseApp::test_app_init_with_invalid_options[1]",
"tests/test_app.py::TestFirebaseApp::test_app_init_with_invalid_options[options3]",
"tests/test_app.py::TestFirebaseApp::test_app_init_with_invalid_options[options4]",
"tests/test_app.py::TestFirebaseApp::test_app_init_with_invalid_options[True]",
"tests/test_app.py::TestFirebaseApp::test_app_init_with_invalid_options[False]",
"tests/test_app.py::TestFirebaseApp::test_app_init_with_invalid_name[None]",
"tests/test_app.py::TestFirebaseApp::test_app_init_with_invalid_name[]",
"tests/test_app.py::TestFirebaseApp::test_app_init_with_invalid_name[0]",
"tests/test_app.py::TestFirebaseApp::test_app_init_with_invalid_name[1]",
"tests/test_app.py::TestFirebaseApp::test_app_init_with_invalid_name[name4]",
"tests/test_app.py::TestFirebaseApp::test_app_init_with_invalid_name[name5]",
"tests/test_app.py::TestFirebaseApp::test_app_init_with_invalid_name[name6]",
"tests/test_app.py::TestFirebaseApp::test_app_init_with_invalid_name[True]",
"tests/test_app.py::TestFirebaseApp::test_app_init_with_invalid_name[False]",
"tests/test_app.py::TestFirebaseApp::test_app_init_with_invalid_config_file[firebase_config_empty.json]",
"tests/test_app.py::TestFirebaseApp::test_app_init_with_invalid_config_file[firebase_config_invalid.json]",
"tests/test_app.py::TestFirebaseApp::test_app_init_with_invalid_config_file[no_such_file]",
"tests/test_app.py::TestFirebaseApp::test_app_init_with_invalid_config_string",
"tests/test_app.py::TestFirebaseApp::test_app_init_with_default_config[Environment",
"tests/test_app.py::TestFirebaseApp::test_app_init_with_default_config[Invalid",
"tests/test_app.py::TestFirebaseApp::test_project_id_from_options[cert]",
"tests/test_app.py::TestFirebaseApp::test_project_id_from_options[refreshtoken]",
"tests/test_app.py::TestFirebaseApp::test_project_id_from_options[explicit-appdefault]",
"tests/test_app.py::TestFirebaseApp::test_project_id_from_options[implicit-appdefault]",
"tests/test_app.py::TestFirebaseApp::test_project_id_from_credentials",
"tests/test_app.py::TestFirebaseApp::test_project_id_from_environment",
"tests/test_app.py::TestFirebaseApp::test_no_project_id",
"tests/test_app.py::TestFirebaseApp::test_app_get[DefaultApp]",
"tests/test_app.py::TestFirebaseApp::test_app_get[CustomApp]",
"tests/test_app.py::TestFirebaseApp::test_non_existing_app_get[DefaultApp]",
"tests/test_app.py::TestFirebaseApp::test_non_existing_app_get[CustomApp]",
"tests/test_app.py::TestFirebaseApp::test_app_get_with_invalid_name[None]",
"tests/test_app.py::TestFirebaseApp::test_app_get_with_invalid_name[]",
"tests/test_app.py::TestFirebaseApp::test_app_get_with_invalid_name[0]",
"tests/test_app.py::TestFirebaseApp::test_app_get_with_invalid_name[1]",
"tests/test_app.py::TestFirebaseApp::test_app_get_with_invalid_name[name4]",
"tests/test_app.py::TestFirebaseApp::test_app_get_with_invalid_name[name5]",
"tests/test_app.py::TestFirebaseApp::test_app_get_with_invalid_name[name6]",
"tests/test_app.py::TestFirebaseApp::test_app_get_with_invalid_name[True]",
"tests/test_app.py::TestFirebaseApp::test_app_get_with_invalid_name[False]",
"tests/test_app.py::TestFirebaseApp::test_invalid_app_delete[None]",
"tests/test_app.py::TestFirebaseApp::test_invalid_app_delete[]",
"tests/test_app.py::TestFirebaseApp::test_invalid_app_delete[0]",
"tests/test_app.py::TestFirebaseApp::test_invalid_app_delete[1]",
"tests/test_app.py::TestFirebaseApp::test_invalid_app_delete[app4]",
"tests/test_app.py::TestFirebaseApp::test_invalid_app_delete[app5]",
"tests/test_app.py::TestFirebaseApp::test_invalid_app_delete[app6]",
"tests/test_app.py::TestFirebaseApp::test_invalid_app_delete[True]",
"tests/test_app.py::TestFirebaseApp::test_invalid_app_delete[False]",
"tests/test_app.py::TestFirebaseApp::test_invalid_app_delete[app9]",
"tests/test_app.py::TestFirebaseApp::test_app_delete[DefaultApp]",
"tests/test_app.py::TestFirebaseApp::test_app_delete[CustomApp]",
"tests/test_app.py::TestFirebaseApp::test_app_services[DefaultApp]",
"tests/test_app.py::TestFirebaseApp::test_app_services[CustomApp]",
"tests/test_app.py::TestFirebaseApp::test_app_services_invalid_arg[0]",
"tests/test_app.py::TestFirebaseApp::test_app_services_invalid_arg[1]",
"tests/test_app.py::TestFirebaseApp::test_app_services_invalid_arg[True]",
"tests/test_app.py::TestFirebaseApp::test_app_services_invalid_arg[False]",
"tests/test_app.py::TestFirebaseApp::test_app_services_invalid_arg[str]",
"tests/test_app.py::TestFirebaseApp::test_app_services_invalid_arg[arg5]",
"tests/test_app.py::TestFirebaseApp::test_app_services_invalid_arg[arg6]",
"tests/test_app.py::TestFirebaseApp::test_app_services_invalid_arg[arg7]",
"tests/test_app.py::TestFirebaseApp::test_app_services_invalid_app[DefaultApp]",
"tests/test_app.py::TestFirebaseApp::test_app_services_invalid_app[CustomApp]"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2018-01-26 23:00:56+00:00
|
apache-2.0
| 2,345 |
|
firebase__firebase-admin-python-510
|
diff --git a/firebase_admin/credentials.py b/firebase_admin/credentials.py
index 1f207e4..5477e1c 100644
--- a/firebase_admin/credentials.py
+++ b/firebase_admin/credentials.py
@@ -15,6 +15,7 @@
"""Firebase credentials module."""
import collections
import json
+import pathlib
import google.auth
from google.auth.transport import requests
@@ -78,7 +79,7 @@ class Certificate(Base):
ValueError: If the specified certificate is invalid.
"""
super(Certificate, self).__init__()
- if isinstance(cert, str):
+ if _is_file_path(cert):
with open(cert) as json_file:
json_data = json.load(json_file)
elif isinstance(cert, dict):
@@ -179,7 +180,7 @@ class RefreshToken(Base):
ValueError: If the refresh token configuration is invalid.
"""
super(RefreshToken, self).__init__()
- if isinstance(refresh_token, str):
+ if _is_file_path(refresh_token):
with open(refresh_token) as json_file:
json_data = json.load(json_file)
elif isinstance(refresh_token, dict):
@@ -212,3 +213,11 @@ class RefreshToken(Base):
Returns:
google.auth.credentials.Credentials: A Google Auth credential instance."""
return self._g_credential
+
+
+def _is_file_path(path):
+ try:
+ pathlib.Path(path)
+ return True
+ except TypeError:
+ return False
|
firebase/firebase-admin-python
|
939375c021f4c4425beb4bd77b76f0d1be9a7ddd
|
diff --git a/tests/test_credentials.py b/tests/test_credentials.py
index d78ef51..cceb6b6 100644
--- a/tests/test_credentials.py
+++ b/tests/test_credentials.py
@@ -16,6 +16,7 @@
import datetime
import json
import os
+import pathlib
import google.auth
from google.auth import crypt
@@ -47,6 +48,12 @@ class TestCertificate:
testutils.resource_filename('service_account.json'))
self._verify_credential(credential)
+ def test_init_from_path_like(self):
+ path = pathlib.Path(testutils.resource_filename('service_account.json'))
+ credential = credentials.Certificate(path)
+ self._verify_credential(credential)
+
+
def test_init_from_dict(self):
parsed_json = json.loads(testutils.resource('service_account.json'))
credential = credentials.Certificate(parsed_json)
@@ -129,6 +136,11 @@ class TestRefreshToken:
testutils.resource_filename('refresh_token.json'))
self._verify_credential(credential)
+ def test_init_from_path_like(self):
+ path = pathlib.Path(testutils.resource_filename('refresh_token.json'))
+ credential = credentials.RefreshToken(path)
+ self._verify_credential(credential)
+
def test_init_from_dict(self):
parsed_json = json.loads(testutils.resource('refresh_token.json'))
credential = credentials.RefreshToken(parsed_json)
|
pathlib and Django v3.1 Compatibility
* Operating System version: Windows 10 home single language
* Firebase SDK version: _____
* Library version: 4.4.0
* Firebase Product: auth
Recently with Django 3.1 release, the previous os.path library was removed and pathlib is introduced for maintaining the file paths. The class type returned by os.path is str while pathlib returns its own pathlib.Path class type.
This raises ValueError even if the path is correct using pathlib and if we do it using the os.path library it works fine.
ValueError: Invalid certificate argument. Certificate argument must be a file path, or a dict containing th
e parsed file contents.
So, to reproduce this I figured out two ways:
1. Explicit typecasting of the path argument.
```
credentials.Certificate(str(path_to_json))
```
2. Some tweaks into the credentials.py file to accept pathlib object as well.
```
if isinstance(cert, str) or isinstance(cert, pathlib.Path):
with open(cert) as json_file:
json_data = json.load(json_file)
elif isinstance(cert, dict):
json_data = cert
else:
raise ValueError(
'Invalid certificate argument: "{0}". Certificate argument must be a file path, '
'or a dict containing the parsed file contents.'.format(cert))
```
|
0.0
|
939375c021f4c4425beb4bd77b76f0d1be9a7ddd
|
[
"tests/test_credentials.py::TestCertificate::test_init_from_path_like",
"tests/test_credentials.py::TestRefreshToken::test_init_from_path_like"
] |
[
"tests/test_credentials.py::TestCertificate::test_init_from_file",
"tests/test_credentials.py::TestCertificate::test_init_from_dict",
"tests/test_credentials.py::TestCertificate::test_init_from_invalid_certificate[NonExistingFile]",
"tests/test_credentials.py::TestCertificate::test_init_from_invalid_certificate[RefreskToken]",
"tests/test_credentials.py::TestCertificate::test_init_from_invalid_certificate[MalformedPrivateKey]",
"tests/test_credentials.py::TestCertificate::test_init_from_invalid_certificate[MissingClientId]",
"tests/test_credentials.py::TestCertificate::test_invalid_args[None]",
"tests/test_credentials.py::TestCertificate::test_invalid_args[0]",
"tests/test_credentials.py::TestCertificate::test_invalid_args[1]",
"tests/test_credentials.py::TestCertificate::test_invalid_args[True]",
"tests/test_credentials.py::TestCertificate::test_invalid_args[False]",
"tests/test_credentials.py::TestCertificate::test_invalid_args[arg5]",
"tests/test_credentials.py::TestCertificate::test_invalid_args[arg6]",
"tests/test_credentials.py::TestCertificate::test_invalid_args[arg7]",
"tests/test_credentials.py::TestApplicationDefault::test_init[/root/data/temp_dir/tmpwdvx82u0/firebase__firebase-admin-python__0.0/tests/data/service_account.json]",
"tests/test_credentials.py::TestApplicationDefault::test_nonexisting_path[/root/data/temp_dir/tmpwdvx82u0/firebase__firebase-admin-python__0.0/tests/data/non_existing.json]",
"tests/test_credentials.py::TestRefreshToken::test_init_from_file",
"tests/test_credentials.py::TestRefreshToken::test_init_from_dict",
"tests/test_credentials.py::TestRefreshToken::test_init_from_nonexisting_file",
"tests/test_credentials.py::TestRefreshToken::test_init_from_invalid_file",
"tests/test_credentials.py::TestRefreshToken::test_invalid_args[None]",
"tests/test_credentials.py::TestRefreshToken::test_invalid_args[0]",
"tests/test_credentials.py::TestRefreshToken::test_invalid_args[1]",
"tests/test_credentials.py::TestRefreshToken::test_invalid_args[True]",
"tests/test_credentials.py::TestRefreshToken::test_invalid_args[False]",
"tests/test_credentials.py::TestRefreshToken::test_invalid_args[arg5]",
"tests/test_credentials.py::TestRefreshToken::test_invalid_args[arg6]",
"tests/test_credentials.py::TestRefreshToken::test_invalid_args[arg7]",
"tests/test_credentials.py::TestRefreshToken::test_required_field[client_id]",
"tests/test_credentials.py::TestRefreshToken::test_required_field[client_secret]",
"tests/test_credentials.py::TestRefreshToken::test_required_field[refresh_token]"
] |
{
"failed_lite_validators": [
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-12-03 23:54:37+00:00
|
apache-2.0
| 2,346 |
|
firebase__firebase-admin-python-538
|
diff --git a/firebase_admin/_token_gen.py b/firebase_admin/_token_gen.py
index 562e77f..135573c 100644
--- a/firebase_admin/_token_gen.py
+++ b/firebase_admin/_token_gen.py
@@ -29,6 +29,7 @@ import google.oauth2.service_account
from firebase_admin import exceptions
from firebase_admin import _auth_utils
+from firebase_admin import _http_client
# ID token constants
@@ -231,12 +232,37 @@ class TokenGenerator:
return body.get('sessionCookie')
+class CertificateFetchRequest(transport.Request):
+ """A google-auth transport that supports HTTP cache-control.
+
+ Also injects a timeout to each outgoing HTTP request.
+ """
+
+ def __init__(self, timeout_seconds=None):
+ self._session = cachecontrol.CacheControl(requests.Session())
+ self._delegate = transport.requests.Request(self.session)
+ self._timeout_seconds = timeout_seconds
+
+ @property
+ def session(self):
+ return self._session
+
+ @property
+ def timeout_seconds(self):
+ return self._timeout_seconds
+
+ def __call__(self, url, method='GET', body=None, headers=None, timeout=None, **kwargs):
+ timeout = timeout or self.timeout_seconds
+ return self._delegate(
+ url, method=method, body=body, headers=headers, timeout=timeout, **kwargs)
+
+
class TokenVerifier:
"""Verifies ID tokens and session cookies."""
def __init__(self, app):
- session = cachecontrol.CacheControl(requests.Session())
- self.request = transport.requests.Request(session=session)
+ timeout = app.options.get('httpTimeout', _http_client.DEFAULT_TIMEOUT_SECONDS)
+ self.request = CertificateFetchRequest(timeout)
self.id_token_verifier = _JWTVerifier(
project_id=app.project_id, short_name='ID token',
operation='verify_id_token()',
|
firebase/firebase-admin-python
|
04c406978948a076db6198b5f9a1fa96a9addc2e
|
diff --git a/tests/test_token_gen.py b/tests/test_token_gen.py
index 29c70da..d8450c5 100644
--- a/tests/test_token_gen.py
+++ b/tests/test_token_gen.py
@@ -31,6 +31,7 @@ import firebase_admin
from firebase_admin import auth
from firebase_admin import credentials
from firebase_admin import exceptions
+from firebase_admin import _http_client
from firebase_admin import _token_gen
from tests import testutils
@@ -702,3 +703,52 @@ class TestCertificateCaching:
assert len(httpserver.requests) == request_count
verifier.verify_id_token(TEST_ID_TOKEN)
assert len(httpserver.requests) == request_count
+
+
+class TestCertificateFetchTimeout:
+
+ timeout_configs = [
+ ({'httpTimeout': 4}, 4),
+ ({'httpTimeout': None}, None),
+ ({}, _http_client.DEFAULT_TIMEOUT_SECONDS),
+ ]
+
+ @pytest.mark.parametrize('options, timeout', timeout_configs)
+ def test_init_request(self, options, timeout):
+ app = firebase_admin.initialize_app(MOCK_CREDENTIAL, options=options)
+
+ client = auth._get_client(app)
+ request = client._token_verifier.request
+
+ assert isinstance(request, _token_gen.CertificateFetchRequest)
+ assert request.timeout_seconds == timeout
+
+ @pytest.mark.parametrize('options, timeout', timeout_configs)
+ def test_verify_id_token_timeout(self, options, timeout):
+ app = firebase_admin.initialize_app(MOCK_CREDENTIAL, options=options)
+ recorder = self._instrument_session(app)
+
+ auth.verify_id_token(TEST_ID_TOKEN)
+
+ assert len(recorder) == 1
+ assert recorder[0]._extra_kwargs['timeout'] == timeout
+
+ @pytest.mark.parametrize('options, timeout', timeout_configs)
+ def test_verify_session_cookie_timeout(self, options, timeout):
+ app = firebase_admin.initialize_app(MOCK_CREDENTIAL, options=options)
+ recorder = self._instrument_session(app)
+
+ auth.verify_session_cookie(TEST_SESSION_COOKIE)
+
+ assert len(recorder) == 1
+ assert recorder[0]._extra_kwargs['timeout'] == timeout
+
+ def _instrument_session(self, app):
+ client = auth._get_client(app)
+ request = client._token_verifier.request
+ recorder = []
+ request.session.mount('https://', testutils.MockAdapter(MOCK_PUBLIC_CERTS, 200, recorder))
+ return recorder
+
+ def teardown(self):
+ testutils.cleanup_apps()
|
Auth call timeout option
Using firebase-admin sdk v4.0.0 for python3.8.
We have recently noticed that one of our time sensitive services is struggling due to long calls on `auth.verify_id_token` function. We'd like the option to have a timeout for the actual request call that happens here, since it does appear that the google-auth library allows you to set a [timeout](https://google-auth.readthedocs.io/en/latest/reference/google.auth.transport.requests.html#module-google.auth.transport.requests) to the request. We do use the `httpTimeout` on initialization of the app already but it appears this config option is not used at all when making the request.
|
0.0
|
04c406978948a076db6198b5f9a1fa96a9addc2e
|
[
"tests/test_token_gen.py::TestCertificateFetchTimeout::test_init_request[options0-4]"
] |
[
"tests/test_token_gen.py::TestCreateCustomToken::test_valid_params[auth_app0-Basic]",
"tests/test_token_gen.py::TestCreateCustomToken::test_valid_params[auth_app0-NoDevClaims]",
"tests/test_token_gen.py::TestCreateCustomToken::test_valid_params[auth_app0-EmptyDevClaims]",
"tests/test_token_gen.py::TestCreateCustomToken::test_valid_params[auth_app1-Basic]",
"tests/test_token_gen.py::TestCreateCustomToken::test_valid_params[auth_app1-NoDevClaims]",
"tests/test_token_gen.py::TestCreateCustomToken::test_valid_params[auth_app1-EmptyDevClaims]",
"tests/test_token_gen.py::TestCreateCustomToken::test_invalid_params[auth_app0-NoUid]",
"tests/test_token_gen.py::TestCreateCustomToken::test_invalid_params[auth_app0-EmptyUid]",
"tests/test_token_gen.py::TestCreateCustomToken::test_invalid_params[auth_app0-LongUid]",
"tests/test_token_gen.py::TestCreateCustomToken::test_invalid_params[auth_app0-BoolUid]",
"tests/test_token_gen.py::TestCreateCustomToken::test_invalid_params[auth_app0-IntUid]",
"tests/test_token_gen.py::TestCreateCustomToken::test_invalid_params[auth_app0-ListUid]",
"tests/test_token_gen.py::TestCreateCustomToken::test_invalid_params[auth_app0-EmptyDictUid]",
"tests/test_token_gen.py::TestCreateCustomToken::test_invalid_params[auth_app0-NonEmptyDictUid]",
"tests/test_token_gen.py::TestCreateCustomToken::test_invalid_params[auth_app0-BoolClaims]",
"tests/test_token_gen.py::TestCreateCustomToken::test_invalid_params[auth_app0-IntClaims]",
"tests/test_token_gen.py::TestCreateCustomToken::test_invalid_params[auth_app0-StrClaims]",
"tests/test_token_gen.py::TestCreateCustomToken::test_invalid_params[auth_app0-ListClaims]",
"tests/test_token_gen.py::TestCreateCustomToken::test_invalid_params[auth_app0-TupleClaims]",
"tests/test_token_gen.py::TestCreateCustomToken::test_invalid_params[auth_app0-SingleReservedClaim]",
"tests/test_token_gen.py::TestCreateCustomToken::test_invalid_params[auth_app0-MultipleReservedClaims]",
"tests/test_token_gen.py::TestCreateCustomToken::test_invalid_params[auth_app1-NoUid]",
"tests/test_token_gen.py::TestCreateCustomToken::test_invalid_params[auth_app1-EmptyUid]",
"tests/test_token_gen.py::TestCreateCustomToken::test_invalid_params[auth_app1-LongUid]",
"tests/test_token_gen.py::TestCreateCustomToken::test_invalid_params[auth_app1-BoolUid]",
"tests/test_token_gen.py::TestCreateCustomToken::test_invalid_params[auth_app1-IntUid]",
"tests/test_token_gen.py::TestCreateCustomToken::test_invalid_params[auth_app1-ListUid]",
"tests/test_token_gen.py::TestCreateCustomToken::test_invalid_params[auth_app1-EmptyDictUid]",
"tests/test_token_gen.py::TestCreateCustomToken::test_invalid_params[auth_app1-NonEmptyDictUid]",
"tests/test_token_gen.py::TestCreateCustomToken::test_invalid_params[auth_app1-BoolClaims]",
"tests/test_token_gen.py::TestCreateCustomToken::test_invalid_params[auth_app1-IntClaims]",
"tests/test_token_gen.py::TestCreateCustomToken::test_invalid_params[auth_app1-StrClaims]",
"tests/test_token_gen.py::TestCreateCustomToken::test_invalid_params[auth_app1-ListClaims]",
"tests/test_token_gen.py::TestCreateCustomToken::test_invalid_params[auth_app1-TupleClaims]",
"tests/test_token_gen.py::TestCreateCustomToken::test_invalid_params[auth_app1-SingleReservedClaim]",
"tests/test_token_gen.py::TestCreateCustomToken::test_invalid_params[auth_app1-MultipleReservedClaims]",
"tests/test_token_gen.py::TestCreateCustomToken::test_noncert_credential[user_mgt_app0]",
"tests/test_token_gen.py::TestCreateCustomToken::test_noncert_credential[user_mgt_app1]",
"tests/test_token_gen.py::TestCreateCustomToken::test_sign_with_iam_error",
"tests/test_token_gen.py::TestCreateCustomToken::test_sign_with_discovery_failure",
"tests/test_token_gen.py::TestCreateSessionCookie::test_invalid_id_token[user_mgt_app0-None]",
"tests/test_token_gen.py::TestCreateSessionCookie::test_invalid_id_token[user_mgt_app0-]",
"tests/test_token_gen.py::TestCreateSessionCookie::test_invalid_id_token[user_mgt_app0-0]",
"tests/test_token_gen.py::TestCreateSessionCookie::test_invalid_id_token[user_mgt_app0-1]",
"tests/test_token_gen.py::TestCreateSessionCookie::test_invalid_id_token[user_mgt_app0-True]",
"tests/test_token_gen.py::TestCreateSessionCookie::test_invalid_id_token[user_mgt_app0-False]",
"tests/test_token_gen.py::TestCreateSessionCookie::test_invalid_id_token[user_mgt_app0-id_token6]",
"tests/test_token_gen.py::TestCreateSessionCookie::test_invalid_id_token[user_mgt_app0-id_token7]",
"tests/test_token_gen.py::TestCreateSessionCookie::test_invalid_id_token[user_mgt_app0-id_token8]",
"tests/test_token_gen.py::TestCreateSessionCookie::test_invalid_id_token[user_mgt_app1-None]",
"tests/test_token_gen.py::TestCreateSessionCookie::test_invalid_id_token[user_mgt_app1-]",
"tests/test_token_gen.py::TestCreateSessionCookie::test_invalid_id_token[user_mgt_app1-0]",
"tests/test_token_gen.py::TestCreateSessionCookie::test_invalid_id_token[user_mgt_app1-1]",
"tests/test_token_gen.py::TestCreateSessionCookie::test_invalid_id_token[user_mgt_app1-True]",
"tests/test_token_gen.py::TestCreateSessionCookie::test_invalid_id_token[user_mgt_app1-False]",
"tests/test_token_gen.py::TestCreateSessionCookie::test_invalid_id_token[user_mgt_app1-id_token6]",
"tests/test_token_gen.py::TestCreateSessionCookie::test_invalid_id_token[user_mgt_app1-id_token7]",
"tests/test_token_gen.py::TestCreateSessionCookie::test_invalid_id_token[user_mgt_app1-id_token8]",
"tests/test_token_gen.py::TestCreateSessionCookie::test_invalid_expires_in[user_mgt_app0-None]",
"tests/test_token_gen.py::TestCreateSessionCookie::test_invalid_expires_in[user_mgt_app0-]",
"tests/test_token_gen.py::TestCreateSessionCookie::test_invalid_expires_in[user_mgt_app0-True]",
"tests/test_token_gen.py::TestCreateSessionCookie::test_invalid_expires_in[user_mgt_app0-False]",
"tests/test_token_gen.py::TestCreateSessionCookie::test_invalid_expires_in[user_mgt_app0-expires_in4]",
"tests/test_token_gen.py::TestCreateSessionCookie::test_invalid_expires_in[user_mgt_app0-expires_in5]",
"tests/test_token_gen.py::TestCreateSessionCookie::test_invalid_expires_in[user_mgt_app0-expires_in6]",
"tests/test_token_gen.py::TestCreateSessionCookie::test_invalid_expires_in[user_mgt_app0-299]",
"tests/test_token_gen.py::TestCreateSessionCookie::test_invalid_expires_in[user_mgt_app0-1209601]",
"tests/test_token_gen.py::TestCreateSessionCookie::test_invalid_expires_in[user_mgt_app1-None]",
"tests/test_token_gen.py::TestCreateSessionCookie::test_invalid_expires_in[user_mgt_app1-]",
"tests/test_token_gen.py::TestCreateSessionCookie::test_invalid_expires_in[user_mgt_app1-True]",
"tests/test_token_gen.py::TestCreateSessionCookie::test_invalid_expires_in[user_mgt_app1-False]",
"tests/test_token_gen.py::TestCreateSessionCookie::test_invalid_expires_in[user_mgt_app1-expires_in4]",
"tests/test_token_gen.py::TestCreateSessionCookie::test_invalid_expires_in[user_mgt_app1-expires_in5]",
"tests/test_token_gen.py::TestCreateSessionCookie::test_invalid_expires_in[user_mgt_app1-expires_in6]",
"tests/test_token_gen.py::TestCreateSessionCookie::test_invalid_expires_in[user_mgt_app1-299]",
"tests/test_token_gen.py::TestCreateSessionCookie::test_invalid_expires_in[user_mgt_app1-1209601]",
"tests/test_token_gen.py::TestCreateSessionCookie::test_valid_args[user_mgt_app0-3600]",
"tests/test_token_gen.py::TestCreateSessionCookie::test_valid_args[user_mgt_app0-expires_in1]",
"tests/test_token_gen.py::TestCreateSessionCookie::test_valid_args[user_mgt_app0-expires_in2]",
"tests/test_token_gen.py::TestCreateSessionCookie::test_valid_args[user_mgt_app1-3600]",
"tests/test_token_gen.py::TestCreateSessionCookie::test_valid_args[user_mgt_app1-expires_in1]",
"tests/test_token_gen.py::TestCreateSessionCookie::test_valid_args[user_mgt_app1-expires_in2]",
"tests/test_token_gen.py::TestCreateSessionCookie::test_error[user_mgt_app0]",
"tests/test_token_gen.py::TestCreateSessionCookie::test_error[user_mgt_app1]",
"tests/test_token_gen.py::TestCreateSessionCookie::test_error_with_details[user_mgt_app0]",
"tests/test_token_gen.py::TestCreateSessionCookie::test_error_with_details[user_mgt_app1]",
"tests/test_token_gen.py::TestCreateSessionCookie::test_unexpected_error_code[user_mgt_app0]",
"tests/test_token_gen.py::TestCreateSessionCookie::test_unexpected_error_code[user_mgt_app1]",
"tests/test_token_gen.py::TestCreateSessionCookie::test_unexpected_error_response[user_mgt_app0]",
"tests/test_token_gen.py::TestCreateSessionCookie::test_unexpected_error_response[user_mgt_app1]",
"tests/test_token_gen.py::TestCreateSessionCookie::test_unexpected_response[user_mgt_app0]",
"tests/test_token_gen.py::TestCreateSessionCookie::test_unexpected_response[user_mgt_app1]",
"tests/test_token_gen.py::TestVerifyIdToken::test_valid_token[user_mgt_app0-BinaryToken]",
"tests/test_token_gen.py::TestVerifyIdToken::test_valid_token[user_mgt_app0-TextToken]",
"tests/test_token_gen.py::TestVerifyIdToken::test_valid_token[user_mgt_app1-BinaryToken]",
"tests/test_token_gen.py::TestVerifyIdToken::test_valid_token[user_mgt_app1-TextToken]",
"tests/test_token_gen.py::TestVerifyIdToken::test_valid_token_with_tenant[user_mgt_app0]",
"tests/test_token_gen.py::TestVerifyIdToken::test_valid_token_with_tenant[user_mgt_app1]",
"tests/test_token_gen.py::TestVerifyIdToken::test_valid_token_check_revoked[user_mgt_app0-BinaryToken]",
"tests/test_token_gen.py::TestVerifyIdToken::test_valid_token_check_revoked[user_mgt_app0-TextToken]",
"tests/test_token_gen.py::TestVerifyIdToken::test_valid_token_check_revoked[user_mgt_app1-BinaryToken]",
"tests/test_token_gen.py::TestVerifyIdToken::test_valid_token_check_revoked[user_mgt_app1-TextToken]",
"tests/test_token_gen.py::TestVerifyIdToken::test_revoked_token_check_revoked[user_mgt_app0-BinaryToken]",
"tests/test_token_gen.py::TestVerifyIdToken::test_revoked_token_check_revoked[user_mgt_app0-TextToken]",
"tests/test_token_gen.py::TestVerifyIdToken::test_revoked_token_check_revoked[user_mgt_app1-BinaryToken]",
"tests/test_token_gen.py::TestVerifyIdToken::test_revoked_token_check_revoked[user_mgt_app1-TextToken]",
"tests/test_token_gen.py::TestVerifyIdToken::test_invalid_check_revoked[user_mgt_app0-None]",
"tests/test_token_gen.py::TestVerifyIdToken::test_invalid_check_revoked[user_mgt_app0-]",
"tests/test_token_gen.py::TestVerifyIdToken::test_invalid_check_revoked[user_mgt_app0-foo]",
"tests/test_token_gen.py::TestVerifyIdToken::test_invalid_check_revoked[user_mgt_app0-0]",
"tests/test_token_gen.py::TestVerifyIdToken::test_invalid_check_revoked[user_mgt_app0-1]",
"tests/test_token_gen.py::TestVerifyIdToken::test_invalid_check_revoked[user_mgt_app0-arg5]",
"tests/test_token_gen.py::TestVerifyIdToken::test_invalid_check_revoked[user_mgt_app0-arg6]",
"tests/test_token_gen.py::TestVerifyIdToken::test_invalid_check_revoked[user_mgt_app0-arg7]",
"tests/test_token_gen.py::TestVerifyIdToken::test_invalid_check_revoked[user_mgt_app1-None]",
"tests/test_token_gen.py::TestVerifyIdToken::test_invalid_check_revoked[user_mgt_app1-]",
"tests/test_token_gen.py::TestVerifyIdToken::test_invalid_check_revoked[user_mgt_app1-foo]",
"tests/test_token_gen.py::TestVerifyIdToken::test_invalid_check_revoked[user_mgt_app1-0]",
"tests/test_token_gen.py::TestVerifyIdToken::test_invalid_check_revoked[user_mgt_app1-1]",
"tests/test_token_gen.py::TestVerifyIdToken::test_invalid_check_revoked[user_mgt_app1-arg5]",
"tests/test_token_gen.py::TestVerifyIdToken::test_invalid_check_revoked[user_mgt_app1-arg6]",
"tests/test_token_gen.py::TestVerifyIdToken::test_invalid_check_revoked[user_mgt_app1-arg7]",
"tests/test_token_gen.py::TestVerifyIdToken::test_revoked_token_do_not_check_revoked[user_mgt_app0-BinaryToken]",
"tests/test_token_gen.py::TestVerifyIdToken::test_revoked_token_do_not_check_revoked[user_mgt_app0-TextToken]",
"tests/test_token_gen.py::TestVerifyIdToken::test_revoked_token_do_not_check_revoked[user_mgt_app1-BinaryToken]",
"tests/test_token_gen.py::TestVerifyIdToken::test_revoked_token_do_not_check_revoked[user_mgt_app1-TextToken]",
"tests/test_token_gen.py::TestVerifyIdToken::test_invalid_arg[user_mgt_app0-NoneToken]",
"tests/test_token_gen.py::TestVerifyIdToken::test_invalid_arg[user_mgt_app0-EmptyToken]",
"tests/test_token_gen.py::TestVerifyIdToken::test_invalid_arg[user_mgt_app0-BoolToken]",
"tests/test_token_gen.py::TestVerifyIdToken::test_invalid_arg[user_mgt_app0-IntToken]",
"tests/test_token_gen.py::TestVerifyIdToken::test_invalid_arg[user_mgt_app0-ListToken]",
"tests/test_token_gen.py::TestVerifyIdToken::test_invalid_arg[user_mgt_app0-EmptyDictToken]",
"tests/test_token_gen.py::TestVerifyIdToken::test_invalid_arg[user_mgt_app0-NonEmptyDictToken]",
"tests/test_token_gen.py::TestVerifyIdToken::test_invalid_arg[user_mgt_app1-NoneToken]",
"tests/test_token_gen.py::TestVerifyIdToken::test_invalid_arg[user_mgt_app1-EmptyToken]",
"tests/test_token_gen.py::TestVerifyIdToken::test_invalid_arg[user_mgt_app1-BoolToken]",
"tests/test_token_gen.py::TestVerifyIdToken::test_invalid_arg[user_mgt_app1-IntToken]",
"tests/test_token_gen.py::TestVerifyIdToken::test_invalid_arg[user_mgt_app1-ListToken]",
"tests/test_token_gen.py::TestVerifyIdToken::test_invalid_arg[user_mgt_app1-EmptyDictToken]",
"tests/test_token_gen.py::TestVerifyIdToken::test_invalid_arg[user_mgt_app1-NonEmptyDictToken]",
"tests/test_token_gen.py::TestVerifyIdToken::test_invalid_token[user_mgt_app0-NoKid]",
"tests/test_token_gen.py::TestVerifyIdToken::test_invalid_token[user_mgt_app0-WrongKid]",
"tests/test_token_gen.py::TestVerifyIdToken::test_invalid_token[user_mgt_app0-BadAudience]",
"tests/test_token_gen.py::TestVerifyIdToken::test_invalid_token[user_mgt_app0-BadIssuer]",
"tests/test_token_gen.py::TestVerifyIdToken::test_invalid_token[user_mgt_app0-EmptySubject]",
"tests/test_token_gen.py::TestVerifyIdToken::test_invalid_token[user_mgt_app0-IntSubject]",
"tests/test_token_gen.py::TestVerifyIdToken::test_invalid_token[user_mgt_app0-LongStrSubject]",
"tests/test_token_gen.py::TestVerifyIdToken::test_invalid_token[user_mgt_app0-FutureToken]",
"tests/test_token_gen.py::TestVerifyIdToken::test_invalid_token[user_mgt_app0-ExpiredToken]",
"tests/test_token_gen.py::TestVerifyIdToken::test_invalid_token[user_mgt_app0-BadFormatToken]",
"tests/test_token_gen.py::TestVerifyIdToken::test_invalid_token[user_mgt_app1-NoKid]",
"tests/test_token_gen.py::TestVerifyIdToken::test_invalid_token[user_mgt_app1-WrongKid]",
"tests/test_token_gen.py::TestVerifyIdToken::test_invalid_token[user_mgt_app1-BadAudience]",
"tests/test_token_gen.py::TestVerifyIdToken::test_invalid_token[user_mgt_app1-BadIssuer]",
"tests/test_token_gen.py::TestVerifyIdToken::test_invalid_token[user_mgt_app1-EmptySubject]",
"tests/test_token_gen.py::TestVerifyIdToken::test_invalid_token[user_mgt_app1-IntSubject]",
"tests/test_token_gen.py::TestVerifyIdToken::test_invalid_token[user_mgt_app1-LongStrSubject]",
"tests/test_token_gen.py::TestVerifyIdToken::test_invalid_token[user_mgt_app1-FutureToken]",
"tests/test_token_gen.py::TestVerifyIdToken::test_invalid_token[user_mgt_app1-ExpiredToken]",
"tests/test_token_gen.py::TestVerifyIdToken::test_invalid_token[user_mgt_app1-BadFormatToken]",
"tests/test_token_gen.py::TestVerifyIdToken::test_expired_token[user_mgt_app0]",
"tests/test_token_gen.py::TestVerifyIdToken::test_expired_token[user_mgt_app1]",
"tests/test_token_gen.py::TestVerifyIdToken::test_project_id_option",
"tests/test_token_gen.py::TestVerifyIdToken::test_project_id_env_var[env_var_app0]",
"tests/test_token_gen.py::TestVerifyIdToken::test_project_id_env_var[env_var_app1]",
"tests/test_token_gen.py::TestVerifyIdToken::test_custom_token[auth_app0]",
"tests/test_token_gen.py::TestVerifyIdToken::test_custom_token[auth_app1]",
"tests/test_token_gen.py::TestVerifyIdToken::test_certificate_request_failure[user_mgt_app0]",
"tests/test_token_gen.py::TestVerifyIdToken::test_certificate_request_failure[user_mgt_app1]",
"tests/test_token_gen.py::TestVerifySessionCookie::test_valid_cookie[user_mgt_app0-BinaryCookie]",
"tests/test_token_gen.py::TestVerifySessionCookie::test_valid_cookie[user_mgt_app0-TextCookie]",
"tests/test_token_gen.py::TestVerifySessionCookie::test_valid_cookie[user_mgt_app1-BinaryCookie]",
"tests/test_token_gen.py::TestVerifySessionCookie::test_valid_cookie[user_mgt_app1-TextCookie]",
"tests/test_token_gen.py::TestVerifySessionCookie::test_valid_cookie_check_revoked[user_mgt_app0-BinaryCookie]",
"tests/test_token_gen.py::TestVerifySessionCookie::test_valid_cookie_check_revoked[user_mgt_app0-TextCookie]",
"tests/test_token_gen.py::TestVerifySessionCookie::test_valid_cookie_check_revoked[user_mgt_app1-BinaryCookie]",
"tests/test_token_gen.py::TestVerifySessionCookie::test_valid_cookie_check_revoked[user_mgt_app1-TextCookie]",
"tests/test_token_gen.py::TestVerifySessionCookie::test_revoked_cookie_check_revoked[user_mgt_app0-BinaryCookie]",
"tests/test_token_gen.py::TestVerifySessionCookie::test_revoked_cookie_check_revoked[user_mgt_app0-TextCookie]",
"tests/test_token_gen.py::TestVerifySessionCookie::test_revoked_cookie_check_revoked[user_mgt_app1-BinaryCookie]",
"tests/test_token_gen.py::TestVerifySessionCookie::test_revoked_cookie_check_revoked[user_mgt_app1-TextCookie]",
"tests/test_token_gen.py::TestVerifySessionCookie::test_revoked_cookie_does_not_check_revoked[user_mgt_app0-BinaryCookie]",
"tests/test_token_gen.py::TestVerifySessionCookie::test_revoked_cookie_does_not_check_revoked[user_mgt_app0-TextCookie]",
"tests/test_token_gen.py::TestVerifySessionCookie::test_revoked_cookie_does_not_check_revoked[user_mgt_app1-BinaryCookie]",
"tests/test_token_gen.py::TestVerifySessionCookie::test_revoked_cookie_does_not_check_revoked[user_mgt_app1-TextCookie]",
"tests/test_token_gen.py::TestVerifySessionCookie::test_invalid_args[user_mgt_app0-NoneToken]",
"tests/test_token_gen.py::TestVerifySessionCookie::test_invalid_args[user_mgt_app0-EmptyToken]",
"tests/test_token_gen.py::TestVerifySessionCookie::test_invalid_args[user_mgt_app0-BoolToken]",
"tests/test_token_gen.py::TestVerifySessionCookie::test_invalid_args[user_mgt_app0-IntToken]",
"tests/test_token_gen.py::TestVerifySessionCookie::test_invalid_args[user_mgt_app0-ListToken]",
"tests/test_token_gen.py::TestVerifySessionCookie::test_invalid_args[user_mgt_app0-EmptyDictToken]",
"tests/test_token_gen.py::TestVerifySessionCookie::test_invalid_args[user_mgt_app0-NonEmptyDictToken]",
"tests/test_token_gen.py::TestVerifySessionCookie::test_invalid_args[user_mgt_app1-NoneToken]",
"tests/test_token_gen.py::TestVerifySessionCookie::test_invalid_args[user_mgt_app1-EmptyToken]",
"tests/test_token_gen.py::TestVerifySessionCookie::test_invalid_args[user_mgt_app1-BoolToken]",
"tests/test_token_gen.py::TestVerifySessionCookie::test_invalid_args[user_mgt_app1-IntToken]",
"tests/test_token_gen.py::TestVerifySessionCookie::test_invalid_args[user_mgt_app1-ListToken]",
"tests/test_token_gen.py::TestVerifySessionCookie::test_invalid_args[user_mgt_app1-EmptyDictToken]",
"tests/test_token_gen.py::TestVerifySessionCookie::test_invalid_args[user_mgt_app1-NonEmptyDictToken]",
"tests/test_token_gen.py::TestVerifySessionCookie::test_invalid_cookie[user_mgt_app0-NoKid]",
"tests/test_token_gen.py::TestVerifySessionCookie::test_invalid_cookie[user_mgt_app0-WrongKid]",
"tests/test_token_gen.py::TestVerifySessionCookie::test_invalid_cookie[user_mgt_app0-BadAudience]",
"tests/test_token_gen.py::TestVerifySessionCookie::test_invalid_cookie[user_mgt_app0-BadIssuer]",
"tests/test_token_gen.py::TestVerifySessionCookie::test_invalid_cookie[user_mgt_app0-EmptySubject]",
"tests/test_token_gen.py::TestVerifySessionCookie::test_invalid_cookie[user_mgt_app0-IntSubject]",
"tests/test_token_gen.py::TestVerifySessionCookie::test_invalid_cookie[user_mgt_app0-LongStrSubject]",
"tests/test_token_gen.py::TestVerifySessionCookie::test_invalid_cookie[user_mgt_app0-FutureCookie]",
"tests/test_token_gen.py::TestVerifySessionCookie::test_invalid_cookie[user_mgt_app0-ExpiredCookie]",
"tests/test_token_gen.py::TestVerifySessionCookie::test_invalid_cookie[user_mgt_app0-BadFormatCookie]",
"tests/test_token_gen.py::TestVerifySessionCookie::test_invalid_cookie[user_mgt_app0-IDToken]",
"tests/test_token_gen.py::TestVerifySessionCookie::test_invalid_cookie[user_mgt_app1-NoKid]",
"tests/test_token_gen.py::TestVerifySessionCookie::test_invalid_cookie[user_mgt_app1-WrongKid]",
"tests/test_token_gen.py::TestVerifySessionCookie::test_invalid_cookie[user_mgt_app1-BadAudience]",
"tests/test_token_gen.py::TestVerifySessionCookie::test_invalid_cookie[user_mgt_app1-BadIssuer]",
"tests/test_token_gen.py::TestVerifySessionCookie::test_invalid_cookie[user_mgt_app1-EmptySubject]",
"tests/test_token_gen.py::TestVerifySessionCookie::test_invalid_cookie[user_mgt_app1-IntSubject]",
"tests/test_token_gen.py::TestVerifySessionCookie::test_invalid_cookie[user_mgt_app1-LongStrSubject]",
"tests/test_token_gen.py::TestVerifySessionCookie::test_invalid_cookie[user_mgt_app1-FutureCookie]",
"tests/test_token_gen.py::TestVerifySessionCookie::test_invalid_cookie[user_mgt_app1-ExpiredCookie]",
"tests/test_token_gen.py::TestVerifySessionCookie::test_invalid_cookie[user_mgt_app1-BadFormatCookie]",
"tests/test_token_gen.py::TestVerifySessionCookie::test_invalid_cookie[user_mgt_app1-IDToken]",
"tests/test_token_gen.py::TestVerifySessionCookie::test_expired_cookie[user_mgt_app0]",
"tests/test_token_gen.py::TestVerifySessionCookie::test_expired_cookie[user_mgt_app1]",
"tests/test_token_gen.py::TestVerifySessionCookie::test_project_id_option",
"tests/test_token_gen.py::TestVerifySessionCookie::test_project_id_env_var[env_var_app0]",
"tests/test_token_gen.py::TestVerifySessionCookie::test_custom_token[auth_app0]",
"tests/test_token_gen.py::TestVerifySessionCookie::test_custom_token[auth_app1]",
"tests/test_token_gen.py::TestVerifySessionCookie::test_certificate_request_failure[user_mgt_app0]",
"tests/test_token_gen.py::TestVerifySessionCookie::test_certificate_request_failure[user_mgt_app1]",
"tests/test_token_gen.py::TestCertificateCaching::test_certificate_caching[user_mgt_app0]",
"tests/test_token_gen.py::TestCertificateCaching::test_certificate_caching[user_mgt_app1]"
] |
{
"failed_lite_validators": [
"has_hyperlinks"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-03-23 23:17:21+00:00
|
apache-2.0
| 2,347 |
|
firebase__firebase-admin-python-96
|
diff --git a/firebase_admin/db.py b/firebase_admin/db.py
index d6f5f99..1efa31e 100644
--- a/firebase_admin/db.py
+++ b/firebase_admin/db.py
@@ -442,10 +442,10 @@ class Query(object):
Query: The updated Query instance.
Raises:
- ValueError: If the value is empty or None.
+ ValueError: If the value is None.
"""
- if not start:
- raise ValueError('Start value must not be empty or None.')
+ if start is None:
+ raise ValueError('Start value must not be None.')
self._params['startAt'] = json.dumps(start)
return self
@@ -462,10 +462,10 @@ class Query(object):
Query: The updated Query instance.
Raises:
- ValueError: If the value is empty or None.
+ ValueError: If the value is None.
"""
- if not end:
- raise ValueError('End value must not be empty or None.')
+ if end is None:
+ raise ValueError('End value must not be None.')
self._params['endAt'] = json.dumps(end)
return self
@@ -481,10 +481,10 @@ class Query(object):
Query: The updated Query instance.
Raises:
- ValueError: If the value is empty or None.
+ ValueError: If the value is None.
"""
- if not value:
- raise ValueError('Equal to value must not be empty or None.')
+ if value is None:
+ raise ValueError('Equal to value must not be None.')
self._params['equalTo'] = json.dumps(value)
return self
|
firebase/firebase-admin-python
|
d8a93457a5dfba8ddb12d229a6f717565f0975e2
|
diff --git a/tests/test_db.py b/tests/test_db.py
index 98be17a..79547c2 100644
--- a/tests/test_db.py
+++ b/tests/test_db.py
@@ -694,16 +694,31 @@ class TestQuery(object):
with pytest.raises(ValueError):
query.start_at(None)
+ @pytest.mark.parametrize('arg', ['', 'foo', True, False, 0, 1, dict()])
+ def test_valid_start_at(self, arg):
+ query = self.ref.order_by_child('foo').start_at(arg)
+ assert query._querystr == 'orderBy="foo"&startAt={0}'.format(json.dumps(arg))
+
def test_end_at_none(self):
query = self.ref.order_by_child('foo')
with pytest.raises(ValueError):
query.end_at(None)
+ @pytest.mark.parametrize('arg', ['', 'foo', True, False, 0, 1, dict()])
+ def test_valid_end_at(self, arg):
+ query = self.ref.order_by_child('foo').end_at(arg)
+ assert query._querystr == 'endAt={0}&orderBy="foo"'.format(json.dumps(arg))
+
def test_equal_to_none(self):
query = self.ref.order_by_child('foo')
with pytest.raises(ValueError):
query.equal_to(None)
+ @pytest.mark.parametrize('arg', ['', 'foo', True, False, 0, 1, dict()])
+ def test_valid_equal_to(self, arg):
+ query = self.ref.order_by_child('foo').equal_to(arg)
+ assert query._querystr == 'equalTo={0}&orderBy="foo"'.format(json.dumps(arg))
+
def test_range_query(self, initquery):
query, order_by = initquery
query.start_at(1)
|
Unable to query by boolean False
* Operating System version: OSX 10.11.4
* Firebase SDK version: Firebase Admin Python SDK 2.4.0
* Firebase Product: database
In firebase-admin-python/firebase_admin/db.py , it's unable to use equal_to(), start_at(), and end_at() with a boolean False value. It throws `ValueError: Equal to value must not be empty or None.`
Suggest the condition of False boolean value to be catered.
|
0.0
|
d8a93457a5dfba8ddb12d229a6f717565f0975e2
|
[
"tests/test_db.py::TestQuery::test_valid_start_at[]",
"tests/test_db.py::TestQuery::test_valid_start_at[False]",
"tests/test_db.py::TestQuery::test_valid_start_at[0]",
"tests/test_db.py::TestQuery::test_valid_start_at[arg6]",
"tests/test_db.py::TestQuery::test_valid_end_at[]",
"tests/test_db.py::TestQuery::test_valid_end_at[False]",
"tests/test_db.py::TestQuery::test_valid_end_at[0]",
"tests/test_db.py::TestQuery::test_valid_end_at[arg6]",
"tests/test_db.py::TestQuery::test_valid_equal_to[]",
"tests/test_db.py::TestQuery::test_valid_equal_to[False]",
"tests/test_db.py::TestQuery::test_valid_equal_to[0]",
"tests/test_db.py::TestQuery::test_valid_equal_to[arg6]"
] |
[
"tests/test_db.py::TestReferencePath::test_valid_path[/-expected0]",
"tests/test_db.py::TestReferencePath::test_valid_path[-expected1]",
"tests/test_db.py::TestReferencePath::test_valid_path[/foo-expected2]",
"tests/test_db.py::TestReferencePath::test_valid_path[foo-expected3]",
"tests/test_db.py::TestReferencePath::test_valid_path[/foo/bar-expected4]",
"tests/test_db.py::TestReferencePath::test_valid_path[foo/bar-expected5]",
"tests/test_db.py::TestReferencePath::test_valid_path[/foo/bar/-expected6]",
"tests/test_db.py::TestReferencePath::test_invalid_key[None]",
"tests/test_db.py::TestReferencePath::test_invalid_key[True]",
"tests/test_db.py::TestReferencePath::test_invalid_key[False]",
"tests/test_db.py::TestReferencePath::test_invalid_key[0]",
"tests/test_db.py::TestReferencePath::test_invalid_key[1]",
"tests/test_db.py::TestReferencePath::test_invalid_key[path5]",
"tests/test_db.py::TestReferencePath::test_invalid_key[path6]",
"tests/test_db.py::TestReferencePath::test_invalid_key[path7]",
"tests/test_db.py::TestReferencePath::test_invalid_key[path8]",
"tests/test_db.py::TestReferencePath::test_invalid_key[foo#]",
"tests/test_db.py::TestReferencePath::test_invalid_key[foo.]",
"tests/test_db.py::TestReferencePath::test_invalid_key[foo$]",
"tests/test_db.py::TestReferencePath::test_invalid_key[foo[]",
"tests/test_db.py::TestReferencePath::test_invalid_key[foo]]",
"tests/test_db.py::TestReferencePath::test_valid_child[foo-expected0]",
"tests/test_db.py::TestReferencePath::test_valid_child[foo/bar-expected1]",
"tests/test_db.py::TestReferencePath::test_valid_child[foo/bar/-expected2]",
"tests/test_db.py::TestReferencePath::test_invalid_child[None]",
"tests/test_db.py::TestReferencePath::test_invalid_child[]",
"tests/test_db.py::TestReferencePath::test_invalid_child[/foo]",
"tests/test_db.py::TestReferencePath::test_invalid_child[/foo/bar]",
"tests/test_db.py::TestReferencePath::test_invalid_child[True]",
"tests/test_db.py::TestReferencePath::test_invalid_child[False]",
"tests/test_db.py::TestReferencePath::test_invalid_child[0]",
"tests/test_db.py::TestReferencePath::test_invalid_child[1]",
"tests/test_db.py::TestReferencePath::test_invalid_child[child8]",
"tests/test_db.py::TestReferencePath::test_invalid_child[child9]",
"tests/test_db.py::TestReferencePath::test_invalid_child[child10]",
"tests/test_db.py::TestReferencePath::test_invalid_child[foo#]",
"tests/test_db.py::TestReferencePath::test_invalid_child[foo.]",
"tests/test_db.py::TestReferencePath::test_invalid_child[foo$]",
"tests/test_db.py::TestReferencePath::test_invalid_child[foo[]",
"tests/test_db.py::TestReferencePath::test_invalid_child[foo]]",
"tests/test_db.py::TestReferencePath::test_invalid_child[child16]",
"tests/test_db.py::TestReference::test_get_value[]",
"tests/test_db.py::TestReference::test_get_value[foo]",
"tests/test_db.py::TestReference::test_get_value[0]",
"tests/test_db.py::TestReference::test_get_value[1]",
"tests/test_db.py::TestReference::test_get_value[100]",
"tests/test_db.py::TestReference::test_get_value[1.2]",
"tests/test_db.py::TestReference::test_get_value[True]",
"tests/test_db.py::TestReference::test_get_value[False]",
"tests/test_db.py::TestReference::test_get_value[data8]",
"tests/test_db.py::TestReference::test_get_value[data9]",
"tests/test_db.py::TestReference::test_get_value[data10]",
"tests/test_db.py::TestReference::test_get_value[data11]",
"tests/test_db.py::TestReference::test_get_with_etag[]",
"tests/test_db.py::TestReference::test_get_with_etag[foo]",
"tests/test_db.py::TestReference::test_get_with_etag[0]",
"tests/test_db.py::TestReference::test_get_with_etag[1]",
"tests/test_db.py::TestReference::test_get_with_etag[100]",
"tests/test_db.py::TestReference::test_get_with_etag[1.2]",
"tests/test_db.py::TestReference::test_get_with_etag[True]",
"tests/test_db.py::TestReference::test_get_with_etag[False]",
"tests/test_db.py::TestReference::test_get_with_etag[data8]",
"tests/test_db.py::TestReference::test_get_with_etag[data9]",
"tests/test_db.py::TestReference::test_get_with_etag[data10]",
"tests/test_db.py::TestReference::test_get_with_etag[data11]",
"tests/test_db.py::TestReference::test_get_if_changed[]",
"tests/test_db.py::TestReference::test_get_if_changed[foo]",
"tests/test_db.py::TestReference::test_get_if_changed[0]",
"tests/test_db.py::TestReference::test_get_if_changed[1]",
"tests/test_db.py::TestReference::test_get_if_changed[100]",
"tests/test_db.py::TestReference::test_get_if_changed[1.2]",
"tests/test_db.py::TestReference::test_get_if_changed[True]",
"tests/test_db.py::TestReference::test_get_if_changed[False]",
"tests/test_db.py::TestReference::test_get_if_changed[data8]",
"tests/test_db.py::TestReference::test_get_if_changed[data9]",
"tests/test_db.py::TestReference::test_get_if_changed[data10]",
"tests/test_db.py::TestReference::test_get_if_changed[data11]",
"tests/test_db.py::TestReference::test_get_if_changed_invalid_etag[0]",
"tests/test_db.py::TestReference::test_get_if_changed_invalid_etag[1]",
"tests/test_db.py::TestReference::test_get_if_changed_invalid_etag[True]",
"tests/test_db.py::TestReference::test_get_if_changed_invalid_etag[False]",
"tests/test_db.py::TestReference::test_get_if_changed_invalid_etag[etag4]",
"tests/test_db.py::TestReference::test_get_if_changed_invalid_etag[etag5]",
"tests/test_db.py::TestReference::test_get_if_changed_invalid_etag[etag6]",
"tests/test_db.py::TestReference::test_order_by_query[]",
"tests/test_db.py::TestReference::test_order_by_query[foo]",
"tests/test_db.py::TestReference::test_order_by_query[0]",
"tests/test_db.py::TestReference::test_order_by_query[1]",
"tests/test_db.py::TestReference::test_order_by_query[100]",
"tests/test_db.py::TestReference::test_order_by_query[1.2]",
"tests/test_db.py::TestReference::test_order_by_query[True]",
"tests/test_db.py::TestReference::test_order_by_query[False]",
"tests/test_db.py::TestReference::test_order_by_query[data8]",
"tests/test_db.py::TestReference::test_order_by_query[data9]",
"tests/test_db.py::TestReference::test_order_by_query[data10]",
"tests/test_db.py::TestReference::test_order_by_query[data11]",
"tests/test_db.py::TestReference::test_limit_query[]",
"tests/test_db.py::TestReference::test_limit_query[foo]",
"tests/test_db.py::TestReference::test_limit_query[0]",
"tests/test_db.py::TestReference::test_limit_query[1]",
"tests/test_db.py::TestReference::test_limit_query[100]",
"tests/test_db.py::TestReference::test_limit_query[1.2]",
"tests/test_db.py::TestReference::test_limit_query[True]",
"tests/test_db.py::TestReference::test_limit_query[False]",
"tests/test_db.py::TestReference::test_limit_query[data8]",
"tests/test_db.py::TestReference::test_limit_query[data9]",
"tests/test_db.py::TestReference::test_limit_query[data10]",
"tests/test_db.py::TestReference::test_limit_query[data11]",
"tests/test_db.py::TestReference::test_range_query[]",
"tests/test_db.py::TestReference::test_range_query[foo]",
"tests/test_db.py::TestReference::test_range_query[0]",
"tests/test_db.py::TestReference::test_range_query[1]",
"tests/test_db.py::TestReference::test_range_query[100]",
"tests/test_db.py::TestReference::test_range_query[1.2]",
"tests/test_db.py::TestReference::test_range_query[True]",
"tests/test_db.py::TestReference::test_range_query[False]",
"tests/test_db.py::TestReference::test_range_query[data8]",
"tests/test_db.py::TestReference::test_range_query[data9]",
"tests/test_db.py::TestReference::test_range_query[data10]",
"tests/test_db.py::TestReference::test_range_query[data11]",
"tests/test_db.py::TestReference::test_set_value[]",
"tests/test_db.py::TestReference::test_set_value[foo]",
"tests/test_db.py::TestReference::test_set_value[0]",
"tests/test_db.py::TestReference::test_set_value[1]",
"tests/test_db.py::TestReference::test_set_value[100]",
"tests/test_db.py::TestReference::test_set_value[1.2]",
"tests/test_db.py::TestReference::test_set_value[True]",
"tests/test_db.py::TestReference::test_set_value[False]",
"tests/test_db.py::TestReference::test_set_value[data8]",
"tests/test_db.py::TestReference::test_set_value[data9]",
"tests/test_db.py::TestReference::test_set_value[data10]",
"tests/test_db.py::TestReference::test_set_value[data11]",
"tests/test_db.py::TestReference::test_set_none_value",
"tests/test_db.py::TestReference::test_set_non_json_value[value0]",
"tests/test_db.py::TestReference::test_set_non_json_value[value1]",
"tests/test_db.py::TestReference::test_set_non_json_value[value2]",
"tests/test_db.py::TestReference::test_update_children",
"tests/test_db.py::TestReference::test_set_if_unchanged_success[]",
"tests/test_db.py::TestReference::test_set_if_unchanged_success[foo]",
"tests/test_db.py::TestReference::test_set_if_unchanged_success[0]",
"tests/test_db.py::TestReference::test_set_if_unchanged_success[1]",
"tests/test_db.py::TestReference::test_set_if_unchanged_success[100]",
"tests/test_db.py::TestReference::test_set_if_unchanged_success[1.2]",
"tests/test_db.py::TestReference::test_set_if_unchanged_success[True]",
"tests/test_db.py::TestReference::test_set_if_unchanged_success[False]",
"tests/test_db.py::TestReference::test_set_if_unchanged_success[data8]",
"tests/test_db.py::TestReference::test_set_if_unchanged_success[data9]",
"tests/test_db.py::TestReference::test_set_if_unchanged_success[data10]",
"tests/test_db.py::TestReference::test_set_if_unchanged_success[data11]",
"tests/test_db.py::TestReference::test_set_if_unchanged_failure[]",
"tests/test_db.py::TestReference::test_set_if_unchanged_failure[foo]",
"tests/test_db.py::TestReference::test_set_if_unchanged_failure[0]",
"tests/test_db.py::TestReference::test_set_if_unchanged_failure[1]",
"tests/test_db.py::TestReference::test_set_if_unchanged_failure[100]",
"tests/test_db.py::TestReference::test_set_if_unchanged_failure[1.2]",
"tests/test_db.py::TestReference::test_set_if_unchanged_failure[True]",
"tests/test_db.py::TestReference::test_set_if_unchanged_failure[False]",
"tests/test_db.py::TestReference::test_set_if_unchanged_failure[data8]",
"tests/test_db.py::TestReference::test_set_if_unchanged_failure[data9]",
"tests/test_db.py::TestReference::test_set_if_unchanged_failure[data10]",
"tests/test_db.py::TestReference::test_set_if_unchanged_failure[data11]",
"tests/test_db.py::TestReference::test_set_if_unchanged_invalid_etag[0]",
"tests/test_db.py::TestReference::test_set_if_unchanged_invalid_etag[1]",
"tests/test_db.py::TestReference::test_set_if_unchanged_invalid_etag[True]",
"tests/test_db.py::TestReference::test_set_if_unchanged_invalid_etag[False]",
"tests/test_db.py::TestReference::test_set_if_unchanged_invalid_etag[etag4]",
"tests/test_db.py::TestReference::test_set_if_unchanged_invalid_etag[etag5]",
"tests/test_db.py::TestReference::test_set_if_unchanged_invalid_etag[etag6]",
"tests/test_db.py::TestReference::test_set_if_unchanged_none_value",
"tests/test_db.py::TestReference::test_set_if_unchanged_non_json_value[value0]",
"tests/test_db.py::TestReference::test_set_if_unchanged_non_json_value[value1]",
"tests/test_db.py::TestReference::test_set_if_unchanged_non_json_value[value2]",
"tests/test_db.py::TestReference::test_update_children_default",
"tests/test_db.py::TestReference::test_set_invalid_update[None]",
"tests/test_db.py::TestReference::test_set_invalid_update[update1]",
"tests/test_db.py::TestReference::test_set_invalid_update[update2]",
"tests/test_db.py::TestReference::test_set_invalid_update[update3]",
"tests/test_db.py::TestReference::test_set_invalid_update[]",
"tests/test_db.py::TestReference::test_set_invalid_update[foo]",
"tests/test_db.py::TestReference::test_set_invalid_update[0]",
"tests/test_db.py::TestReference::test_set_invalid_update[1]",
"tests/test_db.py::TestReference::test_set_invalid_update[update8]",
"tests/test_db.py::TestReference::test_set_invalid_update[update9]",
"tests/test_db.py::TestReference::test_set_invalid_update[update10]",
"tests/test_db.py::TestReference::test_push[]",
"tests/test_db.py::TestReference::test_push[foo]",
"tests/test_db.py::TestReference::test_push[0]",
"tests/test_db.py::TestReference::test_push[1]",
"tests/test_db.py::TestReference::test_push[100]",
"tests/test_db.py::TestReference::test_push[1.2]",
"tests/test_db.py::TestReference::test_push[True]",
"tests/test_db.py::TestReference::test_push[False]",
"tests/test_db.py::TestReference::test_push[data8]",
"tests/test_db.py::TestReference::test_push[data9]",
"tests/test_db.py::TestReference::test_push[data10]",
"tests/test_db.py::TestReference::test_push[data11]",
"tests/test_db.py::TestReference::test_push_default",
"tests/test_db.py::TestReference::test_push_none_value",
"tests/test_db.py::TestReference::test_delete",
"tests/test_db.py::TestReference::test_transaction",
"tests/test_db.py::TestReference::test_transaction_scalar",
"tests/test_db.py::TestReference::test_transaction_error",
"tests/test_db.py::TestReference::test_transaction_invalid_function[None]",
"tests/test_db.py::TestReference::test_transaction_invalid_function[0]",
"tests/test_db.py::TestReference::test_transaction_invalid_function[1]",
"tests/test_db.py::TestReference::test_transaction_invalid_function[True]",
"tests/test_db.py::TestReference::test_transaction_invalid_function[False]",
"tests/test_db.py::TestReference::test_transaction_invalid_function[foo]",
"tests/test_db.py::TestReference::test_transaction_invalid_function[func6]",
"tests/test_db.py::TestReference::test_transaction_invalid_function[func7]",
"tests/test_db.py::TestReference::test_transaction_invalid_function[func8]",
"tests/test_db.py::TestReference::test_get_root_reference",
"tests/test_db.py::TestReference::test_get_reference[/-expected0]",
"tests/test_db.py::TestReference::test_get_reference[-expected1]",
"tests/test_db.py::TestReference::test_get_reference[/foo-expected2]",
"tests/test_db.py::TestReference::test_get_reference[foo-expected3]",
"tests/test_db.py::TestReference::test_get_reference[/foo/bar-expected4]",
"tests/test_db.py::TestReference::test_get_reference[foo/bar-expected5]",
"tests/test_db.py::TestReference::test_get_reference[/foo/bar/-expected6]",
"tests/test_db.py::TestReference::test_server_error[400]",
"tests/test_db.py::TestReference::test_server_error[401]",
"tests/test_db.py::TestReference::test_server_error[500]",
"tests/test_db.py::TestReference::test_other_error[400]",
"tests/test_db.py::TestReference::test_other_error[401]",
"tests/test_db.py::TestReference::test_other_error[500]",
"tests/test_db.py::TestReferenceWithAuthOverride::test_get_value",
"tests/test_db.py::TestReferenceWithAuthOverride::test_set_value",
"tests/test_db.py::TestReferenceWithAuthOverride::test_order_by_query",
"tests/test_db.py::TestReferenceWithAuthOverride::test_range_query",
"tests/test_db.py::TestDatabseInitialization::test_no_app",
"tests/test_db.py::TestDatabseInitialization::test_no_db_url",
"tests/test_db.py::TestDatabseInitialization::test_invalid_db_url[None]",
"tests/test_db.py::TestDatabseInitialization::test_invalid_db_url[]",
"tests/test_db.py::TestDatabseInitialization::test_invalid_db_url[foo]",
"tests/test_db.py::TestDatabseInitialization::test_invalid_db_url[http://test.firebaseio.com]",
"tests/test_db.py::TestDatabseInitialization::test_invalid_db_url[https://google.com]",
"tests/test_db.py::TestDatabseInitialization::test_invalid_db_url[True]",
"tests/test_db.py::TestDatabseInitialization::test_invalid_db_url[False]",
"tests/test_db.py::TestDatabseInitialization::test_invalid_db_url[1]",
"tests/test_db.py::TestDatabseInitialization::test_invalid_db_url[0]",
"tests/test_db.py::TestDatabseInitialization::test_invalid_db_url[url9]",
"tests/test_db.py::TestDatabseInitialization::test_invalid_db_url[url10]",
"tests/test_db.py::TestDatabseInitialization::test_invalid_db_url[url11]",
"tests/test_db.py::TestDatabseInitialization::test_invalid_db_url[url12]",
"tests/test_db.py::TestDatabseInitialization::test_valid_auth_override[override0]",
"tests/test_db.py::TestDatabseInitialization::test_valid_auth_override[override1]",
"tests/test_db.py::TestDatabseInitialization::test_valid_auth_override[None]",
"tests/test_db.py::TestDatabseInitialization::test_invalid_auth_override[]",
"tests/test_db.py::TestDatabseInitialization::test_invalid_auth_override[foo]",
"tests/test_db.py::TestDatabseInitialization::test_invalid_auth_override[0]",
"tests/test_db.py::TestDatabseInitialization::test_invalid_auth_override[1]",
"tests/test_db.py::TestDatabseInitialization::test_invalid_auth_override[True]",
"tests/test_db.py::TestDatabseInitialization::test_invalid_auth_override[False]",
"tests/test_db.py::TestDatabseInitialization::test_invalid_auth_override[override6]",
"tests/test_db.py::TestDatabseInitialization::test_invalid_auth_override[override7]",
"tests/test_db.py::TestDatabseInitialization::test_invalid_auth_override[override8]",
"tests/test_db.py::TestDatabseInitialization::test_http_timeout",
"tests/test_db.py::TestDatabseInitialization::test_app_delete",
"tests/test_db.py::TestDatabseInitialization::test_user_agent_format",
"tests/test_db.py::TestQuery::test_invalid_path[]",
"tests/test_db.py::TestQuery::test_invalid_path[None]",
"tests/test_db.py::TestQuery::test_invalid_path[/]",
"tests/test_db.py::TestQuery::test_invalid_path[/foo]",
"tests/test_db.py::TestQuery::test_invalid_path[0]",
"tests/test_db.py::TestQuery::test_invalid_path[1]",
"tests/test_db.py::TestQuery::test_invalid_path[True]",
"tests/test_db.py::TestQuery::test_invalid_path[False]",
"tests/test_db.py::TestQuery::test_invalid_path[path8]",
"tests/test_db.py::TestQuery::test_invalid_path[path9]",
"tests/test_db.py::TestQuery::test_invalid_path[path10]",
"tests/test_db.py::TestQuery::test_invalid_path[path11]",
"tests/test_db.py::TestQuery::test_invalid_path[$foo]",
"tests/test_db.py::TestQuery::test_invalid_path[.foo]",
"tests/test_db.py::TestQuery::test_invalid_path[#foo]",
"tests/test_db.py::TestQuery::test_invalid_path[[foo]",
"tests/test_db.py::TestQuery::test_invalid_path[foo]]",
"tests/test_db.py::TestQuery::test_invalid_path[$key]",
"tests/test_db.py::TestQuery::test_invalid_path[$value]",
"tests/test_db.py::TestQuery::test_invalid_path[$priority]",
"tests/test_db.py::TestQuery::test_order_by_valid_path[foo-foo]",
"tests/test_db.py::TestQuery::test_order_by_valid_path[foo/bar-foo/bar]",
"tests/test_db.py::TestQuery::test_order_by_valid_path[foo/bar/-foo/bar]",
"tests/test_db.py::TestQuery::test_filter_by_valid_path[foo-foo]",
"tests/test_db.py::TestQuery::test_filter_by_valid_path[foo/bar-foo/bar]",
"tests/test_db.py::TestQuery::test_filter_by_valid_path[foo/bar/-foo/bar]",
"tests/test_db.py::TestQuery::test_order_by_key",
"tests/test_db.py::TestQuery::test_key_filter",
"tests/test_db.py::TestQuery::test_order_by_value",
"tests/test_db.py::TestQuery::test_value_filter",
"tests/test_db.py::TestQuery::test_multiple_limits",
"tests/test_db.py::TestQuery::test_invalid_limit[None]",
"tests/test_db.py::TestQuery::test_invalid_limit[-1]",
"tests/test_db.py::TestQuery::test_invalid_limit[foo]",
"tests/test_db.py::TestQuery::test_invalid_limit[1.2]",
"tests/test_db.py::TestQuery::test_invalid_limit[limit4]",
"tests/test_db.py::TestQuery::test_invalid_limit[limit5]",
"tests/test_db.py::TestQuery::test_invalid_limit[limit6]",
"tests/test_db.py::TestQuery::test_invalid_limit[limit7]",
"tests/test_db.py::TestQuery::test_start_at_none",
"tests/test_db.py::TestQuery::test_valid_start_at[foo]",
"tests/test_db.py::TestQuery::test_valid_start_at[True]",
"tests/test_db.py::TestQuery::test_valid_start_at[1]",
"tests/test_db.py::TestQuery::test_end_at_none",
"tests/test_db.py::TestQuery::test_valid_end_at[foo]",
"tests/test_db.py::TestQuery::test_valid_end_at[True]",
"tests/test_db.py::TestQuery::test_valid_end_at[1]",
"tests/test_db.py::TestQuery::test_equal_to_none",
"tests/test_db.py::TestQuery::test_valid_equal_to[foo]",
"tests/test_db.py::TestQuery::test_valid_equal_to[True]",
"tests/test_db.py::TestQuery::test_valid_equal_to[1]",
"tests/test_db.py::TestQuery::test_range_query[foo]",
"tests/test_db.py::TestQuery::test_range_query[$key]",
"tests/test_db.py::TestQuery::test_range_query[$value]",
"tests/test_db.py::TestQuery::test_limit_first_query[foo]",
"tests/test_db.py::TestQuery::test_limit_first_query[$key]",
"tests/test_db.py::TestQuery::test_limit_first_query[$value]",
"tests/test_db.py::TestQuery::test_limit_last_query[foo]",
"tests/test_db.py::TestQuery::test_limit_last_query[$key]",
"tests/test_db.py::TestQuery::test_limit_last_query[$value]",
"tests/test_db.py::TestQuery::test_all_in[foo]",
"tests/test_db.py::TestQuery::test_all_in[$key]",
"tests/test_db.py::TestQuery::test_all_in[$value]",
"tests/test_db.py::TestQuery::test_invalid_query_args",
"tests/test_db.py::TestSorter::test_order_by_value[result0-expected0]",
"tests/test_db.py::TestSorter::test_order_by_value[result1-expected1]",
"tests/test_db.py::TestSorter::test_order_by_value[result2-expected2]",
"tests/test_db.py::TestSorter::test_order_by_value[result3-expected3]",
"tests/test_db.py::TestSorter::test_order_by_value[result4-expected4]",
"tests/test_db.py::TestSorter::test_order_by_value[result5-expected5]",
"tests/test_db.py::TestSorter::test_order_by_value[result6-expected6]",
"tests/test_db.py::TestSorter::test_order_by_value[result7-expected7]",
"tests/test_db.py::TestSorter::test_order_by_value[result8-expected8]",
"tests/test_db.py::TestSorter::test_order_by_value[result9-expected9]",
"tests/test_db.py::TestSorter::test_order_by_value[result10-expected10]",
"tests/test_db.py::TestSorter::test_order_by_value[result11-expected11]",
"tests/test_db.py::TestSorter::test_order_by_value[result12-expected12]",
"tests/test_db.py::TestSorter::test_order_by_value[result13-expected13]",
"tests/test_db.py::TestSorter::test_order_by_value[result14-expected14]",
"tests/test_db.py::TestSorter::test_order_by_value_with_list[result0-expected0]",
"tests/test_db.py::TestSorter::test_order_by_value_with_list[result1-expected1]",
"tests/test_db.py::TestSorter::test_order_by_value_with_list[result2-expected2]",
"tests/test_db.py::TestSorter::test_order_by_value_with_list[result3-expected3]",
"tests/test_db.py::TestSorter::test_order_by_value_with_list[result4-expected4]",
"tests/test_db.py::TestSorter::test_order_by_value_with_list[result5-expected5]",
"tests/test_db.py::TestSorter::test_order_by_value_with_list[result6-expected6]",
"tests/test_db.py::TestSorter::test_order_by_value_with_list[result7-expected7]",
"tests/test_db.py::TestSorter::test_invalid_sort[None]",
"tests/test_db.py::TestSorter::test_invalid_sort[False]",
"tests/test_db.py::TestSorter::test_invalid_sort[True]",
"tests/test_db.py::TestSorter::test_invalid_sort[0]",
"tests/test_db.py::TestSorter::test_invalid_sort[1]",
"tests/test_db.py::TestSorter::test_invalid_sort[foo]",
"tests/test_db.py::TestSorter::test_order_by_key[result0-expected0]",
"tests/test_db.py::TestSorter::test_order_by_key[result1-expected1]",
"tests/test_db.py::TestSorter::test_order_by_key[result2-expected2]",
"tests/test_db.py::TestSorter::test_order_by_child[result0-expected0]",
"tests/test_db.py::TestSorter::test_order_by_child[result1-expected1]",
"tests/test_db.py::TestSorter::test_order_by_child[result2-expected2]",
"tests/test_db.py::TestSorter::test_order_by_child[result3-expected3]",
"tests/test_db.py::TestSorter::test_order_by_child[result4-expected4]",
"tests/test_db.py::TestSorter::test_order_by_child[result5-expected5]",
"tests/test_db.py::TestSorter::test_order_by_child[result6-expected6]",
"tests/test_db.py::TestSorter::test_order_by_child[result7-expected7]",
"tests/test_db.py::TestSorter::test_order_by_child[result8-expected8]",
"tests/test_db.py::TestSorter::test_order_by_child[result9-expected9]",
"tests/test_db.py::TestSorter::test_order_by_child[result10-expected10]",
"tests/test_db.py::TestSorter::test_order_by_child[result11-expected11]",
"tests/test_db.py::TestSorter::test_order_by_child[result12-expected12]",
"tests/test_db.py::TestSorter::test_order_by_child[result13-expected13]",
"tests/test_db.py::TestSorter::test_order_by_child[result14-expected14]",
"tests/test_db.py::TestSorter::test_order_by_grand_child[result0-expected0]",
"tests/test_db.py::TestSorter::test_order_by_grand_child[result1-expected1]",
"tests/test_db.py::TestSorter::test_order_by_grand_child[result2-expected2]",
"tests/test_db.py::TestSorter::test_order_by_grand_child[result3-expected3]",
"tests/test_db.py::TestSorter::test_order_by_grand_child[result4-expected4]",
"tests/test_db.py::TestSorter::test_order_by_grand_child[result5-expected5]",
"tests/test_db.py::TestSorter::test_order_by_grand_child[result6-expected6]",
"tests/test_db.py::TestSorter::test_order_by_grand_child[result7-expected7]",
"tests/test_db.py::TestSorter::test_order_by_grand_child[result8-expected8]",
"tests/test_db.py::TestSorter::test_order_by_grand_child[result9-expected9]",
"tests/test_db.py::TestSorter::test_order_by_grand_child[result10-expected10]",
"tests/test_db.py::TestSorter::test_order_by_grand_child[result11-expected11]",
"tests/test_db.py::TestSorter::test_order_by_grand_child[result12-expected12]",
"tests/test_db.py::TestSorter::test_order_by_grand_child[result13-expected13]",
"tests/test_db.py::TestSorter::test_order_by_grand_child[result14-expected14]",
"tests/test_db.py::TestSorter::test_child_path_resolution[result0-expected0]",
"tests/test_db.py::TestSorter::test_child_path_resolution[result1-expected1]",
"tests/test_db.py::TestSorter::test_child_path_resolution[result2-expected2]"
] |
{
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
}
|
2017-11-23 01:37:34+00:00
|
apache-2.0
| 2,348 |
|
fitbenchmarking__fitbenchmarking-379
|
diff --git a/examples/options_template.ini b/examples/options_template.ini
index 050d0fae..27946dfb 100644
--- a/examples/options_template.ini
+++ b/examples/options_template.ini
@@ -106,6 +106,11 @@ use_errors: no
##############################################################################
[PLOTTING]
+# make_plots is used to allow the user to either create plots during runtime.
+# Toggling this False will be much faster on small data sets.
+# default True (yes/no can also be used)
+# make_plots: yes
+
# colour_scale lists thresholds for each colour in the html table
# In the below example, this means that values less than 1.1 will
# have the top ranking (brightest) and values over 3 will show as
diff --git a/fitbenchmarking/HTML_templates/results_template.html b/fitbenchmarking/HTML_templates/results_template.html
index 3014d968..e844abe8 100644
--- a/fitbenchmarking/HTML_templates/results_template.html
+++ b/fitbenchmarking/HTML_templates/results_template.html
@@ -25,8 +25,12 @@
</tr>
</tbody>
</table>
+{% if make_plots %}
<div align="center" class="figure align-center">
<img alt={{ initial_plot }} src={{ initial_plot }} />
+{% else %}
+<h3>{{ initial_plot }}</h3>
+{% endif %}
</div>
</div>
<div class="section" id="plot-of-the-solution-found">
@@ -49,8 +53,12 @@
</tr>
</tbody>
</table>
+{% if make_plots %}
<div align="center" class="figure align-center">
<img alt={{ fitted_plot }} src={{ fitted_plot }} />
+{% else %}
+<h3>{{ fitted_plot }}</h3>
+{% endif %}
</div>
</div>
</body>
diff --git a/fitbenchmarking/results_processing/visual_pages.py b/fitbenchmarking/results_processing/visual_pages.py
index bee3ed68..dde59dd9 100644
--- a/fitbenchmarking/results_processing/visual_pages.py
+++ b/fitbenchmarking/results_processing/visual_pages.py
@@ -79,19 +79,22 @@ def create(prob_results, group_name, results_dir, count, options):
prob_name = prob_name.replace(' ', '_')
directory = os.path.join(results_dir, group_name)
- plot = plots.Plot(problem=best_result.problem,
- options=options,
- count=count,
- group_results_dir=directory)
- plot.plot_initial_guess()
- plot.plot_best_fit(best_result.minimizer, best_result.params)
-
support_pages_dir, file_path = \
get_filename_and_path(group_name, prob_name,
best_result, results_dir, count)
- fig_fit, fig_start = \
- get_figure_paths(support_pages_dir, prob_name, count)
-
+ if options.make_plots:
+ plot = plots.Plot(problem=best_result.problem,
+ options=options,
+ count=count,
+ group_results_dir=directory)
+ plot.plot_initial_guess()
+ plot.plot_best_fit(best_result.minimizer, best_result.params)
+
+ fig_fit, fig_start = \
+ get_figure_paths(support_pages_dir, prob_name, count)
+ else:
+ fig_fit = fig_start = "Re-run with make_plots set to yes in the " \
+ "ini file to generate plots"
root = os.path.dirname(os.path.abspath(__file__))
main_dir = os.path.dirname(root)
html_page_dir = os.path.join(main_dir, "HTML_templates")
@@ -106,6 +109,7 @@ def create(prob_results, group_name, results_dir, count, options):
css_style_sheet=style_css,
title=prob_name,
equation=best_result.problem.equation,
+ make_plots=options.make_plots,
initial_guess=best_result.ini_function_params,
best_minimiser=best_result.minimizer,
initial_plot=fig_start,
diff --git a/fitbenchmarking/utils/default_options.ini b/fitbenchmarking/utils/default_options.ini
index 12004776..4df7b3d2 100644
--- a/fitbenchmarking/utils/default_options.ini
+++ b/fitbenchmarking/utils/default_options.ini
@@ -110,6 +110,11 @@ use_errors: yes
##############################################################################
[PLOTTING]
+# make_plots is used to allow the user to either create plots during runtime.
+# Toggling this False will be much faster on small data sets.
+# default True (yes/no can also be used)
+make_plots: yes
+
# colour_scale lists thresholds for each colour in the html table
# In the below example, this means that values less than 1.1 will
# have the top ranking (brightest) and values over 3 will show as
diff --git a/fitbenchmarking/utils/options.py b/fitbenchmarking/utils/options.py
index 8cca7218..44215347 100644
--- a/fitbenchmarking/utils/options.py
+++ b/fitbenchmarking/utils/options.py
@@ -5,6 +5,7 @@ This file will handle all interaction with the options configuration file.
import configparser
import os
+import sys
class Options(object):
@@ -24,6 +25,9 @@ class Options(object):
:param file_name: The options file to load
:type file_name: str
"""
+ template = "ERROR IN OPTIONS FILE:\n" \
+ "The option {0} must be of type {1}. \n" \
+ "Please alter the ini file to reflect this and re-run."
self._results_dir = ''
config = configparser.ConfigParser(converters={'list': read_list,
'str': str})
@@ -43,6 +47,13 @@ class Options(object):
self.use_errors = fitting.getboolean('use_errors')
plotting = config['PLOTTING']
+ # sys.exit() will be addressed in future FitBenchmarking
+ # error handling issue
+ try:
+ self.make_plots = plotting.getboolean('make_plots')
+ except ValueError:
+ print(template.format('make_plots', "boolean"))
+ sys.exit()
self.colour_scale = plotting.getlist('colour_scale')
self.colour_scale = [(float(cs.split(',', 1)[0].strip()),
cs.split(',', 1)[1].strip())
|
fitbenchmarking/fitbenchmarking
|
10605b8d50369d2987de65e7507e292b534c7822
|
diff --git a/fitbenchmarking/utils/tests/test_options.py b/fitbenchmarking/utils/tests/test_options.py
index 6b4077b7..d64003f3 100644
--- a/fitbenchmarking/utils/tests/test_options.py
+++ b/fitbenchmarking/utils/tests/test_options.py
@@ -31,6 +31,7 @@ class OptionsTests(unittest.TestCase):
bar
[PLOTTING]
+ make_plots: no
colour_scale: 17.1, b_string?
inf, final_string
comparison_mode: abs
@@ -38,13 +39,18 @@ class OptionsTests(unittest.TestCase):
runtime
results_dir: new_results
"""
+ incorrect_config_str = """
+ [PLOTTING]
+ make_plots: incorrect_falue
+ """
opts = {'MINIMIZERS': {'scipy': ['nonesense',
'another_fake_minimizer'],
'dfogn': ['test']},
'FITTING': {'use_errors': False,
'num_runs': 2,
'software': ['foo', 'bar']},
- 'PLOTTING': {'colour_scale': [(17.1, 'b_string?'),
+ 'PLOTTING': {'make_plots': False,
+ 'colour_scale': [(17.1, 'b_string?'),
(float('inf'), 'final_string')],
'comparison_mode': 'abs',
'table_type': ['acc', 'runtime'],
@@ -58,8 +64,15 @@ class OptionsTests(unittest.TestCase):
self.options = opts
self.options_file = opts_file
+ opts_file_incorrect = 'test_incorrect_options_tests_{}.txt'.format(
+ datetime.datetime.now())
+ with open(opts_file_incorrect, 'w') as f:
+ f.write(incorrect_config_str)
+ self.options_file_incorrect = opts_file_incorrect
+
def tearDown(self):
os.remove(self.options_file)
+ os.remove(self.options_file_incorrect)
def test_from_file(self):
options = Options(file_name=self.options_file)
@@ -81,6 +94,15 @@ class OptionsTests(unittest.TestCase):
self.assertTrue(
options.results_dir.endswith(plotting_opts['results_dir']))
+ def test_make_plots_false(self):
+ with self.assertRaises(SystemExit):
+ Options(file_name=self.options_file_incorrect)
+
+ def test_make_plots_true(self):
+ options = Options(file_name=self.options_file)
+ plotting_opts = self.options['PLOTTING']
+ self.assertEqual(plotting_opts['make_plots'], options.make_plots)
+
if __name__ == '__main__':
unittest.main()
|
Making plotting optional
**Is your feature request related to a problem? Please describe.**
Adds option to the options file whether or not to produce plots.
**Describe the solution you'd like**
Create new `make_plots` option in options file.
|
0.0
|
10605b8d50369d2987de65e7507e292b534c7822
|
[
"fitbenchmarking/utils/tests/test_options.py::OptionsTests::test_make_plots_false",
"fitbenchmarking/utils/tests/test_options.py::OptionsTests::test_make_plots_true"
] |
[
"fitbenchmarking/utils/tests/test_options.py::OptionsTests::test_from_file"
] |
{
"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
}
|
2020-01-08 15:11:04+00:00
|
bsd-3-clause
| 2,349 |
|
fitbenchmarking__fitbenchmarking-514
|
diff --git a/examples/all_softwares.ini b/examples/all_softwares.ini
index b054ae82..dc589f6d 100644
--- a/examples/all_softwares.ini
+++ b/examples/all_softwares.ini
@@ -196,7 +196,7 @@ software: dfo
# file_name specifies the file path to write the logs to
# default is fitbenchmarking.log
-#file_name: fitbenchmarking.log
+#file_name: fitbenchmarking.log
# append specifies whether to log in append mode or not.
# If append mode is active, the log file will be extended with each subsequent
@@ -210,3 +210,9 @@ software: dfo
# ERROR, and CRITICAL
# default is INFO
#level: INFO
+
+# external_output toggles whether the output grabber collects the third party
+# output. We note that for the windows operating system the
+# default will be off.
+# default True (yes/no can also be used)
+#external_output: yes
diff --git a/examples/options_template.ini b/examples/options_template.ini
index 671d2ba6..dced07d0 100644
--- a/examples/options_template.ini
+++ b/examples/options_template.ini
@@ -196,7 +196,7 @@
# file_name specifies the file path to write the logs to
# default is fitbenchmarking.log
-#file_name: fitbenchmarking.log
+#file_name: fitbenchmarking.log
# append specifies whether to log in append mode or not.
# If append mode is active, the log file will be extended with each subsequent
@@ -210,3 +210,9 @@
# ERROR, and CRITICAL
# default is INFO
#level: INFO
+
+# external_output toggles whether the output grabber collects the third party
+# output. We note that for the windows operating system the
+# default will be off.
+# default True (yes/no can also be used)
+#external_output: yes
diff --git a/fitbenchmarking/core/fitbenchmark_one_problem.py b/fitbenchmarking/core/fitbenchmark_one_problem.py
index a65f5292..0dfbde15 100644
--- a/fitbenchmarking/core/fitbenchmark_one_problem.py
+++ b/fitbenchmarking/core/fitbenchmark_one_problem.py
@@ -30,7 +30,7 @@ def fitbm_one_prob(problem, options):
:return: list of all results
:rtype: list of fibenchmarking.utils.fitbm_result.FittingResult
"""
- grabbed_output = output_grabber.OutputGrabber()
+ grabbed_output = output_grabber.OutputGrabber(options)
results = []
software = options.software
@@ -85,7 +85,7 @@ def benchmark(controller, minimizers, options):
:return: list of all results
:rtype: list of fibenchmarking.utils.fitbm_result.FittingResult
"""
- grabbed_output = output_grabber.OutputGrabber()
+ grabbed_output = output_grabber.OutputGrabber(options)
problem = controller.problem
results_problem = []
diff --git a/fitbenchmarking/core/fitting_benchmarking.py b/fitbenchmarking/core/fitting_benchmarking.py
index 17b970f3..22c8aa41 100644
--- a/fitbenchmarking/core/fitting_benchmarking.py
+++ b/fitbenchmarking/core/fitting_benchmarking.py
@@ -34,7 +34,7 @@ def fitbenchmark_group(group_name, options, data_dir):
the problem group and the location of the results
:rtype: tuple(list, str)
"""
- grabbed_output = output_grabber.OutputGrabber()
+ grabbed_output = output_grabber.OutputGrabber(options)
# Extract problem definitions
problem_group = misc.get_problem_files(data_dir)
diff --git a/fitbenchmarking/utils/default_options.ini b/fitbenchmarking/utils/default_options.ini
index 36555638..4e97f1ad 100644
--- a/fitbenchmarking/utils/default_options.ini
+++ b/fitbenchmarking/utils/default_options.ini
@@ -196,7 +196,7 @@ results_dir: results
# file_name specifies the file path to write the logs to
# default is fitbenchmarking.log
-file_name: fitbenchmarking.log
+file_name: fitbenchmarking.log
# append specifies whether to log in append mode or not.
# If append mode is active, the log file will be extended with each subsequent
@@ -210,3 +210,9 @@ append: no
# ERROR, and CRITICAL
# default is INFO
level: INFO
+
+# external_output toggles whether the output grabber collects the third party
+# output. We note that for the windows operating system the
+# default will be off.
+# default True (yes/no can also be used)
+external_output: yes
diff --git a/fitbenchmarking/utils/options.py b/fitbenchmarking/utils/options.py
index 14721ec1..f752852e 100644
--- a/fitbenchmarking/utils/options.py
+++ b/fitbenchmarking/utils/options.py
@@ -75,6 +75,11 @@ class Options(object):
self.log_file = logging.getstr('file_name')
self.log_level = logging.getstr('level')
+ try:
+ self.external_output = logging.getboolean('external_output')
+ except ValueError:
+ error_message.append(template.format('external_output', "boolean"))
+
# sys.exit() will be addressed in future FitBenchmarking
# error handling issue
if error_message != []:
@@ -116,7 +121,8 @@ class Options(object):
'table_type': list_to_string(self.table_type)}
config['LOGGING'] = {'file_name': self.log_file,
'level': self.log_level,
- 'append': self.log_append}
+ 'append': self.log_append,
+ 'external_output': self.external_output}
with open(file_name, 'w') as f:
config.write(f)
diff --git a/fitbenchmarking/utils/output_grabber.py b/fitbenchmarking/utils/output_grabber.py
index baf8d967..e1e444b7 100644
--- a/fitbenchmarking/utils/output_grabber.py
+++ b/fitbenchmarking/utils/output_grabber.py
@@ -1,28 +1,37 @@
import os
import sys
+import platform
from fitbenchmarking.utils.log import get_logger
LOGGER = get_logger()
+
class OutputGrabber(object):
"""
Class used to grab standard output or another stream.
"""
escape_char = "\b"
- def __init__(self):
+ def __init__(self, options):
self.origstream = sys.stdout
self.origstreamfd = self.origstream.fileno()
self.capturedtext = ""
+ # From issue 500 the output grabber does not currently on windows, thus
+ # we set the __enter__ and __exit__ functions to pass through for this
+ # case
+ self.system = platform.system() != "Windows"
+ self.external_output = options.external_output
def __enter__(self):
- self.start()
+ if self.system and self.external_output:
+ self.start()
return self
def __exit__(self, type, value, traceback):
- self.stop()
+ if self.system and self.external_output:
+ self.stop()
def start(self):
"""
|
fitbenchmarking/fitbenchmarking
|
944b1cf42fd1429b84e0dad092a5cd789f4ad6a7
|
diff --git a/fitbenchmarking/utils/tests/test_options.py b/fitbenchmarking/utils/tests/test_options.py
index da5e66a3..acc98f5f 100644
--- a/fitbenchmarking/utils/tests/test_options.py
+++ b/fitbenchmarking/utils/tests/test_options.py
@@ -42,6 +42,7 @@ class OptionsTests(unittest.TestCase):
file_name: THE_LOG.log
append: yes
level: debug
+ external_output: no
"""
incorrect_config_str = """
[FITTING]
@@ -51,6 +52,7 @@ class OptionsTests(unittest.TestCase):
make_plots: incorrect_falue
[LOGGING]
append: sure
+ external_output: maybe
"""
opts = {'MINIMIZERS': {'scipy': ['nonesense',
'another_fake_minimizer'],
@@ -67,7 +69,8 @@ class OptionsTests(unittest.TestCase):
'results_dir': 'new_results'},
'LOGGING': {'file_name': 'THE_LOG.log',
'append': True,
- 'level': 'debug'}}
+ 'level': 'debug',
+ 'external_output': False}}
opts_file = 'test_options_tests_{}.txt'.format(
datetime.datetime.now())
@@ -163,6 +166,18 @@ class OptionsTests(unittest.TestCase):
logging_opts = self.options['LOGGING']
self.assertEqual(logging_opts['append'], options.log_append)
+ def test_log_external_output_false(self):
+ with self.assertRaises(exceptions.OptionsError) as cm:
+ Options(file_name=self.options_file_incorrect)
+ excep = cm.exception
+ self.assertIn('external_output', excep._obj_message)
+
+ def test_log_external_output_true(self):
+ options = Options(file_name=self.options_file)
+ logging_opts = self.options['LOGGING']
+ self.assertEqual(logging_opts['external_output'],
+ options.external_output)
+
if __name__ == '__main__':
unittest.main()
diff --git a/fitbenchmarking/utils/tests/test_output_grabber.py b/fitbenchmarking/utils/tests/test_output_grabber.py
index 45bb404f..a9700f40 100644
--- a/fitbenchmarking/utils/tests/test_output_grabber.py
+++ b/fitbenchmarking/utils/tests/test_output_grabber.py
@@ -2,13 +2,16 @@ from __future__ import (absolute_import, division, print_function)
import unittest
from fitbenchmarking.utils.output_grabber import OutputGrabber
-
+from fitbenchmarking.utils.options import Options
class OutputGrabberTests(unittest.TestCase):
+ def setUp(self):
+ self.options = Options()
+
def test_correct_output(self):
output_string = 'This is the correct output string\nSecond line'
- output = OutputGrabber()
+ output = OutputGrabber(self.options)
with output:
print(output_string)
# print adds an extra \n
@@ -16,12 +19,11 @@ class OutputGrabberTests(unittest.TestCase):
def test_incorrect_output(self):
output_string = 'This is the correct output string\nSecond line'
- incorrect_output_sting = 'This is the incorrect string'
- output = OutputGrabber()
+ incorrect_output_sting = 'This is the incorrect string\n'
+ output = OutputGrabber(self.options)
with output:
print(output_string)
- # print adds an extra \n
- assert output.capturedtext != incorrect_output_sting + "\n"
+ assert output.capturedtext != incorrect_output_sting
if __name__ == "__main__":
|
Create an option to toggle the 3rd party output grabber
As observed in #500 the output grabber is not working on windows and as part of #511 to enable windows test a solution was to have the output grabber to pass through. It would also be useful to have this as a option within FitBenchmarking.
|
0.0
|
944b1cf42fd1429b84e0dad092a5cd789f4ad6a7
|
[
"fitbenchmarking/utils/tests/test_options.py::OptionsTests::test_log_external_output_false",
"fitbenchmarking/utils/tests/test_options.py::OptionsTests::test_log_external_output_true",
"fitbenchmarking/utils/tests/test_output_grabber.py::OutputGrabberTests::test_correct_output",
"fitbenchmarking/utils/tests/test_output_grabber.py::OutputGrabberTests::test_incorrect_output"
] |
[
"fitbenchmarking/utils/tests/test_options.py::OptionsTests::test_from_file",
"fitbenchmarking/utils/tests/test_options.py::OptionsTests::test_log_append_false",
"fitbenchmarking/utils/tests/test_options.py::OptionsTests::test_log_append_true",
"fitbenchmarking/utils/tests/test_options.py::OptionsTests::test_make_plots_false",
"fitbenchmarking/utils/tests/test_options.py::OptionsTests::test_make_plots_true",
"fitbenchmarking/utils/tests/test_options.py::OptionsTests::test_num_runs_int_value",
"fitbenchmarking/utils/tests/test_options.py::OptionsTests::test_num_runs_non_int_value",
"fitbenchmarking/utils/tests/test_options.py::OptionsTests::test_use_errors_false",
"fitbenchmarking/utils/tests/test_options.py::OptionsTests::test_use_errors_true",
"fitbenchmarking/utils/tests/test_options.py::OptionsTests::test_write"
] |
{
"failed_lite_validators": [
"has_issue_reference",
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-05-07 10:14:32+00:00
|
bsd-3-clause
| 2,350 |
|
fitbenchmarking__fitbenchmarking-539
|
diff --git a/examples/all_softwares.ini b/examples/all_softwares.ini
index 9e2ddec6..37ae1670 100644
--- a/examples/all_softwares.ini
+++ b/examples/all_softwares.ini
@@ -8,6 +8,15 @@
# entry for the software with a newline separated list of minimizers.
# default is all available minimizers as follows:
+# bumps: available minimizers (amoeba, lm-bumps, newton, de, mp)
+# for more information see
+# https://bumps.readthedocs.io/en/latest/guide/optimizer.html
+#bumps: amoeba
+# lm-bumps
+# newton
+# de
+# mp
+
# dfo: available minimimizers (dfogn, dfols)
# for more information see
# http://people.maths.ox.ac.uk/robertsl/dfogn/
@@ -64,27 +73,18 @@
# hybrid
# hybrid_reg
-# sasview: available minimizers (amoeba, lm-bumps, newton, de, mp)
-# for more information see
-# https://bumps.readthedocs.io/en/latest/guide/optimizer.html
-#sasview: amoeba
-# lm-bumps
-# newton
-# de
-# mp
-
# scipy: available minimizers (Nelder-Mead, Powell, CG, BFGS, Newton-CG,
# L-BFGS-B, TNC, SLSQP)
# for more information see scipy.optimize.minimize.html
# https://docs.scipy.org/doc/scipy/reference/generated/
-#scipy: Nelder-Mead
-# Powell
-# CG
-# BFGS
-# Newton-CG
-# L-BFGS-B
-# TNC
-# SLSQP
+scipy: Nelder-Mead
+ Powell
+ CG
+ BFGS
+ Newton-CG
+ L-BFGS-B
+ TNC
+ SLSQP
# scipy_ls: available minimizers (lm-scipy-no-jac, lm-scipy, trf, dogbox)
# for more information see scipy.optimize.least_squares.html
@@ -95,10 +95,10 @@
# Jacobian evaluation. We do not see significant speed changes or
# difference in the accuracy results when running trf or dogbox with
# or without problem.eval_j for the Jacobian evaluation
-#scipy_ls: lm-scipy-no-jac
-# lm-scipy
-# trf
-# dogbox
+scipy_ls: lm-scipy-no-jac
+ lm-scipy
+ trf
+ dogbox
##############################################################################
@@ -112,13 +112,13 @@
# software is used to select the fitting software to benchmark, this should be
# a newline-separated list
-# default is dfo, minuit, sasview, and scipy
-software: dfo
+# default is bumps, dfo, gsl, mantid, minuit, ralfit, and scipy
+software: bumps
+ dfo
gsl
mantid
minuit
ralfit
- sasview
scipy
# use_errors will switch between weighted and unweighted least squares
diff --git a/examples/options_template.ini b/examples/options_template.ini
index f1843f9a..36336bc0 100644
--- a/examples/options_template.ini
+++ b/examples/options_template.ini
@@ -8,6 +8,15 @@
# entry for the software with a newline separated list of minimizers.
# default is all available minimizers as follows:
+# bumps: available minimizers (amoeba, lm-bumps, newton, de, mp)
+# for more information see
+# https://bumps.readthedocs.io/en/latest/guide/optimizer.html
+#bumps: amoeba
+# lm-bumps
+# newton
+# de
+# mp
+
# dfo: available minimimizers (dfogn, dfols)
# for more information see
# http://people.maths.ox.ac.uk/robertsl/dfogn/
@@ -64,27 +73,18 @@
# hybrid
# hybrid_reg
-# sasview: available minimizers (amoeba, lm-bumps, newton, de, mp)
-# for more information see
-# https://bumps.readthedocs.io/en/latest/guide/optimizer.html
-#sasview: amoeba
-# lm-bumps
-# newton
-# de
-# mp
-
# scipy: available minimizers (Nelder-Mead, Powell, CG, BFGS, Newton-CG,
# L-BFGS-B, TNC, SLSQP)
# for more information see scipy.optimize.minimize.html
# https://docs.scipy.org/doc/scipy/reference/generated/
-#scipy: Nelder-Mead
-# Powell
-# CG
-# BFGS
-# Newton-CG
-# L-BFGS-B
-# TNC
-# SLSQP
+scipy: Nelder-Mead
+ Powell
+ CG
+ BFGS
+ Newton-CG
+ L-BFGS-B
+ TNC
+ SLSQP
# scipy_ls: available minimizers (lm-scipy-no-jac, lm-scipy, trf, dogbox)
# for more information see scipy.optimize.least_squares.html
@@ -95,10 +95,10 @@
# Jacobian evaluation. We do not see significant speed changes or
# difference in the accuracy results when running trf or dogbox with
# or without problem.eval_j for the Jacobian evaluation
-#scipy_ls: lm-scipy-no-jac
-# lm-scipy
-# trf
-# dogbox
+scipy_ls: lm-scipy-no-jac
+ lm-scipy
+ trf
+ dogbox
##############################################################################
@@ -112,13 +112,13 @@
# software is used to select the fitting software to benchmark, this should be
# a newline-separated list
-# default is dfo, minuit, sasview, and scipy
-#software: dfo
+# default is bumps, dfo, gsl, mantid, minuit, ralfit, and scipy
+#software: bumps
+# dfo
# gsl
# mantid
# minuit
# ralfit
-# sasview
# scipy
# use_errors will switch between weighted and unweighted least squares
diff --git a/fitbenchmarking/controllers/sasview_controller.py b/fitbenchmarking/controllers/bumps_controller.py
similarity index 89%
rename from fitbenchmarking/controllers/sasview_controller.py
rename to fitbenchmarking/controllers/bumps_controller.py
index 1c11112d..ab1dfa44 100644
--- a/fitbenchmarking/controllers/sasview_controller.py
+++ b/fitbenchmarking/controllers/bumps_controller.py
@@ -1,5 +1,5 @@
"""
-Implements a controller for the SasView fitting software.
+Implements a controller for the Bumps fitting software.
"""
from bumps.fitters import fit as bumpsFit
@@ -10,9 +10,9 @@ import numpy as np
from fitbenchmarking.controllers.base_controller import Controller
-class SasviewController(Controller):
+class BumpsController(Controller):
"""
- Controller for the Sasview fitting software.
+ Controller for the Bumps fitting software.
Sasview requires a model to fit.
Setup creates a model with the correct function.
@@ -25,7 +25,7 @@ class SasviewController(Controller):
:param problem: Problem to fit
:type problem: FittingProblem
"""
- super(SasviewController, self).__init__(problem)
+ super(BumpsController, self).__init__(problem)
self._param_names = self.problem.param_names
@@ -35,9 +35,9 @@ class SasviewController(Controller):
def setup(self):
"""
- Setup problem ready to run with SasView.
+ Setup problem ready to run with Bumps.
- Creates a Sasview FitProblem for calling in fit()
+ Creates a FitProblem for calling in the fit() function of Bumps
"""
# Bumps fails with the *args notation
param_name_str = ', '.join(self._param_names)
@@ -82,7 +82,7 @@ class SasviewController(Controller):
def fit(self):
"""
- Run problem with SasView.
+ Run problem with Bumps.
"""
result = bumpsFit(self._fit_problem, method=self.minimizer)
diff --git a/fitbenchmarking/utils/default_options.ini b/fitbenchmarking/utils/default_options.ini
index 118ffabb..85f09136 100644
--- a/fitbenchmarking/utils/default_options.ini
+++ b/fitbenchmarking/utils/default_options.ini
@@ -8,6 +8,15 @@
# entry for the software with a newline separated list of minimizers.
# default is all available minimizers as follows:
+# bumps: available minimizers (amoeba, lm-bumps, newton, de, mp)
+# for more information see
+# https://bumps.readthedocs.io/en/latest/guide/optimizer.html
+bumps: amoeba
+ lm-bumps
+ newton
+ de
+ mp
+
# dfo: available minimimizers (dfogn, dfols)
# for more information see
# http://people.maths.ox.ac.uk/robertsl/dfogn/
@@ -64,15 +73,6 @@ ralfit: gn
hybrid
hybrid_reg
-# sasview: available minimizers (amoeba, lm-bumps, newton, de, mp)
-# for more information see
-# https://bumps.readthedocs.io/en/latest/guide/optimizer.html
-sasview: amoeba
- lm-bumps
- newton
- de
- mp
-
# scipy: available minimizers (Nelder-Mead, Powell, CG, BFGS, Newton-CG,
# L-BFGS-B, TNC, SLSQP)
# for more information see scipy.optimize.minimize.html
@@ -112,13 +112,13 @@ num_runs: 5
# software is used to select the fitting software to benchmark, this should be
# a newline-separated list
-# default is dfo, minuit, sasview, and scipy
-software: dfo
+# default is bumps, dfo, minuit, and scipy
+software: bumps
+ dfo
# gsl
# mantid
minuit
# ralfit
- sasview
scipy
scipy_ls
|
fitbenchmarking/fitbenchmarking
|
5d00e88fd6a89f30bc089571de6c30e89372aadd
|
diff --git a/fitbenchmarking/controllers/tests/test_default_controllers.py b/fitbenchmarking/controllers/tests/test_default_controllers.py
index 09fb4396..ca6a8ce0 100644
--- a/fitbenchmarking/controllers/tests/test_default_controllers.py
+++ b/fitbenchmarking/controllers/tests/test_default_controllers.py
@@ -6,10 +6,10 @@ from unittest import TestCase
from fitbenchmarking import mock_problems
from fitbenchmarking.controllers.base_controller import Controller
+from fitbenchmarking.controllers.bumps_controller import BumpsController
from fitbenchmarking.controllers.controller_factory import ControllerFactory
from fitbenchmarking.controllers.dfo_controller import DFOController
from fitbenchmarking.controllers.minuit_controller import MinuitController
-from fitbenchmarking.controllers.sasview_controller import SasviewController
from fitbenchmarking.controllers.scipy_controller import ScipyController
from fitbenchmarking.controllers.scipy_ls_controller import ScipyLSController
@@ -154,11 +154,11 @@ class ControllerTests(TestCase):
def setUp(self):
self.problem = make_fitting_problem()
- def test_sasview(self):
+ def test_bumps(self):
"""
- SasviewController: Test for output shape
+ BumpsController: Test for output shape
"""
- controller = SasviewController(self.problem)
+ controller = BumpsController(self.problem)
controller.minimizer = 'amoeba'
self.shared_testing(controller)
@@ -169,36 +169,6 @@ class ControllerTests(TestCase):
controller._status = 1
self.check_diverged(controller)
- def test_scipy_ls(self):
- """
- ScipyController: Test for output shape
- """
- controller = ScipyLSController(self.problem)
- controller.minimizer = 'lm'
- self.shared_testing(controller)
-
- controller._status = 1
- self.check_converged(controller)
- controller._status = 0
- self.check_max_iterations(controller)
- controller._status = -1
- self.check_diverged(controller)
-
- def test_scipy(self):
- """
- ScipyController: Test for output shape
- """
- controller = ScipyController(self.problem)
- controller.minimizer = 'CG'
- self.shared_testing(controller)
-
- controller._status = 1
- self.check_converged(controller)
- controller._status = 0
- self.check_max_iterations(controller)
- controller._status = -1
- self.check_diverged(controller)
-
def test_dfo(self):
"""
DFOController: Tests for output shape
@@ -230,6 +200,37 @@ class ControllerTests(TestCase):
controller._status = 2
self.check_diverged(controller)
+ def test_scipy(self):
+ """
+ ScipyController: Test for output shape
+ """
+ controller = ScipyController(self.problem)
+ controller.minimizer = 'CG'
+ self.shared_testing(controller)
+
+ controller._status = 1
+ self.check_converged(controller)
+ controller._status = 0
+ self.check_max_iterations(controller)
+ controller._status = -1
+ self.check_diverged(controller)
+
+ def test_scipy_ls(self):
+ """
+ ScipyLSController: Test for output shape
+ """
+ controller = ScipyLSController(self.problem)
+ controller.minimizer = 'lm'
+
+ self.shared_testing(controller)
+
+ controller._status = 1
+ self.check_converged(controller)
+ controller._status = 0
+ self.check_max_iterations(controller)
+ controller._status = -1
+ self.check_diverged(controller)
+
def shared_testing(self, controller):
"""
Utility function to run controller and check output is in generic form
@@ -286,13 +287,12 @@ class FactoryTests(TestCase):
Test that the factory returns the correct class for inputs
"""
- valid = ['scipy_ls', 'mantid', 'sasview', 'ralfit']
- valid_names = ['scipyls', 'mantid', 'sasview', 'ralfit']
+ valid = ['scipy_ls', 'mantid', 'ralfit']
+ valid_names = ['scipyls', 'mantid', 'ralfit']
invalid = ['foo', 'bar', 'hello', 'r2d2']
for software, v in zip(valid, valid_names):
controller = ControllerFactory.create_controller(software)
- print(controller.__name__.lower())
self.assertTrue(controller.__name__.lower().startswith(v))
for software in invalid:
diff --git a/fitbenchmarking/systests/expected_results/all_parsers.txt b/fitbenchmarking/systests/expected_results/all_parsers.txt
index 795c3075..9d033b70 100644
--- a/fitbenchmarking/systests/expected_results/all_parsers.txt
+++ b/fitbenchmarking/systests/expected_results/all_parsers.txt
@@ -1,8 +1,8 @@
- dfo gsl mantid minuit ralfit sasview scipy scipy_ls
- dfogn lmsder BFGS minuit gn amoeba Nelder-Mead lm-scipy-no-jac
-BENNETT5 inf (inf)[3] 1.639e-05 (1.021)[1] 0.02038 (1269)[2] 2.114e-05 (1.316) 1.606e-05 (1) 1.608e-05 (1.001) 1.653e-05 (1.029) 1.905e-05 (1.186)[1]
-cubic, Start 1 5.244e-14 (1.358e+08) 3.861e-22 (1) 1.85e-12 (4.792e+09) 3.586e-11 (9.288e+10) 6.723e-13 (1.741e+09) 1.119e-14 (2.899e+07) 6.267e-05 (1.623e+17) 3.861e-22 (1)
-cubic, Start 2 2.424e-17 (6.278e+04) 3.861e-22 (1) 3.306e-06 (8.563e+15) 7.579e-06 (1.963e+16) 6.926e-18 (1.794e+04) 1.146e-14 (2.969e+07) 7.176e-11 (1.859e+11)[1] 3.861e-22 (1)
-cubic-fba 7.913e-19 (2049) 3.861e-22 (1) 3.306e-06 (8.563e+15) 7.579e-06 (1.963e+16) 9.768e-18 (2.53e+04) 1.146e-14 (2.969e+07) 7.176e-11 (1.859e+11)[1] 3.861e-22 (1)
-EMU 73673 1046 (1) 1053 (1.007)[1] 1552 (1.484)[2] 1057 (1.01) inf (inf)[3] 1.032e+05 (98.62) 1055 (1.009)[1] 1046 (1)
-Problem Def 1 1.299e-10 (1) 0.04153 (3.199e+08) 33.36 (2.569e+11)[2] 4.214e-07 (3245) 0.1119 (8.618e+08) 6.784e+05 (5.225e+15) 3.837e-09 (29.55) 0.03966 (3.055e+08)
+ bumps dfo gsl mantid minuit ralfit scipy scipy_ls
+ amoeba dfogn lmsder BFGS minuit gn Nelder-Mead lm-scipy-no-jac
+BENNETT5 1.608e-05 (1.001) inf (inf)[3] 1.639e-05 (1.021)[1] 0.02038 (1269)[2] 2.114e-05 (1.316) 1.606e-05 (1) 1.653e-05 (1.029) 1.905e-05 (1.186)[1]
+cubic, Start 1 1.119e-14 (2.899e+07) 5.244e-14 (1.358e+08) 3.861e-22 (1) 1.85e-12 (4.792e+09) 3.586e-11 (9.288e+10) 6.723e-13 (1.741e+09) 6.267e-05 (1.623e+17) 3.861e-22 (1)
+cubic, Start 2 1.146e-14 (2.969e+07) 2.424e-17 (6.278e+04) 3.861e-22 (1) 3.306e-06 (8.563e+15) 7.579e-06 (1.963e+16) 6.926e-18 (1.794e+04) 7.176e-11 (1.859e+11)[1] 3.861e-22 (1)
+cubic-fba 1.146e-14 (2.969e+07) 7.913e-19 (2049) 3.861e-22 (1) 3.306e-06 (8.563e+15) 7.579e-06 (1.963e+16) 9.768e-18 (2.53e+04) 7.176e-11 (1.859e+11)[1] 3.861e-22 (1)
+EMU 73673 1.032e+05 (98.62) 1046 (1) 1053 (1.007)[1] 1552 (1.484)[2] 1057 (1.01) inf (inf)[3] 1055 (1.009)[1] 1046 (1)
+Problem Def 1 6.784e+05 (5.225e+15) 1.299e-10 (1) 0.04153 (3.199e+08) 33.36 (2.569e+11)[2] 4.214e-07 (3245) 0.1119 (8.618e+08) 3.837e-09 (29.55) 0.03966 (3.055e+08)
|
Rename `sasview` to `bump` in controllers
The controllers name `sasview` should really be called bumps since that is the software package that does the minimization.
|
0.0
|
5d00e88fd6a89f30bc089571de6c30e89372aadd
|
[
"fitbenchmarking/controllers/tests/test_default_controllers.py::BaseControllerTests::test_check_flag_attr_false",
"fitbenchmarking/controllers/tests/test_default_controllers.py::BaseControllerTests::test_check_flag_attr_true",
"fitbenchmarking/controllers/tests/test_default_controllers.py::BaseControllerTests::test_data",
"fitbenchmarking/controllers/tests/test_default_controllers.py::BaseControllerTests::test_eval_chisq_no_errors",
"fitbenchmarking/controllers/tests/test_default_controllers.py::BaseControllerTests::test_eval_chisq_with_errors",
"fitbenchmarking/controllers/tests/test_default_controllers.py::BaseControllerTests::test_prepare",
"fitbenchmarking/controllers/tests/test_default_controllers.py::ControllerTests::test_bumps",
"fitbenchmarking/controllers/tests/test_default_controllers.py::ControllerTests::test_scipy",
"fitbenchmarking/controllers/tests/test_default_controllers.py::ControllerTests::test_scipy_ls"
] |
[] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-05-20 10:30:08+00:00
|
bsd-3-clause
| 2,351 |
|
fitbenchmarking__fitbenchmarking-619
|
diff --git a/fitbenchmarking/cli/main.py b/fitbenchmarking/cli/main.py
index 1626ea33..818d199f 100755
--- a/fitbenchmarking/cli/main.py
+++ b/fitbenchmarking/cli/main.py
@@ -132,6 +132,9 @@ def run(problem_sets, options_file='', debug=False):
result_dir.append(group_results_dir)
groups.append(label)
+ # resets options to original values
+ options.reset()
+
root = os.path.dirname(inspect.getfile(fitbenchmarking))
template_dir = os.path.join(root, 'templates')
env = Environment(loader=FileSystemLoader(template_dir))
diff --git a/fitbenchmarking/utils/options.py b/fitbenchmarking/utils/options.py
index 52ce7094..7cad4285 100644
--- a/fitbenchmarking/utils/options.py
+++ b/fitbenchmarking/utils/options.py
@@ -120,6 +120,9 @@ class Options(object):
:param file_name: The options file to load
:type file_name: str
"""
+ # stores the file name to be used to reset options for multiple
+ # problem groups
+ self.stored_file_name = file_name
self.error_message = []
self._results_dir = ''
config = configparser.ConfigParser(converters={'list': read_list,
@@ -192,6 +195,12 @@ class Options(object):
if self.error_message != []:
raise OptionsError('\n'.join(self.error_message))
+ def reset(self):
+ """
+ Resets options object when running multiple problem groups.
+ """
+ self.__init__(self.stored_file_name)
+
def read_value(self, func, option):
"""
Helper function which loads in the value
|
fitbenchmarking/fitbenchmarking
|
a15f012656a7363ed694a90306a73907282c8c54
|
diff --git a/fitbenchmarking/utils/tests/test_options_generic.py b/fitbenchmarking/utils/tests/test_options_generic.py
index 92db49cd..caca4bbb 100644
--- a/fitbenchmarking/utils/tests/test_options_generic.py
+++ b/fitbenchmarking/utils/tests/test_options_generic.py
@@ -1,6 +1,7 @@
'''
Test the options write function
'''
+import copy
import os
import unittest
@@ -73,6 +74,13 @@ class OptionsWriteTests(unittest.TestCase):
os.remove(new_file_name)
+ assert options.stored_file_name == self.options_file
+ assert new_options.stored_file_name == new_file_name
+
+ # Overwrite file names
+ options.stored_file_name = ""
+ new_options.stored_file_name = ""
+
self.assertDictEqual(options.__dict__, new_options.__dict__)
def test_user_section_valid(self):
@@ -106,6 +114,18 @@ class OptionsWriteTests(unittest.TestCase):
Options(opts_file)
os.remove(opts_file)
+ def test_options_reset(self):
+ """
+ Tests options reset
+ """
+ options = Options()
+ options_save = copy.copy(options)
+ options.minimizers = {}
+ options.software = ['updated_software1', 'updated_software2']
+
+ options.reset()
+ self.assertDictEqual(options.__dict__, options_save.__dict__)
+
if __name__ == '__main__':
unittest.main()
|
Multiple problem groups error
**Description of the error**
When you run multiple problem groups, for example `fitbenchmark examples/benchmark_problems/NIST/*` the minimizers in the options are written over and produces the following errors
```
Minimizer: Newton-CG: scipy 2-point
Minimizer cannot be run with Controller with current "algorithm_type" option set.
Details: The minimizer selected, Newton-CG: scipy 2-point, is not within algorithm_check[options.algorithm_type] = ['Nelder-Mead', 'Powell', 'CG', 'BFGS', 'Newton-CG', 'L-BFGS-B', 'TNC', 'SLSQP']
```
**Describe the expected result**
Runs with multiple problem groups
|
0.0
|
a15f012656a7363ed694a90306a73907282c8c54
|
[
"fitbenchmarking/utils/tests/test_options_generic.py::OptionsWriteTests::test_options_reset",
"fitbenchmarking/utils/tests/test_options_generic.py::OptionsWriteTests::test_write"
] |
[
"fitbenchmarking/utils/tests/test_options_generic.py::OptionsWriteTests::test_user_section_invalid",
"fitbenchmarking/utils/tests/test_options_generic.py::OptionsWriteTests::test_user_section_valid"
] |
{
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-09-17 13:42:02+00:00
|
bsd-3-clause
| 2,352 |
|
fitbenchmarking__fitbenchmarking-664
|
diff --git a/.gitignore b/.gitignore
index 7c463b7d..4c9f0069 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,4 +1,4 @@
-results/
+fitbenchmarking_results/
*.pyc
logs/
.idea/
diff --git a/fitbenchmarking/cli/main.py b/fitbenchmarking/cli/main.py
index c0920dc3..18ff33f8 100755
--- a/fitbenchmarking/cli/main.py
+++ b/fitbenchmarking/cli/main.py
@@ -11,6 +11,7 @@ import argparse
import glob
import inspect
import os
+import tempfile
import sys
import webbrowser
@@ -99,6 +100,17 @@ def run(problem_sets, options_file='', debug=False):
append=options.log_append,
level=options.log_level)
+ opt_file = tempfile.NamedTemporaryFile(suffix='.ini',
+ mode='w',
+ delete=False)
+ options.write_to_stream(opt_file)
+ opt_file.close()
+ LOGGER.debug("The options file used is as follows:")
+ with open(opt_file.name) as f:
+ for line in f:
+ LOGGER.debug(line.replace("\n", ""))
+ os.remove(opt_file.name)
+
groups = []
result_dir = []
for sub_dir in problem_sets:
@@ -142,11 +154,17 @@ def run(problem_sets, options_file='', debug=False):
# resets options to original values
options.reset()
+ if os.path.basename(options.results_dir) == \
+ options.DEFAULT_PLOTTING['results_dir']:
+ LOGGER.info("\nWARNING: \nThe FitBenchmarking results will be "
+ "placed into the folder: \n\n {}\n\nTo change this "
+ "alter the input options "
+ "file.\n".format(options.results_dir))
root = os.path.dirname(inspect.getfile(fitbenchmarking))
template_dir = os.path.join(root, 'templates')
env = Environment(loader=FileSystemLoader(template_dir))
- css = get_css(options,options.results_dir)
+ css = get_css(options, options.results_dir)
template = env.get_template("index_page.html")
group_links = [os.path.join(d, "{}_index.html".format(g))
for g, d in zip(groups, result_dir)]
diff --git a/fitbenchmarking/utils/options.py b/fitbenchmarking/utils/options.py
index 0de1e2e9..946c2660 100644
--- a/fitbenchmarking/utils/options.py
+++ b/fitbenchmarking/utils/options.py
@@ -101,7 +101,7 @@ class Options(object):
(np.inf, "#b30000")],
'comparison_mode': 'both',
'table_type': ['acc', 'runtime', 'compare', 'local_min'],
- 'results_dir': 'results'}
+ 'results_dir': 'fitbenchmarking_results'}
DEFAULT_LOGGING = \
{'file_name': 'fitbenchmarking.log',
'append': False,
@@ -155,10 +155,10 @@ class Options(object):
default_options_list))
minimizers = config['MINIMIZERS']
- self.minimizers = {}
+ self._minimizers = {}
for key in self.VALID_FITTING["software"]:
- self.minimizers[key] = self.read_value(minimizers.getlist,
- key)
+ self._minimizers[key] = self.read_value(minimizers.getlist,
+ key)
fitting = config['FITTING']
self.num_runs = self.read_value(fitting.getint, 'num_runs')
@@ -246,6 +246,14 @@ class Options(object):
def results_dir(self, value):
self._results_dir = os.path.abspath(value)
+ @property
+ def minimizers(self):
+ return {s: self._minimizers[s] for s in self.software}
+
+ @minimizers.setter
+ def minimizers(self, value):
+ self._minimizers = value
+
def _create_config(self):
"""
Return the contents of the options object as a ConfigParser object,
|
fitbenchmarking/fitbenchmarking
|
1c8128e4972981f6494eded2d0fdcf1e9db8082e
|
diff --git a/fitbenchmarking/systests/test_regression.py b/fitbenchmarking/systests/test_regression.py
index ea9ceaaa..4e1197cb 100644
--- a/fitbenchmarking/systests/test_regression.py
+++ b/fitbenchmarking/systests/test_regression.py
@@ -66,7 +66,7 @@ class TestRegressionAll(TestCase):
'all_parsers.txt')
actual_file = os.path.join(os.path.dirname(__file__),
- 'results',
+ 'fitbenchmarking_results',
'all_parsers_set',
'all_parsers_set_acc_weighted_table.txt')
@@ -90,7 +90,7 @@ class TestRegressionAll(TestCase):
'multifit.txt')
actual_file = os.path.join(os.path.dirname(__file__),
- 'results',
+ 'fitbenchmarking_results',
'multifit_set',
'multifit_set_acc_weighted_table.txt')
@@ -146,7 +146,7 @@ class TestRegressionDefault(TestCase):
'default_parsers.txt')
actual_file = os.path.join(os.path.dirname(__file__),
- 'results',
+ 'fitbenchmarking_results',
'default_parsers',
'default_parsers_acc_weighted_table.txt')
@@ -205,12 +205,14 @@ def setup_options(multifit=False):
opts.software = ['mantid']
opts.minimizers = {'mantid': [opts.minimizers['mantid'][0]]}
elif TEST_TYPE != "default":
+ opts.software = ['bumps', 'dfo', 'gsl', 'mantid', 'minuit',
+ 'ralfit', 'scipy', 'scipy_ls']
opts.minimizers = {k: [v[0]] for k, v in opts.minimizers.items()}
- opts.software = sorted(opts.minimizers.keys())
else:
opts.software = ['bumps', 'dfo', 'minuit', 'scipy', 'scipy_ls']
opts.minimizers = {s: [opts.minimizers[s][0]] for s in opts.software}
- opts.results_dir = os.path.join(os.path.dirname(__file__), 'results')
+ opts.results_dir = os.path.join(os.path.dirname(__file__),
+ 'fitbenchmarking_results')
return opts
diff --git a/fitbenchmarking/utils/tests/test_options_minimizers.py b/fitbenchmarking/utils/tests/test_options_minimizers.py
index 8f3b1a53..eda87815 100644
--- a/fitbenchmarking/utils/tests/test_options_minimizers.py
+++ b/fitbenchmarking/utils/tests/test_options_minimizers.py
@@ -20,6 +20,9 @@ class MininimizerOptionTests(unittest.TestCase):
Initializes options class with defaults
"""
self.options = Options()
+ software = ['bumps', 'dfo', 'gsl', 'mantid', 'minuit',
+ 'ralfit', 'scipy', 'scipy_ls']
+ self.options.software = software
def test_minimizer_bumps(self):
"""
@@ -37,6 +40,16 @@ class MininimizerOptionTests(unittest.TestCase):
actual = self.options.minimizers['dfo']
self.assertEqual(expected, actual)
+ def test_minimizer_gsl(self):
+ """
+ Checks valid gsl minimizers are set correctly
+ """
+ expected = ['lmsder', 'lmder', 'nmsimplex', 'nmsimplex2',
+ 'conjugate_pr', 'conjugate_fr', 'vector_bfgs',
+ 'vector_bfgs2', 'steepest_descent']
+ actual = self.options.minimizers['gsl']
+ self.assertEqual(expected, actual)
+
def test_minimizer_mantid(self):
"""
Checks valid mantid minimizers are set correctly
@@ -137,6 +150,8 @@ class UserMininimizerOptionTests(unittest.TestCase):
"""
opts_file = self.generate_user_ini_file(options_set, software)
options = Options(opts_file)
+ if software not in options.software:
+ options.software.append(software)
actual = options.minimizers[software]
self.assertEqual(options_set, actual)
@@ -188,6 +203,20 @@ class UserMininimizerOptionTests(unittest.TestCase):
set_option = ['CG']
self.shared_invalid(set_option, 'dfo')
+ def test_minimizer_gsl_valid(self):
+ """
+ Checks user set gsl minimizers is valid
+ """
+ set_option = ['lmsder', 'lmder', 'nmsimplex']
+ self.shared_valid(set_option, 'gsl')
+
+ def test_minimizer_gsl_invalid(self):
+ """
+ Checks user set gsl minimizers is invalid
+ """
+ set_option = ['newton']
+ self.shared_invalid(set_option, 'gsl')
+
def test_minimizer_mantid_valid(self):
"""
Checks user set mantid minimizers is valid
diff --git a/fitbenchmarking/utils/tests/test_options_plotting.py b/fitbenchmarking/utils/tests/test_options_plotting.py
index 3b8ac9df..9369c201 100644
--- a/fitbenchmarking/utils/tests/test_options_plotting.py
+++ b/fitbenchmarking/utils/tests/test_options_plotting.py
@@ -62,7 +62,7 @@ class PlottingOptionTests(unittest.TestCase):
"""
Checks results_dir default
"""
- expected = os.path.abspath('results')
+ expected = os.path.abspath('fitbenchmarking_results')
actual = self.options.results_dir
self.assertEqual(expected, actual)
|
Options printing
Adds the options to the log file and will print given to the terminal given a certain log level.
|
0.0
|
1c8128e4972981f6494eded2d0fdcf1e9db8082e
|
[
"fitbenchmarking/utils/tests/test_options_plotting.py::PlottingOptionTests::test_results_dir_default"
] |
[
"fitbenchmarking/utils/tests/test_options_minimizers.py::MininimizerOptionTests::test_minimizer_bumps",
"fitbenchmarking/utils/tests/test_options_minimizers.py::MininimizerOptionTests::test_minimizer_dfo",
"fitbenchmarking/utils/tests/test_options_minimizers.py::MininimizerOptionTests::test_minimizer_gsl",
"fitbenchmarking/utils/tests/test_options_minimizers.py::MininimizerOptionTests::test_minimizer_mantid",
"fitbenchmarking/utils/tests/test_options_minimizers.py::MininimizerOptionTests::test_minimizer_minuit",
"fitbenchmarking/utils/tests/test_options_minimizers.py::MininimizerOptionTests::test_minimizer_ralfit",
"fitbenchmarking/utils/tests/test_options_minimizers.py::MininimizerOptionTests::test_minimizer_scipy",
"fitbenchmarking/utils/tests/test_options_minimizers.py::MininimizerOptionTests::test_minimizer_scipy_ls",
"fitbenchmarking/utils/tests/test_options_minimizers.py::UserMininimizerOptionTests::test_invalid_option_key",
"fitbenchmarking/utils/tests/test_options_minimizers.py::UserMininimizerOptionTests::test_minimizer_bumps_invalid",
"fitbenchmarking/utils/tests/test_options_minimizers.py::UserMininimizerOptionTests::test_minimizer_bumps_valid",
"fitbenchmarking/utils/tests/test_options_minimizers.py::UserMininimizerOptionTests::test_minimizer_dfo_invalid",
"fitbenchmarking/utils/tests/test_options_minimizers.py::UserMininimizerOptionTests::test_minimizer_dfo_valid",
"fitbenchmarking/utils/tests/test_options_minimizers.py::UserMininimizerOptionTests::test_minimizer_gsl_invalid",
"fitbenchmarking/utils/tests/test_options_minimizers.py::UserMininimizerOptionTests::test_minimizer_gsl_valid",
"fitbenchmarking/utils/tests/test_options_minimizers.py::UserMininimizerOptionTests::test_minimizer_mantid_invalid",
"fitbenchmarking/utils/tests/test_options_minimizers.py::UserMininimizerOptionTests::test_minimizer_mantid_valid",
"fitbenchmarking/utils/tests/test_options_minimizers.py::UserMininimizerOptionTests::test_minimizer_minuit_invalid",
"fitbenchmarking/utils/tests/test_options_minimizers.py::UserMininimizerOptionTests::test_minimizer_minuit_valid",
"fitbenchmarking/utils/tests/test_options_minimizers.py::UserMininimizerOptionTests::test_minimizer_ralfit_invalid",
"fitbenchmarking/utils/tests/test_options_minimizers.py::UserMininimizerOptionTests::test_minimizer_ralfit_valid",
"fitbenchmarking/utils/tests/test_options_minimizers.py::UserMininimizerOptionTests::test_minimizer_scipy_invalid",
"fitbenchmarking/utils/tests/test_options_minimizers.py::UserMininimizerOptionTests::test_minimizer_scipy_ls_invalid",
"fitbenchmarking/utils/tests/test_options_minimizers.py::UserMininimizerOptionTests::test_minimizer_scipy_ls_valid",
"fitbenchmarking/utils/tests/test_options_minimizers.py::UserMininimizerOptionTests::test_minimizer_scipy_valid",
"fitbenchmarking/utils/tests/test_options_plotting.py::PlottingOptionTests::test_colour_scale_default",
"fitbenchmarking/utils/tests/test_options_plotting.py::PlottingOptionTests::test_comparison_mode_default",
"fitbenchmarking/utils/tests/test_options_plotting.py::PlottingOptionTests::test_make_plots_default",
"fitbenchmarking/utils/tests/test_options_plotting.py::PlottingOptionTests::test_table_type_default",
"fitbenchmarking/utils/tests/test_options_plotting.py::UserPlottingOptionTests::test_invalid_option_key",
"fitbenchmarking/utils/tests/test_options_plotting.py::UserPlottingOptionTests::test_minimizer_colour_scale_valid",
"fitbenchmarking/utils/tests/test_options_plotting.py::UserPlottingOptionTests::test_minimizer_comparison_mode_invalid",
"fitbenchmarking/utils/tests/test_options_plotting.py::UserPlottingOptionTests::test_minimizer_comparison_mode_valid",
"fitbenchmarking/utils/tests/test_options_plotting.py::UserPlottingOptionTests::test_minimizer_make_plots_invalid",
"fitbenchmarking/utils/tests/test_options_plotting.py::UserPlottingOptionTests::test_minimizer_make_plots_valid",
"fitbenchmarking/utils/tests/test_options_plotting.py::UserPlottingOptionTests::test_minimizer_results_dir_valid",
"fitbenchmarking/utils/tests/test_options_plotting.py::UserPlottingOptionTests::test_minimizer_table_type_invalid",
"fitbenchmarking/utils/tests/test_options_plotting.py::UserPlottingOptionTests::test_minimizer_table_type_valid"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-10-13 13:03:44+00:00
|
bsd-3-clause
| 2,353 |
|
fitnr__visvalingamwyatt-6
|
diff --git a/.travis.yml b/.travis.yml
index 1bfad4d..1c406f5 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -8,12 +8,9 @@
language: python
python:
- - 2.7
- - 3.4
- - 3.5
- - 3.6
- 3.7
- 3.8
+ - 3.9
matrix:
fast_finish: true
diff --git a/Makefile b/Makefile
index 8bced23..ce32e95 100644
--- a/Makefile
+++ b/Makefile
@@ -21,8 +21,8 @@ cov:
coverage report
coverage html
-test: README.rst
- python setup.py test
+test:
+ tox
upload: README.rst | clean build
twine upload dist/*
diff --git a/setup.py b/setup.py
index ff9369f..0920fb2 100644
--- a/setup.py
+++ b/setup.py
@@ -43,11 +43,10 @@ setup(
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Operating System :: Unix',
- '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',
+ 'Programming Language :: Python :: 3.9',
'Programming Language :: Python :: Implementation :: PyPy',
'Operating System :: OS Independent',
],
diff --git a/tox.ini b/tox.ini
index a9ef38f..7bbadc8 100644
--- a/tox.ini
+++ b/tox.ini
@@ -6,11 +6,7 @@
# Copyright (c) 2015, fitnr <[email protected]>
[tox]
-envlist = py37, py38, pypy
+envlist = py37, py38, py39, pypy
[testenv]
-whitelist_externals = make
-
-commands =
- make install
- make test
+commands = python -m unittest
diff --git a/visvalingamwyatt/visvalingamwyatt.py b/visvalingamwyatt/visvalingamwyatt.py
index 518480a..565b530 100644
--- a/visvalingamwyatt/visvalingamwyatt.py
+++ b/visvalingamwyatt/visvalingamwyatt.py
@@ -226,9 +226,12 @@ def simplify_geometry(geom, **kwargs):
pass
elif geom['type'] == 'MultiPolygon':
- g['coordinates'] = [simplify_rings(rings, **kwargs) for rings in geom['coordinates']]
+ g['coordinates'] = [simplify_rings(rings, closed=True, **kwargs) for rings in geom['coordinates']]
- elif geom['type'] in ('Polygon', 'MultiLineString'):
+ elif geom['type'] == 'Polygon':
+ g['coordinates'] = simplify_rings(geom['coordinates'], closed=True, **kwargs)
+
+ elif geom['type'] == 'MultiLineString':
g['coordinates'] = simplify_rings(geom['coordinates'], **kwargs)
elif geom['type'] == 'LineString':
@@ -247,9 +250,12 @@ def simplify_rings(rings, **kwargs):
return [simplify(ring, **kwargs) for ring in rings]
-def simplify(coordinates, number=None, ratio=None, threshold=None):
+def simplify(coordinates, number=None, ratio=None, threshold=None, closed=False):
'''Simplify a list of coordinates'''
- return Simplifier(coordinates).simplify(number=number, ratio=ratio, threshold=threshold).tolist()
+ result = Simplifier(coordinates).simplify(number=number, ratio=ratio, threshold=threshold).tolist()
+ if closed:
+ result[-1] = result[0]
+ return result
def simplify_feature(feat, number=None, ratio=None, threshold=None):
|
fitnr/visvalingamwyatt
|
38c64f4f1c5b227aa76ea9ad7aa9694b2c56fdef
|
diff --git a/tests/test_vw.py b/tests/test_vw.py
index 51053fd..fb31d7a 100644
--- a/tests/test_vw.py
+++ b/tests/test_vw.py
@@ -15,10 +15,12 @@ import numpy as np
import visvalingamwyatt as vw
from visvalingamwyatt import __main__ as cli
+
class TestCase(unittest.TestCase):
def setUp(self):
- with open('tests/data/sample.json') as f:
+ self.samplefile = os.path.join(os.path.dirname(__file__), 'data', 'sample.json')
+ with open(self.samplefile) as f:
self.fixture = json.load(f).get('features')[0]
def standard(self, **kwargs):
@@ -70,7 +72,6 @@ class TestCase(unittest.TestCase):
# a e
#
# so b and d are eliminated
-
a, b, c, d, e = Point(0, 0), Point(1, 1), Point(2, 2), Point(3, 1), Point(4, 0)
inp = [a, b, c, d, e]
expected_output = np.array([a, c, e])
@@ -86,7 +87,6 @@ class TestCase(unittest.TestCase):
# a e
#
# so b and d are eliminated
-
a, b, c, d, e = (0, 0), (1, 1), (2, 2), (3, 1), (4, 0)
inp = [a, b, c, d, e]
expected_output = np.array([a, c, e])
@@ -94,13 +94,44 @@ class TestCase(unittest.TestCase):
actual_output = vw.simplify(inp, threshold=0.001)
self.assertTrue(np.array_equal(actual_output, expected_output))
+ def testSimplifyClosedFeature(self):
+ '''When simplifying geometries with closed rings (Polygons and MultiPolygons),
+ the first and last points in each ring should remain the same'''
+ test_ring = [[121.20803833007811,24.75431413309125],[121.1846923828125,24.746831298412058],[121.1517333984375,24.74059525872194],[121.14486694335936,24.729369599118222],[121.12152099609375,24.693191139677126],[121.13525390625,24.66449040712424],[121.10504150390625,24.66449040712424],[121.10092163085936,24.645768980151793],[121.0748291015625,24.615808859044243],[121.09405517578125,24.577099744289427],[121.12564086914062,24.533381526147682],[121.14624023437499,24.515889973088104],[121.19018554687499,24.528384188171866],[121.19430541992186,24.57959746772822],[121.23687744140624,24.587090339209634],[121.24099731445311,24.552119771544227],[121.2451171875,24.525885444592642],[121.30279541015624,24.55087064225044],[121.27258300781251,24.58958786341259],[121.26708984374999,24.623299562653035],[121.32614135742188,24.62579636412304],[121.34674072265624,24.602074737077242],[121.36871337890625,24.580846310771612],[121.40853881835936,24.653257887871963],[121.40853881835936,24.724380091871726],[121.37283325195312,24.716895455859337],[121.3604736328125,24.693191139677126],[121.343994140625,24.69942955501979],[121.32888793945312,24.728122241065808],[121.3714599609375,24.743089712134605],[121.37695312499999,24.77177232822881],[121.35635375976562,24.792968265314457],[121.32476806640625,24.807927923059236],[121.29730224609375,24.844072974931866],[121.24923706054688,24.849057671305268],[121.24786376953125,24.816653556469955],[121.27944946289062,24.79047481357294],[121.30142211914061,24.761796517185815],[121.27258300781251,24.73311159823193],[121.25335693359374,24.708162811665265],[121.20391845703125,24.703172454280217],[121.19979858398438,24.731864277701714],[121.20803833007811,24.75431413309125]]
+ multipolygon = {
+ "type": "MultiPolygon",
+ "coordinates": [[test_ring]]
+ }
+ number = vw.simplify_geometry(multipolygon, number=10)
+ self.assertEqual(number['coordinates'][0][0][0], number['coordinates'][0][0][-1])
+
+ ratio = vw.simplify_geometry(multipolygon, ratio=0.3)
+ self.assertEqual(ratio['coordinates'][0][0][0], ratio['coordinates'][0][0][-1])
+
+ thres = vw.simplify_geometry(multipolygon, threshold=0.01)
+ self.assertEqual(thres['coordinates'][0][0][0], thres['coordinates'][0][0][-1])
+
+ polygon = {
+ "type": "Polygon",
+ "coordinates": [test_ring]
+ }
+ number = vw.simplify_geometry(multipolygon, number=10)
+ self.assertEqual(number['coordinates'][0][0][0], number['coordinates'][0][0][-1])
+
+ ratio = vw.simplify_geometry(multipolygon, ratio=0.3)
+ self.assertEqual(ratio['coordinates'][0][0][0], ratio['coordinates'][0][0][-1])
+
+ thres = vw.simplify_geometry(multipolygon, threshold=0.01)
+ self.assertEqual(thres['coordinates'][0][0][0], thres['coordinates'][0][0][-1])
+
def testCli(self):
pass
def testSimplify(self):
+ '''Use the command-line function to simplify the sample data.'''
try:
output = 'tmp.json'
- cli.simplify('tests/data/sample.json', output, number=9)
+ cli.simplify(self.samplefile, output, number=9)
self.assertTrue(os.path.exists(output))
|
first & last position not the same in coordinates after simplify_geometry
# Environment
OS: mscOS Big Sur 11.1
Python: 3.8.6
pip list:
numpy 1.19.4
pip 20.2.4
setuptools 50.3.2
visvalingamwyatt 0.1.3
wheel 0.35.1
# Reproduce
```python
import pprint
import visvalingamwyatt as vw
pp = pprint.PrettyPrinter(sort_dicts=False)
test_data={"type":"Feature","properties":{},"geometry":{"type":"MultiPolygon","coordinates":[[[[121.20803833007811,24.75431413309125],[121.1846923828125,24.746831298412058],[121.1517333984375,24.74059525872194],[121.14486694335936,24.729369599118222],[121.12152099609375,24.693191139677126],[121.13525390625,24.66449040712424],[121.10504150390625,24.66449040712424],[121.10092163085936,24.645768980151793],[121.0748291015625,24.615808859044243],[121.09405517578125,24.577099744289427],[121.12564086914062,24.533381526147682],[121.14624023437499,24.515889973088104],[121.19018554687499,24.528384188171866],[121.19430541992186,24.57959746772822],[121.23687744140624,24.587090339209634],[121.24099731445311,24.552119771544227],[121.2451171875,24.525885444592642],[121.30279541015624,24.55087064225044],[121.27258300781251,24.58958786341259],[121.26708984374999,24.623299562653035],[121.32614135742188,24.62579636412304],[121.34674072265624,24.602074737077242],[121.36871337890625,24.580846310771612],[121.40853881835936,24.653257887871963],[121.40853881835936,24.724380091871726],[121.37283325195312,24.716895455859337],[121.3604736328125,24.693191139677126],[121.343994140625,24.69942955501979],[121.32888793945312,24.728122241065808],[121.3714599609375,24.743089712134605],[121.37695312499999,24.77177232822881],[121.35635375976562,24.792968265314457],[121.32476806640625,24.807927923059236],[121.29730224609375,24.844072974931866],[121.24923706054688,24.849057671305268],[121.24786376953125,24.816653556469955],[121.27944946289062,24.79047481357294],[121.30142211914061,24.761796517185815],[121.27258300781251,24.73311159823193],[121.25335693359374,24.708162811665265],[121.20391845703125,24.703172454280217],[121.19979858398438,24.731864277701714],[121.20803833007811,24.75431413309125]]]]}}
pp.pprint(vw.simplify_geometry(test_data['geometry'], number=10))
pp.pprint(vw.simplify_geometry(test_data['geometry'], ratio=0.3))
pp.pprint(vw.simplify_geometry(test_data['geometry'], threshold=0.01))
```
# output
```
{'type': 'MultiPolygon',
'coordinates': [[[[121.20803833007811, 24.75431413309125],
[121.1517333984375, 24.74059525872194],
[121.0748291015625, 24.615808859044243],
[121.14624023437499, 24.515889973088104],
[121.26708984374999, 24.623299562653035],
[121.36871337890625, 24.580846310771612],
[121.40853881835936, 24.724380091871726],
[121.29730224609375, 24.844072974931866],
[121.30142211914061, 24.761796517185815],
[121.20391845703125, 24.703172454280217]]]]}
{'type': 'MultiPolygon',
'coordinates': [[[[121.20803833007811, 24.75431413309125],
[121.1517333984375, 24.74059525872194],
[121.0748291015625, 24.615808859044243],
[121.14624023437499, 24.515889973088104],
[121.23687744140624, 24.587090339209634],
[121.2451171875, 24.525885444592642],
[121.30279541015624, 24.55087064225044],
[121.26708984374999, 24.623299562653035],
[121.36871337890625, 24.580846310771612],
[121.40853881835936, 24.724380091871726],
[121.29730224609375, 24.844072974931866],
[121.24786376953125, 24.816653556469955]]]]}
{'type': 'MultiPolygon',
'coordinates': [[[[121.20803833007811, 24.75431413309125],
[121.0748291015625, 24.615808859044243],
[121.14624023437499, 24.515889973088104],
[121.36871337890625, 24.580846310771612],
[121.40853881835936, 24.724380091871726],
[121.29730224609375, 24.844072974931866],
[121.20803833007811, 24.75431413309125]]]]}
```
From the result above, simplify_geometry works perfectly with threshold (3rd json).
But for number and ratio, the last position is not the same as first positon.
So... it's a bug or I do this wrong?
|
0.0
|
38c64f4f1c5b227aa76ea9ad7aa9694b2c56fdef
|
[
"tests/test_vw.py::TestCase::testSimplifyClosedFeature"
] |
[
"tests/test_vw.py::TestCase::test3dCoords",
"tests/test_vw.py::TestCase::testCli",
"tests/test_vw.py::TestCase::testSimplify",
"tests/test_vw.py::TestCase::testSimplifyFeature",
"tests/test_vw.py::TestCase::testSimplifyFeatureNumber",
"tests/test_vw.py::TestCase::testSimplifyFeatureRatio",
"tests/test_vw.py::TestCase::testSimplifyFeatureThreshold",
"tests/test_vw.py::TestCase::testSimplifyIntegerCoords",
"tests/test_vw.py::TestCase::testSimplifyTupleLike"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-01-31 19:47:20+00:00
|
mit
| 2,354 |
|
florimondmanca__asgi-caches-21
|
diff --git a/src/asgi_caches/exceptions.py b/src/asgi_caches/exceptions.py
index 29a3bbf..1d1d270 100644
--- a/src/asgi_caches/exceptions.py
+++ b/src/asgi_caches/exceptions.py
@@ -20,3 +20,10 @@ class ResponseNotCachable(ASGICachesException):
def __init__(self, response: Response) -> None:
super().__init__()
self.response = response
+
+
+class DuplicateCaching(ASGICachesException):
+ """
+ Raised when more than one cache middleware
+ were detected in the middleware stack.
+ """
diff --git a/src/asgi_caches/middleware.py b/src/asgi_caches/middleware.py
index 13673ed..206d5aa 100644
--- a/src/asgi_caches/middleware.py
+++ b/src/asgi_caches/middleware.py
@@ -6,7 +6,7 @@ from starlette.requests import Request
from starlette.responses import Response
from starlette.types import ASGIApp, Message, Receive, Scope, Send
-from .exceptions import RequestNotCachable, ResponseNotCachable
+from .exceptions import DuplicateCaching, RequestNotCachable, ResponseNotCachable
from .utils.cache import get_from_cache, patch_cache_control, store_in_cache
from .utils.logging import HIT_EXTRA, MISS_EXTRA, get_logger
from .utils.misc import kvformat
@@ -32,6 +32,18 @@ class CacheMiddleware:
await self.app(scope, receive, send)
return
+ if "__asgi_caches__" in scope:
+ raise DuplicateCaching(
+ "Another `CacheMiddleware` was detected in the middleware stack.\n"
+ "HINT: this exception probably occurred because:\n"
+ "- You wrapped an application around `CacheMiddleware` multiple "
+ "times.\n"
+ "- You tried to apply `@cached()` onto an endpoint, but "
+ "the application is already wrapped around a `CacheMiddleware`."
+ )
+
+ scope["__asgi_caches__"] = True
+
responder = CacheResponder(self.app, cache=self.cache)
await responder(scope, receive, send)
|
florimondmanca/asgi-caches
|
2979cf8ac9082145eaafd68b27fabc4897c4d25c
|
diff --git a/tests/test_functional.py b/tests/test_functional.py
index f0ca319..7278d30 100644
--- a/tests/test_functional.py
+++ b/tests/test_functional.py
@@ -10,6 +10,7 @@ from starlette.requests import Request
from starlette.responses import JSONResponse, PlainTextResponse, Response
from asgi_caches.decorators import cache_control, cached
+from asgi_caches.exceptions import DuplicateCaching
from asgi_caches.middleware import CacheMiddleware
cache = Cache("locmem://default", ttl=2 * 60)
@@ -100,3 +101,20 @@ async def test_caching(client: httpx.AsyncClient) -> None:
r = await client.get("/exp")
assert e_calls == 1
+
+
[email protected]
+async def test_duplicate_caching() -> None:
+ app = Starlette()
+ app.add_middleware(CacheMiddleware, cache=cache)
+
+ @app.route("/duplicate_cache")
+ @cached(special_cache)
+ class DuplicateCache(HTTPEndpoint):
+ pass
+
+ client = httpx.AsyncClient(app=app, base_url="http://testserver")
+
+ async with cache, special_cache, client:
+ with pytest.raises(DuplicateCaching):
+ await client.get("/duplicate_cache")
|
Disallow multiple endpoint-level cache configuration
Currently, it is theoretically possible for a user to do the following:
```python
@cached(cache)
@cached(cache)
...
@cached(cache)
class Endpoint(HTTPEndpoint):
...
```
i.e. to apply the `@cached` decorator introduced by #15 an arbitrary number of times.
I can't see a situation when this would make sense. Even when #3 lands, the only reasonable behavior is to apply the top-most decorator, which means others decorators have no effect and should then be disallowed to prevent confusion.
Users could also have `CacheMiddleware` applied onto the app, and then applied `cached` to an endpoint. This shouldn't be allowed either.
To implement this feature:
- Modify the `@cached` decorator to raise an exception (`ValueError` is probably fine) if the decorated `app` is an instance of `CacheMiddleware` (because this means that the decorator has already been applied).
- Add a test to verify that the exception is raised if we try to apply the decorator twice.
|
0.0
|
2979cf8ac9082145eaafd68b27fabc4897c4d25c
|
[
"tests/test_functional.py::test_duplicate_caching"
] |
[] |
{
"failed_lite_validators": [
"has_issue_reference",
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2019-11-17 15:13:40+00:00
|
mit
| 2,355 |
|
florimondmanca__fountain-lang-7
|
diff --git a/src/fountain/_ast/visitor.py b/src/fountain/_ast/visitor.py
index 12308b0..7859e02 100644
--- a/src/fountain/_ast/visitor.py
+++ b/src/fountain/_ast/visitor.py
@@ -1,4 +1,4 @@
-from typing import Generic, TypeVar
+from typing import Any, Generic, TypeVar
from .nodes import Expr, Stmt
@@ -12,11 +12,11 @@ class NodeVisitor(Generic[R]):
)
return method(node)
- def execute(self, node: Stmt) -> None:
+ def execute(self, node: Stmt) -> Any:
method = getattr(
self, f"execute_{node.__class__.__name__}", self.execute_default
)
- method(node)
+ return method(node)
def evaluate_default(self, expr: Expr) -> R:
raise NotImplementedError(f"Unexpected node: {expr}") # pragma: no cover
diff --git a/src/fountain/_cli.py b/src/fountain/_cli.py
index 2f258fc..45778de 100644
--- a/src/fountain/_cli.py
+++ b/src/fountain/_cli.py
@@ -1,10 +1,11 @@
import argparse
import pathlib
import sys
+from typing import Any
from ._ast import parse, tokenize
from ._exceptions import EvalError, ParseError, TokenizeError
-from ._interpreter import Interpreter
+from ._interpreter import Interpreter, stringify
def main() -> None:
@@ -32,28 +33,27 @@ class CLI:
else:
return self._run_prompt()
+ def evaluate(self, source: str) -> Any:
+ tokens = tokenize(source)
+ statements = parse(tokens)
+ return self._interpreter.interpret(statements)
+
def run(self, source: str) -> int:
try:
- tokens = tokenize(source)
+ self.evaluate(source)
except TokenizeError as exc:
self._report(exc.message, lineno=exc.lineno)
return 65
-
- try:
- statements = parse(tokens)
except ParseError as exc:
where = "at end" if exc.at_eof else f"at {exc.token.lexeme!r}"
self._report(exc.message, lineno=exc.token.lineno, where=where)
return 65
-
- try:
- self._interpreter.interpret(statements)
except EvalError as exc:
where = f"at {exc.token.lexeme!r}"
self._report(exc.message, lineno=exc.token.lineno, where=where)
return 70
-
- return 0
+ else:
+ return 0
def _run_file(self, path: str) -> int:
try:
@@ -78,7 +78,9 @@ class CLI:
if not line:
break
- _ = self.run(line)
+ value = self.evaluate(line)
+ if value is not None:
+ print(stringify(value))
return 0
diff --git a/src/fountain/_interpreter.py b/src/fountain/_interpreter.py
index 566e332..112f810 100644
--- a/src/fountain/_interpreter.py
+++ b/src/fountain/_interpreter.py
@@ -40,21 +40,23 @@ class Interpreter(NodeVisitor[Any]):
scope.assign(name, value)
self._scope = scope
- def interpret(self, statements: list[Stmt]) -> None:
+ def interpret(self, statements: list[Stmt]) -> Any:
+ value: Any = None
try:
for stmt in statements:
- self.execute(stmt)
+ value = self.execute(stmt)
except EvalError:
raise
+ else:
+ return value
def execute_Assign(self, stmt: Assign) -> None:
name = stmt.target.lexeme
value = self.evaluate(stmt.value)
self._scope.assign(name, value)
- def execute_Expression(self, stmt: Expression) -> None:
- value = self.evaluate(stmt.expression)
- print(stringify(value))
+ def execute_Expression(self, stmt: Expression) -> Any:
+ return self.evaluate(stmt.expression)
def execute_Print(self, stmt: Print) -> None:
value = self.evaluate(stmt.expression)
|
florimondmanca/fountain-lang
|
4ca44d301117e2bd738aa98411d6eab7bb381b26
|
diff --git a/tests/test_cli.py b/tests/test_cli.py
index b8a3bef..434a4fa 100644
--- a/tests/test_cli.py
+++ b/tests/test_cli.py
@@ -117,9 +117,7 @@ def test_cli_repl(monkeypatch: Any, capsys: Any) -> None:
),
(
"fn f() print 'OK' end; f()",
- # TODO: drop 'nil' after:
- # https://github.com/florimondmanca/fountain-lang/issues/1
- "OK\nnil\n",
+ "OK\n",
),
(
"""
|
Handling of expression statements results in unwanted prints
Currently, expression statements such as:
```lua
"hello, world"
some_func(a, b, c)
```
Result in printing the result to the console. In the REPL or via `fountain -c` this is what we want, but not when running from a file.
We should move the "print the expression" behavour out of the `Interpreter` and to the `CLI`. Most likely:
* Modify `Interpreter.execute()` to fit `() -> Any` (may return a value).
* Modify `Interpreter.execute_Expression()` so that it _returns_ the value of the expression.
* Modify `interpret` to be `(list[Stmt]) -> Any` so that it keeps track of the statement return values (in practice only `Expression` statements may return a value), and return the last one.
* Add a new `CLI.evaluate(source: str) -> Any` method that returns the result from `interpret()`.
* Update `CLI.run`, `CLI._run_file` and `CLI._run_prompt` so that they do the right thing, i.e. only show `stringify(value)` in the prompt.
|
0.0
|
4ca44d301117e2bd738aa98411d6eab7bb381b26
|
[
"tests/test_cli.py::test_cli_eval[fn"
] |
[
"tests/test_cli.py::test_cli_repl",
"tests/test_cli.py::test_cli_eval[print",
"tests/test_cli.py::test_cli_eval[x",
"tests/test_cli.py::test_cli_eval[\\n",
"tests/test_cli.py::test_cli_eval[do",
"tests/test_cli.py::test_cli_eval[assert",
"tests/test_cli.py::test_cli_eval[--",
"tests/test_cli.py::test_cli_eval[-]",
"tests/test_cli.py::test_cli_eval_error[(3",
"tests/test_cli.py::test_cli_eval_error['hello-[line",
"tests/test_cli.py::test_cli_eval_error['hello\"-[line",
"tests/test_cli.py::test_cli_eval_error['hello\\n-[line",
"tests/test_cli.py::test_cli_eval_error[3",
"tests/test_cli.py::test_cli_eval_error[\\n",
"tests/test_cli.py::test_cli_eval_error[do",
"tests/test_cli.py::test_cli_eval_error[break-[line",
"tests/test_cli.py::test_cli_eval_error[continue-[line",
"tests/test_cli.py::test_cli_eval_error[fn",
"tests/test_cli.py::test_cli_eval_error[return",
"tests/test_cli.py::test_cli_eval_error[1/0-[line",
"tests/test_cli.py::test_cli_eval_error[1",
"tests/test_cli.py::test_cli_eval_error['hello'",
"tests/test_cli.py::test_cli_eval_error[print",
"tests/test_cli.py::test_cli_eval_error[assert",
"tests/test_cli.py::test_cli_eval_error[1()-[line"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-10-02 13:59:15+00:00
|
apache-2.0
| 2,356 |
|
flyingcircusio__batou-228
|
diff --git a/CHANGES.md b/CHANGES.md
index 4967aa33..913923b6 100644
--- a/CHANGES.md
+++ b/CHANGES.md
@@ -18,6 +18,9 @@
- Support `ls` syntax in mode attributes.
([#61](https://github.com/flyingcircusio/batou/issues/61))
+- Integrate `remote-pdb` to debug batou runs.
+ ([#199](https://github.com/flyingcircusio/batou/issues/199))
+
- Fail if an attribute is set both in environment and via secrets.
([#28](https://github.com/flyingcircusio/batou/issues/28))
diff --git a/doc/source/user/advanced.txt b/doc/source/user/advanced.txt
index d8f9f392..4c0928dd 100644
--- a/doc/source/user/advanced.txt
+++ b/doc/source/user/advanced.txt
@@ -5,6 +5,61 @@ Advanced Usage
Writing a custom component (TODO)
---------------------------------
+Debugging batou runs
+--------------------
+
+Using a debugger
+++++++++++++++++
+
+``batou`` comes with `remote-pdb <https://pypi.org/project/remote-pdb/>`_
+pre-installed. When running on Python 3.7+ [#]_ you can use ``breakpoint()`` to
+drop into the debugger. You need ``telnet`` or ``netcat`` to connect to the
+hostname and port displayed.
+
+If you are using the default configuration, call::
+
+ $ nc -C 127.0.0.1 4444
+ or
+ $ telnet 127.0.0.1 4444
+
+If you are debugging a remote deployment you should create a port forward
+beforehand like this::
+
+ $ ssh -L 4444:localhost:4444 my.remote.host.dev
+
+You are able to configure hostname and port. For details see the documentation
+of `remote-pdb <https://pypi.org/project/remote-pdb/>`_. This works both for
+local and remote deployments. The environment variables for host and port are
+propagated to the remote host.
+
+Example shell session for debugging using a custom port::
+
+ $ REMOTE_PDB_PORT=4445 ./batou deploy dev
+ batou/2.3b2.dev0 (cpython 3.6.15-final0, Darwin 20.6.0 x86_64)
+ ============================= Preparing ============================
+ main: Loading environment `dev`...
+ main: Verifying repository ...
+ main: Loading secrets ...
+ ============================= Connecting ... =======================
+ localhost: Connecting via local (1/1)
+ ============================= Configuring model ... ================
+ RemotePdb session open at 127.0.0.1:4445, waiting for connection ...
+
+Example for a second terminal where the opened port gets connected to::
+
+ $ nc -C 127.0.0.1 4445
+ > /.../components/supervisor/component.py(32)configure()
+ -> if self.host.platform in ('gocept.net', 'fcio.net'):
+ (Pdb)
+
+
+Using "print debugging"
++++++++++++++++++++++++
+
+* Inside a component you can use ``self.log("output")`` to print to the
+ console.
+* You can call ``batou`` with the ``-d`` flag to enable debugging output during
+ the deployment run.
Using 3rd party libraries within batou
@@ -196,3 +251,5 @@ batou.c (TODO)
--------------
ordered alphabetically (significant for imports)
+
+.. [#] On Python 3.6 you have to use ``from remote_pdb import set_trace; set_trace()``.
diff --git a/setup.py b/setup.py
index b57f9cd0..79e45eb0 100644
--- a/setup.py
+++ b/setup.py
@@ -21,9 +21,10 @@ setup(
# ConfigUpdater does not manage its minimum requirements correctly.
"setuptools>=38.3",
"execnet>=1.8.1",
- "pyyaml",
"importlib_metadata",
- "py",],
+ "py",
+ "pyyaml",
+ 'remote-pdb',],
extras_require={
"test": [
"mock",
diff --git a/src/batou/__init__.py b/src/batou/__init__.py
index b1fb3171..b2eaf5bb 100644
--- a/src/batou/__init__.py
+++ b/src/batou/__init__.py
@@ -1,5 +1,6 @@
# This code must not cause non-stdlib imports to support self-bootstrapping.
import os.path
+import os
import traceback
from ._output import output
@@ -7,6 +8,13 @@ from ._output import output
with open(os.path.dirname(__file__) + "/version.txt") as f:
__version__ = f.read().strip()
+# Configure `remote-pdb` to be used with `breakpoint()` in Python 3.7+:
+os.environ['PYTHONBREAKPOINT'] = "remote_pdb.set_trace"
+if not os.environ.get('REMOTE_PDB_HOST', None):
+ os.environ['REMOTE_PDB_HOST'] = "127.0.0.1"
+if not os.environ.get('REMOTE_PDB_PORT', None):
+ os.environ['REMOTE_PDB_PORT'] = "4444"
+
class ReportingException(Exception):
"""Exceptions that support user-readable reporting."""
diff --git a/src/batou/host.py b/src/batou/host.py
index ce232734..aa7c2e52 100644
--- a/src/batou/host.py
+++ b/src/batou/host.py
@@ -8,6 +8,12 @@ import yaml
from batou import (DeploymentError, SilentConfigurationError, output,
remote_core)
+# Keys in os.environ which get propagated to the remote side:
+REMOTE_OS_ENV_KEYS = (
+ 'REMOTE_PDB_HOST',
+ 'REMOTE_PDB_PORT',
+)
+
# Monkeypatch execnet to support 'vagrant ssh' and 'kitchen exec'.
# 'vagrant' support has been added to 'execnet' release 1.4.
@@ -285,9 +291,19 @@ pre=\"\"; else pre=\"sudo -ni -u {user}\"; fi; $pre\
# know about locally)
self.rpc.setup_output()
- self.rpc.setup_deployment(env.name, self.name, env.overrides,
- env.secret_files, env.secret_data,
- env._host_data(), env.timeout, env.platform)
+ self.rpc.setup_deployment(
+ env.name,
+ self.name,
+ env.overrides,
+ env.secret_files,
+ env.secret_data,
+ env._host_data(),
+ env.timeout,
+ env.platform,
+ {
+ key: os.environ.get(key)
+ for key in REMOTE_OS_ENV_KEYS if os.environ.get(key)},
+ )
def disconnect(self):
if self.gateway is not None:
diff --git a/src/batou/remote_core.py b/src/batou/remote_core.py
index 8b7856b4..1cb0555a 100644
--- a/src/batou/remote_core.py
+++ b/src/batou/remote_core.py
@@ -129,8 +129,16 @@ class Deployment(object):
environment = None
- def __init__(self, env_name, host_name, overrides, secret_files,
- secret_data, host_data, timeout, platform):
+ def __init__(self,
+ env_name,
+ host_name,
+ overrides,
+ secret_files,
+ secret_data,
+ host_data,
+ timeout,
+ platform,
+ os_env=None):
self.env_name = env_name
self.host_name = host_name
self.overrides = overrides
@@ -139,10 +147,13 @@ class Deployment(object):
self.secret_data = secret_data
self.timeout = timeout
self.platform = platform
+ self.os_env = os_env
def load(self):
from batou.environment import Environment
+ if self.os_env:
+ os.environ.update(self.os_env)
self.environment = Environment(self.env_name, self.timeout,
self.platform)
self.environment.deployment = self
|
flyingcircusio/batou
|
1be1770e2e502e11971ac49c2d3a89d6f4cd0b73
|
diff --git a/src/batou/tests/test_config.py b/src/batou/tests/test_config.py
index 0be4d4b7..50738eb7 100644
--- a/src/batou/tests/test_config.py
+++ b/src/batou/tests/test_config.py
@@ -133,3 +133,10 @@ def test_config_exceptions_orderable(env):
for x in exceptions:
for y in exceptions:
x.sort_key < y.sort_key
+
+
+def test_remote_pdb_config():
+ """There are some environment variables set with default values."""
+ assert os.environ["PYTHONBREAKPOINT"] == "remote_pdb.set_trace"
+ assert os.environ["REMOTE_PDB_HOST"] == "127.0.0.1"
+ assert os.environ["REMOTE_PDB_PORT"] == "4444"
diff --git a/src/batou/tests/test_remote_core.py b/src/batou/tests/test_remote_core.py
index 3ac23711..9d1709d5 100644
--- a/src/batou/tests/test_remote_core.py
+++ b/src/batou/tests/test_remote_core.py
@@ -1,6 +1,7 @@
from batou import remote_core
import inspect
import mock
+import os
import os.path
import pytest
@@ -287,3 +288,28 @@ def test_git_remote_init_pull(tmpdir):
remote_core.git_update_working_copy("master")
assert "bar" == dest.join("foo.txt").read()
+
+
+def test_Deployment_sets_os_environ_on_load(monkeypatch):
+ """If ``os_env`` is given to ``Deployment`` it changes os.environ, ...or
+
+ when the ``load()`` method is called.
+ """
+ monkeypatch.chdir('examples/tutorial-helloworld')
+
+ assert 'MY_ENV_VAR' not in os.environ
+
+ dep = remote_core.Deployment(
+ env_name='tutorial',
+ host_name='localhost',
+ overrides={},
+ secret_files=None,
+ secret_data=None,
+ host_data={},
+ timeout=None,
+ platform=None,
+ os_env={'MY_ENV_VAR': 'MY-VALUE'},
+ )
+ dep.load()
+
+ assert os.environ['MY_ENV_VAR'] == 'MY-VALUE'
|
Debugging batou?
To debug issues in `batou` I am nowadays using [remote-pdb](https://pypi.org/project/remote-pdb/). It allows to start a debugger at any point in the code as it opens a remote port where the debugger can be accessed via `nc` or `telnet`.
To be able to use it in the tests I added `remote-pdb` locally to `tox.ini` as a dependency.
Would it be a good idea to add it (or another remote debugger) there permanently? (It does not hurt and eases debugging end to end tests.)
I can live with being forced to have to add the debugger to `requirements.txt` to debug actual `batou` runs.
|
0.0
|
1be1770e2e502e11971ac49c2d3a89d6f4cd0b73
|
[
"src/batou/tests/test_config.py::test_remote_pdb_config",
"src/batou/tests/test_remote_core.py::test_Deployment_sets_os_environ_on_load"
] |
[
"src/batou/tests/test_config.py::test_parse_nonexisting_environment_raises_error",
"src/batou/tests/test_config.py::test_service_options_are_set",
"src/batou/tests/test_config.py::test_components_are_fully_loaded",
"src/batou/tests/test_config.py::test_production_environment_is_loaded",
"src/batou/tests/test_config.py::test_dev_environment_is_loaded",
"src/batou/tests/test_config.py::test_component_has_features_set",
"src/batou/tests/test_config.py::test_load_environment_with_overrides",
"src/batou/tests/test_config.py::test_config_exceptions_orderable",
"src/batou/tests/test_remote_core.py::test_deployment_and_channel_exist_as_names",
"src/batou/tests/test_remote_core.py::test_lock",
"src/batou/tests/test_remote_core.py::test_cmd",
"src/batou/tests/test_remote_core.py::test_update_code_existing_target",
"src/batou/tests/test_remote_core.py::test_update_code_new_target",
"src/batou/tests/test_remote_core.py::test_hg_bundle_shipping",
"src/batou/tests/test_remote_core.py::test_build_batou_fresh_install",
"src/batou/tests/test_remote_core.py::test_build_batou_virtualenv_exists",
"src/batou/tests/test_remote_core.py::test_expand_deployment_base",
"src/batou/tests/test_remote_core.py::test_deploy_component",
"src/batou/tests/test_remote_core.py::test_whoami",
"src/batou/tests/test_remote_core.py::test_channelexec_already_closed",
"src/batou/tests/test_remote_core.py::test_channelexec_echo_cmd",
"src/batou/tests/test_remote_core.py::test_channelexec_multiple_echo_cmds",
"src/batou/tests/test_remote_core.py::test_channelexec_handle_exception",
"src/batou/tests/test_remote_core.py::test_git_remote_init_bundle",
"src/batou/tests/test_remote_core.py::test_git_remote_init_pull"
] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-09-13 14:54:29+00:00
|
bsd-2-clause
| 2,357 |
|
flyingcircusio__batou-263
|
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index b3ab2188..baad4427 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -1,7 +1,7 @@
exclude: '(components/component5/component.py|haproxy.cfg|encrypted.cfg|\.appenv|\.batou|lib/python|examples/.*/environments/.*/secret.*)'
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
- rev: v4.0.1
+ rev: v4.1.0
hooks:
- id: check-yaml
- id: end-of-file-fixer
@@ -12,7 +12,7 @@ repos:
- id: isort
name: isort (python)
- repo: https://github.com/pre-commit/mirrors-yapf
- rev: 'v0.31.0' # Use the sha / tag you want to point at
+ rev: 'v0.32.0' # Use the sha / tag you want to point at
hooks:
- id: yapf
args: [-i, -p]
diff --git a/CHANGES.md b/CHANGES.md
index 6da4aab9..f07c0ec1 100644
--- a/CHANGES.md
+++ b/CHANGES.md
@@ -10,6 +10,9 @@
`batou migrate`.
([#185](https://github.com/flyingcircusio/batou/issues/185))
+- Allow to pin the `pip` version used in the `Buildout` component.
+ ([#263](https://github.com/flyingcircusio/batou/issues/263))
+
- Automatically migrate environments and secrets to the new structure using
`./batou migrate`.
([#185](https://github.com/flyingcircusio/batou/issues/185))
diff --git a/doc/source/components/python.txt b/doc/source/components/python.txt
index 6c2f988e..917ef6cf 100644
--- a/doc/source/components/python.txt
+++ b/doc/source/components/python.txt
@@ -103,7 +103,8 @@ files makes it necessary. A typical usage example:
.. code-block:: python
- self += Buildout(python='2.7', version='2.2', setuptools='1.0',
+ self += Buildout(python='3.7', version='2.2', setuptools='1.0',
+ pip='21.1',
additional_config=[Directory('profiles', source='profiles')])
.. py:class:: batou.lib.buildout.Buildout()
@@ -129,6 +130,11 @@ files makes it necessary. A typical usage example:
to the buildout version, e.g. since 2.2 buildout requires setuptools, but
some versions before that required distribute) (**required**)
+.. py:attribute:: pip
+
+ Version of pip to install into the virtualenv (must be appropriate
+ to the buildout version).
+
.. py:attribute:: distribute
Version of distribute to install into the virtualenv. Mutually exclusive
diff --git a/src/batou/lib/buildout.py b/src/batou/lib/buildout.py
index 274df718..a217f702 100644
--- a/src/batou/lib/buildout.py
+++ b/src/batou/lib/buildout.py
@@ -19,6 +19,7 @@ class Buildout(Component):
distribute = None
setuptools = None
wheel = None
+ pip = None
version = None
build_env = {} # XXX not frozen. :/
@@ -58,6 +59,9 @@ class Buildout(Component):
if self.wheel:
venv += Package("wheel", version=self.wheel)
+ if self.pip:
+ venv += Package("pip", version=self.pip)
+
# Install without dependencies (that's just setuptools anyway), since
# that could cause pip to pull in the latest version of setuptools,
# regardless of the version we wanted to be installed above.
|
flyingcircusio/batou
|
9577420ebf1d3dc7d31c611ff4e1d15b54b4fb7a
|
diff --git a/src/batou/lib/tests/test_buildout.py b/src/batou/lib/tests/test_buildout.py
index 2ae6a58d..fd88c8b4 100644
--- a/src/batou/lib/tests/test_buildout.py
+++ b/src/batou/lib/tests/test_buildout.py
@@ -55,9 +55,7 @@ def test_runs_buildout_successfully(root):
os.path.join(root.environment.workdir_base, "mycomponent/bin/py"))
-# XFAIL due to https://github.com/flyingcircusio/batou/issues/169
@pytest.mark.slow
[email protected]
@pytest.mark.timeout(60)
def test_runs_buildout3_successfully(root, output):
b = Buildout(
@@ -65,6 +63,7 @@ def test_runs_buildout3_successfully(root, output):
version="3.0.0b1",
setuptools="54.1.1",
wheel="0.36.2",
+ pip="21.0.1",
config=File(
"buildout3.cfg",
source=pkg_resources.resource_filename(__name__,
|
buildout 3 test fails due to buildout / pip 21.1 incompatibility
```
Run bin/tox
py36 create: /home/runner/work/batou/batou/.tox/py36
SKIPPED: InterpreterNotFound: python3.6
py37 create: /home/runner/work/batou/batou/.tox/py37
SKIPPED: InterpreterNotFound: python3.7
py38 create: /home/runner/work/batou/batou/.tox/py38
py38 develop-inst: /home/runner/work/batou/batou
py38 installed: apipkg==1.5,attrs==21.2.0,-e git+https://github.com/flyingcircusio/batou@c811fad72083579e945d0c0eddfbdc85393f304a#egg=batou,certifi==2020.12.5,chardet==4.0.0,ConfigUpdater==2.0,coverage==5.5,execnet==1.8.0,idna==2.10,iniconfig==1.1.1,Jinja2==3.0.1,MarkupSafe==2.0.1,mock==4.0.3,packaging==20.9,pluggy==0.13.1,py==1.10.0,pyparsing==2.4.7,pytest==6.2.4,pytest-cov==2.12.0,pytest-cover==3.0.0,pytest-coverage==0.0,pytest-timeout==1.4.2,PyYAML==5.4.1,requests==2.25.1,toml==0.10.2,urllib3==1.26.4
py38 run-test-pre: PYTHONHASHSEED='3322565937'
py38 run-test: commands[0] | pytest src/batou
============================= test session starts ==============================
platform linux -- Python 3.8.10, pytest-6.2.4, py-1.10.0, pluggy-0.13.1
cachedir: .tox/py38/.pytest_cache
rootdir: /home/runner/work/batou/batou, configfile: pytest.ini
plugins: timeout-1.4.2, cov-2.12.0
timeout: 45.0s
timeout method: signal
timeout func_only: False
collected 364 items
src/batou/lib/tests/test_appenv.py .. [ 0%]
src/batou/lib/tests/test_archive.py .......s. [ 3%]
src/batou/lib/tests/test_buildout.py ...F [ 4%]
src/batou/lib/tests/test_cmmi.py ...... [ 5%]
src/batou/lib/tests/test_cron.py ..... [ 7%]
src/batou/lib/tests/test_debian.py ... [ 7%]
src/batou/lib/tests/test_download.py ..... [ 9%]
src/batou/lib/tests/test_file.py ....................................... [ 20%]
.........................s.................. [ 32%]
src/batou/lib/tests/test_git.py .............. [ 35%]
src/batou/lib/tests/test_mercurial.py ............ [ 39%]
src/batou/lib/tests/test_nagios.py . [ 39%]
src/batou/lib/tests/test_python.py .. [ 40%]
src/batou/lib/tests/test_service.py ... [ 40%]
src/batou/lib/tests/test_supervisor.py ....... [ 42%]
src/batou/lib/tests/test_svn.py . [ 43%]
src/batou/secrets/tests/test_editor.py .. [ 43%]
src/batou/secrets/tests/test_secrets.py ............ [ 46%]
src/batou/tests/test_component.py ...................................... [ 57%]
....................... [ 63%]
src/batou/tests/test_config.py ........ [ 65%]
src/batou/tests/test_dependencies.py ........... [ 68%]
src/batou/tests/test_deploy.py . [ 69%]
src/batou/tests/test_endtoend.py ........ [ 71%]
src/batou/tests/test_environment.py ........................... [ 78%]
src/batou/tests/test_exceptions.py . [ 79%]
src/batou/tests/test_host.py ... [ 79%]
src/batou/tests/test_remote.py ... [ 80%]
src/batou/tests/test_remote_core.py ................. [ 85%]
src/batou/tests/test_resources.py .. [ 85%]
src/batou/tests/test_template.py ......... [ 88%]
src/batou/tests/test_utils.py ........................................ [ 99%]
src/batou/tests/test_vfs.py .. [100%]
=================================== FAILURES ===================================
_______________________ test_runs_buildout3_successfully _______________________
Traceback (most recent call last):
File "/home/runner/work/batou/batou/src/batou/component.py", line 332, in deploy
call_with_optional_args(
File "/home/runner/work/batou/batou/src/batou/utils.py", line 424, in call_with_optional_args
return func(**call_kw)
File "/home/runner/work/batou/batou/src/batou/lib/buildout.py", line 72, in verify
installed.assert_component_is_current([Presence("bin/buildout")] +
File "/home/runner/work/batou/batou/src/batou/component.py", line 671, in assert_component_is_current
raise batou.UpdateNeeded()
batou.UpdateNeeded
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/runner/work/batou/batou/src/batou/lib/tests/test_buildout.py", line 71, in test_runs_buildout3_successfully
root.component.deploy()
File "/home/runner/work/batou/batou/src/batou/component.py", line 320, in deploy
sub_component.deploy(predict_only)
File "/home/runner/work/batou/batou/src/batou/component.py", line 339, in deploy
self.update()
File "/home/runner/work/batou/batou/src/batou/lib/buildout.py", line 80, in update
self.cmd('bin/buildout -t {} -c "{}"'.format(
File "/home/runner/work/batou/batou/src/batou/component.py", line 776, in cmd
return batou.utils.cmd(cmd, silent, ignore_returncode, communicate,
File "/home/runner/work/batou/batou/src/batou/utils.py", line 384, in cmd
raise CmdExecutionError(cmd, process.returncode, stdout, stderr)
batou.utils.CmdExecutionError: The deployment encountered an error.
----------------------------- Captured stdout call -----------------------------
host > MyComponent > Buildout > File('work/mycomponent/buildout3.cfg') > Presence('buildout3.cfg')
host > MyComponent > Buildout > File('work/mycomponent/buildout3.cfg') > Content('buildout3.cfg')
buildout3.cfg ---
buildout3.cfg +++
buildout3.cfg @@ -0,0 +1,14 @@
buildout3.cfg +[buildout]
buildout3.cfg +parts = app
buildout3.cfg +versions = versions
buildout3.cfg +allow-picked-versions = false
buildout3.cfg +
buildout3.cfg +[app]
buildout3.cfg +recipe = zc.recipe.egg
buildout3.cfg +eggs = zc.buildout
buildout3.cfg +interpreter = py
buildout3.cfg +
buildout3.cfg +[versions]
buildout3.cfg +setuptools = 54.1.1
buildout3.cfg +zc.buildout = 3.0.0b1
buildout3.cfg +zc.recipe.egg = 2.0.7
host > MyComponent > Buildout > VirtualEnv('3') > VirtualEnvPy
host > MyComponent > Buildout > VirtualEnv('3') > Package('setuptools==54.1.1')
host > MyComponent > Buildout > VirtualEnv('3') > Package('wheel==0.36.2')
host > MyComponent > Buildout > VirtualEnv('3') > Package('zc.buildout==3.0.0b1')
host > MyComponent > Buildout
ERROR: bin/buildout -t 3 -c "buildout3.cfg"
Return code: 1
STDOUT
Setting socket time out to 3 seconds.
Creating directory '/tmp/pytest-of-runner/pytest-0/test_runs_buildout3_successful0/work/mycomponent/eggs'.
Creating directory '/tmp/pytest-of-runner/pytest-0/test_runs_buildout3_successful0/work/mycomponent/parts'.
Creating directory '/tmp/pytest-of-runner/pytest-0/test_runs_buildout3_successful0/work/mycomponent/develop-eggs'.
Getting distribution for 'zc.recipe.egg==2.0.7'.
An error occurred when trying to install /tmp/tmp6fj07r2tget_dist/zc.recipe.egg-2.0.7.tar.gz. Look above this message for any errors that were output by pip install.
STDERR
Traceback (most recent call last):
File "<string>", line 1, in <module>
ImportError: cannot import name '_main' from 'pip.__main__' (/tmp/pytest-of-runner/pytest-0/test_runs_buildout3_successful0/work/mycomponent/lib/python3.8/site-packages/pip/__main__.py)
--------- generated xml file: /home/runner/work/batou/batou/report.xml ---------
---------- coverage: platform linux, python 3.8.10-final-0 -----------
Coverage HTML written to dir htmlcov
=========================== short test summary info ============================
FAILED src/batou/lib/tests/test_buildout.py::test_runs_buildout3_successfully
============= 1 failed, 361 passed, 2 skipped in 218.95s (0:03:38) =============
ERROR: InvocationError for command /home/runner/work/batou/batou/.tox/py38/bin/pytest src/batou (exited with code 1)
py39 create: /home/runner/work/batou/batou/.tox/py39
SKIPPED: InterpreterNotFound: python3.9
pre-commit create: /home/runner/work/batou/batou/.tox/pre-commit
SKIPPED: InterpreterNotFound: python3.9
___________________________________ summary ____________________________________
SKIPPED: py36: InterpreterNotFound: python3.6
SKIPPED: py37: InterpreterNotFound: python3.7
ERROR: py38: commands failed
SKIPPED: py39: InterpreterNotFound: python3.9
SKIPPED: pre-commit: InterpreterNotFound: python3.9
Error: Process completed with exit code 1.
```
Sounds like `pip`s broken: https://stackoverflow.com/questions/49836676
|
0.0
|
9577420ebf1d3dc7d31c611ff4e1d15b54b4fb7a
|
[
"src/batou/lib/tests/test_buildout.py::test_runs_buildout3_successfully"
] |
[
"src/batou/lib/tests/test_buildout.py::test_update_should_pass_config_file_name",
"src/batou/lib/tests/test_buildout.py::test_update_should_pass_custom_timeout"
] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_git_commit_hash",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-12-09 10:13:44+00:00
|
bsd-3-clause
| 2,358 |
|
flyingcircusio__batou-421
|
diff --git a/.readthedocs.yaml b/.readthedocs.yaml
index 5fb909f8..aae9ffef 100644
--- a/.readthedocs.yaml
+++ b/.readthedocs.yaml
@@ -16,7 +16,7 @@ build:
# Build documentation in the "docs/" directory with Sphinx
sphinx:
- configuration: docs/sourcse/conf.py
+ configuration: doc/source/conf.py
# You can configure Sphinx to use a different builder, for instance use the dirhtml builder for simpler URLs
# builder: "dirhtml"
# Fail on all warnings to avoid broken references
diff --git a/src/batou/main.py b/src/batou/main.py
index 2b8c7449..f1066e98 100644
--- a/src/batou/main.py
+++ b/src/batou/main.py
@@ -166,6 +166,18 @@ def main(args: Optional[list] = None) -> None:
)
p.set_defaults(func=batou.secrets.manage.remove_user)
+ p = sp.add_parser(
+ "reencrypt",
+ help="Re-encrypt all secret files with the current members.",
+ )
+ p.set_defaults(func=p.print_usage)
+ p.add_argument(
+ "--environments",
+ default="",
+ help="The environments to update. Update all if not specified.",
+ )
+ p.set_defaults(func=batou.secrets.manage.reencrypt)
+
# migrate
migrate = subparsers.add_parser(
"migrate",
diff --git a/src/batou/secrets/__init__.py b/src/batou/secrets/__init__.py
index 1f745832..bc5ffae5 100644
--- a/src/batou/secrets/__init__.py
+++ b/src/batou/secrets/__init__.py
@@ -372,7 +372,7 @@ class ConfigFileSecretProvider(SecretProvider):
raise NotImplementedError("_get_file() not implemented.")
def write_file(self, file: EncryptedFile, content: bytes):
- recipients = self._get_recipients()
+ recipients = self._get_recipients_for_encryption()
if not recipients:
raise ValueError(
"No recipients found for environment. "
@@ -385,6 +385,14 @@ class ConfigFileSecretProvider(SecretProvider):
with self.config_file:
self.write_config(content)
+ def _get_recipients(self) -> List[str]:
+ recipients = self.config.get("batou", "members")
+ if recipients.value is None:
+ return []
+ recipients = re.split(r"(\n|,)+", recipients.value)
+ recipients = [r.strip() for r in recipients if r.strip()]
+ return recipients
+
class GPGSecretProvider(ConfigFileSecretProvider):
def __init__(self, environment: "Environment"):
@@ -421,13 +429,8 @@ class GPGSecretProvider(ConfigFileSecretProvider):
writeable,
)
- def _get_recipients(self) -> List[str]:
- recipients = self.config.get("batou", "members")
- if recipients.value is None:
- return []
- recipients = re.split(r"(\n|,)+", recipients.value)
- recipients = [r.strip() for r in recipients if r.strip()]
- return recipients
+ def _get_recipients_for_encryption(self) -> List[str]:
+ return self._get_recipients()
def write_config(self, content: bytes):
config = ConfigUpdater().read_string(content.decode("utf-8"))
@@ -562,12 +565,8 @@ class AGESecretProvider(ConfigFileSecretProvider):
writeable,
)
- def _get_recipients(self) -> List[str]:
- recipients = self.config.get("batou", "members")
- if recipients.value is None:
- return []
- recipients = re.split(r"(\n|,)+", recipients.value)
- recipients = [r.strip() for r in recipients if r.strip()]
+ def _get_recipients_for_encryption(self) -> List[str]:
+ recipients = self._get_recipients()
return process_age_recipients(
recipients,
pathlib.Path(self.environment.base_dir)
diff --git a/src/batou/secrets/manage.py b/src/batou/secrets/manage.py
index e5300f91..f518126b 100644
--- a/src/batou/secrets/manage.py
+++ b/src/batou/secrets/manage.py
@@ -3,7 +3,7 @@ import sys
from configupdater import ConfigUpdater
from batou import AgeCallError, GPGCallError
-from batou.environment import Environment
+from batou.environment import Environment, UnknownEnvironmentError
def summary():
@@ -44,10 +44,6 @@ def add_user(keyid, environments, **kw):
environment.secret_provider.write_config(
str(config).encode("utf-8")
)
- if not environments_:
- raise UnknownEnvironmentError(
- [e.strip() for e in environments.split(",")]
- )
def remove_user(keyid, environments, **kw):
@@ -69,7 +65,19 @@ def remove_user(keyid, environments, **kw):
environment.secret_provider.write_config(
str(config).encode("utf-8")
)
- if not environments:
- raise UnknownEnvironmentError(
- [e.strip() for e in environments.split(",")]
- )
+
+
+def reencrypt(environments, **kw):
+ """Re-encrypt all secrets in given environments.
+
+ If environments is not given, all secrets are re-encrypted.
+
+ """
+ environments_ = Environment.filter(environments)
+ for environment in environments_:
+ environment.load_secrets()
+ with environment.secret_provider.edit():
+ config = environment.secret_provider.config
+ environment.secret_provider.write_config(
+ str(config).encode("utf-8")
+ )
|
flyingcircusio/batou
|
e6dabac30733f5a90205b9eb994e34aab21493a0
|
diff --git a/src/batou/secrets/tests/test_manage.py b/src/batou/secrets/tests/test_manage.py
index ca9f3c73..5257b645 100644
--- a/src/batou/secrets/tests/test_manage.py
+++ b/src/batou/secrets/tests/test_manage.py
@@ -1,12 +1,14 @@
+import glob
import os
import shutil
+import sys
import textwrap
import pytest
from batou.environment import UnknownEnvironmentError
-from ..manage import add_user, remove_user, summary
+from ..manage import add_user, reencrypt, remove_user, summary
@pytest.mark.parametrize("func", (add_user, remove_user))
@@ -38,6 +40,32 @@ def test_manage__2(tmp_path, monkeypatch, capsys):
assert "306151601E813A47" in out
[email protected](
+ sys.version_info < (3, 7),
+ reason="age is available in tests with python 3.7 only",
+)
+def test_manage__2_age(tmp_path, monkeypatch, capsys):
+ """It allows to add/remove_users in an age encrypted environment."""
+ shutil.copytree("examples/tutorial-secrets", tmp_path / "tutorial-secrets")
+ monkeypatch.chdir(tmp_path / "tutorial-secrets")
+
+ key_name = "https://github.com/ctheune.keys"
+
+ summary()
+ out, err = capsys.readouterr()
+ assert key_name in out
+
+ remove_user(key_name, "age")
+ summary()
+ out, err = capsys.readouterr()
+ assert key_name not in out
+
+ add_user(key_name, "age")
+ summary()
+ out, err = capsys.readouterr()
+ assert key_name in out
+
+
def test_manage__summary__1(capsys, monkeypatch):
"""It prints a summary of the environments, members and secret files."""
monkeypatch.chdir("examples/errors")
@@ -77,3 +105,34 @@ def test_manage__summary__3(capsys, monkeypatch):
expected = "secretserror\n\t members"
assert expected in out
assert err == ""
+
+
[email protected](
+ sys.version_info < (3, 7),
+ reason="age is available in tests with python 3.7 only",
+)
+def test_manage__reencrypt__1(tmp_path, monkeypatch, capsys):
+ """It re-encrypts all files with the current members."""
+ shutil.copytree("examples/tutorial-secrets", tmp_path / "tutorial-secrets")
+
+ monkeypatch.chdir(tmp_path / "tutorial-secrets")
+
+ # read files environments/*/secret*
+ # and make sure all of them change
+ # when we re-encrypt
+
+ old = {}
+ for path in glob.glob("environments/*/secret*"):
+ with open(path, "rb") as f:
+ old[path] = f.read()
+
+ reencrypt("") # empty string means all environments
+ new = {}
+ for path in glob.glob("environments/*/secret*"):
+ with open(path, "rb") as f:
+ new[path] = f.read()
+
+ for path in old:
+ assert old[path] != new[path]
+
+ assert set(old) == set(new)
|
age-based encryption - need general command to update/reencrypt all secrets in all environments
Adding a new person requires to re-encrypt the files. AFAIK currently one has to edit (and change!) all environments to fetch updates for the keys end reencrypt and do that manually for all environments.
I think we need something like a `secrets update` command.
Also, there seems to be a bug with the existing add/remove commands (which are gpg-specific) and the "environments" parameter seems broken.
|
0.0
|
e6dabac30733f5a90205b9eb994e34aab21493a0
|
[
"src/batou/secrets/tests/test_manage.py::test_manage__1[add_user]",
"src/batou/secrets/tests/test_manage.py::test_manage__1[remove_user]",
"src/batou/secrets/tests/test_manage.py::test_manage__summary__2"
] |
[] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2023-12-19 01:31:24+00:00
|
bsd-3-clause
| 2,359 |
|
flyingcircusio__batou-427
|
diff --git a/src/batou/lib/file.py b/src/batou/lib/file.py
index 329a7038..980e3c59 100644
--- a/src/batou/lib/file.py
+++ b/src/batou/lib/file.py
@@ -244,13 +244,22 @@ class Directory(Component):
source = None
exclude = ()
+ verify_opts = None
+ sync_opts = None
+
def configure(self):
self.path = self.map(self.path)
if self.source:
# XXX The ordering is wrong. SyncDirectory should run *after*.
- self += SyncDirectory(
- self.path, source=self.source, exclude=self.exclude
- )
+ args = {
+ "source": self.source,
+ "exclude": self.exclude,
+ }
+ if self.verify_opts:
+ args["verify_opts"] = self.verify_opts
+ if self.sync_opts:
+ args["sync_opts"] = self.sync_opts
+ self += SyncDirectory(self.path, **args)
def verify(self):
assert os.path.isdir(self.path)
|
flyingcircusio/batou
|
396bfa71ff6d15a63f884a130cdf35b28d9c0416
|
diff --git a/src/batou/lib/tests/test_file.py b/src/batou/lib/tests/test_file.py
index 9d35bd15..841611b6 100644
--- a/src/batou/lib/tests/test_file.py
+++ b/src/batou/lib/tests/test_file.py
@@ -1153,3 +1153,14 @@ def test_syncdirectory_needs_update_on_nonexisting_target(root):
with pytest.raises(batou.UpdateNeeded):
sd = SyncDirectory("non_existing_dir", source="existing_dir")
sd.verify()
+
+
+def test_directory_passes_args_to_syncdirectory(root):
+ d = Directory(
+ "target", source="source", verify_opts="-abc", sync_opts="-xyz"
+ )
+ d.prepare(root.component)
+ sd = d._
+ assert isinstance(sd, SyncDirectory)
+ assert sd.verify_opts == "-abc"
+ assert sd.sync_opts == "-xyz"
|
batou.lib.file.Directory: Allow to explicitly overwrite target directory
`batou.lib.file.Directory` should get a flag to either append or overwrite (-> rsync --delete) the contents of a target directory based on given source folder.
Usecase:
When syncing sourcecode via something like
```
self += Directory(
"docroot",
source=os.path.join(self.root.defdir, "..", "..", "docroot"),
exclude=["/docroot/wp-config.php", "/docroot/.htaccess"],
)
```
it might happen that deleted files are not gone after. On the other hand making deletion a default would be dangerous
|
0.0
|
396bfa71ff6d15a63f884a130cdf35b28d9c0416
|
[
"src/batou/lib/tests/test_file.py::test_directory_passes_args_to_syncdirectory"
] |
[
"src/batou/lib/tests/test_file.py::test_ensure_path_nonexistent_removes_normal_file",
"src/batou/lib/tests/test_file.py::test_ensure_path_nonexistent_removes_normal_symlink",
"src/batou/lib/tests/test_file.py::test_ensure_path_nonexistent_removes_broken_symlink",
"src/batou/lib/tests/test_file.py::test_ensure_path_nonexistent_removes_directory",
"src/batou/lib/tests/test_file.py::test_ensure_path_does_not_fail_on_nonexisting_path",
"src/batou/lib/tests/test_file.py::test_presence_creates_nonexisting_file",
"src/batou/lib/tests/test_file.py::test_presence_leaves_existing_file_with_content_intact",
"src/batou/lib/tests/test_file.py::test_presence_creates_directories_if_configured",
"src/batou/lib/tests/test_file.py::test_presence_doesnt_create_directories_by_default",
"src/batou/lib/tests/test_file.py::test_presence_removes_conflicting_symlinks",
"src/batou/lib/tests/test_file.py::test_presence_removes_conflicting_directories",
"src/batou/lib/tests/test_file.py::test_directory_creates_directory",
"src/batou/lib/tests/test_file.py::test_directory_creates_leading_directories_if_configured",
"src/batou/lib/tests/test_file.py::test_directory_doesnt_create_leading_directories_by_default",
"src/batou/lib/tests/test_file.py::test_filecomponent_baseclass_carries_path",
"src/batou/lib/tests/test_file.py::test_content_passed_by_string",
"src/batou/lib/tests/test_file.py::test_content_passed_by_string_template",
"src/batou/lib/tests/test_file.py::test_content_with_unicode_requires_encoding",
"src/batou/lib/tests/test_file.py::test_content_passed_by_string_notemplate",
"src/batou/lib/tests/test_file.py::test_content_passed_by_file",
"src/batou/lib/tests/test_file.py::test_content_passed_by_file_handles_encoding",
"src/batou/lib/tests/test_file.py::test_content_passed_by_file_handles_encoding_on_verify",
"src/batou/lib/tests/test_file.py::test_content_passed_by_file_defaults_to_utf8",
"src/batou/lib/tests/test_file.py::test_content_passed_by_file_template",
"src/batou/lib/tests/test_file.py::test_content_passed_by_file_template_handles_encoding",
"src/batou/lib/tests/test_file.py::test_content_passed_by_file_template_defaults_to_utf8",
"src/batou/lib/tests/test_file.py::test_content_passed_by_file_no_template_is_binary",
"src/batou/lib/tests/test_file.py::test_binary_file_component",
"src/batou/lib/tests/test_file.py::test_content_from_file_as_template_guessed",
"src/batou/lib/tests/test_file.py::test_content_source_unclear",
"src/batou/lib/tests/test_file.py::test_content_passed_by_file_using_path_as_default",
"src/batou/lib/tests/test_file.py::test_content_template_with_explicit_context",
"src/batou/lib/tests/test_file.py::test_content_relative_source_path_computed_wrt_definition_dir",
"src/batou/lib/tests/test_file.py::test_content_only_required_changes_touch_file",
"src/batou/lib/tests/test_file.py::test_content_does_not_allow_both_content_and_source",
"src/batou/lib/tests/test_file.py::test_content_large_diff_logged",
"src/batou/lib/tests/test_file.py::test_json_content_data_given",
"src/batou/lib/tests/test_file.py::test_json_diff",
"src/batou/lib/tests/test_file.py::test_json_diff_not_for_sensitive",
"src/batou/lib/tests/test_file.py::test_json_content_data_given_compact",
"src/batou/lib/tests/test_file.py::test_json_content_source_given",
"src/batou/lib/tests/test_file.py::test_json_content_delayed_source_given",
"src/batou/lib/tests/test_file.py::test_json_content_delayed_source_causes_predicting_verify_to_raise",
"src/batou/lib/tests/test_file.py::test_json_content_source_with_override",
"src/batou/lib/tests/test_file.py::test_json_content_source_missing",
"src/batou/lib/tests/test_file.py::test_json_content_either_source_or_data",
"src/batou/lib/tests/test_file.py::test_json_content_implicit_source",
"src/batou/lib/tests/test_file.py::test_json_content_explicit_source",
"src/batou/lib/tests/test_file.py::test_json_content_explicit_absolute_source",
"src/batou/lib/tests/test_file.py::test_yaml_content_data_given",
"src/batou/lib/tests/test_file.py::test_yaml_diff",
"src/batou/lib/tests/test_file.py::test_yaml_diff_not_for_sensitive",
"src/batou/lib/tests/test_file.py::test_yaml_content_source_given",
"src/batou/lib/tests/test_file.py::test_yaml_content_delayed_source_given",
"src/batou/lib/tests/test_file.py::test_yaml_content_delayed_source_causes_predicting_verify_to_raise",
"src/batou/lib/tests/test_file.py::test_yaml_content_source_with_override",
"src/batou/lib/tests/test_file.py::test_yaml_content_source_missing",
"src/batou/lib/tests/test_file.py::test_yaml_content_either_source_or_data",
"src/batou/lib/tests/test_file.py::test_yaml_content_implicit_source",
"src/batou/lib/tests/test_file.py::test_yaml_content_explicit_source",
"src/batou/lib/tests/test_file.py::test_yaml_content_explicit_absolute_source",
"src/batou/lib/tests/test_file.py::test_mode_verifies_for_nonexistent_file",
"src/batou/lib/tests/test_file.py::test_mode_ensures_mode_for_files[511-511]",
"src/batou/lib/tests/test_file.py::test_mode_converts_to_numeric",
"src/batou/lib/tests/test_file.py::test_mode_ensures_mode_for_directories",
"src/batou/lib/tests/test_file.py::test_mode_does_not_break_on_platforms_without_lchmod",
"src/batou/lib/tests/test_file.py::test_symlink_creates_new_link",
"src/batou/lib/tests/test_file.py::test_symlink_updates_existing_link",
"src/batou/lib/tests/test_file.py::test_file_creates_subcomponent_for_presence",
"src/batou/lib/tests/test_file.py::test_file_creates_subcomponent_for_directory",
"src/batou/lib/tests/test_file.py::test_file_creates_subcomponent_for_symlink",
"src/batou/lib/tests/test_file.py::test_file_prohibits_unknown_ensure_parameter",
"src/batou/lib/tests/test_file.py::test_owner_lazy",
"src/batou/lib/tests/test_file.py::test_owner_is_configurable_when_user_doesnt_exist_yet",
"src/batou/lib/tests/test_file.py::test_group_lazy",
"src/batou/lib/tests/test_file.py::test_group_is_configurable_when_group_doesnt_exist_yet",
"src/batou/lib/tests/test_file.py::test_purge_globs_and_deletes_tree",
"src/batou/lib/tests/test_file.py::test_purge_globs_and_deletes_files",
"src/batou/lib/tests/test_file.py::test_syncdirectory_needs_update_on_nonexisting_target"
] |
{
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
}
|
2023-12-20 11:24:11+00:00
|
bsd-3-clause
| 2,360 |
|
flyingcircusio__batou-430
|
diff --git a/requirements-dev.txt b/requirements-dev.txt
index 9869218e..7263cd44 100644
--- a/requirements-dev.txt
+++ b/requirements-dev.txt
@@ -15,5 +15,5 @@ six==1.15.0
toml==0.10.2
tox==3.20.1
virtualenv==20.1.0
-sphinx==4.0.2
+sphinx==4.2.0
recommonmark==0.7.1
diff --git a/src/batou/repository.py b/src/batou/repository.py
index a8761418..2467cd11 100644
--- a/src/batou/repository.py
+++ b/src/batou/repository.py
@@ -395,14 +395,21 @@ class GitBundleRepository(GitRepository):
)
fd, bundle_file = tempfile.mkstemp()
os.close(fd)
- out, err = cmd(
- "git bundle create {file} {range}".format(
- file=bundle_file, range=bundle_range
- ),
- acceptable_returncodes=[0, 128],
- )
- if "create empty bundle" in err:
- return
+ try:
+ out, err = cmd(
+ "git bundle create {file} {range}".format(
+ file=bundle_file, range=bundle_range
+ ),
+ acceptable_returncodes=[0],
+ )
+ except CmdExecutionError as e:
+ if (
+ e.returncode == 128
+ and "fatal: Refusing to create empty bundle." in e.stderr
+ ):
+ return
+ raise
+
change_size = os.stat(bundle_file).st_size
if change_size == 0:
output.error("Created invalid bundle (0 bytes):")
|
flyingcircusio/batou
|
10caa6564689d6329988cb4ac5c53d0f998b2623
|
diff --git a/src/batou/tests/test_remote.py b/src/batou/tests/test_remote.py
index d03317d8..0274826b 100644
--- a/src/batou/tests/test_remote.py
+++ b/src/batou/tests/test_remote.py
@@ -1,10 +1,12 @@
+import os
+
import mock
import pytest
from batou.deploy import Deployment
from batou.environment import Environment
from batou.host import RemoteHost
-from batou.utils import cmd
+from batou.utils import CmdExecutionError, cmd
@pytest.mark.slow
@@ -36,6 +38,30 @@ def test_remote_bundle_breaks_on_missing_head(sample_service):
)
+def test_git_remote_bundle_fails_if_needed(tmp_path):
+ env = mock.Mock()
+ env.base_dir = tmp_path
+ env.branch = "master"
+ host = mock.Mock()
+ host.rpc.git_current_head.return_value.decode.return_value = "HEAD"
+ from batou.repository import GitBundleRepository
+
+ os.chdir(tmp_path)
+ cmd("git init")
+ cmd("touch foo")
+ cmd("git add foo")
+ cmd("git commit -m 'initial commit'")
+ repository = GitBundleRepository(env)
+ assert repository._ship(host) is None
+
+ # now destroy the repository state
+ head_commit = cmd("git rev-parse HEAD")[0].strip()
+ cmd(f"rm -rf .git/objects/{head_commit[:2]}/{head_commit[2:]}")
+ with pytest.raises(CmdExecutionError) as e:
+ repository._ship(host)
+ assert "Invalid revision range" in str(e.value)
+
+
def test_remotehost_start(sample_service):
env = Environment("test-with-env-config")
env.load()
|
Better reporting of invalid revision range when using git-bundle
```
('fatal: Refusing to create empty bundle.\n', 'host00')
('fatal: Refusing to create empty bundle.\n', 'host33')
('fatal: Refusing to create empty bundle.\n', 'host21')
('fatal: Refusing to create empty bundle.\n', 'host03')
('fatal: Refusing to create empty bundle.\n', 'host01')
('fatal: Refusing to create empty bundle.\n', 'host46')
('fatal: Refusing to create empty bundle.\n', 'host47')
('fatal: Invalid revision range 7b7aeb0c5d0ef8480d60469205c39bb4ecc5d2fb..testing\n', 'clxstagc60')
('fatal: Refusing to create empty bundle.\n', 'host61')
ERROR: git fetch batou-bundle
Return code: 128
STDOUT
STDERR
fatal: invalid gitfile format: batou-bundle.git
fatal: Could not read from remote repository.
Please make sure you have the correct access rights
and the repository exists.
============================================================================================== Waiting for remaining connections ... ==============================================================================================
ERROR: Unexpected exception
Traceback (most recent call last):
File ".appenv/80112659/lib/python3.8/site-packages/batou/deploy.py", line 252, in main
getattr(deployment, step)()
File ".appenv/80112659/lib/python3.8/site-packages/batou/deploy.py", line 182, in deploy
[c.join() for c in self.connections]
File ".appenv/80112659/lib/python3.8/site-packages/batou/deploy.py", line 182, in <listcomp>
[c.join() for c in self.connections]
File ".appenv/80112659/lib/python3.8/site-packages/batou/deploy.py", line 50, in join
raise exc_value.with_traceback(exc_tb)
File ".appenv/80112659/lib/python3.8/site-packages/batou/deploy.py", line 42, in run
self.host.start()
File ".appenv/80112659/lib/python3.8/site-packages/batou/host.py", line 287, in start
env.repository.update(self)
File ".appenv/80112659/lib/python3.8/site-packages/batou/repository.py", line 246, in update
self._ship(host)
File ".appenv/80112659/lib/python3.8/site-packages/batou/repository.py", line 332, in _ship
host.rpc.git_unbundle_code()
File ".appenv/80112659/lib/python3.8/site-packages/batou/host.py", line 99, in call
raise RuntimeError(
RuntimeError: host.fcio.net: Remote exception encountered.
================================================================================================ DEPLOYMENT FAILED (during deploy) ================================================================================================
```
|
0.0
|
10caa6564689d6329988cb4ac5c53d0f998b2623
|
[
"src/batou/tests/test_remote.py::test_git_remote_bundle_fails_if_needed"
] |
[
"src/batou/tests/test_remote.py::test_remote_deployment_initializable",
"src/batou/tests/test_remote.py::test_remote_bundle_breaks_on_missing_head",
"src/batou/tests/test_remote.py::test_remotehost_start"
] |
{
"failed_lite_validators": [
"has_git_commit_hash",
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2023-12-21 00:10:49+00:00
|
bsd-3-clause
| 2,361 |
|
fmi-faim__faim-wako-searchfirst-5
|
diff --git a/README.md b/README.md
index 4afc3c9..2223146 100644
--- a/README.md
+++ b/README.md
@@ -37,7 +37,14 @@ segmentation:
threshold: 128
include_holes: yes
min_size: 10
+ max_size: 99999999999
+ min_eccentricity: 0.0
max_eccentricity: 0.4
+bounding_box:
+ min_x: 0
+ min_y: 0
+ max_x: 256
+ max_y: 256
additional_analysis:
enabled: yes
target_channel: C03
diff --git a/config.yml b/config.yml
index 2dad472..5f94267 100644
--- a/config.yml
+++ b/config.yml
@@ -11,6 +11,11 @@ segmentation:
max_size: 99999999999
min_eccentricity: 0.0
max_eccentricity: 0.4
+bounding_box:
+ min_x: 0
+ min_y: 0
+ max_x: 256
+ max_y: 256
additional_analysis:
enabled: yes
target_channel: C03
diff --git a/src/faim_wako_searchfirst/segment.py b/src/faim_wako_searchfirst/segment.py
index 1d979b3..abee273 100644
--- a/src/faim_wako_searchfirst/segment.py
+++ b/src/faim_wako_searchfirst/segment.py
@@ -49,6 +49,7 @@ def run(folder: Union[str, Path], configfile: str):
folder_path,
file_selection_params=config["file_selection"].get(),
segmentation_params=config["segmentation"].get(),
+ bounding_box_params=config["bounding_box"].get(),
additional_analysis_params=config["additional_analysis"].get(),
output_params=config["output"].get(),
grid_sampling_params=config["grid_sampling"].get(),
@@ -179,10 +180,20 @@ def save_segmentation_image(folder_path, filename, img, labels):
imsave(destination_folder / (Path(filename).stem + '.png'), preview)
+def apply_bounding_box(labels, min_x: int, min_y: int, max_x: int, max_y: int):
+ """Set everything outside the bounding box to zero."""
+ labels[0:max(min_y, 0), :] = 0
+ labels[:, 0:max(min_x, 0)] = 0
+ y, x = labels.shape
+ labels[min(max_y, y):y, :] = 0
+ labels[:, min(max_x, x):x] = 0
+
+
def process(
folder: Path,
file_selection_params: dict,
segmentation_params: dict,
+ bounding_box_params: dict,
additional_analysis_params: dict,
output_params: dict,
grid_sampling_params: dict,
@@ -202,6 +213,9 @@ def process(
# file -> segmentation mask and image
img, labels = segment_file(tif_file, segment, **segmentation_params)
+ # mask everything outside bounding box
+ apply_bounding_box(labels, **bounding_box_params)
+
# addition analysis (e.g. filter by intensity in other channel)
labels = additional_analysis(
tif_file, labels, filter_objects_by_intensity,
|
fmi-faim/faim-wako-searchfirst
|
c1edc95624a7b3d9ca4780e7ebc510aaf016a553
|
diff --git a/tests/test_segment.py b/tests/test_segment.py
index 1d5b225..11a19aa 100644
--- a/tests/test_segment.py
+++ b/tests/test_segment.py
@@ -66,6 +66,12 @@ def test_process_test_set(_data_path):
"min_eccentricity": 0.0,
"max_eccentricity": 0.9,
}
+ bounding_box_params = {
+ "min_x": 0,
+ "min_y": 0,
+ "max_x": 256,
+ "max_y": 256,
+ }
additional_analysis_params = {
"enabled": False,
}
@@ -76,11 +82,12 @@ def test_process_test_set(_data_path):
process(
_data_path,
- file_selection_params,
- segmentation_params,
- additional_analysis_params,
- output_params,
- grid_sampling_params,
+ file_selection_params=file_selection_params,
+ segmentation_params=segmentation_params,
+ bounding_box_params=bounding_box_params,
+ additional_analysis_params=additional_analysis_params,
+ output_params=output_params,
+ grid_sampling_params=grid_sampling_params,
)
csv_path = _data_path / "TestSet_D07_T0001F002L01A02Z01C01.csv"
@@ -119,6 +126,12 @@ def test_process_invalid_second_channel(_data_path):
"min_eccentricity": 0.0,
"max_eccentricity": 0.9,
}
+ bounding_box_params = {
+ "min_x": 0,
+ "min_y": 0,
+ "max_x": 256,
+ "max_y": 256,
+ }
additional_analysis_params = {
"enabled": True,
"target_channel": "C04",
@@ -129,9 +142,60 @@ def test_process_invalid_second_channel(_data_path):
with pytest.raises(FileNotFoundError):
process(
_data_path,
- file_selection_params,
- segmentation_params,
- additional_analysis_params,
- output_params,
- grid_sampling_params,
+ file_selection_params=file_selection_params,
+ segmentation_params=segmentation_params,
+ bounding_box_params=bounding_box_params,
+ additional_analysis_params=additional_analysis_params,
+ output_params=output_params,
+ grid_sampling_params=grid_sampling_params,
)
+
+
+def test_process_bounding_box(_data_path):
+ """Test bounding box for segmentation."""
+ file_selection_params = {
+ "channel": "C01",
+ }
+ segmentation_params = {
+ "threshold": 1,
+ "include_holes": False,
+ "min_size": 10,
+ "max_size": 9999999,
+ "min_eccentricity": 0.0,
+ "max_eccentricity": 0.9,
+ }
+ bounding_box_params = {
+ "min_x": 180,
+ "min_y": 30,
+ "max_x": 1000000,
+ "max_y": 110,
+ }
+ additional_analysis_params = {
+ "enabled": False,
+ }
+ output_params = {
+ "type": "centers",
+ }
+ grid_sampling_params = {}
+
+ process(
+ _data_path,
+ file_selection_params=file_selection_params,
+ segmentation_params=segmentation_params,
+ bounding_box_params=bounding_box_params,
+ additional_analysis_params=additional_analysis_params,
+ output_params=output_params,
+ grid_sampling_params=grid_sampling_params,
+ )
+
+ csv_path = _data_path / "TestSet_D07_T0001F002L01A02Z01C01.csv"
+ assert csv_path.exists()
+
+ with open(csv_path, 'r') as csv_file:
+ reader = csv.reader(csv_file)
+ entries = list(reader)
+ assert len(entries) == 1, "Incorrect number of objects detected."
+ assert entries[0] == ['2', '209.6689930209372', '67.93419740777667']
+
+ segmentation_folder = _data_path.parent / (_data_path.name + "_segmentation")
+ assert sum(1 for _ in segmentation_folder.glob("*")) == 1
|
Allow specifying bounding box for segmentation
Similar to these parameters in previous ImageJ macros:
```java
// Define box in which for objects should be searched
bBx = 30; //x size of FOV is 2560 (for CV7000), 2000 (for CV8000)
bBy = 30; //y size of the FOV is 2160 (for CV7000), 2000 (for CV8000)
width = 2500;
height = 2100;
```
... we should implement these config parameters:
```yaml
bounding-box:
- min_x: 0
- min_y: 0
- max_x: 2000
- max_y: 2000
```
|
0.0
|
c1edc95624a7b3d9ca4780e7ebc510aaf016a553
|
[
"tests/test_segment.py::test_process_invalid_second_channel"
] |
[
"tests/test_segment.py::test_run_invalid_folder"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2023-03-08 12:00:32+00:00
|
mit
| 2,362 |
|
fniessink__access-modifiers-11
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index af2c6e6..00866cc 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,12 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.
<!-- The line "## <square-bracket>Unreleased</square-bracket>" is replaced by the ci/release.py script with the new release version and release date. -->
+## [Unreleased]
+
+### Fixed
+
+- A public method calling a private method calling another private method would raise an AccessException. Fixes [#10](https://github.com/fniessink/access-modifiers/issues/10).
+
## [0.2.0] - [2019-08-26]
### Added
diff --git a/access_modifiers/access_modifiers.py b/access_modifiers/access_modifiers.py
index 18d76bc..77ec865 100644
--- a/access_modifiers/access_modifiers.py
+++ b/access_modifiers/access_modifiers.py
@@ -26,11 +26,13 @@ def privatemethod(method: Callable[..., ReturnType]) -> Callable[..., ReturnType
caller_frame = caller_frame.f_back
caller_code = caller_frame.f_code
caller_name = caller_code.co_name
- caller_instance = caller_frame.f_locals.get("self")
- # Look up the calling method to see if it's defined in the same class as the private method
- for caller_class in caller_instance.__class__.mro():
- caller = caller_class.__dict__.get(caller_name)
- if caller and caller.__code__ == caller_code and method_class_qualname == caller_class.__qualname__:
+ caller_class = caller_frame.f_locals.get("self").__class__
+ # Look up the caller method to see if it's defined in the same class as the wrapped method
+ classes = [cls for cls in caller_class.mro() if caller_name in cls.__dict__]
+ for cls in classes:
+ caller = cls.__dict__[caller_name]
+ caller = caller.__dict__["__wrapped__"] if "__wrapped__" in caller.__dict__ else caller
+ if caller.__code__ == caller_code and method_class_qualname == cls.__qualname__:
return method(*args, **kwargs)
raise AccessException(f"Attempted call to private method {method} from outside its class")
return private_method_wrapper
|
fniessink/access-modifiers
|
cd8142b539ea25a031d59ccfd039218a848cd72e
|
diff --git a/access_modifiers/tests/test_private.py b/access_modifiers/tests/test_private.py
index a3cea7d..97ac772 100644
--- a/access_modifiers/tests/test_private.py
+++ b/access_modifiers/tests/test_private.py
@@ -5,11 +5,52 @@ import unittest
from ..access_modifiers import AccessException, privatemethod, protectedmethod
-class PrivateMethodTestsMixin:
+class PrivateMethodTests(unittest.TestCase):
"""Shared unit tests for the private method and static private method access modifiers."""
# pylint: disable=missing-docstring,too-few-public-methods
+ class Class:
+ @privatemethod
+ def private_method(self): # pylint: disable=no-self-use
+ return "Class.private_method"
+
+ @privatemethod
+ def private_method_calling_private_method(self):
+ return "Class.private_method_calling_private_method -> " + self.private_method()
+
+ def public_method(self):
+ return "Class.public_method -> " + self.private_method()
+
+ def public_method_calling_private_method_via_private_method(self):
+ return "Class.public_method_calling_private_method_via_private_method -> " + \
+ self.private_method_calling_private_method()
+
+ def public_method_using_list_comprehension(self):
+ return ["Class.public_method -> " + self.private_method() for _ in range(1)][0]
+
+ def public_method_using_nested_lambdas(self):
+ # pylint: disable=unnecessary-lambda
+ inner_lambda_function = lambda: self.private_method()
+ outer_lambda_function = lambda: "Class.public_method -> " + inner_lambda_function()
+ return outer_lambda_function()
+
+ def public_method_using_try_except(self):
+ try:
+ return "Class.public_method -> " + self.private_method()
+ except AttributeError: # pragma: nocover
+ pass
+
+ class Subclass(Class):
+ @privatemethod
+ def private_method(self):
+ super().private_method() # pragma: nocover
+
+ class SubclassOverridesWithProtectedMethod(Class):
+ @protectedmethod
+ def private_method(self):
+ return "Subclass.private_method -> " + super().private_method() # pragma: nocover
+
def test_call_private_method_directly(self):
"""Test the accessing a private method throws an exception."""
self.assertRaises(AccessException, self.Class().private_method)
@@ -72,47 +113,15 @@ class PrivateMethodTestsMixin:
self.assertRaises(AccessException, self.Subclass().public_method)
self.assertRaises(AccessException, self.Subclass().private_method)
-
-class PrivateMethodTest(PrivateMethodTestsMixin, unittest.TestCase):
- """Unit tests for the @privatemethod decorator."""
-
- # pylint: disable=missing-docstring
-
- class Class:
- @privatemethod
- def private_method(self): # pylint: disable=no-self-use
- return "Class.private_method"
-
- def public_method(self):
- return "Class.public_method -> " + self.private_method()
-
- def public_method_using_list_comprehension(self):
- return ["Class.public_method -> " + self.private_method() for _ in range(1)][0]
-
- def public_method_using_nested_lambdas(self):
- # pylint: disable=unnecessary-lambda
- inner_lambda_function = lambda: self.private_method()
- outer_lambda_function = lambda: "Class.public_method -> " + inner_lambda_function()
- return outer_lambda_function()
-
- def public_method_using_try_except(self):
- try:
- return "Class.public_method -> " + self.private_method()
- except AttributeError: # pragma: nocover
- pass
-
- class Subclass(Class):
- @privatemethod
- def private_method(self):
- super().private_method() # pragma: nocover
-
- class SubclassOverridesWithProtectedMethod(Class):
- @protectedmethod
- def private_method(self):
- return "Subclass.private_method -> " + super().private_method() # pragma: nocover
+ def test_call_private_method_via_private_method(self):
+ """Test that a private method can be called via another private method."""
+ self.assertEqual(
+ "Class.public_method_calling_private_method_via_private_method -> "
+ "Class.private_method_calling_private_method -> Class.private_method",
+ self.Class().public_method_calling_private_method_via_private_method())
-class StaticPrivateMethodTest(PrivateMethodTestsMixin, unittest.TestCase):
+class StaticPrivateMethodTests(PrivateMethodTests):
"""Unit tests for the combined @staticmethod @privatemethod decorator."""
# pylint: disable=missing-docstring
@@ -123,9 +132,17 @@ class StaticPrivateMethodTest(PrivateMethodTestsMixin, unittest.TestCase):
def private_method():
return "Class.private_method"
+ @privatemethod
+ def private_method_calling_private_method(self):
+ return "Class.private_method_calling_private_method -> " + self.private_method()
+
def public_method(self):
return "Class.public_method -> " + self.private_method()
+ def public_method_calling_private_method_via_private_method(self):
+ return "Class.public_method_calling_private_method_via_private_method -> " + \
+ self.private_method_calling_private_method()
+
def public_method_using_list_comprehension(self):
return ["Class.public_method -> " + self.private_method() for _ in range(1)][0]
|
Calling a private method from a private method from a public method raises AccessException
|
0.0
|
cd8142b539ea25a031d59ccfd039218a848cd72e
|
[
"access_modifiers/tests/test_private.py::PrivateMethodTests::test_call_private_method_via_private_method",
"access_modifiers/tests/test_private.py::StaticPrivateMethodTests::test_call_private_method_via_private_method"
] |
[
"access_modifiers/tests/test_private.py::PrivateMethodTests::test_call_private_method_directly",
"access_modifiers/tests/test_private.py::PrivateMethodTests::test_call_private_method_from_try_except_block",
"access_modifiers/tests/test_private.py::PrivateMethodTests::test_call_private_method_via_list_comprehension",
"access_modifiers/tests/test_private.py::PrivateMethodTests::test_call_private_method_via_nested_lambda",
"access_modifiers/tests/test_private.py::PrivateMethodTests::test_call_private_method_via_public_method",
"access_modifiers/tests/test_private.py::PrivateMethodTests::test_call_private_method_via_public_method_from_subclass",
"access_modifiers/tests/test_private.py::PrivateMethodTests::test_call_private_method_via_public_method_in_subclass",
"access_modifiers/tests/test_private.py::PrivateMethodTests::test_call_private_method_via_public_method_in_subclass_using_super",
"access_modifiers/tests/test_private.py::PrivateMethodTests::test_override_private_method",
"access_modifiers/tests/test_private.py::PrivateMethodTests::test_override_private_method_with_protected_method",
"access_modifiers/tests/test_private.py::StaticPrivateMethodTests::test_call_private_method_directly",
"access_modifiers/tests/test_private.py::StaticPrivateMethodTests::test_call_private_method_from_try_except_block",
"access_modifiers/tests/test_private.py::StaticPrivateMethodTests::test_call_private_method_via_list_comprehension",
"access_modifiers/tests/test_private.py::StaticPrivateMethodTests::test_call_private_method_via_nested_lambda",
"access_modifiers/tests/test_private.py::StaticPrivateMethodTests::test_call_private_method_via_public_method",
"access_modifiers/tests/test_private.py::StaticPrivateMethodTests::test_call_private_method_via_public_method_from_subclass",
"access_modifiers/tests/test_private.py::StaticPrivateMethodTests::test_call_private_method_via_public_method_in_subclass",
"access_modifiers/tests/test_private.py::StaticPrivateMethodTests::test_call_private_method_via_public_method_in_subclass_using_super",
"access_modifiers/tests/test_private.py::StaticPrivateMethodTests::test_override_private_method",
"access_modifiers/tests/test_private.py::StaticPrivateMethodTests::test_override_private_method_with_protected_method"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2019-08-26 21:31:07+00:00
|
apache-2.0
| 2,363 |
|
fniessink__access-modifiers-13
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 0a696ab..2e0ae89 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,12 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.
<!-- The line "## <square-bracket>Unreleased</square-bracket>" is replaced by the ci/release.py script with the new release version and release date. -->
+## [Unreleased]
+
+### Added
+
+- Added `access_modifiers.disable()` to disable access checks, e.g. in production. This method should be called before any access modifier decorators are compiled, so somewhere at the start of your program. Closes [#3](https://github.com/fniessink/access-modifiers/issues/3).
+
## [0.2.1] - [2019-08-26]
### Fixed
diff --git a/README.md b/README.md
index e2b4fd9..f0fc54b 100644
--- a/README.md
+++ b/README.md
@@ -70,6 +70,23 @@ print(c.static_private_method()) # Raises an exception
Combining protected methods with static methods is not supported. Combining access modifiers with class methods is not supported (yet).
+## Performance
+
+The access modifier decorators work by looking at the code that is calling the decorator to decide whether it is allowed to call the method. To do so, the decorators use implementation details of CPython, like sys._getframe() and the names of code objects such as lambdas and modules. These checks are done on each method call. Consequently, there is a considerable performance impact. Therefore it's recommended to use the access modifiers during testing and turn them off in production using the `access_modifiers.disable()` method. Note that you need to call this method before any of the access modifier decorators are evaluated, i.e.:
+
+```python
+from access_modifiers import disable, privatemethod
+
+disable() # This will disable the access checks
+
+class Class:
+ @privatemethod
+ def private_method(self) -> str:
+ return "private_method"
+
+disable() # Calling disable here will not work, Class.private_method has already been wrapped
+```
+
## Installation
The package is available from the Python Package Index, install with `pip install access-modifiers`.
@@ -84,8 +101,4 @@ To run the unittests and measure the coverage (which should always be at 100%):
To run Pylint (which should score a 10) and Mypy (which shouldn't complain): `ci/quality.sh`.
-## Implementation notes
-
-Both the `privatemethod` and the `protectedmethod` decorator work by looking at the code that is calling the decorator to decide whether it is allowed to call the method. To do so, the decorators use implementation details of CPython, like `sys._getframe()` and the names of code objects such as lambdas and modules.
-
The implementation is driven by (unit) tests and has 100% unit test statement and branch coverage. Please look at the tests to see which usage scenario's are currently covered.
diff --git a/access_modifiers/access_modifiers.py b/access_modifiers/access_modifiers.py
index 77ec865..cf99620 100644
--- a/access_modifiers/access_modifiers.py
+++ b/access_modifiers/access_modifiers.py
@@ -12,8 +12,25 @@ class AccessException(Exception):
ReturnType = TypeVar('ReturnType')
+_CHECK_ACCESS = True
+
+
+def disable() -> None:
+ """Disable all access checks. Needs to be invoked before the decorators are evaluated."""
+ global _CHECK_ACCESS # pylint: disable=global-statement
+ _CHECK_ACCESS = False
+
+
+def enable() -> None:
+ """Enable all access checks. For testing purposes."""
+ global _CHECK_ACCESS # pylint: disable=global-statement
+ _CHECK_ACCESS = True
+
+
def privatemethod(method: Callable[..., ReturnType]) -> Callable[..., ReturnType]:
"""Decorator that creates a private method."""
+ if not _CHECK_ACCESS:
+ return method
method_class_qualname = getframe(1).f_locals.get("__qualname__")
@wraps(method)
def private_method_wrapper(*args, **kwargs) -> ReturnType:
@@ -40,6 +57,8 @@ def privatemethod(method: Callable[..., ReturnType]) -> Callable[..., ReturnType
def protectedmethod(method: Callable[..., ReturnType]) -> Callable[..., ReturnType]:
"""Decorator that creates a protected method."""
+ if not _CHECK_ACCESS:
+ return method
@wraps(method)
def protected_method_wrapper(*args, **kwargs) -> ReturnType:
"""Wrap the original method to make it protected."""
|
fniessink/access-modifiers
|
e9a0d2091bd0dc795e972456b7d70c9032dd9522
|
diff --git a/access_modifiers/tests/test_private.py b/access_modifiers/tests/test_private.py
index 97ac772..747d525 100644
--- a/access_modifiers/tests/test_private.py
+++ b/access_modifiers/tests/test_private.py
@@ -2,7 +2,7 @@
import unittest
-from ..access_modifiers import AccessException, privatemethod, protectedmethod
+from ..access_modifiers import AccessException, disable, enable, privatemethod, protectedmethod
class PrivateMethodTests(unittest.TestCase):
@@ -52,16 +52,29 @@ class PrivateMethodTests(unittest.TestCase):
return "Subclass.private_method -> " + super().private_method() # pragma: nocover
def test_call_private_method_directly(self):
- """Test the accessing a private method throws an exception."""
+ """Test that accessing a private method throws an exception."""
self.assertRaises(AccessException, self.Class().private_method)
- self.assertRaises(AccessException, self.Class.private_method, self.Class())
+
+ def test_call_private_method_directly_without_access_checks(self):
+ """Test that accessing a private method without access checks works."""
+ try:
+ disable()
+
+ class Class:
+ @privatemethod
+ def private_method(self): # pylint: disable=no-self-use
+ return "Class.private_method"
+
+ self.assertEqual("Class.private_method", Class().private_method())
+ finally:
+ enable()
def test_call_private_method_via_public_method(self):
- """Test the accessing a private method via a public method is allowed."""
+ """Test that accessing a private method via a public method is allowed."""
self.assertEqual("Class.public_method -> Class.private_method", self.Class().public_method())
def test_call_private_method_via_public_method_from_subclass(self):
- """Test the accessing a private method via an overridden public method is allowed."""
+ """Test that accessing a private method via an overridden public method is allowed."""
class Subclass(self.Class):
def public_method(self):
@@ -80,7 +93,7 @@ class PrivateMethodTests(unittest.TestCase):
self.assertRaises(AccessException, Subclass().public_method)
def test_call_private_method_via_public_method_in_subclass_using_super(self):
- """Test the accessing a private method via a public method in a subclass is not allowed,
+ """Test that accessing a private method via a public method in a subclass is not allowed,
not even when using super()."""
class Subclass(self.Class):
@@ -168,3 +181,18 @@ class StaticPrivateMethodTests(PrivateMethodTests):
@protectedmethod
def private_method(self):
return "Subclass.private_method -> " + super().private_method() # pragma: nocover
+
+ def test_call_private_method_directly_without_access_checks(self):
+ """Test that accessing a private method without access checks works."""
+ try:
+ disable()
+
+ class Class: # pylint: disable=too-few-public-methods
+ @staticmethod
+ @privatemethod
+ def private_method():
+ return "Class.private_method"
+
+ self.assertEqual("Class.private_method", Class().private_method())
+ finally:
+ enable()
diff --git a/access_modifiers/tests/test_protected.py b/access_modifiers/tests/test_protected.py
index 414e06d..2ec5a78 100644
--- a/access_modifiers/tests/test_protected.py
+++ b/access_modifiers/tests/test_protected.py
@@ -2,7 +2,7 @@
import unittest
-from ..access_modifiers import AccessException, protectedmethod, privatemethod
+from ..access_modifiers import AccessException, enable, disable, protectedmethod, privatemethod
class ProtectedMethodTest(unittest.TestCase):
@@ -21,14 +21,27 @@ class ProtectedMethodTest(unittest.TestCase):
def test_protected_method(self):
"""Test that accessing a protected method throws an exception."""
self.assertRaises(AccessException, self.Class().protected_method)
- self.assertRaises(AccessException, self.Class.protected_method, self.Class())
+
+ def test_call_protected_method_directly_without_access_checks(self):
+ """Test that accessing a protected method without access checks works."""
+ try:
+ disable()
+
+ class Class: # pylint: disable=too-few-public-methods
+ @protectedmethod
+ def protected_method(self): # pylint: disable=no-self-use
+ return "Class.protected_method"
+
+ self.assertEqual("Class.protected_method", Class().protected_method())
+ finally:
+ enable()
def test_call_protected_method_via_public_method(self):
- """Test the accessing a protected method via a public method is allowed."""
+ """Test that accessing a protected method via a public method is allowed."""
self.assertEqual("Class.public_method -> Class.protected_method", self.Class().public_method())
def test_call_protected_method_via_protected_method(self):
- """Test the accessing a protected method via a another protected method is allowed."""
+ """Test that accessing a protected method via a another protected method is allowed."""
class Subclass(self.Class):
@protectedmethod
|
Add flag to turn off the access modifiers' checks in production
|
0.0
|
e9a0d2091bd0dc795e972456b7d70c9032dd9522
|
[
"access_modifiers/tests/test_private.py::PrivateMethodTests::test_call_private_method_directly",
"access_modifiers/tests/test_private.py::PrivateMethodTests::test_call_private_method_directly_without_access_checks",
"access_modifiers/tests/test_private.py::PrivateMethodTests::test_call_private_method_from_try_except_block",
"access_modifiers/tests/test_private.py::PrivateMethodTests::test_call_private_method_via_list_comprehension",
"access_modifiers/tests/test_private.py::PrivateMethodTests::test_call_private_method_via_nested_lambda",
"access_modifiers/tests/test_private.py::PrivateMethodTests::test_call_private_method_via_private_method",
"access_modifiers/tests/test_private.py::PrivateMethodTests::test_call_private_method_via_public_method",
"access_modifiers/tests/test_private.py::PrivateMethodTests::test_call_private_method_via_public_method_from_subclass",
"access_modifiers/tests/test_private.py::PrivateMethodTests::test_call_private_method_via_public_method_in_subclass",
"access_modifiers/tests/test_private.py::PrivateMethodTests::test_call_private_method_via_public_method_in_subclass_using_super",
"access_modifiers/tests/test_private.py::PrivateMethodTests::test_override_private_method",
"access_modifiers/tests/test_private.py::PrivateMethodTests::test_override_private_method_with_protected_method",
"access_modifiers/tests/test_private.py::StaticPrivateMethodTests::test_call_private_method_directly",
"access_modifiers/tests/test_private.py::StaticPrivateMethodTests::test_call_private_method_directly_without_access_checks",
"access_modifiers/tests/test_private.py::StaticPrivateMethodTests::test_call_private_method_from_try_except_block",
"access_modifiers/tests/test_private.py::StaticPrivateMethodTests::test_call_private_method_via_list_comprehension",
"access_modifiers/tests/test_private.py::StaticPrivateMethodTests::test_call_private_method_via_nested_lambda",
"access_modifiers/tests/test_private.py::StaticPrivateMethodTests::test_call_private_method_via_private_method",
"access_modifiers/tests/test_private.py::StaticPrivateMethodTests::test_call_private_method_via_public_method",
"access_modifiers/tests/test_private.py::StaticPrivateMethodTests::test_call_private_method_via_public_method_from_subclass",
"access_modifiers/tests/test_private.py::StaticPrivateMethodTests::test_call_private_method_via_public_method_in_subclass",
"access_modifiers/tests/test_private.py::StaticPrivateMethodTests::test_call_private_method_via_public_method_in_subclass_using_super",
"access_modifiers/tests/test_private.py::StaticPrivateMethodTests::test_override_private_method",
"access_modifiers/tests/test_private.py::StaticPrivateMethodTests::test_override_private_method_with_protected_method",
"access_modifiers/tests/test_protected.py::ProtectedMethodTest::test_call_overridden_protected_method_via_overridden_public_method",
"access_modifiers/tests/test_protected.py::ProtectedMethodTest::test_call_protected_method_directly_without_access_checks",
"access_modifiers/tests/test_protected.py::ProtectedMethodTest::test_call_protected_method_via_overridden_public_method",
"access_modifiers/tests/test_protected.py::ProtectedMethodTest::test_call_protected_method_via_protected_method",
"access_modifiers/tests/test_protected.py::ProtectedMethodTest::test_call_protected_method_via_public_method",
"access_modifiers/tests/test_protected.py::ProtectedMethodTest::test_call_protected_method_via_public_method_in_subclass",
"access_modifiers/tests/test_protected.py::ProtectedMethodTest::test_call_protected_method_via_public_method_using_super",
"access_modifiers/tests/test_protected.py::ProtectedMethodTest::test_override_protected_method_with_private_method",
"access_modifiers/tests/test_protected.py::ProtectedMethodTest::test_override_protected_method_with_protected_method",
"access_modifiers/tests/test_protected.py::ProtectedMethodTest::test_override_protected_method_with_public_method",
"access_modifiers/tests/test_protected.py::ProtectedMethodTest::test_protected_method"
] |
[] |
{
"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
}
|
2019-08-27 11:37:27+00:00
|
apache-2.0
| 2,364 |
|
fniessink__access-modifiers-6
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a780331..e14d12f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,12 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.
<!-- The line "## <square-bracket>Unreleased</square-bracket>" is replaced by the ci/release.py script with the new release version and release date. -->
+## [Unreleased]
+
+### Fixed
+
+- Make the access modifiers work when called from a dict comprehension, list comprehension, lambda, or other code block that gets its own frame. Fixes [#5](https://github.com/fniessink/access-modifiers/issues/5).
+
## [0.1.3] - [2019-08-24]
### Fixed
diff --git a/access_modifiers/access_modifiers.py b/access_modifiers/access_modifiers.py
index 948c72c..b8a56d9 100644
--- a/access_modifiers/access_modifiers.py
+++ b/access_modifiers/access_modifiers.py
@@ -19,11 +19,15 @@ def privatemethod(method: Callable[..., ReturnType]) -> Callable[..., ReturnType
def private_method_wrapper(*args, **kwargs) -> ReturnType:
"""Wrap the original method to make it private."""
caller_frame = getframe(1)
+ caller_code = caller_frame.f_code
+ caller_name = caller_code.co_name
+ while caller_name.startswith("<"): # Code is a <lambda>, <dictcomp>, <listcomp>, or other non-method code block
+ caller_frame = caller_frame.f_back
+ caller_code = caller_frame.f_code
+ caller_name = caller_code.co_name
caller_instance = caller_frame.f_locals.get("self")
if caller_instance is not args[0]:
raise AccessException(f"Attempted call to private method {method} from another object")
- caller_code = caller_frame.f_code
- caller_name = caller_code.co_name
# Look up the calling method to see if it's defined in the same class as the private method
for caller_class in caller_instance.__class__.mro():
caller = caller_class.__dict__.get(caller_name)
|
fniessink/access-modifiers
|
1c3800e09d6d283ba08e257c95bcb4bbaf32e18b
|
diff --git a/access_modifiers/tests/test_private.py b/access_modifiers/tests/test_private.py
index 1d113e6..bf2aff1 100644
--- a/access_modifiers/tests/test_private.py
+++ b/access_modifiers/tests/test_private.py
@@ -56,6 +56,51 @@ class PrivateMethodTest(unittest.TestCase):
self.assertRaises(AccessException, Subclass().public_method)
+ def test_call_private_method_via_list_comprehension(self):
+ """Test that accessing a private method via a list comprehension in a public method works."""
+
+ class Class:
+ @privatemethod
+ def private_method(self): # pylint: disable=no-self-use
+ return "Class.private_method"
+
+ def public_method(self):
+ return ["Class.public_method -> " + self.private_method() for _ in range(1)][0]
+
+ self.assertEqual("Class.public_method -> Class.private_method", Class().public_method())
+
+ def test_call_private_method_via_nested_lambda(self):
+ """Test that accessing a private method via a nested lambda in a public method works."""
+
+ class Class:
+ @privatemethod
+ def private_method(self): # pylint: disable=no-self-use
+ return "Class.private_method"
+
+ def public_method(self):
+ # pylint: disable=unnecessary-lambda
+ inner_lambda_function = lambda: self.private_method()
+ outer_lambda_function = lambda: "Class.public_method -> " + inner_lambda_function()
+ return outer_lambda_function()
+
+ self.assertEqual("Class.public_method -> Class.private_method", Class().public_method())
+
+ def test_call_private_method_from_try_except_block(self):
+ """Test that accessing a private method from a try/except in a public method works."""
+
+ class Class:
+ @privatemethod
+ def private_method(self): # pylint: disable=no-self-use
+ return "Class.private_method"
+
+ def public_method(self):
+ try:
+ return "Class.public_method -> " + self.private_method()
+ except AttributeError: # pragma: nocover
+ pass
+
+ self.assertEqual("Class.public_method -> Class.private_method", Class().public_method())
+
def test_override_private_method(self):
"""Test that an overridden private method can't call its super."""
|
Make access modifiers work when called from a list comprehension
|
0.0
|
1c3800e09d6d283ba08e257c95bcb4bbaf32e18b
|
[
"access_modifiers/tests/test_private.py::PrivateMethodTest::test_call_private_method_via_list_comprehension",
"access_modifiers/tests/test_private.py::PrivateMethodTest::test_call_private_method_via_nested_lambda"
] |
[
"access_modifiers/tests/test_private.py::PrivateMethodTest::test_call_private_method_directly",
"access_modifiers/tests/test_private.py::PrivateMethodTest::test_call_private_method_from_try_except_block",
"access_modifiers/tests/test_private.py::PrivateMethodTest::test_call_private_method_via_public_method",
"access_modifiers/tests/test_private.py::PrivateMethodTest::test_call_private_method_via_public_method_from_subclass",
"access_modifiers/tests/test_private.py::PrivateMethodTest::test_call_private_method_via_public_method_in_subclass",
"access_modifiers/tests/test_private.py::PrivateMethodTest::test_call_private_method_via_public_method_in_subclass_using_super",
"access_modifiers/tests/test_private.py::PrivateMethodTest::test_override_private_method",
"access_modifiers/tests/test_private.py::PrivateMethodTest::test_override_private_method_with_protected_method"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2019-08-24 22:37:20+00:00
|
apache-2.0
| 2,365 |
|
fniessink__next-action-103
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index bbdd695..eb96b4e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,12 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/)
and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html).
+## [Unreleased]
+
+### Fixed
+
+- Short options immediately followed by a value weren't parsed correctly. Fixes #84.
+
## [0.16.1] - 2018-06-04
### Fixed
diff --git a/next_action/arguments/parser.py b/next_action/arguments/parser.py
index 725d787..0d7a4b1 100644
--- a/next_action/arguments/parser.py
+++ b/next_action/arguments/parser.py
@@ -153,7 +153,8 @@ class NextActionArgumentParser(argparse.ArgumentParser):
@staticmethod
def arguments_not_specified(*arguments: str) -> bool:
""" Return whether any of the arguments was specified on the command line. """
- return all([argument not in sys.argv for argument in arguments])
+ return not any([command_line_arg.startswith(argument) for argument in arguments
+ for command_line_arg in sys.argv])
def fix_filenames(self, namespace: argparse.Namespace) -> None:
""" Fix the filenames. """
|
fniessink/next-action
|
1a1278fb1e5854ea7291f385307ae9e8f8eb67d1
|
diff --git a/tests/unittests/arguments/test_config.py b/tests/unittests/arguments/test_config.py
index 8eb5728..12e9a15 100644
--- a/tests/unittests/arguments/test_config.py
+++ b/tests/unittests/arguments/test_config.py
@@ -270,13 +270,19 @@ class PriorityTest(ConfigTestCase):
@patch.object(sys, "argv", ["next-action", "--priority", "M"])
@patch.object(config, "open", mock_open(read_data="priority: Z"))
def test_override_priority(self):
- """ Test that a command line style overrides the priority in the config file. """
+ """ Test that a command line option overrides the priority in the config file. """
+ self.assertEqual("M", parse_arguments()[1].priority)
+
+ @patch.object(sys, "argv", ["next-action", "-pM"])
+ @patch.object(config, "open", mock_open(read_data="priority: Z"))
+ def test_override_short(self):
+ """ Test that a short command line option overrides the priority in the config file. """
self.assertEqual("M", parse_arguments()[1].priority)
@patch.object(sys, "argv", ["next-action", "--priority"])
@patch.object(config, "open", mock_open(read_data="priority: Z"))
def test_cancel_priority(self):
- """ Test that a command line style overrides the priority in the config file. """
+ """ Test that a command line option overrides the priority in the config file. """
self.assertEqual(None, parse_arguments()[1].priority)
@patch.object(sys, "argv", ["next-action"])
|
next-action -pA isn't interpreted as next-action -p A
|
0.0
|
1a1278fb1e5854ea7291f385307ae9e8f8eb67d1
|
[
"tests/unittests/arguments/test_config.py::PriorityTest::test_override_short"
] |
[
"tests/unittests/arguments/test_config.py::ConfigFileTest::test_empty_file",
"tests/unittests/arguments/test_config.py::ConfigFileTest::test_error_opening",
"tests/unittests/arguments/test_config.py::ConfigFileTest::test_error_parsing",
"tests/unittests/arguments/test_config.py::ConfigFileTest::test_file_not_found",
"tests/unittests/arguments/test_config.py::ConfigFileTest::test_invalid_document",
"tests/unittests/arguments/test_config.py::ConfigFileTest::test_missing_default_config",
"tests/unittests/arguments/test_config.py::ConfigFileTest::test_no_file_key",
"tests/unittests/arguments/test_config.py::ConfigFileTest::test_skip_config",
"tests/unittests/arguments/test_config.py::ConfigFileTest::test_write_config",
"tests/unittests/arguments/test_config.py::FilenameTest::test_cli_takes_precedence",
"tests/unittests/arguments/test_config.py::FilenameTest::test_invalid_filename",
"tests/unittests/arguments/test_config.py::FilenameTest::test_valid_and_invalid",
"tests/unittests/arguments/test_config.py::FilenameTest::test_valid_file",
"tests/unittests/arguments/test_config.py::FilenameTest::test_valid_files",
"tests/unittests/arguments/test_config.py::NumberTest::test_all_and_number",
"tests/unittests/arguments/test_config.py::NumberTest::test_all_false",
"tests/unittests/arguments/test_config.py::NumberTest::test_all_true",
"tests/unittests/arguments/test_config.py::NumberTest::test_argument_all_overrides",
"tests/unittests/arguments/test_config.py::NumberTest::test_argument_nr_overrides",
"tests/unittests/arguments/test_config.py::NumberTest::test_cli_takes_precedence",
"tests/unittests/arguments/test_config.py::NumberTest::test_invalid_number",
"tests/unittests/arguments/test_config.py::NumberTest::test_valid_number",
"tests/unittests/arguments/test_config.py::NumberTest::test_zero",
"tests/unittests/arguments/test_config.py::ConfigStyleTest::test_cancel_style",
"tests/unittests/arguments/test_config.py::ConfigStyleTest::test_invalid_style",
"tests/unittests/arguments/test_config.py::ConfigStyleTest::test_override_style",
"tests/unittests/arguments/test_config.py::ConfigStyleTest::test_valid_style",
"tests/unittests/arguments/test_config.py::PriorityTest::test_cancel_priority",
"tests/unittests/arguments/test_config.py::PriorityTest::test_invalid_priority",
"tests/unittests/arguments/test_config.py::PriorityTest::test_override_priority",
"tests/unittests/arguments/test_config.py::PriorityTest::test_valid_priority",
"tests/unittests/arguments/test_config.py::ReferenceTest::test_invalid_priority",
"tests/unittests/arguments/test_config.py::ReferenceTest::test_override",
"tests/unittests/arguments/test_config.py::ReferenceTest::test_valid_reference"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2018-06-05 17:42:32+00:00
|
apache-2.0
| 2,366 |
|
fniessink__next-action-104
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index eb96b4e..ee37b1d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.
### Fixed
+- Mention how to deal with options with optional arguments followed by positional arguments in the help information and README. Closes #100.
- Short options immediately followed by a value weren't parsed correctly. Fixes #84.
## [0.16.1] - 2018-06-04
diff --git a/README.md b/README.md
index f0a5712..f225b7f 100644
--- a/README.md
+++ b/README.md
@@ -21,8 +21,9 @@ Don't know what *Todo.txt* is? See <https://github.com/todotxt/todo.txt> for the
- [Usage](#usage)
- [Limiting the tasks from which next actions are selected](#limiting-the-tasks-from-which-next-actions-are-selected)
- [Showing more than one next action](#showing-more-than-one-next-action)
- - [Output options](#output-options)
+ - [Styling the output](#styling-the-output)
- [Configuring *Next-action*](#configuring-next-action)
+ - [Option details](#option-details)
- [Recent changes](#recent-changes)
- [Develop](#develop)
@@ -41,7 +42,7 @@ Don't know what *Todo.txt* is? See <https://github.com/todotxt/todo.txt> for the
```console
$ next-action --help
usage: next-action [-h] [--version] [-c [<config.cfg>] | -w] [-f <todo.txt> ...] [-r <ref>] [-s [<style>]] [-a
-| -n <number>] [-d [<due date>] | -o] [-p [<priority>]] [<context|project> ...]
+| -n <number>] [-d [<due date>] | -o] [-p [<priority>]] [--] [<context|project> ...]
Show the next action in your todo.txt. The next action is selected from the tasks in the todo.txt file based
on task properties such as priority, due date, and creation date. Limit the tasks from which the next action
@@ -90,6 +91,9 @@ limit the tasks from which the next actions are selected:
of at least one of the projects
-@<context> ... contexts the next action must not have
-+<project> ... projects the next action must not be part of
+
+Use -- to separate options with optional arguments from contexts and projects, in order to handle cases
+where a context or project is mistaken for an argument to an option.
```
Assuming your todo.txt file is your home folder, running *Next-action* without arguments will show the next action you should do. Given this [todo.txt](https://raw.githubusercontent.com/fniessink/next-action/master/docs/todo.txt), calling mom would be the next action:
@@ -192,7 +196,7 @@ $ next-action --all @store
Note again that completed tasks and task with a future creation date are never shown since they can't be a next action.
-### Output options
+### Styling the output
By default, *Next-action* references the todo.txt file from which actions were read if you read tasks from multiple todo.txt files. The `--reference` option controls this:
@@ -298,12 +302,39 @@ style: colorful
Run `next-action --help` to see the list of possible styles.
-#### Precedence of options
+### Option details
+
+#### Precedence
Options in the configuration file override the default options. Command-line options in turn override options in the configuration file.
If you have a configuration file with default options that you occasionally want to ignore, you can skip reading the configuration file entirely with the `--no-config-file` option.
+#### Optional arguments followed by positional arguments
+
+When you use an option that takes an optional argument, but have it followed by a positional argument, *Next-action* will interpret the positional argument as the argument to the option and complain, e.g.:
+
+```console
+$ next-action --due @home
+usage: next-action [-h] [--version] [-c [<config.cfg>] | -w] [-f <todo.txt> ...] [-r <ref>] [-s [<style>]] [-a
+| -n <number>] [-d [<due date>] | -o] [-p [<priority>]] [--] [<context|project> ...]
+next-action: error: argument -d/--due: invalid date: @home
+```
+
+There's two ways to help *Next-action* figure out what you mean. Either reverse the order of the arguments:
+
+```console
+$ next-action @home --due
+(K) Pay July invoice @home due:2018-07-28
+```
+
+Or use `--` to separate the option from the positional argument(s):
+
+```console
+$ next-action --due -- @home
+(K) Pay July invoice @home due:2018-07-28
+```
+
## Recent changes
See the [change log](https://github.com/fniessink/next-action/blob/master/CHANGELOG.md).
@@ -316,9 +347,9 @@ To run the unit tests:
```console
$ python -m unittest
-...................................................................................................................................................................
+....................................................................................................................................................................
----------------------------------------------------------------------
-Ran 163 tests in 0.614s
+Ran 164 tests in 0.592s
OK
```
diff --git a/docs/update_readme.py b/docs/update_readme.py
index 6d5d826..0c6a123 100644
--- a/docs/update_readme.py
+++ b/docs/update_readme.py
@@ -9,9 +9,10 @@ def do_command(line):
""" Run the command on the line and return its stdout and stderr. """
command = shlex.split(line[2:])
if command[0] == "next-action" and "--write-config-file" not in command:
- command.extend(["--config", "docs/.next-action.cfg"])
+ command.insert(1, "--config")
+ command.insert(2, "docs/.next-action.cfg")
command_output = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
- check=True, universal_newlines=True)
+ universal_newlines=True)
return command_output.stdout.strip(), command_output.stderr.strip()
diff --git a/next_action/arguments/parser.py b/next_action/arguments/parser.py
index 0d7a4b1..2e2e9e2 100644
--- a/next_action/arguments/parser.py
+++ b/next_action/arguments/parser.py
@@ -20,14 +20,16 @@ class NextActionArgumentParser(argparse.ArgumentParser):
def __init__(self) -> None:
super().__init__(
+ usage=textwrap.fill("next-action [-h] [--version] [-c [<config.cfg>] | -w] [-f <todo.txt> ...] "
+ "[-r <ref>] [-s [<style>]] [-a | -n <number>] [-d [<due date>] | -o] "
+ "[-p [<priority>]] [--] [<context|project> ...]",
+ width=shutil.get_terminal_size().columns - len("usage: ")),
description="Show the next action in your todo.txt. The next action is selected from the tasks in the "
"todo.txt file based on task properties such as priority, due date, and creation date. Limit "
"the tasks from which the next action is selected by specifying contexts the tasks must have "
"and/or projects the tasks must belong to.",
- usage=textwrap.fill("next-action [-h] [--version] [-c [<config.cfg>] | -w] [-f <todo.txt> ...] "
- "[-r <ref>] [-s [<style>]] [-a | -n <number>] [-d [<due date>] | -o] "
- "[-p [<priority>]] [<context|project> ...]",
- width=shutil.get_terminal_size().columns - len("usage: ")))
+ epilog="Use -- to separate options with optional arguments from contexts and projects, in order to handle "
+ "cases where a context or project is mistaken for an argument to an option.")
self.__default_filenames = ["~/todo.txt"]
self.add_optional_arguments()
self.add_filter_arguments()
|
fniessink/next-action
|
db664ba1c1b642acedf768c9283a1ebf19e2bc35
|
diff --git a/tests/unittests/arguments/test_parser.py b/tests/unittests/arguments/test_parser.py
index e0867ee..4e6a5ec 100644
--- a/tests/unittests/arguments/test_parser.py
+++ b/tests/unittests/arguments/test_parser.py
@@ -12,7 +12,7 @@ from next_action.arguments import config, parse_arguments
USAGE_MESSAGE = textwrap.fill(
"usage: next-action [-h] [--version] [-c [<config.cfg>] | -w] [-f <todo.txt> ...] [-r <ref>] [-s [<style>]] "
- "[-a | -n <number>] [-d [<due date>] | -o] [-p [<priority>]] [<context|project> ...]", 120) + "\n"
+ "[-a | -n <number>] [-d [<due date>] | -o] [-p [<priority>]] [--] [<context|project> ...]", 120) + "\n"
class ParserTestCase(unittest.TestCase):
diff --git a/tests/unittests/test_cli.py b/tests/unittests/test_cli.py
index ec2d8cc..8c8978b 100644
--- a/tests/unittests/test_cli.py
+++ b/tests/unittests/test_cli.py
@@ -66,7 +66,7 @@ class CLITest(unittest.TestCase):
self.assertRaises(SystemExit, next_action)
self.assertEqual(call("""\
usage: next-action [-h] [--version] [-c [<config.cfg>] | -w] [-f <todo.txt> ...] [-r <ref>] [-s [<style>]] [-a | -n
-<number>] [-d [<due date>] | -o] [-p [<priority>]] [<context|project> ...]
+<number>] [-d [<due date>] | -o] [-p [<priority>]] [--] [<context|project> ...]
Show the next action in your todo.txt. The next action is selected from the tasks in the todo.txt file based on task
properties such as priority, due date, and creation date. Limit the tasks from which the next action is selected by
@@ -115,6 +115,9 @@ limit the tasks from which the next actions are selected:
one of the projects
-@<context> ... contexts the next action must not have
-+<project> ... projects the next action must not be part of
+
+Use -- to separate options with optional arguments from contexts and projects, in order to handle cases where a
+context or project is mistaken for an argument to an option.
"""),
mock_stdout_write.call_args_list[0])
|
next-action --due @work gives error message
This is because `--due` has an optional argument. Mention in docs that either `next-action @work --due` or `next-action --due -- @work` works.
|
0.0
|
db664ba1c1b642acedf768c9283a1ebf19e2bc35
|
[
"tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_empty_context",
"tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_empty_excluded_project",
"tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_empty_project",
"tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_faulty_option",
"tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_include_exclude_context",
"tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_include_exclude_project",
"tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_invalid_extra_argument",
"tests/unittests/arguments/test_parser.py::NumberTest::test_all_and_number",
"tests/unittests/arguments/test_parser.py::NumberTest::test_faulty_number",
"tests/unittests/arguments/test_parser.py::DueDateTest::test_faulty_date",
"tests/unittests/arguments/test_parser.py::DueDateTest::test_invalid_date",
"tests/unittests/arguments/test_parser.py::DueDateTest::test_too_long",
"tests/unittests/arguments/test_parser.py::ReferenceTest::test_faulty_date",
"tests/unittests/test_cli.py::CLITest::test_missing_file"
] |
[
"tests/unittests/arguments/test_parser.py::NoArgumentTest::test_filename",
"tests/unittests/arguments/test_parser.py::NoArgumentTest::test_filters",
"tests/unittests/arguments/test_parser.py::NoArgumentTest::test_style",
"tests/unittests/arguments/test_parser.py::FilenameTest::test__add_filename_twice",
"tests/unittests/arguments/test_parser.py::FilenameTest::test_add_default_filename",
"tests/unittests/arguments/test_parser.py::FilenameTest::test_default_and_non_default",
"tests/unittests/arguments/test_parser.py::FilenameTest::test_filename_argument",
"tests/unittests/arguments/test_parser.py::FilenameTest::test_long_filename_argument",
"tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_contexts_and_projects",
"tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_exclude_context",
"tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_exclude_project",
"tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_multiple_contexts",
"tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_multiple_projects",
"tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_one_context",
"tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_one_project",
"tests/unittests/arguments/test_parser.py::NumberTest::test_all_actions",
"tests/unittests/arguments/test_parser.py::NumberTest::test_default_number",
"tests/unittests/arguments/test_parser.py::NumberTest::test_number",
"tests/unittests/arguments/test_parser.py::DueDateTest::test_default",
"tests/unittests/arguments/test_parser.py::DueDateTest::test_due_date",
"tests/unittests/arguments/test_parser.py::DueDateTest::test_no_due_date",
"tests/unittests/arguments/test_parser.py::ReferenceTest::test_always",
"tests/unittests/arguments/test_parser.py::ReferenceTest::test_default",
"tests/unittests/arguments/test_parser.py::ReferenceTest::test_multiple",
"tests/unittests/arguments/test_parser.py::ReferenceTest::test_never",
"tests/unittests/test_cli.py::CLITest::test_context",
"tests/unittests/test_cli.py::CLITest::test_empty_task_file",
"tests/unittests/test_cli.py::CLITest::test_ignore_empty_lines",
"tests/unittests/test_cli.py::CLITest::test_number",
"tests/unittests/test_cli.py::CLITest::test_one_task",
"tests/unittests/test_cli.py::CLITest::test_project",
"tests/unittests/test_cli.py::CLITest::test_reading_stdin",
"tests/unittests/test_cli.py::CLITest::test_reference_filename",
"tests/unittests/test_cli.py::CLITest::test_show_all_actions",
"tests/unittests/test_cli.py::CLITest::test_version"
] |
{
"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-06-05 19:09:06+00:00
|
apache-2.0
| 2,367 |
|
fniessink__next-action-106
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2a6d5a5..8a3b394 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,12 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/)
and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html).
+## [Unreleased]
+
+### Fixed
+
+- Capitalise the help information. Fixes #105.
+
## [0.16.2] - 2018-06-05
### Fixed
diff --git a/next_action/arguments/parser.py b/next_action/arguments/parser.py
index 2e2e9e2..6f6fd37 100644
--- a/next_action/arguments/parser.py
+++ b/next_action/arguments/parser.py
@@ -29,16 +29,25 @@ class NextActionArgumentParser(argparse.ArgumentParser):
"the tasks from which the next action is selected by specifying contexts the tasks must have "
"and/or projects the tasks must belong to.",
epilog="Use -- to separate options with optional arguments from contexts and projects, in order to handle "
- "cases where a context or project is mistaken for an argument to an option.")
+ "cases where a context or project is mistaken for an argument to an option.",
+ formatter_class=CapitalisedHelpFormatter)
self.__default_filenames = ["~/todo.txt"]
self.add_optional_arguments()
+ self.add_configuration_options()
+ self.add_input_options()
+ self.add_output_options()
+ self.add_number_options()
self.add_filter_arguments()
def add_optional_arguments(self) -> None:
""" Add the optional arguments to the parser. """
+ self._optionals.title = self._optionals.title.capitalize()
self.add_argument(
"--version", action="version", version="%(prog)s {0}".format(next_action.__version__))
- config_group = self.add_argument_group("configuration options")
+
+ def add_configuration_options(self) -> None:
+ """ Add the configuration options to the parser. """
+ config_group = self.add_argument_group("Configuration options")
config_file = config_group.add_mutually_exclusive_group()
config_file.add_argument(
"-c", "--config-file", metavar="<config.cfg>", type=str, default="~/.next-action.cfg", nargs="?",
@@ -46,12 +55,18 @@ class NextActionArgumentParser(argparse.ArgumentParser):
"configuration file")
config_file.add_argument(
"-w", "--write-config-file", help="generate a sample configuration file and exit", action="store_true")
- input_group = self.add_argument_group("input options")
+
+ def add_input_options(self) -> None:
+ """ Add the input options to the parser. """
+ input_group = self.add_argument_group("Input options")
input_group.add_argument(
"-f", "--file", action="append", metavar="<todo.txt>", default=self.__default_filenames[:], type=str,
help="filename of todo.txt file to read; can be '-' to read from standard input; argument can be "
"repeated to read tasks from multiple todo.txt files (default: ~/todo.txt)")
- output_group = self.add_argument_group("output options")
+
+ def add_output_options(self) -> None:
+ """ Add the output/styling options to the parser. """
+ output_group = self.add_argument_group("Output options")
output_group.add_argument(
"-r", "--reference", choices=["always", "never", "multiple"], default="multiple",
help="reference next actions with the name of their todo.txt file (default: when reading multiple "
@@ -60,7 +75,10 @@ class NextActionArgumentParser(argparse.ArgumentParser):
output_group.add_argument(
"-s", "--style", metavar="<style>", choices=styles, default=None, nargs="?",
help="colorize the output; available styles: {0} (default: %(default)s)".format(", ".join(styles)))
- number_group = self.add_argument_group("show multiple next actions")
+
+ def add_number_options(self) -> None:
+ """ Add the number options to the parser. """
+ number_group = self.add_argument_group("Show multiple next actions")
number = number_group.add_mutually_exclusive_group()
number.add_argument(
"-a", "--all", default=1, action="store_const", dest="number", const=sys.maxsize,
@@ -71,7 +89,7 @@ class NextActionArgumentParser(argparse.ArgumentParser):
def add_filter_arguments(self) -> None:
""" Add the filter arguments to the parser. """
- filters = self.add_argument_group("limit the tasks from which the next actions are selected")
+ filters = self.add_argument_group("Limit the tasks from which the next actions are selected")
date = filters.add_mutually_exclusive_group()
date.add_argument(
"-d", "--due", metavar="<due date>", type=date_type, nargs="?", const=datetime.date.max,
@@ -171,6 +189,13 @@ class NextActionArgumentParser(argparse.ArgumentParser):
namespace.file = list(dict.fromkeys(filenames))
+class CapitalisedHelpFormatter(argparse.HelpFormatter):
+ """ Capitalise the usage string. """
+ def add_usage(self, usage, actions, groups, prefix=None):
+ prefix = prefix or 'Usage: '
+ return super(CapitalisedHelpFormatter, self).add_usage(usage, actions, groups, prefix or "Usage: ")
+
+
def filter_type(value: str) -> str:
""" Return the filter if it's valid, else raise an error. """
if value.startswith("@") or value.startswith("+"):
|
fniessink/next-action
|
7fb68d17949d8bf901bd29963d427aeb8aaf600e
|
diff --git a/tests/unittests/arguments/test_parser.py b/tests/unittests/arguments/test_parser.py
index 4e6a5ec..7a085f1 100644
--- a/tests/unittests/arguments/test_parser.py
+++ b/tests/unittests/arguments/test_parser.py
@@ -11,7 +11,7 @@ from next_action.arguments import config, parse_arguments
USAGE_MESSAGE = textwrap.fill(
- "usage: next-action [-h] [--version] [-c [<config.cfg>] | -w] [-f <todo.txt> ...] [-r <ref>] [-s [<style>]] "
+ "Usage: next-action [-h] [--version] [-c [<config.cfg>] | -w] [-f <todo.txt> ...] [-r <ref>] [-s [<style>]] "
"[-a | -n <number>] [-d [<due date>] | -o] [-p [<priority>]] [--] [<context|project> ...]", 120) + "\n"
diff --git a/tests/unittests/test_cli.py b/tests/unittests/test_cli.py
index 8c8978b..23c4ee7 100644
--- a/tests/unittests/test_cli.py
+++ b/tests/unittests/test_cli.py
@@ -65,30 +65,30 @@ class CLITest(unittest.TestCase):
os.environ['COLUMNS'] = "120" # Fake that the terminal is wide enough.
self.assertRaises(SystemExit, next_action)
self.assertEqual(call("""\
-usage: next-action [-h] [--version] [-c [<config.cfg>] | -w] [-f <todo.txt> ...] [-r <ref>] [-s [<style>]] [-a | -n
+Usage: next-action [-h] [--version] [-c [<config.cfg>] | -w] [-f <todo.txt> ...] [-r <ref>] [-s [<style>]] [-a | -n
<number>] [-d [<due date>] | -o] [-p [<priority>]] [--] [<context|project> ...]
Show the next action in your todo.txt. The next action is selected from the tasks in the todo.txt file based on task
properties such as priority, due date, and creation date. Limit the tasks from which the next action is selected by
specifying contexts the tasks must have and/or projects the tasks must belong to.
-optional arguments:
+Optional arguments:
-h, --help show this help message and exit
--version show program's version number and exit
-configuration options:
+Configuration options:
-c [<config.cfg>], --config-file [<config.cfg>]
filename of configuration file to read (default: ~/.next-action.cfg); omit filename to not
read any configuration file
-w, --write-config-file
generate a sample configuration file and exit
-input options:
+Input options:
-f <todo.txt>, --file <todo.txt>
filename of todo.txt file to read; can be '-' to read from standard input; argument can be
repeated to read tasks from multiple todo.txt files (default: ~/todo.txt)
-output options:
+Output options:
-r {always,never,multiple}, --reference {always,never,multiple}
reference next actions with the name of their todo.txt file (default: when reading multiple
todo.txt files)
@@ -98,12 +98,12 @@ output options:
paraiso-dark, paraiso-light, pastie, perldoc, rainbow_dash, rrt, tango, trac, vim, vs, xcode
(default: None)
-show multiple next actions:
+Show multiple next actions:
-a, --all show all next actions
-n <number>, --number <number>
number of next actions to show (default: 1)
-limit the tasks from which the next actions are selected:
+Limit the tasks from which the next actions are selected:
-d [<due date>], --due [<due date>]
show only next actions with a due date; if a date is given, show only next actions due on or
before that date
|
Capitalise the sections in the help information
|
0.0
|
7fb68d17949d8bf901bd29963d427aeb8aaf600e
|
[
"tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_empty_context",
"tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_empty_excluded_project",
"tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_empty_project",
"tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_faulty_option",
"tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_include_exclude_context",
"tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_include_exclude_project",
"tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_invalid_extra_argument",
"tests/unittests/arguments/test_parser.py::NumberTest::test_all_and_number",
"tests/unittests/arguments/test_parser.py::NumberTest::test_faulty_number",
"tests/unittests/arguments/test_parser.py::DueDateTest::test_faulty_date",
"tests/unittests/arguments/test_parser.py::DueDateTest::test_invalid_date",
"tests/unittests/arguments/test_parser.py::DueDateTest::test_too_long",
"tests/unittests/arguments/test_parser.py::ReferenceTest::test_faulty_date",
"tests/unittests/test_cli.py::CLITest::test_missing_file"
] |
[
"tests/unittests/arguments/test_parser.py::NoArgumentTest::test_filename",
"tests/unittests/arguments/test_parser.py::NoArgumentTest::test_filters",
"tests/unittests/arguments/test_parser.py::NoArgumentTest::test_style",
"tests/unittests/arguments/test_parser.py::FilenameTest::test__add_filename_twice",
"tests/unittests/arguments/test_parser.py::FilenameTest::test_add_default_filename",
"tests/unittests/arguments/test_parser.py::FilenameTest::test_default_and_non_default",
"tests/unittests/arguments/test_parser.py::FilenameTest::test_filename_argument",
"tests/unittests/arguments/test_parser.py::FilenameTest::test_long_filename_argument",
"tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_contexts_and_projects",
"tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_exclude_context",
"tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_exclude_project",
"tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_multiple_contexts",
"tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_multiple_projects",
"tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_one_context",
"tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_one_project",
"tests/unittests/arguments/test_parser.py::NumberTest::test_all_actions",
"tests/unittests/arguments/test_parser.py::NumberTest::test_default_number",
"tests/unittests/arguments/test_parser.py::NumberTest::test_number",
"tests/unittests/arguments/test_parser.py::DueDateTest::test_default",
"tests/unittests/arguments/test_parser.py::DueDateTest::test_due_date",
"tests/unittests/arguments/test_parser.py::DueDateTest::test_no_due_date",
"tests/unittests/arguments/test_parser.py::ReferenceTest::test_always",
"tests/unittests/arguments/test_parser.py::ReferenceTest::test_default",
"tests/unittests/arguments/test_parser.py::ReferenceTest::test_multiple",
"tests/unittests/arguments/test_parser.py::ReferenceTest::test_never",
"tests/unittests/test_cli.py::CLITest::test_context",
"tests/unittests/test_cli.py::CLITest::test_empty_task_file",
"tests/unittests/test_cli.py::CLITest::test_ignore_empty_lines",
"tests/unittests/test_cli.py::CLITest::test_number",
"tests/unittests/test_cli.py::CLITest::test_one_task",
"tests/unittests/test_cli.py::CLITest::test_project",
"tests/unittests/test_cli.py::CLITest::test_reading_stdin",
"tests/unittests/test_cli.py::CLITest::test_reference_filename",
"tests/unittests/test_cli.py::CLITest::test_show_all_actions",
"tests/unittests/test_cli.py::CLITest::test_version"
] |
{
"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-06-05 20:30:53+00:00
|
apache-2.0
| 2,368 |
|
fniessink__next-action-110
|
diff --git a/README.md b/README.md
index 2797c49..dc14156 100644
--- a/README.md
+++ b/README.md
@@ -103,9 +103,9 @@ $ next-action
(A) Call mom @phone
```
-The next action is determined using priority. Due date is considered after priority, with tasks due earlier getting precedence over tasks due later. Creation date is considered after due date, with older tasks getting precedence over newer tasks. FInally, tasks that belong to more projects get precedence over tasks that belong to fewer projects.
+The next action is determined using priority. Due date is considered after priority, with tasks due earlier getting precedence over tasks due later. Creation date is considered after due date, with older tasks getting precedence over newer tasks. Finally, tasks that belong to more projects get precedence over tasks that belong to fewer projects.
-Completed tasks (~~`x This is a completed task`~~) and tasks with a creation date in the future (`9999-01-01 Start preparing for five-digit years`) are not considered when determining the next action.
+Completed tasks (~~`x This is a completed task`~~), tasks with a creation date in the future (`9999-01-01 Start preparing for five-digit years`), and tasks with a future threshold date (`Start preparing for emigration to Mars t:3000-01-01`) are not considered when determining the next action.
### Limiting the tasks from which next actions are selected
@@ -194,7 +194,7 @@ $ next-action --all @store
(G) Buy wood for new +DogHouse @store
```
-Note again that completed tasks and task with a future creation date are never shown since they can't be a next action.
+Note again that completed tasks and task with a future creation or threshold date are never shown since they can't be a next action.
### Styling the output
diff --git a/docs/todo.txt b/docs/todo.txt
index 06842c9..7df531b 100644
--- a/docs/todo.txt
+++ b/docs/todo.txt
@@ -9,3 +9,4 @@ Buy flowers due:2018-02-14
(K) Pay July invoice @home due:2018-07-28
x This is a completed task
9999-01-01 Start preparing for five-digit years
+Start preparing for emigration to Mars t:3000-01-01
diff --git a/next_action/pick_action.py b/next_action/pick_action.py
index b65d42a..24dbff0 100644
--- a/next_action/pick_action.py
+++ b/next_action/pick_action.py
@@ -24,7 +24,8 @@ def next_actions(tasks: Sequence[Task], arguments: argparse.Namespace) -> Sequen
projects = subset(arguments.filters, "+")
excluded_contexts = subset(arguments.filters, "-@")
excluded_projects = subset(arguments.filters, "-+")
- # First, get the potential next actions by filtering out completed tasks and tasks with a future creation date
+ # First, get the potential next actions by filtering out completed tasks and tasks with a future creation date or
+ # future threshold date
actionable_tasks = [task for task in tasks if task.is_actionable()]
# Then, exclude tasks that have an excluded context
eligible_tasks = filter(lambda task: not excluded_contexts & task.contexts() if excluded_contexts else True,
diff --git a/next_action/todotxt/task.py b/next_action/todotxt/task.py
index 6e420db..a8733b6 100644
--- a/next_action/todotxt/task.py
+++ b/next_action/todotxt/task.py
@@ -45,10 +45,13 @@ class Task(object):
match = re.match(r"(?:\([A-Z]\) )?{0}\b".format(self.iso_date_reg_exp), self.text)
return self.__create_date(match)
+ def threshold_date(self) -> Optional[datetime.date]:
+ """ Return the threshold date of the task. """
+ return self.__find_keyed_date("t")
+
def due_date(self) -> Optional[datetime.date]:
""" Return the due date of the task. """
- match = re.search(r"\bdue:{0}\b".format(self.iso_date_reg_exp), self.text)
- return self.__create_date(match)
+ return self.__find_keyed_date("due")
def is_due(self, due_date: datetime.date) -> bool:
""" Return whether the task is due on or before the given due date. """
@@ -60,9 +63,15 @@ class Task(object):
return self.text.startswith("x ")
def is_future(self) -> bool:
- """ Return whether the task is a future task, i.e. has a creation date in the future. """
+ """ Return whether the task is a future task, i.e. has a creation or threshold date in the future. """
+ today = datetime.date.today()
creation_date = self.creation_date()
- return creation_date > datetime.date.today() if creation_date else False
+ if creation_date:
+ return creation_date > today
+ threshold_date = self.threshold_date()
+ if threshold_date:
+ return threshold_date > today
+ return False
def is_actionable(self) -> bool:
""" Return whether the task is actionable, i.e. whether it's not completed and doesn't have a future creation
@@ -70,7 +79,7 @@ class Task(object):
return not self.is_completed() and not self.is_future()
def is_overdue(self) -> bool:
- """ Return whether the taks is overdue, i.e. whether it has a due date in the past. """
+ """ Return whether the task is overdue, i.e. whether it has a due date in the past. """
due_date = self.due_date()
return due_date < datetime.date.today() if due_date else False
@@ -78,6 +87,11 @@ class Task(object):
""" Return the prefixed items in the task. """
return {match.group(1) for match in re.finditer(" {0}([^ ]+)".format(prefix), self.text)}
+ def __find_keyed_date(self, key: str) -> Optional[datetime.date]:
+ """ Find a key:value pair with the supplied key where the value is a date. """
+ match = re.search(r"\b{0}:{1}\b".format(key, self.iso_date_reg_exp), self.text)
+ return self.__create_date(match)
+
@staticmethod
def __create_date(match: Optional[typing.Match[str]]) -> Optional[datetime.date]:
""" Create a date from the match, if possible. """
|
fniessink/next-action
|
cc56f793b0e7f8b9bce0a11aeb5749f77126619d
|
diff --git a/tests/unittests/todotxt/test_task.py b/tests/unittests/todotxt/test_task.py
index 6172c77..e890535 100644
--- a/tests/unittests/todotxt/test_task.py
+++ b/tests/unittests/todotxt/test_task.py
@@ -87,7 +87,8 @@ class TaskPriorityTest(unittest.TestCase):
class CreationDateTest(unittest.TestCase):
- """ Unit tests for task creation dates. """
+ """ Unit tests for task creation dates. Next-action interprets creation dates in the future as threshold, or
+ start date. """
def test_no_creation_date(self):
""" Test that tasks have no creation date by default. """
@@ -121,6 +122,35 @@ class CreationDateTest(unittest.TestCase):
self.assertFalse(todotxt.Task("{0} Todo".format(datetime.date.today().isoformat())).is_future())
+class ThresholdDateTest(unittest.TestCase):
+ """ Unit tests for the threshold date of a task. The core todo.txt standard only defines creation date, but
+ threshold (t:<date>) seems to be a widely used convention. """
+
+ def test_no_threshold(self):
+ """ Test that tasks have no threshold by default. """
+ task = todotxt.Task("Todo")
+ self.assertEqual(None, task.threshold_date())
+ self.assertFalse(task.is_future())
+
+ def test_past_threshold(self):
+ """ Test a past threshold date. """
+ task = todotxt.Task("Todo t:2018-01-02")
+ self.assertEqual(datetime.date(2018, 1, 2), task.threshold_date())
+ self.assertFalse(task.is_future())
+
+ def test_future_threshold(self):
+ """ Test a future threshold date. """
+ task = todotxt.Task("Todo t:9999-01-01")
+ self.assertEqual(datetime.date(9999, 1, 1), task.threshold_date())
+ self.assertTrue(task.is_future())
+
+ def test_threshold_today(self):
+ """ Test a task with threshold today. """
+ task = todotxt.Task("Todo t:{0}".format(datetime.date.today().isoformat()))
+ self.assertEqual(datetime.date.today(), task.threshold_date())
+ self.assertFalse(task.is_future())
+
+
class DueDateTest(unittest.TestCase):
""" Unit tests for the due date of tasks. """
|
Support t: for threshold (start date) in todo.txt files
|
0.0
|
cc56f793b0e7f8b9bce0a11aeb5749f77126619d
|
[
"tests/unittests/todotxt/test_task.py::ThresholdDateTest::test_future_threshold",
"tests/unittests/todotxt/test_task.py::ThresholdDateTest::test_no_threshold",
"tests/unittests/todotxt/test_task.py::ThresholdDateTest::test_past_threshold",
"tests/unittests/todotxt/test_task.py::ThresholdDateTest::test_threshold_today"
] |
[
"tests/unittests/todotxt/test_task.py::TodoTest::test_task_repr",
"tests/unittests/todotxt/test_task.py::TodoTest::test_task_text",
"tests/unittests/todotxt/test_task.py::TodoContextTest::test_no_context",
"tests/unittests/todotxt/test_task.py::TodoContextTest::test_no_space_before_at_sign",
"tests/unittests/todotxt/test_task.py::TodoContextTest::test_one_context",
"tests/unittests/todotxt/test_task.py::TodoContextTest::test_two_contexts",
"tests/unittests/todotxt/test_task.py::TaskProjectTest::test_no_projects",
"tests/unittests/todotxt/test_task.py::TaskProjectTest::test_no_space_before_at_sign",
"tests/unittests/todotxt/test_task.py::TaskProjectTest::test_one_project",
"tests/unittests/todotxt/test_task.py::TaskProjectTest::test_two_projects",
"tests/unittests/todotxt/test_task.py::TaskPriorityTest::test_faulty_priorities",
"tests/unittests/todotxt/test_task.py::TaskPriorityTest::test_no_priority",
"tests/unittests/todotxt/test_task.py::TaskPriorityTest::test_priorities",
"tests/unittests/todotxt/test_task.py::TaskPriorityTest::test_priority_at_least",
"tests/unittests/todotxt/test_task.py::CreationDateTest::test_creation_date",
"tests/unittests/todotxt/test_task.py::CreationDateTest::test_creation_date_after_priority",
"tests/unittests/todotxt/test_task.py::CreationDateTest::test_invalid_creation_date",
"tests/unittests/todotxt/test_task.py::CreationDateTest::test_is_future_task",
"tests/unittests/todotxt/test_task.py::CreationDateTest::test_no_creation_date",
"tests/unittests/todotxt/test_task.py::CreationDateTest::test_no_space_after",
"tests/unittests/todotxt/test_task.py::CreationDateTest::test_single_digits",
"tests/unittests/todotxt/test_task.py::DueDateTest::test_due_today",
"tests/unittests/todotxt/test_task.py::DueDateTest::test_future_due_date",
"tests/unittests/todotxt/test_task.py::DueDateTest::test_invalid_date",
"tests/unittests/todotxt/test_task.py::DueDateTest::test_is_due",
"tests/unittests/todotxt/test_task.py::DueDateTest::test_no_due_date",
"tests/unittests/todotxt/test_task.py::DueDateTest::test_no_space_after",
"tests/unittests/todotxt/test_task.py::DueDateTest::test_past_due_date",
"tests/unittests/todotxt/test_task.py::DueDateTest::test_single_digits",
"tests/unittests/todotxt/test_task.py::TaskCompletionTest::test_completed",
"tests/unittests/todotxt/test_task.py::TaskCompletionTest::test_not_completed",
"tests/unittests/todotxt/test_task.py::TaskCompletionTest::test_space_after_x",
"tests/unittests/todotxt/test_task.py::TaskCompletionTest::test_x_must_be_lowercase",
"tests/unittests/todotxt/test_task.py::ActionableTest::test_completed_task",
"tests/unittests/todotxt/test_task.py::ActionableTest::test_default",
"tests/unittests/todotxt/test_task.py::ActionableTest::test_future_creation_date",
"tests/unittests/todotxt/test_task.py::ActionableTest::test_past_creation_date",
"tests/unittests/todotxt/test_task.py::ActionableTest::test_two_dates"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2018-06-07 20:08:06+00:00
|
apache-2.0
| 2,369 |
|
fniessink__next-action-112
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 66a03aa..38070b6 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,12 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/)
and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html).
+## [Unreleased] - 2018-06-09
+
+### Added
+
+- Default context and/or project filters can be configured in the configuration file. Closes #109.
+
## [0.17.0] - 2018-06-07
### Added
diff --git a/README.md b/README.md
index 1fa3797..e64a6e4 100644
--- a/README.md
+++ b/README.md
@@ -239,11 +239,11 @@ $ next-action --config-file docs/.next-action.cfg
To skip reading the default configuration file, and also not read an alternative configuration file, use the `--config-file` option without arguments.
-The configuration file format is [YAML](http://yaml.org). The options currently supported are which todo.txt files must be read, how many next actions should be shown, and the styling.
+The configuration file format is [YAML](http://yaml.org). The options currently supported are which todo.txt files must be read, how many next actions should be shown, output styling, and context and/or project filters.
#### Configuring a default todo.txt
-A default todo.txt file to use can be specified like this:
+A default todo.txt file to use can be specified like this in the configuration file:
```yaml
file: ~/Dropbox/todo.txt
@@ -272,7 +272,30 @@ Or you can have *Next-action* show all next actions:
all: True
```
-#### Configuring the minimum priority to show
+#### Limiting the tasks from which next actions are selected
+
+##### By contexts and/or projects
+
+You can limit the tasks from which the next action is selected by specifying contexts and/or projects to filter on, just like you would do on the command line:
+
+```yaml
+filters: -+FutureProject @work -@waiting
+```
+
+This would make *Next-action* by default select next actions from tasks with a `@work` context and without the `@waiting` context and not belonging to the `+FutureProject`.
+
+An alternative syntax is:
+
+```yaml
+filters:
+ - -+FutureProject
+ - '@work'
+ - -@waiting
+```
+
+Note that filters starting with `@` need to be in quotes. This is a [YAML restriction](http://yaml.org/spec/1.1/current.html#c-directive).
+
+##### By priority
The minimum priority of next action to show can be specified as well:
@@ -347,9 +370,9 @@ To run the unit tests:
```console
$ python -m unittest
-.........................................................................................................................................................................
+.....................................................................................................................................................................................
----------------------------------------------------------------------
-Ran 169 tests in 0.601s
+Ran 181 tests in 0.709s
OK
```
diff --git a/next_action/arguments/config.py b/next_action/arguments/config.py
index 6c6acdc..5cf2f99 100644
--- a/next_action/arguments/config.py
+++ b/next_action/arguments/config.py
@@ -39,8 +39,8 @@ def validate_config_file(config, config_filename: str, error: Callable[[str], No
schema = {
"file": {
"type": ["string", "list"],
- "schema": {
- "type": "string"}},
+ "schema": {"type": "string"}
+ },
"number": {
"type": "integer",
"min": 1,
@@ -54,6 +54,11 @@ def validate_config_file(config, config_filename: str, error: Callable[[str], No
"type": "string",
"allowed": [letter for letter in string.ascii_uppercase]
},
+ "filters": {
+ "type": ["string", "list"],
+ "regex": r"^\-?[@|\+]\S+(\s+\-?[@|\+]\S+)*",
+ "schema": {"type": "string", "regex": r"^\-?[@|\+]\S+"}
+ },
"reference": {
"type": "string",
"allowed": ["always", "never", "multiple"]
diff --git a/next_action/arguments/parser.py b/next_action/arguments/parser.py
index 7805962..a112145 100644
--- a/next_action/arguments/parser.py
+++ b/next_action/arguments/parser.py
@@ -2,6 +2,7 @@
import argparse
import datetime
+import re
import shutil
import string
import sys
@@ -170,6 +171,12 @@ class NextActionArgumentParser(argparse.ArgumentParser):
if self.arguments_not_specified("-p", "--priority"):
priority = config.get("priority", self.get_default("priority"))
setattr(namespace, "priority", priority)
+ filters = config.get("filters", [])
+ if isinstance(filters, str):
+ filters = re.split(r"\s", filters)
+ for configured_filter in filters:
+ if self.filter_not_specified(configured_filter):
+ getattr(namespace, "filters").append(configured_filter)
@staticmethod
def arguments_not_specified(*arguments: str) -> bool:
@@ -177,6 +184,13 @@ class NextActionArgumentParser(argparse.ArgumentParser):
return not any([command_line_arg.startswith(argument) for argument in arguments
for command_line_arg in sys.argv])
+ @staticmethod
+ def filter_not_specified(filtered: str) -> bool:
+ """ Return whether the context or project or its opposite were specified on the command line. """
+ prefix = "-"
+ opposite = filtered[len(prefix):] if filtered.startswith(prefix) else prefix + filtered
+ return not (filtered in sys.argv or opposite in sys.argv)
+
def fix_filenames(self, namespace: argparse.Namespace) -> None:
""" Fix the filenames. """
# Work around the issue that the "append" action doesn't overwrite defaults.
|
fniessink/next-action
|
6a1ddef824d5dbdd1151f4f34512a77d1a57ed88
|
diff --git a/tests/unittests/arguments/test_config.py b/tests/unittests/arguments/test_config.py
index 12e9a15..6fe669c 100644
--- a/tests/unittests/arguments/test_config.py
+++ b/tests/unittests/arguments/test_config.py
@@ -322,3 +322,91 @@ class ReferenceTest(ConfigTestCase):
[call(USAGE_MESSAGE),
call("next-action: error: ~/.next-action.cfg is invalid: reference: unallowed value invalid\n")],
mock_stderr_write.call_args_list)
+
+
+class FiltersTest(ConfigTestCase):
+ """ Unit tests for the filters parameter. """
+
+ @patch.object(sys, "argv", ["next-action"])
+ @patch.object(config, "open", mock_open(read_data="filters: +ImportantProject"))
+ def test_project(self):
+ """ Test that a valid project changes the filters argument. """
+ self.assertEqual(["+ImportantProject"], parse_arguments()[1].filters)
+
+ @patch.object(sys, "argv", ["next-action"])
+ @patch.object(config, "open", mock_open(read_data="filters: +ImportantProject +SideProject"))
+ def test_projects(self):
+ """ Test that multiple valid projects change the filters argument. """
+ self.assertEqual(["+ImportantProject", "+SideProject"], parse_arguments()[1].filters)
+
+ @patch.object(sys, "argv", ["next-action"])
+ @patch.object(config, "open", mock_open(read_data="filters: '@work'"))
+ def test_context(self):
+ """ Test that a valid context changes the filters argument. """
+ self.assertEqual(["@work"], parse_arguments()[1].filters)
+
+ @patch.object(sys, "argv", ["next-action"])
+ @patch.object(config, "open", mock_open(read_data="filters: '@work @desk'"))
+ def test_contexts(self):
+ """ Test that valid contexts change the filters argument. """
+ self.assertEqual(["@work", "@desk"], parse_arguments()[1].filters)
+
+ @patch.object(sys, "argv", ["next-action"])
+ @patch.object(config, "open", mock_open(read_data="filters:\n- '@work'\n- -@waiting\n"))
+ def test_context_list(self):
+ """ Test that a valid context changes the filters argument. """
+ self.assertEqual(["@work", "-@waiting"], parse_arguments()[1].filters)
+
+ @patch.object(sys, "argv", ["next-action"])
+ @patch.object(config, "open", mock_open(read_data="filters: -+SideProject"))
+ def test_excluded_project(self):
+ """ Test that an excluded valid project changes the filters argument. """
+ self.assertEqual(["-+SideProject"], parse_arguments()[1].filters)
+
+ @patch.object(sys, "argv", ["next-action"])
+ @patch.object(config, "open", mock_open(read_data="filters: -@home"))
+ def test_excluded_context(self):
+ """ Test that an excluded valid context changes the filters argument. """
+ self.assertEqual(["-@home"], parse_arguments()[1].filters)
+
+ @patch.object(sys, "argv", ["next-action", "+ImportantProject"])
+ @patch.object(config, "open", mock_open(read_data="filters: +ImportantProject"))
+ def test_same_project(self):
+ """ Test that the configuration is ignored when the command line specifies the same project. """
+ self.assertEqual(["+ImportantProject"], parse_arguments()[1].filters)
+
+ @patch.object(sys, "argv", ["next-action", "+ImportantProject"])
+ @patch.object(config, "open", mock_open(read_data="filters: -+ImportantProject"))
+ def test_inverse_project(self):
+ """ Test that the configuration is ignored when the command line specifies the same project. """
+ self.assertEqual(["+ImportantProject"], parse_arguments()[1].filters)
+
+ @patch.object(sys, "argv", ["next-action", "+ImportantProject"])
+ @patch.object(config, "open", mock_open(read_data="filters: -+ImportantProject @work"))
+ def test_ignore_project_not_context(self):
+ """ Test that the configuration is ignored when the command line specifies the same project. """
+ self.assertEqual(["+ImportantProject", "@work"], parse_arguments()[1].filters)
+
+ @patch.object(sys, "argv", ["next-action"])
+ @patch.object(config, "open", mock_open(read_data="filters:\n- invalid\n"))
+ @patch.object(sys.stderr, "write")
+ def test_invalid_filter_list(self, mock_stderr_write):
+ """ Test that an invalid filter raises an error. """
+ self.assertRaises(SystemExit, parse_arguments)
+ regex = r"^\-?[@|\+]\S+"
+ self.assertEqual(
+ [call(USAGE_MESSAGE), call("next-action: error: ~/.next-action.cfg is invalid: filters: 0: "
+ "value does not match regex '{0}'\n".format(regex))],
+ mock_stderr_write.call_args_list)
+
+ @patch.object(sys, "argv", ["next-action"])
+ @patch.object(config, "open", mock_open(read_data="filters: invalid\n"))
+ @patch.object(sys.stderr, "write")
+ def test_invalid_filter_string(self, mock_stderr_write):
+ """ Test that an invalid filter raises an error. """
+ self.assertRaises(SystemExit, parse_arguments)
+ regex = r"^\-?[@|\+]\S+(\s+\-?[@|\+]\S+)*"
+ self.assertEqual(
+ [call(USAGE_MESSAGE), call("next-action: error: ~/.next-action.cfg is invalid: filters: "
+ "value does not match regex '{0}'\n".format(regex))],
+ mock_stderr_write.call_args_list)
|
Allow for configuring context or project filters in the configuration file
This would allow for hiding certain contexts by default:
```yaml
filter: -@waiting
```
As for other options, command-line options should override configured options.
|
0.0
|
6a1ddef824d5dbdd1151f4f34512a77d1a57ed88
|
[
"tests/unittests/arguments/test_config.py::FiltersTest::test_context",
"tests/unittests/arguments/test_config.py::FiltersTest::test_context_list",
"tests/unittests/arguments/test_config.py::FiltersTest::test_contexts",
"tests/unittests/arguments/test_config.py::FiltersTest::test_excluded_context",
"tests/unittests/arguments/test_config.py::FiltersTest::test_excluded_project",
"tests/unittests/arguments/test_config.py::FiltersTest::test_ignore_project_not_context",
"tests/unittests/arguments/test_config.py::FiltersTest::test_invalid_filter_list",
"tests/unittests/arguments/test_config.py::FiltersTest::test_invalid_filter_string",
"tests/unittests/arguments/test_config.py::FiltersTest::test_inverse_project",
"tests/unittests/arguments/test_config.py::FiltersTest::test_project",
"tests/unittests/arguments/test_config.py::FiltersTest::test_projects",
"tests/unittests/arguments/test_config.py::FiltersTest::test_same_project"
] |
[
"tests/unittests/arguments/test_config.py::ConfigFileTest::test_empty_file",
"tests/unittests/arguments/test_config.py::ConfigFileTest::test_error_opening",
"tests/unittests/arguments/test_config.py::ConfigFileTest::test_error_parsing",
"tests/unittests/arguments/test_config.py::ConfigFileTest::test_file_not_found",
"tests/unittests/arguments/test_config.py::ConfigFileTest::test_invalid_document",
"tests/unittests/arguments/test_config.py::ConfigFileTest::test_missing_default_config",
"tests/unittests/arguments/test_config.py::ConfigFileTest::test_no_file_key",
"tests/unittests/arguments/test_config.py::ConfigFileTest::test_skip_config",
"tests/unittests/arguments/test_config.py::ConfigFileTest::test_write_config",
"tests/unittests/arguments/test_config.py::FilenameTest::test_cli_takes_precedence",
"tests/unittests/arguments/test_config.py::FilenameTest::test_invalid_filename",
"tests/unittests/arguments/test_config.py::FilenameTest::test_valid_and_invalid",
"tests/unittests/arguments/test_config.py::FilenameTest::test_valid_file",
"tests/unittests/arguments/test_config.py::FilenameTest::test_valid_files",
"tests/unittests/arguments/test_config.py::NumberTest::test_all_and_number",
"tests/unittests/arguments/test_config.py::NumberTest::test_all_false",
"tests/unittests/arguments/test_config.py::NumberTest::test_all_true",
"tests/unittests/arguments/test_config.py::NumberTest::test_argument_all_overrides",
"tests/unittests/arguments/test_config.py::NumberTest::test_argument_nr_overrides",
"tests/unittests/arguments/test_config.py::NumberTest::test_cli_takes_precedence",
"tests/unittests/arguments/test_config.py::NumberTest::test_invalid_number",
"tests/unittests/arguments/test_config.py::NumberTest::test_valid_number",
"tests/unittests/arguments/test_config.py::NumberTest::test_zero",
"tests/unittests/arguments/test_config.py::ConfigStyleTest::test_cancel_style",
"tests/unittests/arguments/test_config.py::ConfigStyleTest::test_invalid_style",
"tests/unittests/arguments/test_config.py::ConfigStyleTest::test_override_style",
"tests/unittests/arguments/test_config.py::ConfigStyleTest::test_valid_style",
"tests/unittests/arguments/test_config.py::PriorityTest::test_cancel_priority",
"tests/unittests/arguments/test_config.py::PriorityTest::test_invalid_priority",
"tests/unittests/arguments/test_config.py::PriorityTest::test_override_priority",
"tests/unittests/arguments/test_config.py::PriorityTest::test_override_short",
"tests/unittests/arguments/test_config.py::PriorityTest::test_valid_priority",
"tests/unittests/arguments/test_config.py::ReferenceTest::test_invalid_priority",
"tests/unittests/arguments/test_config.py::ReferenceTest::test_override",
"tests/unittests/arguments/test_config.py::ReferenceTest::test_valid_reference"
] |
{
"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-06-09 19:11:53+00:00
|
apache-2.0
| 2,370 |
|
fniessink__next-action-124
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index df99d47..043401f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,7 +9,8 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.
### Added
-- Next to `p:parent_task` it's also possible to use `before:parent_task` for better readability.
+- Next to `p:parent_task` it's also possible to use `before:parent_task` to specifiy task dependencies.
+- In addition to `before:other_task`, it's also possible to use `after:other_task` to specify task dependencies.
## [1.2.0] - 2018-06-16
diff --git a/README.md b/README.md
index d58af14..a8d5551 100644
--- a/README.md
+++ b/README.md
@@ -214,33 +214,34 @@ Or show all next actions, e.g. for a specific context:
$ next-action --all @store
(B) Buy paint to +PaintHouse @store @weekend
(G) Buy wood for new +DogHouse @store
-Buy groceries @store +DinnerParty p:meal
+Buy groceries @store +DinnerParty before:meal
```
Note again that completed tasks, tasks with a future creation or threshold date, and blocked tasks are never shown since they can't be a next action.
### Task dependencies
-*Next-action* takes task dependencies into account when determining the next actions. For example, that cooking a meal depends on buying groceries can be specified in the todo.txt file as follows:
+*Next-action* takes task dependencies into account when determining the next actions. For example, that cooking a meal depends on buying groceries and that doing the dishes comes after cooking the meal can be specified as follows:
```text
-Buy groceries @store +DinnerParty p:meal
+Buy groceries @store +DinnerParty before:meal
Cook meal @home +DinnerParty id:meal
+Do the dishes @home +DinnerParty after:meal
```
-`Buy groceries` has `Cook meal` as its `p`-parent task. This means that buying groceries blocks cooking the meal; cooking can't be done until buying the groceries has been completed:
+This means that buying groceries blocks cooking the meal; cooking, and thus doing the dishes as well, can't be done until buying the groceries has been completed:
```console
$ next-action --all +DinnerParty
-Buy groceries @store +DinnerParty p:meal
+Buy groceries @store +DinnerParty before:meal
```
Notes:
- The ids can be any string without whitespace.
-- Instead of `p` you can also use `before` for better readability, e.g. `Do this before:that`.
-- A parent task can have multiple child tasks, meaning that the parent task remains blocked until all children are completed.
-- A child task can block multiple parents by repeating the parent, e.g. `Buy groceries before:cooking and before:invites`.
+- Instead of `before` you can also use `p` (for "parent") because some other tools that work with *Todo.txt* files use that.
+- A task can come before multiple other tasks by repeating the before key, e.g. `Buy groceries before:cooking and before:sending_invites`.
+- A task can come after multiple other tasks by repeating the after key, e.g. `Eat meal after:cooking and after:setting_the_table`.
### Styling the output
@@ -422,7 +423,7 @@ To run the unit tests:
$ python -m unittest
.............................................................................................................................................................................................................................
----------------------------------------------------------------------
-Ran 221 tests in 1.758s
+Ran 221 tests in 1.637s
OK
```
@@ -435,7 +436,7 @@ To create the unit test coverage report run the unit tests under coverage with:
$ coverage run --branch -m unittest
.............................................................................................................................................................................................................................
----------------------------------------------------------------------
-Ran 221 tests in 4.562s
+Ran 221 tests in 2.085s
OK
```
@@ -447,7 +448,7 @@ $ coverage report --fail-under=100 --omit=".venv/*" --skip-covered
Name Stmts Miss Branch BrPart Cover
-----------------------------------------
-----------------------------------------
-TOTAL 1175 0 150 0 100%
+TOTAL 1188 0 150 0 100%
25 files skipped due to complete coverage.
```
diff --git a/docs/todo.txt b/docs/todo.txt
index 0d9176c..36c7342 100644
--- a/docs/todo.txt
+++ b/docs/todo.txt
@@ -7,8 +7,9 @@ Borrow ladder from the neighbors +PaintHouse @home
Buy flowers due:2018-02-14
(L) Pay June invoice @home due:2018-06-28
(K) Pay July invoice @home due:2018-07-28
-Buy groceries @store +DinnerParty p:meal
+Buy groceries @store +DinnerParty before:meal
Cook meal @home +DinnerParty id:meal
+Do the dishes @home +DinnerParty after:meal
x This is a completed task
9999-01-01 Start preparing for five-digit years
Start preparing for emigration to Mars t:3000-01-01
diff --git a/next_action/todotxt/task.py b/next_action/todotxt/task.py
index 94afcd2..63eb8c9 100644
--- a/next_action/todotxt/task.py
+++ b/next_action/todotxt/task.py
@@ -85,20 +85,21 @@ class Task(object):
def is_blocked(self, tasks: Iterable["Task"]) -> bool:
""" Return whether a task is blocked, i.e. whether it has uncompleted child tasks. """
- return any([task for task in tasks if not task.is_completed() and self.task_id() in task.parent_ids()])
+ return any([task for task in tasks if not task.is_completed() and
+ (self.task_id() in task.parent_ids() or task.task_id() in self.child_ids())])
- def task_id(self) -> str:
- """ Return the id of the task. """
- match = re.search(r"\bid:(\S+)\b", self.text)
- return match.group(1) if match else ""
+ def child_ids(self) -> Set[str]:
+ """ Return the ids of the child tasks. """
+ return {match.group(1) for match in re.finditer(r"\bafter:(\S+)\b", self.text)}
def parent_ids(self) -> Set[str]:
""" Return the ids of the parent tasks. """
return {match.group(2) for match in re.finditer(r"\b(p|before):(\S+)\b", self.text)}
- def parents(self, tasks: Iterable["Task"]) -> Iterable["Task"]:
- """ Return the parent tasks. """
- return [task for task in tasks if task.task_id() in self.parent_ids()]
+ def task_id(self) -> str:
+ """ Return the id of the task. """
+ match = re.search(r"\bid:(\S+)\b", self.text)
+ return match.group(1) if match else ""
def __prefixed_items(self, prefix: str) -> Set[str]:
""" Return the prefixed items in the task. """
|
fniessink/next-action
|
92321b0ee48848310993608984f631be51cd5dc9
|
diff --git a/tests/unittests/todotxt/test_task.py b/tests/unittests/todotxt/test_task.py
index 670ed2a..38ab3eb 100644
--- a/tests/unittests/todotxt/test_task.py
+++ b/tests/unittests/todotxt/test_task.py
@@ -251,90 +251,103 @@ class ActionableTest(unittest.TestCase):
self.assertFalse(todotxt.Task("x 2018-01-01 2018-01-01 Todo").is_actionable())
-class ParentTest(unittest.TestCase):
- """ Unit tests for parent/child relations. """
-
- parent_keys = strategies.sampled_from(["p", "before"])
+class DependenciesTest(unittest.TestCase):
+ """ Unit tests for dependency relations. """
+
+ before_keys = strategies.sampled_from(["p", "before"])
+
+ @given(strategies.sampled_from(["Todo", "Todo id:", "Todo id:id", "Todo p:", "Todo p:id",
+ "Todo before:", "Todo before:id", "Todo after:", "Todo after:id"]))
+ def test_task_without_dependencies(self, todo_text):
+ """ Test that a task without dependencies is not blocked. """
+ task = todotxt.Task(todo_text)
+ self.assertFalse(task.is_blocked([]))
+ self.assertFalse(task.is_blocked([task, todotxt.Task("Another task")]))
+
+ @given(before_keys)
+ def test_one_before_another(self, before_key):
+ """ Test that a task specified to be done before another task blocks the latter. """
+ self.assertTrue(todotxt.Task("After id:1").is_blocked([todotxt.Task("Before {0}:1".format(before_key))]))
+
+ def test_one_after_another(self):
+ """ Test that a task specified to be done after another task blocks the first. """
+ self.assertTrue(todotxt.Task("After after:1").is_blocked([todotxt.Task("Before id:1")]))
+
+ @given(before_keys)
+ def test_one_before_two(self, before_key):
+ """ Test that a task that is specified to be done before two other tasks blocks both tasks. """
+ before = todotxt.Task("Before {0}:1 {0}:2".format(before_key))
+ self.assertTrue(todotxt.Task("After id:1").is_blocked([before]))
+ self.assertTrue(todotxt.Task("After id:2").is_blocked([before]))
+
+ def test_one_after_two(self):
+ """ Test that a task that is specified to be done after two other tasks is blocked by both. """
+ before1 = todotxt.Task("Before 1 id:1")
+ before2 = todotxt.Task("Before 2 id:2")
+ after = todotxt.Task("After after:1 after:2")
+ self.assertTrue(after.is_blocked([before1, before2]))
+ self.assertTrue(after.is_blocked([before1]))
+ self.assertTrue(after.is_blocked([before2]))
+
+ @given(before_keys)
+ def test_two_before_one(self, before_key):
+ """ Test that a task that is specified to be done after two other tasks is blocked by both. """
+ before1 = todotxt.Task("Before 1 {0}:1".format(before_key))
+ before2 = todotxt.Task("Before 2 {0}:1".format(before_key))
+ after = todotxt.Task("After id:1")
+ self.assertTrue(after.is_blocked([before1, before2]))
+ self.assertTrue(after.is_blocked([before1]))
+ self.assertTrue(after.is_blocked([before2]))
+
+ def test_two_after_one(self):
+ """ Test that two tasks that are specified to be done after one other task are both blocked. """
+ before = todotxt.Task("Before id:before")
+ after1 = todotxt.Task("After 1 after:before")
+ after2 = todotxt.Task("After 2 after:before")
+ self.assertTrue(after1.is_blocked([before]))
+ self.assertTrue(after2.is_blocked([before]))
+
+ @given(before_keys)
+ def test_completed_before_task(self, before_key):
+ """ Test that a task is not blocked by a completed task. """
+ after = todotxt.Task("After id:1")
+ before = todotxt.Task("Before {0}:1".format(before_key))
+ completed_before = todotxt.Task("x Before {0}:1".format(before_key))
+ self.assertFalse(after.is_blocked([completed_before]))
+ self.assertTrue(after.is_blocked([completed_before, before]))
+
+ def test_after_completed_task(self):
+ """ Test that a task is not blocked if it is specified to be done after a completed task. """
+ after = todotxt.Task("After after:before after:completed_before")
+ before = todotxt.Task("Before id:before")
+ completed_before = todotxt.Task("x Before id:completed_before")
+ self.assertFalse(after.is_blocked([completed_before]))
+ self.assertTrue(after.is_blocked([completed_before, before]))
+
+ @given(before_keys)
+ def test_self_before_self(self, before_key):
+ """ Test that a task can be blocked by itself. This doesn't make sense, but we're not in the business
+ of validating todo.txt files. """
+ task = todotxt.Task("Todo id:1 {0}:1".format(before_key))
+ self.assertTrue(task.is_blocked([task]))
- def test_default(self):
- """ Test that a default task has no parents. """
- default_task = todotxt.Task("Todo")
- self.assertEqual(set(), default_task.parent_ids())
- self.assertEqual("", default_task.task_id())
- self.assertFalse(default_task.is_blocked([]))
- self.assertFalse(default_task.is_blocked([default_task]))
-
- def test_missing_id(self):
- """ Test id key without ids. """
- self.assertEqual("", todotxt.Task("Todo id:").task_id())
-
- @given(parent_keys)
- def test_missing_values(self, parent_key):
- """ Test parent key without id. """
- self.assertEqual(set(), todotxt.Task("Todo {0}:".format(parent_key)).parent_ids())
-
- @given(parent_keys)
- def test_one_parent(self, parent_key):
- """ Test that a task with a parent id return the correct id. """
- self.assertEqual({"1"}, todotxt.Task("Todo {0}:1".format(parent_key)).parent_ids())
-
- @given(parent_keys)
- def test_two_parents(self, parent_key):
- """ Test that a task with two parent ids return all ids. """
- self.assertEqual({"1", "123a"}, todotxt.Task("Todo {0}:1 {0}:123a".format(parent_key)).parent_ids())
-
- def test_task_id(self):
- """ Test a task id. """
- self.assertEqual("foo", todotxt.Task("Todo id:foo").task_id())
-
- @given(parent_keys)
- def test_get_parent(self, parent_key):
- """ Test getting a task's parent. """
- parent = todotxt.Task("Parent id:1")
- child = todotxt.Task("Child {0}:1".format(parent_key))
- self.assertEqual([parent], child.parents([child, parent]))
-
- @given(parent_keys)
- def test_get_multiple_parents(self, parent_key):
- """ Test getting a task's mutiple parents. """
- parent1 = todotxt.Task("Parent 1 id:1")
- parent2 = todotxt.Task("Parent 2 id:2")
- child = todotxt.Task("Child {0}:1 {0}:2".format(parent_key))
- self.assertEqual([parent1, parent2], child.parents([child, parent1, parent2]))
-
- @given(parent_keys)
- def test_is_blocked(self, parent_key):
- """ Test that a task with children is blocked. """
- parent = todotxt.Task("Parent id:1")
- child = todotxt.Task("Child {0}:1".format(parent_key))
- self.assertTrue(parent.is_blocked([child, parent]))
-
- @given(parent_keys)
- def test_completed_child(self, parent_key):
- """ Test that a task with completed children only is not blocked. """
- parent = todotxt.Task("Parent id:1")
- child = todotxt.Task("x Child {0}:1".format(parent_key))
- self.assertFalse(parent.is_blocked([child, parent]))
-
- @given(parent_keys)
- def test_is_blocked_by_mix(self, parent_key):
- """ Test that a task with completed children and uncompleted children is blocked. """
- parent = todotxt.Task("Parent id:1")
- child1 = todotxt.Task("Child 1 {0}:1".format(parent_key))
- child2 = todotxt.Task("x Child 2 {0}:1".format(parent_key))
- self.assertTrue(parent.is_blocked([child1, child2, parent]))
-
- @given(parent_keys)
- def test_is_blocked_by_self(self, parent_key):
+ def test_self_after_self(self):
""" Test that a task can be blocked by itself. This doesn't make sense, but we're not in the business
of validating todo.txt files. """
- parent = todotxt.Task("Parent id:1 {0}:1".format(parent_key))
- self.assertTrue(parent.is_blocked([parent]))
+ task = todotxt.Task("Todo id:1 after:1")
+ self.assertTrue(task.is_blocked([task]))
+
+ @given(before_keys)
+ def test_self_before_self_indirect(self, before_key):
+ """ Test that a task can be blocked by a second task that is blocked by the first task. This doesn't make sense,
+ but we're not in the business of validating todo.txt files. """
+ task1 = todotxt.Task("Task 1 id:1 {0}:2".format(before_key))
+ task2 = todotxt.Task("Task 2 id:2 {0}:1".format(before_key))
+ self.assertTrue(task1.is_blocked([task1, task2]))
- @given(parent_keys)
- def test_block_circle(self, parent_key):
- """ Test that a task can be blocked by its child who is blocked by the task. This doesn't make sense,
+ def test_self_after_self_indirect(self):
+ """ Test that a task can be blocked by a second task that is blocked by the first task. This doesn't make sense,
but we're not in the business of validating todo.txt files. """
- task1 = todotxt.Task("Task 1 id:1 {0}:2".format(parent_key))
- task2 = todotxt.Task("Task 2 id:2 {0}:1".format(parent_key))
+ task1 = todotxt.Task("Task 1 id:1 after:2")
+ task2 = todotxt.Task("Task 2 id:2 after:1")
self.assertTrue(task1.is_blocked([task1, task2]))
|
Allow for after:<id> key/value pairs to specify dependencies
|
0.0
|
92321b0ee48848310993608984f631be51cd5dc9
|
[
"tests/unittests/todotxt/test_task.py::DependenciesTest::test_one_after_another",
"tests/unittests/todotxt/test_task.py::DependenciesTest::test_two_after_one",
"tests/unittests/todotxt/test_task.py::DependenciesTest::test_self_after_self",
"tests/unittests/todotxt/test_task.py::DependenciesTest::test_self_after_self_indirect",
"tests/unittests/todotxt/test_task.py::DependenciesTest::test_after_completed_task",
"tests/unittests/todotxt/test_task.py::DependenciesTest::test_one_after_two"
] |
[
"tests/unittests/todotxt/test_task.py::ActionableTest::test_future_creation_date",
"tests/unittests/todotxt/test_task.py::ActionableTest::test_completed_task",
"tests/unittests/todotxt/test_task.py::ActionableTest::test_default",
"tests/unittests/todotxt/test_task.py::ActionableTest::test_past_creation_date",
"tests/unittests/todotxt/test_task.py::ActionableTest::test_two_dates",
"tests/unittests/todotxt/test_task.py::TaskPriorityTest::test_faulty_priorities",
"tests/unittests/todotxt/test_task.py::TaskPriorityTest::test_no_priority",
"tests/unittests/todotxt/test_task.py::TaskPriorityTest::test_priorities",
"tests/unittests/todotxt/test_task.py::TaskPriorityTest::test_priority_at_least",
"tests/unittests/todotxt/test_task.py::DueDateTest::test_due_today",
"tests/unittests/todotxt/test_task.py::DueDateTest::test_past_due_date",
"tests/unittests/todotxt/test_task.py::DueDateTest::test_invalid_date",
"tests/unittests/todotxt/test_task.py::DueDateTest::test_is_due",
"tests/unittests/todotxt/test_task.py::DueDateTest::test_no_due_date",
"tests/unittests/todotxt/test_task.py::DueDateTest::test_future_due_date",
"tests/unittests/todotxt/test_task.py::DueDateTest::test_no_space_after",
"tests/unittests/todotxt/test_task.py::DueDateTest::test_single_digits",
"tests/unittests/todotxt/test_task.py::CreationDateTest::test_single_digits",
"tests/unittests/todotxt/test_task.py::CreationDateTest::test_is_future_task",
"tests/unittests/todotxt/test_task.py::CreationDateTest::test_invalid_creation_date",
"tests/unittests/todotxt/test_task.py::CreationDateTest::test_no_creation_date",
"tests/unittests/todotxt/test_task.py::CreationDateTest::test_creation_date_after_priority",
"tests/unittests/todotxt/test_task.py::CreationDateTest::test_creation_date",
"tests/unittests/todotxt/test_task.py::CreationDateTest::test_no_space_after",
"tests/unittests/todotxt/test_task.py::ThresholdDateTest::test_past_threshold",
"tests/unittests/todotxt/test_task.py::ThresholdDateTest::test_future_threshold",
"tests/unittests/todotxt/test_task.py::ThresholdDateTest::test_no_threshold",
"tests/unittests/todotxt/test_task.py::ThresholdDateTest::test_threshold_today",
"tests/unittests/todotxt/test_task.py::TaskProjectTest::test_no_projects",
"tests/unittests/todotxt/test_task.py::TaskProjectTest::test_no_space_before_at_sign",
"tests/unittests/todotxt/test_task.py::TaskProjectTest::test_one_project",
"tests/unittests/todotxt/test_task.py::TaskProjectTest::test_two_projects",
"tests/unittests/todotxt/test_task.py::TodoContextTest::test_no_space_before_at_sign",
"tests/unittests/todotxt/test_task.py::TodoContextTest::test_one_context",
"tests/unittests/todotxt/test_task.py::TodoContextTest::test_no_context",
"tests/unittests/todotxt/test_task.py::TodoContextTest::test_two_contexts",
"tests/unittests/todotxt/test_task.py::DependenciesTest::test_one_before_another",
"tests/unittests/todotxt/test_task.py::DependenciesTest::test_self_before_self_indirect",
"tests/unittests/todotxt/test_task.py::DependenciesTest::test_completed_before_task",
"tests/unittests/todotxt/test_task.py::DependenciesTest::test_two_before_one",
"tests/unittests/todotxt/test_task.py::DependenciesTest::test_one_before_two",
"tests/unittests/todotxt/test_task.py::DependenciesTest::test_self_before_self",
"tests/unittests/todotxt/test_task.py::DependenciesTest::test_task_without_dependencies",
"tests/unittests/todotxt/test_task.py::TodoTest::test_task_repr",
"tests/unittests/todotxt/test_task.py::TodoTest::test_task_text",
"tests/unittests/todotxt/test_task.py::TaskCompletionTest::test_space_after_x",
"tests/unittests/todotxt/test_task.py::TaskCompletionTest::test_not_completed",
"tests/unittests/todotxt/test_task.py::TaskCompletionTest::test_x_must_be_lowercase",
"tests/unittests/todotxt/test_task.py::TaskCompletionTest::test_completed"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2018-06-19 21:26:06+00:00
|
apache-2.0
| 2,371 |
|
fniessink__next-action-129
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f0df435..3232b44 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.
### Added
+- Tasks are considered to have a priority that's the maximum of their own priority and the priorities of the task(s) they block, recursively. Closes #114.
- Tasks are considered to have a due date that's the minimum of their own due date and the due dates of the task(s) they block, recursively. Closes #115.
## [1.3.0] - 2018-06-19
diff --git a/README.md b/README.md
index d259760..67e9fc7 100644
--- a/README.md
+++ b/README.md
@@ -108,7 +108,7 @@ $ next-action
The next action is determined using priority. Due date is considered after priority, with tasks due earlier getting precedence over tasks due later. Creation date is considered after due date, with older tasks getting precedence over newer tasks. Finally, tasks that belong to more projects get precedence over tasks that belong to fewer projects.
-Several types of tasks are not considered when determining the next action:
+Several types of tasks can not be a next action:
- completed tasks (~~`x This is a completed task`~~),
- tasks with a creation date in the future (`9999-01-01 Start preparing for five-digit years`),
@@ -239,7 +239,7 @@ Buy groceries @store +DinnerParty before:meal
Take out the garbage @home +DinnerParty due:2018-07-02
```
-Note how buying the groceries comes before taking out the garbage even though buying the groceries has no due date and taking out the garbage does. As buying groceries has to be done before cooking the meal and cooking the meal does have a due date, buying groceries takes on the same due date as cooking the meal.
+Note how buying the groceries comes before taking out the garbage even though buying the groceries has no due date and taking out the garbage does. As buying groceries has to be done before cooking the meal and cooking the meal does have a due date, buying groceries takes on the same due date as cooking the meal. Priority is taken into account in a similar way.
Additional notes:
@@ -247,7 +247,9 @@ Additional notes:
- Instead of `before` you can also use `p` (for "parent") because some other tools that work with *Todo.txt* files use that.
- A task can block multiple other tasks by repeating the before key, e.g. `Buy groceries before:cooking and before:sending_invites`.
- A task can be blocked by multiple other tasks by repeating the after key, e.g. `Eat meal after:cooking and after:setting_the_table`.
-- If a task blocks one or more tasks, the blocking task is considered to have a due date that's the minimum of its own due date and the due dates of the tasks it's blocking.
+- If a task blocks one or more tasks, the blocking task takes on the priority and due date of the tasks it is blocking:
+ - the blocking task is considered to have a priority that is the maximum of its own priority and the priorities of the tasks it is blocking, and
+ - the blocking task is considered to have a due date that is the minimum of its own due date and the due dates of the tasks it is blocking.
### Styling the output
@@ -427,9 +429,9 @@ To run the unit tests:
```console
$ python -m unittest
-.................................................................................................................................................................................................................................
+.....................................................................................................................................................................................................................................
----------------------------------------------------------------------
-Ran 225 tests in 1.891s
+Ran 229 tests in 2.728s
OK
```
@@ -440,9 +442,9 @@ To create the unit test coverage report run the unit tests under coverage with:
```console
$ coverage run --branch -m unittest
-.................................................................................................................................................................................................................................
+.....................................................................................................................................................................................................................................
----------------------------------------------------------------------
-Ran 225 tests in 2.567s
+Ran 229 tests in 3.794s
OK
```
@@ -454,7 +456,7 @@ $ coverage report --fail-under=100 --omit=".venv/*" --skip-covered
Name Stmts Miss Branch BrPart Cover
-----------------------------------------
-----------------------------------------
-TOTAL 1254 0 154 0 100%
+TOTAL 1282 0 160 0 100%
25 files skipped due to complete coverage.
```
diff --git a/next_action/todotxt/task.py b/next_action/todotxt/task.py
index 1d238db..5f9d794 100644
--- a/next_action/todotxt/task.py
+++ b/next_action/todotxt/task.py
@@ -3,7 +3,7 @@
import datetime
import re
import typing
-from typing import Optional, Sequence, Set
+from typing import List, Optional, Sequence, Set
class Task(object):
@@ -30,7 +30,9 @@ class Task(object):
def priority(self) -> Optional[str]:
""" Return the priority of the task """
match = re.match(r"\(([A-Z])\) ", self.text)
- return match.group(1) if match else None
+ priorities: List[Optional[str]] = [match.group(1)] if match else []
+ priorities.extend([blocked_task.priority() for blocked_task in self.__blocked_tasks()])
+ return min(priorities, default=None, key=lambda priority: priority or "ZZZ")
def priority_at_least(self, min_priority: Optional[str]) -> bool:
""" Return whether the priority of task is at least the given priority. """
@@ -52,9 +54,9 @@ class Task(object):
def due_date(self) -> Optional[datetime.date]:
""" Return the due date of the task. """
- due_dates = [self.__find_keyed_date("due") or datetime.date.max]
- due_dates.extend([blocking.due_date() or datetime.date.max for blocking in self.__blocking()])
- return None if min(due_dates) == datetime.date.max else min(due_dates)
+ due_dates = [self.__find_keyed_date("due")]
+ due_dates.extend([blocked_task.due_date() for blocked_task in self.__blocked_tasks()])
+ return min(due_dates, default=None, key=lambda due_date: due_date or datetime.date.max)
def is_due(self, due_date: datetime.date) -> bool:
""" Return whether the task is due on or before the given due date. """
@@ -104,7 +106,7 @@ class Task(object):
match = re.search(r"\bid:(\S+)\b", self.text)
return match.group(1) if match else ""
- def __blocking(self) -> Sequence["Task"]:
+ def __blocked_tasks(self) -> Sequence["Task"]:
""" Return the tasks this task is blocking. """
return [task for task in self.tasks if not task.is_completed() and
(task.task_id() in self.parent_ids() or self.task_id() in task.child_ids())]
|
fniessink/next-action
|
4b78879e73bb47641ce11db77d4834b058883b26
|
diff --git a/tests/unittests/test_pick_action.py b/tests/unittests/test_pick_action.py
index 5bb83a6..559e236 100644
--- a/tests/unittests/test_pick_action.py
+++ b/tests/unittests/test_pick_action.py
@@ -220,16 +220,6 @@ class DueTasks(PickActionTestCase):
self.assertEqual([overdue, future_duedate],
pick_action.next_actions([no_duedate, future_duedate, overdue], self.namespace))
- def test_due_date_of_blocked_task(self):
- """ Test that a task that blocks a task with an earlier due date takes precendence. """
- tasks = todotxt.Tasks()
- due_first_but_blocked = todotxt.Task("Task id:1 due:2018-01-01", tasks=tasks)
- blocking_task = todotxt.Task("Blocking before:1", tasks=tasks)
- due_second = todotxt.Task("Task due:2018-02-01", tasks=tasks)
- tasks.extend([due_first_but_blocked, blocking_task, due_second])
- self.namespace.due = datetime.date.max
- self.assertEqual([blocking_task, due_second], pick_action.next_actions(tasks, self.namespace))
-
class MinimimPriorityTest(PickActionTest):
""" Unit test for the mininum priority filter. """
@@ -282,3 +272,21 @@ class BlockedTasksTest(PickActionTest):
child = todotxt.Task("Child 1 p:1 p:2", tasks=tasks)
tasks.extend([parent1, parent2, child])
self.assertEqual([child], pick_action.next_actions(tasks, self.namespace))
+
+ def test_due_date_of_blocked_task(self):
+ """ Test that a task that blocks a task with an earlier due date takes precendence. """
+ tasks = todotxt.Tasks()
+ due_first_but_blocked = todotxt.Task("Task id:1 due:2018-01-01", tasks=tasks)
+ blocking_task = todotxt.Task("Blocking before:1", tasks=tasks)
+ due_second = todotxt.Task("Task due:2018-02-01", tasks=tasks)
+ tasks.extend([due_first_but_blocked, blocking_task, due_second])
+ self.assertEqual([blocking_task, due_second], pick_action.next_actions(tasks, self.namespace))
+
+ def test_priority_of_blocked_task(self):
+ """ Test that a task that blocks a task with a higher priority takes precendence. """
+ tasks = todotxt.Tasks()
+ high_prio_but_blocked = todotxt.Task("(A) Task id:1", tasks=tasks)
+ blocking_task = todotxt.Task("Blocking before:1", tasks=tasks)
+ second_prio = todotxt.Task("(B) Task", tasks=tasks)
+ tasks.extend([high_prio_but_blocked, blocking_task, second_prio])
+ self.assertEqual([blocking_task, second_prio], pick_action.next_actions(tasks, self.namespace))
diff --git a/tests/unittests/todotxt/test_task.py b/tests/unittests/todotxt/test_task.py
index c772674..e99116b 100644
--- a/tests/unittests/todotxt/test_task.py
+++ b/tests/unittests/todotxt/test_task.py
@@ -87,6 +87,34 @@ class TaskPriorityTest(unittest.TestCase):
self.assertTrue(todotxt.Task("(Z) Task").priority_at_least(None))
self.assertTrue(todotxt.Task("Task").priority_at_least(None))
+ def test_blocking(self):
+ """ Test that the priority of a task without its own priority equals the priority of the task it is
+ blocking. """
+ tasks = todotxt.Tasks()
+ after = todotxt.Task("(A) After id:1", tasks=tasks)
+ before = todotxt.Task("Before before:1", tasks=tasks)
+ tasks.extend([before, after])
+ self.assertEqual("A", before.priority())
+
+ def test_blocking_multiple(self):
+ """ Test that the priority of a task without its own priority equals the highest priority of the tasks it is
+ blocking. """
+ tasks = todotxt.Tasks()
+ after1 = todotxt.Task("(A) After id:1", tasks=tasks)
+ after2 = todotxt.Task("(B) After after:before", tasks=tasks)
+ before = todotxt.Task("Before before:1 id:before", tasks=tasks)
+ tasks.extend([before, after1, after2])
+ self.assertEqual("A", before.priority())
+
+ def test_blocking_completed(self):
+ """ Test that the priority of a completed blocked task is ignored. """
+ tasks = todotxt.Tasks()
+ after = todotxt.Task("(B) After id:1", tasks=tasks)
+ after_completed = todotxt.Task("x (A) After id:2", tasks=tasks)
+ before = todotxt.Task("Before before:1 before:2", tasks=tasks)
+ tasks.extend([before, after, after_completed])
+ self.assertEqual("B", before.priority())
+
class CreationDateTest(unittest.TestCase):
""" Unit tests for task creation dates. Next-action interprets creation dates in the future as threshold, or
|
Child tasks inherit their parent's priority
max(parents' priorities) in case of multiple priorities
|
0.0
|
4b78879e73bb47641ce11db77d4834b058883b26
|
[
"tests/unittests/test_pick_action.py::BlockedTasksTest::test_priority_of_blocked_task",
"tests/unittests/todotxt/test_task.py::TaskPriorityTest::test_blocking_multiple",
"tests/unittests/todotxt/test_task.py::TaskPriorityTest::test_blocking",
"tests/unittests/todotxt/test_task.py::TaskPriorityTest::test_blocking_completed"
] |
[
"tests/unittests/test_pick_action.py::BlockedTasksTest::test_due_and_creation_dates",
"tests/unittests/test_pick_action.py::BlockedTasksTest::test_priority_and_creation_date",
"tests/unittests/test_pick_action.py::BlockedTasksTest::test_blocked",
"tests/unittests/test_pick_action.py::BlockedTasksTest::test_due_dates",
"tests/unittests/test_pick_action.py::BlockedTasksTest::test_multiple_childs",
"tests/unittests/test_pick_action.py::BlockedTasksTest::test_higher_prio_goes_first",
"tests/unittests/test_pick_action.py::BlockedTasksTest::test_due_date_of_blocked_task",
"tests/unittests/test_pick_action.py::BlockedTasksTest::test_blocked_chain",
"tests/unittests/test_pick_action.py::BlockedTasksTest::test_multiple_tasks",
"tests/unittests/test_pick_action.py::BlockedTasksTest::test_creation_dates",
"tests/unittests/test_pick_action.py::BlockedTasksTest::test_no_tasks",
"tests/unittests/test_pick_action.py::BlockedTasksTest::test_project",
"tests/unittests/test_pick_action.py::BlockedTasksTest::test_multiple_parents",
"tests/unittests/test_pick_action.py::BlockedTasksTest::test_one_task",
"tests/unittests/test_pick_action.py::BlockedTasksTest::test_projects",
"tests/unittests/test_pick_action.py::DueTasks::test_any_due_tasks",
"tests/unittests/test_pick_action.py::DueTasks::test_due_tasks",
"tests/unittests/test_pick_action.py::IgnoredTasksTest::test_ignore_completed_task",
"tests/unittests/test_pick_action.py::IgnoredTasksTest::test_ignore_future_task",
"tests/unittests/test_pick_action.py::IgnoredTasksTest::test_ignore_these_tasks",
"tests/unittests/test_pick_action.py::PickActionTest::test_no_tasks",
"tests/unittests/test_pick_action.py::PickActionTest::test_one_task",
"tests/unittests/test_pick_action.py::PickActionTest::test_due_and_creation_dates",
"tests/unittests/test_pick_action.py::PickActionTest::test_priority_and_creation_date",
"tests/unittests/test_pick_action.py::PickActionTest::test_creation_dates",
"tests/unittests/test_pick_action.py::PickActionTest::test_project",
"tests/unittests/test_pick_action.py::PickActionTest::test_multiple_tasks",
"tests/unittests/test_pick_action.py::PickActionTest::test_higher_prio_goes_first",
"tests/unittests/test_pick_action.py::PickActionTest::test_due_dates",
"tests/unittests/test_pick_action.py::PickActionTest::test_projects",
"tests/unittests/test_pick_action.py::MinimimPriorityTest::test_priority_and_creation_date",
"tests/unittests/test_pick_action.py::MinimimPriorityTest::test_projects",
"tests/unittests/test_pick_action.py::MinimimPriorityTest::test_priority",
"tests/unittests/test_pick_action.py::MinimimPriorityTest::test_multiple_tasks",
"tests/unittests/test_pick_action.py::MinimimPriorityTest::test_creation_dates",
"tests/unittests/test_pick_action.py::MinimimPriorityTest::test_one_task",
"tests/unittests/test_pick_action.py::MinimimPriorityTest::test_due_and_creation_dates",
"tests/unittests/test_pick_action.py::MinimimPriorityTest::test_due_dates",
"tests/unittests/test_pick_action.py::MinimimPriorityTest::test_project",
"tests/unittests/test_pick_action.py::MinimimPriorityTest::test_higher_prio_goes_first",
"tests/unittests/test_pick_action.py::MinimimPriorityTest::test_no_tasks",
"tests/unittests/test_pick_action.py::FilterTasksTest::test_not_excluded_context",
"tests/unittests/test_pick_action.py::FilterTasksTest::test_not_excluded_project",
"tests/unittests/test_pick_action.py::FilterTasksTest::test_excluded_project",
"tests/unittests/test_pick_action.py::FilterTasksTest::test_project",
"tests/unittests/test_pick_action.py::FilterTasksTest::test_excluded_contexts",
"tests/unittests/test_pick_action.py::FilterTasksTest::test_contexts",
"tests/unittests/test_pick_action.py::FilterTasksTest::test_excluded_projects",
"tests/unittests/test_pick_action.py::FilterTasksTest::test_excluded_context",
"tests/unittests/test_pick_action.py::FilterTasksTest::test_context",
"tests/unittests/test_pick_action.py::FilterTasksTest::test_project_and_context",
"tests/unittests/test_pick_action.py::OverdueTasks::test_overdue_tasks",
"tests/unittests/todotxt/test_task.py::TodoContextTest::test_no_space_before_at_sign",
"tests/unittests/todotxt/test_task.py::TodoContextTest::test_two_contexts",
"tests/unittests/todotxt/test_task.py::TodoContextTest::test_no_context",
"tests/unittests/todotxt/test_task.py::TodoContextTest::test_one_context",
"tests/unittests/todotxt/test_task.py::TaskCompletionTest::test_completed",
"tests/unittests/todotxt/test_task.py::TaskCompletionTest::test_space_after_x",
"tests/unittests/todotxt/test_task.py::TaskCompletionTest::test_x_must_be_lowercase",
"tests/unittests/todotxt/test_task.py::TaskCompletionTest::test_not_completed",
"tests/unittests/todotxt/test_task.py::ActionableTest::test_completed_task",
"tests/unittests/todotxt/test_task.py::ActionableTest::test_two_dates",
"tests/unittests/todotxt/test_task.py::ActionableTest::test_default",
"tests/unittests/todotxt/test_task.py::ActionableTest::test_future_creation_date",
"tests/unittests/todotxt/test_task.py::ActionableTest::test_past_creation_date",
"tests/unittests/todotxt/test_task.py::CreationDateTest::test_is_future_task",
"tests/unittests/todotxt/test_task.py::CreationDateTest::test_invalid_creation_date",
"tests/unittests/todotxt/test_task.py::CreationDateTest::test_no_space_after",
"tests/unittests/todotxt/test_task.py::CreationDateTest::test_single_digits",
"tests/unittests/todotxt/test_task.py::CreationDateTest::test_no_creation_date",
"tests/unittests/todotxt/test_task.py::CreationDateTest::test_creation_date",
"tests/unittests/todotxt/test_task.py::CreationDateTest::test_creation_date_after_priority",
"tests/unittests/todotxt/test_task.py::TodoTest::test_task_text",
"tests/unittests/todotxt/test_task.py::TodoTest::test_task_repr",
"tests/unittests/todotxt/test_task.py::TaskProjectTest::test_no_projects",
"tests/unittests/todotxt/test_task.py::TaskProjectTest::test_one_project",
"tests/unittests/todotxt/test_task.py::TaskProjectTest::test_two_projects",
"tests/unittests/todotxt/test_task.py::TaskProjectTest::test_no_space_before_at_sign",
"tests/unittests/todotxt/test_task.py::TaskPriorityTest::test_faulty_priorities",
"tests/unittests/todotxt/test_task.py::TaskPriorityTest::test_priority_at_least",
"tests/unittests/todotxt/test_task.py::TaskPriorityTest::test_priorities",
"tests/unittests/todotxt/test_task.py::TaskPriorityTest::test_no_priority",
"tests/unittests/todotxt/test_task.py::DependenciesTest::test_one_after_two",
"tests/unittests/todotxt/test_task.py::DependenciesTest::test_after_completed_task",
"tests/unittests/todotxt/test_task.py::DependenciesTest::test_one_after_another",
"tests/unittests/todotxt/test_task.py::DependenciesTest::test_one_before_two",
"tests/unittests/todotxt/test_task.py::DependenciesTest::test_self_after_self_indirect",
"tests/unittests/todotxt/test_task.py::DependenciesTest::test_task_without_dependencies",
"tests/unittests/todotxt/test_task.py::DependenciesTest::test_self_after_self",
"tests/unittests/todotxt/test_task.py::DependenciesTest::test_two_before_one",
"tests/unittests/todotxt/test_task.py::DependenciesTest::test_two_after_one",
"tests/unittests/todotxt/test_task.py::DependenciesTest::test_self_before_self",
"tests/unittests/todotxt/test_task.py::DependenciesTest::test_completed_before_task",
"tests/unittests/todotxt/test_task.py::DependenciesTest::test_one_before_another",
"tests/unittests/todotxt/test_task.py::DependenciesTest::test_self_before_self_indirect",
"tests/unittests/todotxt/test_task.py::DueDateTest::test_invalid_date",
"tests/unittests/todotxt/test_task.py::DueDateTest::test_past_due_date",
"tests/unittests/todotxt/test_task.py::DueDateTest::test_single_digits",
"tests/unittests/todotxt/test_task.py::DueDateTest::test_future_due_date",
"tests/unittests/todotxt/test_task.py::DueDateTest::test_due_today",
"tests/unittests/todotxt/test_task.py::DueDateTest::test_blocking",
"tests/unittests/todotxt/test_task.py::DueDateTest::test_no_space_after",
"tests/unittests/todotxt/test_task.py::DueDateTest::test_is_due",
"tests/unittests/todotxt/test_task.py::DueDateTest::test_no_due_date",
"tests/unittests/todotxt/test_task.py::DueDateTest::test_blocking_completed",
"tests/unittests/todotxt/test_task.py::DueDateTest::test_blocking_multiple",
"tests/unittests/todotxt/test_task.py::ThresholdDateTest::test_future_threshold",
"tests/unittests/todotxt/test_task.py::ThresholdDateTest::test_threshold_today",
"tests/unittests/todotxt/test_task.py::ThresholdDateTest::test_no_threshold",
"tests/unittests/todotxt/test_task.py::ThresholdDateTest::test_past_threshold"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2018-06-25 21:38:19+00:00
|
apache-2.0
| 2,372 |
|
fniessink__next-action-140
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 9b17215..906588e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,12 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/)
and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html).
+## [Unreleased] - 2018-06-30
+
+### Added
+
+- When generating a configuration file with `--write-config-file` add any other options on the command-line to the generated configuration file. Closes #78.
+
## [1.4.0] - 2018-06-25
### Added
diff --git a/README.md b/README.md
index 67e9fc7..a24da95 100644
--- a/README.md
+++ b/README.md
@@ -171,14 +171,14 @@ To limit the the tasks from which the next action is selected to actions with a
```console
$ next-action @home --due
-(K) Pay July invoice @home due:2018-07-28
+(K) Pay July invoice @home due:2019-07-28
```
Add a due date to select a next action from tasks due on or before that date:
```console
$ next-action @home --due "june 2018"
-(L) Pay June invoice @home due:2018-06-28
+Nothing to do!
```
To make sure you have no overdue actions, or work on overdue actions first, limit the tasks from which the next action is selected to overdue actions:
@@ -270,7 +270,10 @@ Not passing an argument to `--style` cancels the style that is configured in the
### Configuring *Next-action*
-In addition to specifying options on the command-line, you can also configure options in a configuration file. By default, *Next-action* tries to read a file called [.next-action.cfg](https://raw.githubusercontent.com/fniessink/next-action/master/docs/.next-action.cfg) in your home folder.
+In addition to specifying options on the command-line, you can also configure options in a configuration file.
+The configuration file format is [YAML](http://yaml.org). The options currently supported are which todo.txt files must be read, how many next actions should be shown, output styling, and context and/or project filters.
+
+#### Writing the configuration file
To get started, you can tell *Next-action* to generate a configuration file with the default options:
@@ -280,11 +283,26 @@ $ next-action --write-config-file
file: ~/todo.txt
number: 1
reference: multiple
-style: default
+style: native
```
To make this the configuration that *Next-action* reads by default, redirect the output to `~/.next-action.cfg` like this: `next-action --write-config-file > ~/.next-action.cfg`.
+Any additional options specified on the command line are used to generate the configuration file:
+
+```console
+$ next-action --write-config-file --number 3 --file ~/tasks.txt --style fruity
+# Configuration file for Next-action. Edit the settings below as you like.
+file: ~/tasks.txt
+number: 3
+reference: multiple
+style: fruity
+```
+
+#### Reading the configuration file
+
+By default, *Next-action* tries to read a file called [.next-action.cfg](https://raw.githubusercontent.com/fniessink/next-action/master/docs/.next-action.cfg) in your home folder.
+
If you want to use a configuration file that is not in the default location (`~/.next-action.cfg`), you'll need to explicitly specify its location:
```console
@@ -294,8 +312,6 @@ $ next-action --config-file docs/.next-action.cfg
To skip reading the default configuration file, and also not read an alternative configuration file, use the `--config-file` option without arguments.
-The configuration file format is [YAML](http://yaml.org). The options currently supported are which todo.txt files must be read, how many next actions should be shown, output styling, and context and/or project filters.
-
#### Configuring a default todo.txt
A default todo.txt file to use can be specified like this in the configuration file:
@@ -403,14 +419,14 @@ There's two ways to help *Next-action* figure out what you mean. Either reverse
```console
$ next-action @home --due
-(K) Pay July invoice @home due:2018-07-28
+(K) Pay July invoice @home due:2019-07-28
```
Or use `--` to separate the option from the positional argument(s):
```console
$ next-action --due -- @home
-(K) Pay July invoice @home due:2018-07-28
+(K) Pay July invoice @home due:2019-07-28
```
## Recent changes
@@ -429,9 +445,9 @@ To run the unit tests:
```console
$ python -m unittest
-.....................................................................................................................................................................................................................................
+.........................................................................................................................................................................................................................................
----------------------------------------------------------------------
-Ran 229 tests in 2.728s
+Ran 233 tests in 2.206s
OK
```
@@ -442,9 +458,9 @@ To create the unit test coverage report run the unit tests under coverage with:
```console
$ coverage run --branch -m unittest
-.....................................................................................................................................................................................................................................
+.........................................................................................................................................................................................................................................
----------------------------------------------------------------------
-Ran 229 tests in 3.794s
+Ran 233 tests in 2.616s
OK
```
@@ -456,7 +472,7 @@ $ coverage report --fail-under=100 --omit=".venv/*" --skip-covered
Name Stmts Miss Branch BrPart Cover
-----------------------------------------
-----------------------------------------
-TOTAL 1282 0 160 0 100%
+TOTAL 1316 0 162 0 100%
25 files skipped due to complete coverage.
```
diff --git a/docs/todo.txt b/docs/todo.txt
index cd9b63c..cfc3281 100644
--- a/docs/todo.txt
+++ b/docs/todo.txt
@@ -5,8 +5,8 @@
Get rid of old +DogHouse @home
Borrow ladder from the neighbors +PaintHouse @home
Buy flowers due:2018-02-14
-(L) Pay June invoice @home due:2018-06-28
-(K) Pay July invoice @home due:2018-07-28
+(L) Pay June invoice @home due:2019-06-28
+(K) Pay July invoice @home due:2019-07-28
Buy groceries @store +DinnerParty before:meal
Cook meal @home +DinnerParty id:meal due:2018-07-01
Take out the garbage @home +DinnerParty due:2018-07-02
diff --git a/next_action/arguments/config.py b/next_action/arguments/config.py
index 5cf2f99..bf27d79 100644
--- a/next_action/arguments/config.py
+++ b/next_action/arguments/config.py
@@ -1,5 +1,6 @@
""" Methods for reading, parsing, and validating Next-action configuration files. """
+import argparse
import os
import string
import sys
@@ -26,11 +27,17 @@ def read_config_file(filename: str, default_filename: str, error: Callable[[str]
error("can't parse {0}: {1}".format(filename, reason))
-def write_config_file() -> None:
+def write_config_file(namespace: argparse.Namespace) -> None:
""" Generate a configuration file on standard out. """
intro = "# Configuration file for Next-action. Edit the settings below as you like.\n"
- config = yaml.dump(dict(file="~/todo.txt", number=1, reference="multiple", style="default"),
- default_flow_style=False)
+ options = dict(file=namespace.file[0] if len(namespace.file) == 1 else namespace.file,
+ reference=namespace.reference, style=namespace.style or "default")
+ if namespace.number == sys.maxsize:
+ options["all"] = True
+ else:
+ options["number"] = namespace.number
+
+ config = yaml.dump(options, default_flow_style=False)
sys.stdout.write(intro + config)
diff --git a/next_action/arguments/parser.py b/next_action/arguments/parser.py
index 682b5ae..aabbcdb 100644
--- a/next_action/arguments/parser.py
+++ b/next_action/arguments/parser.py
@@ -126,10 +126,10 @@ class NextActionArgumentParser(argparse.ArgumentParser):
self.parse_remaining_args(remaining, namespace)
if getattr(namespace, "config_file", self.get_default("config_file")) is not None:
self.process_config_file(namespace)
+ self.fix_filenames(namespace)
if namespace.write_config_file:
- write_config_file()
+ write_config_file(namespace)
self.exit()
- self.fix_filenames(namespace)
return namespace
def parse_remaining_args(self, remaining: List[str], namespace: argparse.Namespace) -> None:
|
fniessink/next-action
|
d0a732435faa091a60909c83672610de2b771c23
|
diff --git a/tests/unittests/arguments/test_config.py b/tests/unittests/arguments/test_config.py
index 42b5a9f..2cef50f 100644
--- a/tests/unittests/arguments/test_config.py
+++ b/tests/unittests/arguments/test_config.py
@@ -18,8 +18,8 @@ class ConfigTestCase(unittest.TestCase):
os.environ['COLUMNS'] = "120" # Fake that the terminal is wide enough.
-class ConfigFileTest(ConfigTestCase):
- """ Unit tests for the config file. """
+class ReadConfigFileTest(ConfigTestCase):
+ """ Unit tests for reading the config file. """
@patch.object(sys, "argv", ["next-action", "--config-file", "config.cfg"])
@patch.object(config, "open", mock_open(read_data=""))
@@ -92,16 +92,61 @@ class ConfigFileTest(ConfigTestCase):
parse_arguments()
self.assertEqual([], mock_file_open.call_args_list)
+
+class WriteConfigFileTest(ConfigTestCase):
+ """ Unit tests for the write-config-file argument. """
+
@patch.object(sys, "argv", ["next-action", "--write-config-file"])
@patch.object(config, "open", mock_open(read_data=""))
@patch.object(sys.stdout, "write")
- def test_write_config(self, mock_stdout_write):
+ def test_default_file(self, mock_stdout_write):
""" Test that a config file can be written to stdout. """
self.assertRaises(SystemExit, parse_arguments)
expected = "# Configuration file for Next-action. Edit the settings below as you like.\n"
expected += "file: ~/todo.txt\nnumber: 1\nreference: multiple\nstyle: default\n"
self.assertEqual([call(expected)], mock_stdout_write.call_args_list)
+ @patch.object(sys, "argv", ["next-action", "--write-config-file", "--number", "3", "--reference", "never",
+ "--style", "fruity", "--file", "~/tasks.txt"])
+ @patch.object(config, "open", mock_open(read_data=""))
+ @patch.object(sys.stdout, "write")
+ def test_with_args(self, mock_stdout_write):
+ """ Test that the config file written to stdout includes the other arguments. """
+ self.assertRaises(SystemExit, parse_arguments)
+ expected = "# Configuration file for Next-action. Edit the settings below as you like.\n"
+ expected += "file: ~/tasks.txt\nnumber: 3\nreference: never\nstyle: fruity\n"
+ self.assertEqual([call(expected)], mock_stdout_write.call_args_list)
+
+ @patch.object(sys, "argv", ["next-action", "--write-config-file", "--file", "~/tasks.txt", "--file", "project.txt"])
+ @patch.object(config, "open", mock_open(read_data=""))
+ @patch.object(sys.stdout, "write")
+ def test_multiple_files(self, mock_stdout_write):
+ """ Test that the config file contains a list of files if multiple file arguments are passed. """
+ self.assertRaises(SystemExit, parse_arguments)
+ expected = "# Configuration file for Next-action. Edit the settings below as you like.\n"
+ expected += "file:\n- ~/tasks.txt\n- project.txt\nnumber: 1\nreference: multiple\nstyle: default\n"
+ self.assertEqual([call(expected)], mock_stdout_write.call_args_list)
+
+ @patch.object(sys, "argv", ["next-action", "--write-config-file", "--all"])
+ @patch.object(config, "open", mock_open(read_data=""))
+ @patch.object(sys.stdout, "write")
+ def test_show_all(self, mock_stdout_write):
+ """ Test that the config file contains "all" true" instead of a number. """
+ self.assertRaises(SystemExit, parse_arguments)
+ expected = "# Configuration file for Next-action. Edit the settings below as you like.\n"
+ expected += "all: true\nfile: ~/todo.txt\nreference: multiple\nstyle: default\n"
+ self.assertEqual([call(expected)], mock_stdout_write.call_args_list)
+
+ @patch.object(sys, "argv", ["next-action", "--write-config-file"])
+ @patch.object(config, "open", mock_open(read_data="number: 3"))
+ @patch.object(sys.stdout, "write")
+ def test_read_config(self, mock_stdout_write):
+ """ Test that the written config file contains the read config file. """
+ self.assertRaises(SystemExit, parse_arguments)
+ expected = "# Configuration file for Next-action. Edit the settings below as you like.\n"
+ expected += "file: ~/todo.txt\nnumber: 3\nreference: multiple\nstyle: default\n"
+ self.assertEqual([call(expected)], mock_stdout_write.call_args_list)
+
class FilenameTest(ConfigTestCase):
""" Unit tests for the config file parameter. """
|
Make --write-config-file take other command-line options into account
```console
$ next-action --write-config-file --style colourful --number 3
# Configuration file for Next-action. Edit the settings below as you like.\n"
file: ~/todo.txt
number: 3
style: colorful
```
|
0.0
|
d0a732435faa091a60909c83672610de2b771c23
|
[
"tests/unittests/arguments/test_config.py::WriteConfigFileTest::test_multiple_files",
"tests/unittests/arguments/test_config.py::WriteConfigFileTest::test_read_config",
"tests/unittests/arguments/test_config.py::WriteConfigFileTest::test_show_all",
"tests/unittests/arguments/test_config.py::WriteConfigFileTest::test_with_args"
] |
[
"tests/unittests/arguments/test_config.py::ReadConfigFileTest::test_empty_file",
"tests/unittests/arguments/test_config.py::ReadConfigFileTest::test_error_opening",
"tests/unittests/arguments/test_config.py::ReadConfigFileTest::test_error_parsing",
"tests/unittests/arguments/test_config.py::ReadConfigFileTest::test_file_not_found",
"tests/unittests/arguments/test_config.py::ReadConfigFileTest::test_invalid_document",
"tests/unittests/arguments/test_config.py::ReadConfigFileTest::test_missing_default_config",
"tests/unittests/arguments/test_config.py::ReadConfigFileTest::test_no_file_key",
"tests/unittests/arguments/test_config.py::ReadConfigFileTest::test_skip_config",
"tests/unittests/arguments/test_config.py::WriteConfigFileTest::test_default_file",
"tests/unittests/arguments/test_config.py::FilenameTest::test_cli_takes_precedence",
"tests/unittests/arguments/test_config.py::FilenameTest::test_invalid_filename",
"tests/unittests/arguments/test_config.py::FilenameTest::test_valid_and_invalid",
"tests/unittests/arguments/test_config.py::FilenameTest::test_valid_file",
"tests/unittests/arguments/test_config.py::FilenameTest::test_valid_files",
"tests/unittests/arguments/test_config.py::NumberTest::test_all_and_number",
"tests/unittests/arguments/test_config.py::NumberTest::test_all_false",
"tests/unittests/arguments/test_config.py::NumberTest::test_all_true",
"tests/unittests/arguments/test_config.py::NumberTest::test_argument_all_overrides",
"tests/unittests/arguments/test_config.py::NumberTest::test_argument_nr_overrides",
"tests/unittests/arguments/test_config.py::NumberTest::test_cli_takes_precedence",
"tests/unittests/arguments/test_config.py::NumberTest::test_invalid_number",
"tests/unittests/arguments/test_config.py::NumberTest::test_valid_number",
"tests/unittests/arguments/test_config.py::NumberTest::test_zero",
"tests/unittests/arguments/test_config.py::ConfigStyleTest::test_cancel_style",
"tests/unittests/arguments/test_config.py::ConfigStyleTest::test_invalid_style",
"tests/unittests/arguments/test_config.py::ConfigStyleTest::test_override_style",
"tests/unittests/arguments/test_config.py::ConfigStyleTest::test_valid_style",
"tests/unittests/arguments/test_config.py::PriorityTest::test_cancel_priority",
"tests/unittests/arguments/test_config.py::PriorityTest::test_invalid_priority",
"tests/unittests/arguments/test_config.py::PriorityTest::test_override_priority",
"tests/unittests/arguments/test_config.py::PriorityTest::test_override_short",
"tests/unittests/arguments/test_config.py::PriorityTest::test_valid_priority",
"tests/unittests/arguments/test_config.py::ReferenceTest::test_invalid_priority",
"tests/unittests/arguments/test_config.py::ReferenceTest::test_override",
"tests/unittests/arguments/test_config.py::ReferenceTest::test_valid_reference",
"tests/unittests/arguments/test_config.py::FiltersTest::test_context",
"tests/unittests/arguments/test_config.py::FiltersTest::test_context_list",
"tests/unittests/arguments/test_config.py::FiltersTest::test_contexts",
"tests/unittests/arguments/test_config.py::FiltersTest::test_excluded_context",
"tests/unittests/arguments/test_config.py::FiltersTest::test_excluded_project",
"tests/unittests/arguments/test_config.py::FiltersTest::test_ignore_project_not_context",
"tests/unittests/arguments/test_config.py::FiltersTest::test_invalid_filter_list",
"tests/unittests/arguments/test_config.py::FiltersTest::test_invalid_filter_string",
"tests/unittests/arguments/test_config.py::FiltersTest::test_inverse_project",
"tests/unittests/arguments/test_config.py::FiltersTest::test_project",
"tests/unittests/arguments/test_config.py::FiltersTest::test_projects",
"tests/unittests/arguments/test_config.py::FiltersTest::test_same_project"
] |
{
"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-06-30 15:59:23+00:00
|
apache-2.0
| 2,373 |
|
fniessink__next-action-146
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 5ced4b2..47525ec 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,12 +5,13 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/)
and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html).
-## [Unreleased] - 2018-06-30
+## [Unreleased] - 2018-07-01
### Fixed
-- When generating a configuration file with `--write-config-file` also include context and project filters passed on the command-line. Closes #141.
-- When generating a configuration file with `--write-config-file` also include the minimum priority if passed on the command-line. Closes #142.
+- When generating a configuration file with `--write-config-file` also include context and project filters passed on the command-line. Fixes #141.
+- When generating a configuration file with `--write-config-file` also include the minimum priority if passed on the command-line. Fixes #142.
+- Accept other arguments after excluded contexts and projects. Fixes #143.
## [1.5.0] - 2018-06-30
diff --git a/README.md b/README.md
index 69b3265..be958a8 100644
--- a/README.md
+++ b/README.md
@@ -448,9 +448,9 @@ To run the unit tests:
```console
$ python -m unittest
-..........................................................................................................................................................................................................................................
+...........................................................................................................................................................................................................................................
----------------------------------------------------------------------
-Ran 234 tests in 2.059s
+Ran 235 tests in 1.970s
OK
```
@@ -461,9 +461,9 @@ To create the unit test coverage report run the unit tests under coverage with:
```console
$ coverage run --branch -m unittest
-..........................................................................................................................................................................................................................................
+...........................................................................................................................................................................................................................................
----------------------------------------------------------------------
-Ran 234 tests in 2.740s
+Ran 235 tests in 3.107s
OK
```
@@ -475,7 +475,7 @@ $ coverage report --fail-under=100 --omit=".venv/*" --skip-covered
Name Stmts Miss Branch BrPart Cover
-----------------------------------------
-----------------------------------------
-TOTAL 1329 0 170 0 100%
+TOTAL 1341 0 173 0 100%
25 files skipped due to complete coverage.
```
diff --git a/next_action/arguments/parser.py b/next_action/arguments/parser.py
index aabbcdb..6e55749 100644
--- a/next_action/arguments/parser.py
+++ b/next_action/arguments/parser.py
@@ -122,7 +122,7 @@ class NextActionArgumentParser(argparse.ArgumentParser):
def parse_args(self, args=None, namespace=None) -> argparse.Namespace:
""" Parse the command-line arguments. """
- namespace, remaining = self.parse_known_args(args, namespace)
+ namespace, remaining = self.parse_known_args(self.sorted_args(args), namespace)
self.parse_remaining_args(remaining, namespace)
if getattr(namespace, "config_file", self.get_default("config_file")) is not None:
self.process_config_file(namespace)
@@ -132,10 +132,18 @@ class NextActionArgumentParser(argparse.ArgumentParser):
self.exit()
return namespace
+ @classmethod
+ def sorted_args(cls, args: List[str] = None) -> List[str]:
+ """ Sort the arguments so that the excluded contexts and projects are last and can be parsed by
+ parse_remaining_args. """
+ args = args or sys.argv[1:]
+ return [arg for arg in args if not cls.is_excluded_filter(arg)] + \
+ [arg for arg in args if cls.is_excluded_filter(arg)]
+
def parse_remaining_args(self, remaining: List[str], namespace: argparse.Namespace) -> None:
""" Parse the remaining command line arguments. """
for value in remaining:
- if value.startswith("-@") or value.startswith("-+"):
+ if self.is_excluded_filter(value):
argument = value[len("-"):]
if not argument[len("@"):]:
argument_type = "context" if argument.startswith("@") else "project"
@@ -198,6 +206,11 @@ class NextActionArgumentParser(argparse.ArgumentParser):
return not any([command_line_arg.startswith(argument) for argument in arguments
for command_line_arg in sys.argv])
+ @staticmethod
+ def is_excluded_filter(argument: str) -> bool:
+ """ Return whether the argument is an excluded context or project. """
+ return argument.startswith("-@") or argument.startswith("-+")
+
@staticmethod
def filter_not_specified(filtered: str) -> bool:
""" Return whether the context or project or its opposite were specified on the command line. """
|
fniessink/next-action
|
b852e392331d1f7496aa4dcb00a49d128d077bdd
|
diff --git a/tests/unittests/arguments/test_parser.py b/tests/unittests/arguments/test_parser.py
index 6e59879..116659e 100644
--- a/tests/unittests/arguments/test_parser.py
+++ b/tests/unittests/arguments/test_parser.py
@@ -173,6 +173,14 @@ class FilterArgumentTest(ParserTestCase):
self.assertEqual({"home", "weekend"}, parse_arguments()[1].contexts)
self.assertEqual({"DogHouse", "PaintHouse"}, parse_arguments()[1].projects)
+ @patch.object(sys, "argv", ["next-action", "@home", "-@work", "+PaintHouse"])
+ def test_project_after_excluded(self):
+ """ Test project after excluded context. """
+ namespace = parse_arguments()[1]
+ self.assertEqual({"home"}, namespace.contexts)
+ self.assertEqual({"work"}, namespace.excluded_contexts)
+ self.assertEqual({"PaintHouse"}, namespace.projects)
+
@patch.object(sys, "argv", ["next-action", "home"])
@patch.object(sys.stderr, "write")
def test_faulty_option(self, mock_stderr_write):
|
Unrecognised argument error when filtering on project after context and excluded context
```console
$ next-action @context -@excluded_context +project
Usage: next-action [-h] [--version] [-c [<config.cfg>] | -w] [-f <todo.txt> ...] [-r <ref>] [-s [<style>]] [-a | -n <number>] [-d [<due date>] | -o] [-p [<priority>]] [--] [<context|project> ...]
next-action: error: unrecognized arguments: +project
```
|
0.0
|
b852e392331d1f7496aa4dcb00a49d128d077bdd
|
[
"tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_project_after_excluded"
] |
[
"tests/unittests/arguments/test_parser.py::NoArgumentTest::test_filename",
"tests/unittests/arguments/test_parser.py::NoArgumentTest::test_filters",
"tests/unittests/arguments/test_parser.py::NoArgumentTest::test_style",
"tests/unittests/arguments/test_parser.py::FilenameTest::test_add_default_filename",
"tests/unittests/arguments/test_parser.py::FilenameTest::test_add_filename_twice",
"tests/unittests/arguments/test_parser.py::FilenameTest::test_default_and_non_default",
"tests/unittests/arguments/test_parser.py::FilenameTest::test_filename_argument",
"tests/unittests/arguments/test_parser.py::FilenameTest::test_home_folder_argument",
"tests/unittests/arguments/test_parser.py::FilenameTest::test_long_filename_argument",
"tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_contexts_and_projects",
"tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_empty_context",
"tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_empty_excluded_project",
"tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_empty_project",
"tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_exclude_context",
"tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_exclude_project",
"tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_faulty_option",
"tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_include_exclude_context",
"tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_include_exclude_project",
"tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_invalid_extra_argument",
"tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_multiple_contexts",
"tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_multiple_projects",
"tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_one_context",
"tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_one_project",
"tests/unittests/arguments/test_parser.py::NumberTest::test_all_actions",
"tests/unittests/arguments/test_parser.py::NumberTest::test_all_and_number",
"tests/unittests/arguments/test_parser.py::NumberTest::test_default_number",
"tests/unittests/arguments/test_parser.py::NumberTest::test_faulty_number",
"tests/unittests/arguments/test_parser.py::NumberTest::test_number",
"tests/unittests/arguments/test_parser.py::DueDateTest::test_default",
"tests/unittests/arguments/test_parser.py::DueDateTest::test_due_date",
"tests/unittests/arguments/test_parser.py::DueDateTest::test_faulty_date",
"tests/unittests/arguments/test_parser.py::DueDateTest::test_invalid_date",
"tests/unittests/arguments/test_parser.py::DueDateTest::test_no_due_date",
"tests/unittests/arguments/test_parser.py::DueDateTest::test_too_long",
"tests/unittests/arguments/test_parser.py::ReferenceTest::test_always",
"tests/unittests/arguments/test_parser.py::ReferenceTest::test_default",
"tests/unittests/arguments/test_parser.py::ReferenceTest::test_faulty_date",
"tests/unittests/arguments/test_parser.py::ReferenceTest::test_multiple",
"tests/unittests/arguments/test_parser.py::ReferenceTest::test_never"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2018-06-30 22:07:44+00:00
|
apache-2.0
| 2,374 |
|
fniessink__next-action-162
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 91e0439..2481f94 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,12 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/)
and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html).
+## [Unreleased] - 2018-07-14
+
+### Fixed
+
+- Allow for using `--config` when generating a configuration file with `--write-config-file` so it is possible to ignore the existing configuration file when generating a new one. Fixes #161.
+
## [1.5.2] - 2018-07-07
### Fixed
diff --git a/README.md b/README.md
index d78de09..ffb50ba 100644
--- a/README.md
+++ b/README.md
@@ -283,7 +283,7 @@ $ next-action --write-config-file
file: ~/todo.txt
number: 1
reference: multiple
-style: native
+style: default
```
To make this the configuration that *Next-action* reads by default, redirect the output to `~/.next-action.cfg` like this: `next-action --write-config-file > ~/.next-action.cfg`.
@@ -448,9 +448,9 @@ To run the unit tests:
```console
$ python -m unittest
-...........................................................................................................................................................................................................................................
+............................................................................................................................................................................................................................................
----------------------------------------------------------------------
-Ran 235 tests in 2.611s
+Ran 236 tests in 2.931s
OK
```
@@ -461,9 +461,9 @@ To create the unit test coverage report run the unit tests under coverage with:
```console
$ coverage run --branch -m unittest
-...........................................................................................................................................................................................................................................
+............................................................................................................................................................................................................................................
----------------------------------------------------------------------
-Ran 235 tests in 2.784s
+Ran 236 tests in 3.557s
OK
```
@@ -475,7 +475,7 @@ $ coverage report --fail-under=100 --omit=".venv/*" --skip-covered
Name Stmts Miss Branch BrPart Cover
-----------------------------------------
-----------------------------------------
-TOTAL 1341 0 173 0 100%
+TOTAL 1347 0 173 0 100%
25 files skipped due to complete coverage.
```
diff --git a/docs/update_readme.py b/docs/update_readme.py
index acdba69..2ff52b6 100644
--- a/docs/update_readme.py
+++ b/docs/update_readme.py
@@ -10,9 +10,10 @@ import sys
def do_command(line):
"""Run the command on the line and return its stdout and stderr."""
command = shlex.split(line[2:])
- if command[0] == "next-action" and "--write-config-file" not in command:
+ if command[0] == "next-action":
command.insert(1, "--config")
- command.insert(2, "docs/.next-action.cfg")
+ if "--write-config-file" not in command:
+ command.insert(2, "docs/.next-action.cfg")
command_output = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
universal_newlines=True)
stdout = command_output.stdout.strip()
diff --git a/next_action/arguments/parser.py b/next_action/arguments/parser.py
index 35c9f6a..3184c55 100644
--- a/next_action/arguments/parser.py
+++ b/next_action/arguments/parser.py
@@ -50,12 +50,11 @@ class NextActionArgumentParser(argparse.ArgumentParser):
def add_configuration_options(self) -> None:
"""Add the configuration options to the parser."""
config_group = self.add_argument_group("Configuration options")
- config_file = config_group.add_mutually_exclusive_group()
- config_file.add_argument(
+ config_group.add_argument(
"-c", "--config-file", metavar="<config.cfg>", type=str, default="~/.next-action.cfg", nargs="?",
help="filename of configuration file to read (default: %(default)s); omit filename to not read any "
"configuration file")
- config_file.add_argument(
+ config_group.add_argument(
"-w", "--write-config-file", help="generate a sample configuration file and exit", action="store_true")
def add_input_options(self) -> None:
|
fniessink/next-action
|
5d93327fa6f163d540a60103a5f829ca94e443f6
|
diff --git a/tests/unittests/arguments/test_config.py b/tests/unittests/arguments/test_config.py
index fadbf58..7eb47f0 100644
--- a/tests/unittests/arguments/test_config.py
+++ b/tests/unittests/arguments/test_config.py
@@ -161,6 +161,16 @@ class WriteConfigFileTest(ConfigTestCase):
expected += "file: ~/todo.txt\nnumber: 3\nreference: multiple\nstyle: default\n"
self.assertEqual([call(expected)], mock_stdout_write.call_args_list)
+ @patch.object(sys, "argv", ["next-action", "--write-config-file", "--config"])
+ @patch.object(config, "open", mock_open(read_data="number: 3"))
+ @patch.object(sys.stdout, "write")
+ def test_ignore_config(self, mock_stdout_write):
+ """Test that the written config file does not contain the read config file."""
+ self.assertRaises(SystemExit, parse_arguments)
+ expected = "# Configuration file for Next-action. Edit the settings below as you like.\n"
+ expected += "file: ~/todo.txt\nnumber: 1\nreference: multiple\nstyle: default\n"
+ self.assertEqual([call(expected)], mock_stdout_write.call_args_list)
+
class FilenameTest(ConfigTestCase):
"""Unit tests for the config file parameter."""
|
Next-action can't be told to not read the current configuration file when generating one
```console
$ next-action -w -c
Usage: next-action [-h] [--version] [-c [<config.cfg>] | -w] [-f <todo.txt> ...] [-r <ref>] [-s [<style>]] [-a | -n
<number>] [-d [<due date>] | -o] [-p [<priority>]] [--] [<context|project> ...]
next-action: error: argument -c/--config-file: not allowed with argument -w/--write-config-file
```
|
0.0
|
5d93327fa6f163d540a60103a5f829ca94e443f6
|
[
"tests/unittests/arguments/test_config.py::WriteConfigFileTest::test_ignore_config"
] |
[
"tests/unittests/arguments/test_config.py::ReadConfigFileTest::test_empty_file",
"tests/unittests/arguments/test_config.py::ReadConfigFileTest::test_error_opening",
"tests/unittests/arguments/test_config.py::ReadConfigFileTest::test_error_parsing",
"tests/unittests/arguments/test_config.py::ReadConfigFileTest::test_file_not_found",
"tests/unittests/arguments/test_config.py::ReadConfigFileTest::test_invalid_document",
"tests/unittests/arguments/test_config.py::ReadConfigFileTest::test_missing_default_config",
"tests/unittests/arguments/test_config.py::ReadConfigFileTest::test_no_file_key",
"tests/unittests/arguments/test_config.py::ReadConfigFileTest::test_skip_config",
"tests/unittests/arguments/test_config.py::WriteConfigFileTest::test_default_file",
"tests/unittests/arguments/test_config.py::WriteConfigFileTest::test_multiple_files",
"tests/unittests/arguments/test_config.py::WriteConfigFileTest::test_priority",
"tests/unittests/arguments/test_config.py::WriteConfigFileTest::test_read_config",
"tests/unittests/arguments/test_config.py::WriteConfigFileTest::test_show_all",
"tests/unittests/arguments/test_config.py::WriteConfigFileTest::test_with_args",
"tests/unittests/arguments/test_config.py::FilenameTest::test_cli_takes_precedence",
"tests/unittests/arguments/test_config.py::FilenameTest::test_invalid_filename",
"tests/unittests/arguments/test_config.py::FilenameTest::test_valid_and_invalid",
"tests/unittests/arguments/test_config.py::FilenameTest::test_valid_file",
"tests/unittests/arguments/test_config.py::FilenameTest::test_valid_files",
"tests/unittests/arguments/test_config.py::NumberTest::test_all_and_number",
"tests/unittests/arguments/test_config.py::NumberTest::test_all_false",
"tests/unittests/arguments/test_config.py::NumberTest::test_all_true",
"tests/unittests/arguments/test_config.py::NumberTest::test_argument_all_overrides",
"tests/unittests/arguments/test_config.py::NumberTest::test_argument_nr_overrides",
"tests/unittests/arguments/test_config.py::NumberTest::test_cli_takes_precedence",
"tests/unittests/arguments/test_config.py::NumberTest::test_invalid_number",
"tests/unittests/arguments/test_config.py::NumberTest::test_valid_number",
"tests/unittests/arguments/test_config.py::NumberTest::test_zero",
"tests/unittests/arguments/test_config.py::ConfigStyleTest::test_cancel_style",
"tests/unittests/arguments/test_config.py::ConfigStyleTest::test_invalid_style",
"tests/unittests/arguments/test_config.py::ConfigStyleTest::test_override_style",
"tests/unittests/arguments/test_config.py::ConfigStyleTest::test_valid_style",
"tests/unittests/arguments/test_config.py::PriorityTest::test_cancel_priority",
"tests/unittests/arguments/test_config.py::PriorityTest::test_invalid_priority",
"tests/unittests/arguments/test_config.py::PriorityTest::test_override_priority",
"tests/unittests/arguments/test_config.py::PriorityTest::test_override_short",
"tests/unittests/arguments/test_config.py::PriorityTest::test_valid_priority",
"tests/unittests/arguments/test_config.py::ReferenceTest::test_invalid_priority",
"tests/unittests/arguments/test_config.py::ReferenceTest::test_override",
"tests/unittests/arguments/test_config.py::ReferenceTest::test_valid_reference",
"tests/unittests/arguments/test_config.py::FiltersTest::test_context",
"tests/unittests/arguments/test_config.py::FiltersTest::test_context_list",
"tests/unittests/arguments/test_config.py::FiltersTest::test_contexts",
"tests/unittests/arguments/test_config.py::FiltersTest::test_excluded_context",
"tests/unittests/arguments/test_config.py::FiltersTest::test_excluded_project",
"tests/unittests/arguments/test_config.py::FiltersTest::test_ignore_project_not_context",
"tests/unittests/arguments/test_config.py::FiltersTest::test_invalid_filter_list",
"tests/unittests/arguments/test_config.py::FiltersTest::test_invalid_filter_string",
"tests/unittests/arguments/test_config.py::FiltersTest::test_inverse_project",
"tests/unittests/arguments/test_config.py::FiltersTest::test_project",
"tests/unittests/arguments/test_config.py::FiltersTest::test_projects",
"tests/unittests/arguments/test_config.py::FiltersTest::test_same_project"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2018-07-14 19:57:03+00:00
|
apache-2.0
| 2,375 |
|
fniessink__next-action-165
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 16cf30d..b325977 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,12 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/)
and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html).
+## [Unreleased] - 2018-07-17
+
+### Fixed
+
+- Give proper error message when the `--number` argument is smaller than one. Fixes #164.
+
## [1.5.3] - 2018-07-14
### Fixed
diff --git a/README.md b/README.md
index ffb50ba..b489018 100644
--- a/README.md
+++ b/README.md
@@ -448,9 +448,9 @@ To run the unit tests:
```console
$ python -m unittest
-............................................................................................................................................................................................................................................
+.............................................................................................................................................................................................................................................
----------------------------------------------------------------------
-Ran 236 tests in 2.931s
+Ran 237 tests in 2.303s
OK
```
@@ -461,9 +461,9 @@ To create the unit test coverage report run the unit tests under coverage with:
```console
$ coverage run --branch -m unittest
-............................................................................................................................................................................................................................................
+.............................................................................................................................................................................................................................................
----------------------------------------------------------------------
-Ran 236 tests in 3.557s
+Ran 237 tests in 3.159s
OK
```
@@ -475,7 +475,7 @@ $ coverage report --fail-under=100 --omit=".venv/*" --skip-covered
Name Stmts Miss Branch BrPart Cover
-----------------------------------------
-----------------------------------------
-TOTAL 1347 0 173 0 100%
+TOTAL 1360 0 177 0 100%
25 files skipped due to complete coverage.
```
diff --git a/next_action/arguments/parser.py b/next_action/arguments/parser.py
index 4d9df44..5d8c8ad 100644
--- a/next_action/arguments/parser.py
+++ b/next_action/arguments/parser.py
@@ -85,7 +85,7 @@ class NextActionArgumentParser(argparse.ArgumentParser):
"-a", "--all", default=1, action="store_const", dest="number", const=sys.maxsize,
help="show all next actions")
number.add_argument(
- "-n", "--number", metavar="<number>", type=int, default=1,
+ "-n", "--number", metavar="<number>", type=number_type, default=1,
help="number of next actions to show (default: %(default)s)")
def add_filter_arguments(self) -> None:
@@ -257,6 +257,17 @@ def date_type(value: str) -> datetime.date:
raise argparse.ArgumentTypeError("invalid date: {0}".format(value))
+def number_type(value: str) -> int:
+ """Return the value if it's positive, else raise an error."""
+ try:
+ number = int(value)
+ if number > 0:
+ return number
+ except ValueError:
+ pass
+ raise argparse.ArgumentTypeError("invalid number: {0}".format(value))
+
+
def subset(filters: List[str], prefix: str) -> Set[str]:
"""Return a subset of the filters based on prefix."""
return set(f.strip(prefix) for f in filters if f.startswith(prefix))
|
fniessink/next-action
|
46f06f9138ef0ca532c7e7ecb281fbbc85880d46
|
diff --git a/tests/unittests/arguments/test_parser.py b/tests/unittests/arguments/test_parser.py
index fed6430..e606485 100644
--- a/tests/unittests/arguments/test_parser.py
+++ b/tests/unittests/arguments/test_parser.py
@@ -212,7 +212,16 @@ class NumberTest(ParserTestCase):
"""Test that the argument parser exits if the option is faulty."""
self.assertRaises(SystemExit, parse_arguments)
self.assertEqual([call(USAGE_MESSAGE),
- call("next-action: error: argument -n/--number: invalid int value: 'not_a_number'\n")],
+ call("next-action: error: argument -n/--number: invalid number: not_a_number\n")],
+ mock_stderr_write.call_args_list)
+
+ @patch.object(sys, "argv", ["next-action", "--number", "-1"])
+ @patch.object(sys.stderr, "write")
+ def test_negative_number(self, mock_stderr_write):
+ """Test that the argument parser exits if the option is faulty."""
+ self.assertRaises(SystemExit, parse_arguments)
+ self.assertEqual([call(USAGE_MESSAGE),
+ call("next-action: error: argument -n/--number: invalid number: -1\n")],
mock_stderr_write.call_args_list)
@patch.object(sys, "argv", ["next-action", "--all"])
|
Give error message when --number argument is a negative integer
|
0.0
|
46f06f9138ef0ca532c7e7ecb281fbbc85880d46
|
[
"tests/unittests/arguments/test_parser.py::NumberTest::test_faulty_number",
"tests/unittests/arguments/test_parser.py::NumberTest::test_negative_number"
] |
[
"tests/unittests/arguments/test_parser.py::NoArgumentTest::test_filename",
"tests/unittests/arguments/test_parser.py::NoArgumentTest::test_filters",
"tests/unittests/arguments/test_parser.py::NoArgumentTest::test_style",
"tests/unittests/arguments/test_parser.py::FilenameTest::test_add_default_filename",
"tests/unittests/arguments/test_parser.py::FilenameTest::test_add_filename_twice",
"tests/unittests/arguments/test_parser.py::FilenameTest::test_default_and_non_default",
"tests/unittests/arguments/test_parser.py::FilenameTest::test_filename_argument",
"tests/unittests/arguments/test_parser.py::FilenameTest::test_home_folder_argument",
"tests/unittests/arguments/test_parser.py::FilenameTest::test_long_filename_argument",
"tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_contexts_and_projects",
"tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_empty_context",
"tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_empty_excluded_project",
"tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_empty_project",
"tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_exclude_context",
"tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_exclude_project",
"tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_faulty_option",
"tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_include_exclude_context",
"tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_include_exclude_project",
"tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_invalid_extra_argument",
"tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_multiple_contexts",
"tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_multiple_projects",
"tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_one_context",
"tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_one_project",
"tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_project_after_excluded",
"tests/unittests/arguments/test_parser.py::NumberTest::test_all_actions",
"tests/unittests/arguments/test_parser.py::NumberTest::test_all_and_number",
"tests/unittests/arguments/test_parser.py::NumberTest::test_default_number",
"tests/unittests/arguments/test_parser.py::NumberTest::test_number",
"tests/unittests/arguments/test_parser.py::DueDateTest::test_default",
"tests/unittests/arguments/test_parser.py::DueDateTest::test_due_date",
"tests/unittests/arguments/test_parser.py::DueDateTest::test_faulty_date",
"tests/unittests/arguments/test_parser.py::DueDateTest::test_invalid_date",
"tests/unittests/arguments/test_parser.py::DueDateTest::test_no_due_date",
"tests/unittests/arguments/test_parser.py::DueDateTest::test_too_long",
"tests/unittests/arguments/test_parser.py::ReferenceTest::test_always",
"tests/unittests/arguments/test_parser.py::ReferenceTest::test_default",
"tests/unittests/arguments/test_parser.py::ReferenceTest::test_faulty_date",
"tests/unittests/arguments/test_parser.py::ReferenceTest::test_multiple",
"tests/unittests/arguments/test_parser.py::ReferenceTest::test_never"
] |
{
"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-07-17 07:25:30+00:00
|
apache-2.0
| 2,376 |
|
fniessink__next-action-24
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f34f269..0f35cce 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,13 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/)
and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html).
+
+## [Unreleased]
+
+### Changed
+
+- Renamed Next-action's binary from `next_action` to `next-action` for consistency with the application and project name.
+
## [0.0.4] - 2018-05-10
### Added
diff --git a/README.md b/README.md
index 2d235e0..df935dd 100644
--- a/README.md
+++ b/README.md
@@ -7,7 +7,7 @@
[](https://www.codacy.com/app/frank_10/next-action?utm_source=github.com&utm_medium=referral&utm_content=fniessink/next-action&utm_campaign=Badge_Grade)
[](https://www.codacy.com/app/frank_10/next-action?utm_source=github.com&utm_medium=referral&utm_content=fniessink/next-action&utm_campaign=Badge_Coverage)
-Determine the next action to work on from a list of actions in a todo.txt file.
+Determine the next action to work on from a list of actions in a todo.txt file. Next-action is alpha-stage at the moment, so its options are rather limited at the moment.
Don't know what todo.txt is? See <https://github.com/todotxt/todo.txt> for the todo.txt specification.
@@ -22,8 +22,8 @@ Next-action requires Python 3.6 or newer.
## Usage
```console
-$ next_action --help
-usage: next_action [-h] [--version] [-f FILE] [@CONTEXT]
+$ next-action --help
+usage: next-action [-h] [--version] [-f FILE] [@CONTEXT]
Show the next action in your todo.txt
@@ -36,6 +36,22 @@ optional arguments:
-f FILE, --file FILE filename of the todo.txt file to read (default: todo.txt)
```
+Assuming your todo.txt file is in the current folder, running Next-action without arguments will show the next action you should do based on your tasks' priorities:
+
+```console
+$ next-action
+(A) Call mom @phone
+```
+
+You can limit the tasks from which Next-action picks the next action by passing a context:
+
+```console
+$ next-action @work
+(C) Finish proposal for important client @work
+```
+
+Since Next-action is still alpha-stage, this is it for the moment. Stay tuned for more options.
+
## Develop
Clone the repository and run the unit tests with `python setup.py test`.
diff --git a/next_action/arguments.py b/next_action/arguments.py
index 8485bf5..6889cd5 100644
--- a/next_action/arguments.py
+++ b/next_action/arguments.py
@@ -23,7 +23,7 @@ def parse_arguments() -> argparse.Namespace:
parser = argparse.ArgumentParser(description="Show the next action in your todo.txt",
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
- parser.add_argument("--version", action="version", version="Next-action {0}".format(next_action.__version__))
+ parser.add_argument("--version", action="version", version="%(prog)s {0}".format(next_action.__version__))
parser.add_argument("-f", "--file", help="filename of the todo.txt file to read",
type=str, default="todo.txt")
parser.add_argument("context", metavar="@CONTEXT", help="Show the next action in the specified context", nargs="?",
diff --git a/setup.py b/setup.py
index 46d8260..4bb8d0d 100644
--- a/setup.py
+++ b/setup.py
@@ -17,7 +17,7 @@ and more.""",
packages=find_packages(),
entry_points={
"console_scripts": [
- "next_action=next_action.cli:next_action",
+ "next-action=next_action.cli:next_action",
],
},
test_suite="tests",
|
fniessink/next-action
|
5c8b2ad17a806bae876c00b86ac4ee8402ecdc84
|
diff --git a/tests/unittests/test_arguments.py b/tests/unittests/test_arguments.py
index 3156a25..3c60285 100644
--- a/tests/unittests/test_arguments.py
+++ b/tests/unittests/test_arguments.py
@@ -9,37 +9,37 @@ from next_action.arguments import parse_arguments
class ArgumentParserTest(unittest.TestCase):
""" Unit tests for the argument parses. """
- @patch.object(sys, "argv", ["next_action"])
+ @patch.object(sys, "argv", ["next-action"])
def test_default_filename(self):
""" Test that the argument parser has a default filename. """
self.assertEqual("todo.txt", parse_arguments().file)
- @patch.object(sys, "argv", ["next_action", "-f", "my_todo.txt"])
+ @patch.object(sys, "argv", ["next-action", "-f", "my_todo.txt"])
def test_filename_argument(self):
""" Test that the argument parser accepts a filename. """
self.assertEqual("my_todo.txt", parse_arguments().file)
- @patch.object(sys, "argv", ["next_action", "--file", "my_other_todo.txt"])
+ @patch.object(sys, "argv", ["next-action", "--file", "my_other_todo.txt"])
def test_long_filename_argument(self):
""" Test that the argument parser accepts a filename. """
self.assertEqual("my_other_todo.txt", parse_arguments().file)
- @patch.object(sys, "argv", ["next_action"])
+ @patch.object(sys, "argv", ["next-action"])
def test_no_context(self):
""" Test that the argument parser returns no context if the user doesn't pass one. """
self.assertEqual(None, parse_arguments().context)
- @patch.object(sys, "argv", ["next_action", "@home"])
+ @patch.object(sys, "argv", ["next-action", "@home"])
def test_one_context(self):
""" Test that the argument parser returns the context if the user passes one. """
self.assertEqual("@home", parse_arguments().context)
- @patch.object(sys, "argv", ["next_action", "home"])
+ @patch.object(sys, "argv", ["next-action", "home"])
@patch.object(sys.stderr, "write")
def test_faulty_context(self, mock_stderr_write):
""" Test that the argument parser exits if the context is faulty. """
os.environ['COLUMNS'] = "120" # Fake that the terminal is wide enough.
self.assertRaises(SystemExit, parse_arguments)
- self.assertEqual([call("usage: next_action [-h] [--version] [-f FILE] [@CONTEXT]\n"),
- call("next_action: error: Contexts should start with an @.\n")],
+ self.assertEqual([call("usage: next-action [-h] [--version] [-f FILE] [@CONTEXT]\n"),
+ call("next-action: error: Contexts should start with an @.\n")],
mock_stderr_write.call_args_list)
\ No newline at end of file
diff --git a/tests/unittests/test_cli.py b/tests/unittests/test_cli.py
index 3cdefe1..5b20ad6 100644
--- a/tests/unittests/test_cli.py
+++ b/tests/unittests/test_cli.py
@@ -10,7 +10,7 @@ from next_action import __version__
class CLITest(unittest.TestCase):
""" Unit tests for the command-line interface. """
- @patch.object(sys, "argv", ["next_action"])
+ @patch.object(sys, "argv", ["next-action"])
@patch("next_action.cli.open", mock_open(read_data=""))
@patch.object(sys.stdout, "write")
def test_empty_task_file(self, mock_stdout_write):
@@ -18,7 +18,7 @@ class CLITest(unittest.TestCase):
next_action()
self.assertEqual([call("Nothing to do!"), call("\n")], mock_stdout_write.call_args_list)
- @patch.object(sys, "argv", ["next_action"])
+ @patch.object(sys, "argv", ["next-action"])
@patch("next_action.cli.open", mock_open(read_data="Todo\n"))
@patch.object(sys.stdout, "write")
def test_one_task(self, mock_stdout_write):
@@ -26,7 +26,7 @@ class CLITest(unittest.TestCase):
next_action()
self.assertEqual([call("Todo"), call("\n")], mock_stdout_write.call_args_list)
- @patch.object(sys, "argv", ["next_action"])
+ @patch.object(sys, "argv", ["next-action"])
@patch("next_action.cli.open")
@patch.object(sys.stdout, "write")
def test_missing_file(self, mock_stdout_write, mock_open):
@@ -35,13 +35,13 @@ class CLITest(unittest.TestCase):
next_action()
self.assertEqual([call("Can't find todo.txt"), call("\n")], mock_stdout_write.call_args_list)
- @patch.object(sys, "argv", ["next_action", "--help"])
+ @patch.object(sys, "argv", ["next-action", "--help"])
@patch.object(sys.stdout, "write")
def test_help(self, mock_stdout_write):
""" Test the help message. """
os.environ['COLUMNS'] = "120" # Fake that the terminal is wide enough.
self.assertRaises(SystemExit, next_action)
- self.assertEqual(call("""usage: next_action [-h] [--version] [-f FILE] [@CONTEXT]
+ self.assertEqual(call("""usage: next-action [-h] [--version] [-f FILE] [@CONTEXT]
Show the next action in your todo.txt
@@ -55,9 +55,9 @@ optional arguments:
"""),
mock_stdout_write.call_args_list[0])
- @patch.object(sys, "argv", ["next_action", "--version"])
+ @patch.object(sys, "argv", ["next-action", "--version"])
@patch.object(sys.stdout, "write")
def test_version(self, mock_stdout_write):
""" Test that --version shows the version number. """
self.assertRaises(SystemExit, next_action)
- self.assertEqual([call("Next-action {0}\n".format(__version__))], mock_stdout_write.call_args_list)
\ No newline at end of file
+ self.assertEqual([call("next-action {0}\n".format(__version__))], mock_stdout_write.call_args_list)
\ No newline at end of file
|
Change binary to next-action for consistency with application name
|
0.0
|
5c8b2ad17a806bae876c00b86ac4ee8402ecdc84
|
[
"tests/unittests/test_cli.py::CLITest::test_version"
] |
[
"tests/unittests/test_arguments.py::ArgumentParserTest::test_default_filename",
"tests/unittests/test_arguments.py::ArgumentParserTest::test_faulty_context",
"tests/unittests/test_arguments.py::ArgumentParserTest::test_filename_argument",
"tests/unittests/test_arguments.py::ArgumentParserTest::test_long_filename_argument",
"tests/unittests/test_arguments.py::ArgumentParserTest::test_no_context",
"tests/unittests/test_arguments.py::ArgumentParserTest::test_one_context",
"tests/unittests/test_cli.py::CLITest::test_empty_task_file",
"tests/unittests/test_cli.py::CLITest::test_help",
"tests/unittests/test_cli.py::CLITest::test_missing_file",
"tests/unittests/test_cli.py::CLITest::test_one_task"
] |
{
"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-05-11 10:13:48+00:00
|
apache-2.0
| 2,377 |
|
fniessink__next-action-31
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 684bdb0..0c3dbfe 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.
### Added
- Specify the number of next actions to show: `next-action --number 3`. Closes #7.
+- Show all next actions: `next-action --all`. Closes #29.
## [0.0.7] - 2018-05-12
diff --git a/README.md b/README.md
index 1c06d62..4876ffb 100644
--- a/README.md
+++ b/README.md
@@ -23,7 +23,7 @@ Don't know what *Todo.txt* is? See <https://github.com/todotxt/todo.txt> for the
```console
$ next-action --help
-usage: next-action [-h] [--version] [-f FILE] [-n N] [@CONTEXT [@CONTEXT ...]] [+PROJECT [+PROJECT ...]]
+uusage: next-action [-h] [--version] [-f FILE] [-n N | -a] [@CONTEXT [@CONTEXT ...]] [+PROJECT [+PROJECT ...]]
Show the next action in your todo.txt
@@ -36,6 +36,7 @@ optional arguments:
--version show program's version number and exit
-f FILE, --file FILE filename of the todo.txt file to read (default: todo.txt)
-n N, --number N number of next actions to show (default: 1)
+ -a, --all show all next actions (default: False)
```
Assuming your todo.txt file is in the current folder, running *Next-action* without arguments will show the next action you should do based on your tasks' priorities:
@@ -74,6 +75,19 @@ $ next-action --number 3
(C) Finish proposal for important client @work
```
+Or even show all next actions:
+
+```console
+$ next-action --number 3
+(A) Call mom @phone
+(B) Buy paint to +PaintHouse @store @weekend
+(C) Finish proposal for important client @work
+(G) Buy wood for new +DogHouse @store
+...
+```
+
+Note that completed tasks are never shown since they can't be a next action.
+
Since *Next-action* is still pre-alpha-stage, this is it for the moment. Stay tuned for more options.
## Develop
diff --git a/next_action/arguments.py b/next_action/arguments.py
index 51249fc..ec87cb1 100644
--- a/next_action/arguments.py
+++ b/next_action/arguments.py
@@ -3,6 +3,7 @@
import argparse
import os
import shutil
+import sys
from typing import Any, Sequence, Union
import next_action
@@ -17,12 +18,12 @@ class ContextProjectAction(argparse.Action): # pylint: disable=too-few-public-m
contexts = []
projects = []
for value in values:
- if self.__is_valid("Context", "@", value, parser):
+ if self.__is_valid("context", "@", value, parser):
contexts.append(value.strip("@"))
- elif self.__is_valid("Project", "+", value, parser):
+ elif self.__is_valid("project", "+", value, parser):
projects.append(value.strip("+"))
else:
- parser.error("Unrecognized argument '{0}'.".format(value))
+ parser.error("unrecognized argument: {0}".format(value))
if namespace.contexts is None:
namespace.contexts = contexts
if namespace.projects is None:
@@ -35,7 +36,7 @@ class ContextProjectAction(argparse.Action): # pylint: disable=too-few-public-m
if len(value) > 1:
return True
else:
- parser.error("{0} name cannot be empty.".format(argument_type.capitalize()))
+ parser.error("{0} name cannot be empty".format(argument_type))
return False
@@ -48,9 +49,14 @@ def parse_arguments() -> argparse.Namespace:
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("--version", action="version", version="%(prog)s {0}".format(next_action.__version__))
parser.add_argument("-f", "--file", help="filename of the todo.txt file to read", type=str, default="todo.txt")
- parser.add_argument("-n", "--number", metavar="N", help="number of next actions to show", type=int, default=1)
+ group = parser.add_mutually_exclusive_group()
+ group.add_argument("-n", "--number", metavar="N", help="number of next actions to show", type=int, default=1)
+ group.add_argument("-a", "--all", help="show all next actions", action="store_true")
parser.add_argument("contexts", metavar="@CONTEXT", help="show the next action in the specified contexts",
nargs="*", type=str, default=None, action=ContextProjectAction)
parser.add_argument("projects", metavar="+PROJECT", help="show the next action for the specified projects",
nargs="*", type=str, default=None, action=ContextProjectAction)
- return parser.parse_args()
+ namespace = parser.parse_args()
+ if namespace.all:
+ namespace.number = sys.maxsize
+ return namespace
|
fniessink/next-action
|
41a4b998821978a9a7ed832d8b6865a8e07a46c1
|
diff --git a/tests/unittests/test_arguments.py b/tests/unittests/test_arguments.py
index 25d20ee..6fa5f60 100644
--- a/tests/unittests/test_arguments.py
+++ b/tests/unittests/test_arguments.py
@@ -11,7 +11,7 @@ from next_action.arguments import parse_arguments
class ArgumentParserTest(unittest.TestCase):
""" Unit tests for the argument parses. """
- usage_message = "usage: next-action [-h] [--version] [-f FILE] [-n N] [@CONTEXT [@CONTEXT ...]] " \
+ usage_message = "usage: next-action [-h] [--version] [-f FILE] [-n N | -a] [@CONTEXT [@CONTEXT ...]] " \
"[+PROJECT [+PROJECT ...]]\n"
@patch.object(sys, "argv", ["next-action"])
@@ -50,7 +50,7 @@ class ArgumentParserTest(unittest.TestCase):
""" Test that the argument parser exits if the context is empty. """
os.environ['COLUMNS'] = "120" # Fake that the terminal is wide enough.
self.assertRaises(SystemExit, parse_arguments)
- self.assertEqual([call(self.usage_message), call("next-action: error: Context name cannot be empty.\n")],
+ self.assertEqual([call(self.usage_message), call("next-action: error: context name cannot be empty\n")],
mock_stderr_write.call_args_list)
@patch.object(sys, "argv", ["next-action", "+DogHouse"])
@@ -69,7 +69,7 @@ class ArgumentParserTest(unittest.TestCase):
""" Test that the argument parser exits if the project is empty. """
os.environ['COLUMNS'] = "120" # Fake that the terminal is wide enough.
self.assertRaises(SystemExit, parse_arguments)
- self.assertEqual([call(self.usage_message), call("next-action: error: Project name cannot be empty.\n")],
+ self.assertEqual([call(self.usage_message), call("next-action: error: project name cannot be empty\n")],
mock_stderr_write.call_args_list)
@patch.object(sys, "argv", ["next-action", "+DogHouse", "@home", "+PaintHouse", "@weekend"])
@@ -84,7 +84,7 @@ class ArgumentParserTest(unittest.TestCase):
""" Test that the argument parser exits if the option is faulty. """
os.environ['COLUMNS'] = "120" # Fake that the terminal is wide enough.
self.assertRaises(SystemExit, parse_arguments)
- self.assertEqual([call(self.usage_message), call("next-action: error: Unrecognized argument 'home'.\n")],
+ self.assertEqual([call(self.usage_message), call("next-action: error: unrecognized argument: home\n")],
mock_stderr_write.call_args_list)
@patch.object(sys, "argv", ["next-action"])
@@ -106,3 +106,19 @@ class ArgumentParserTest(unittest.TestCase):
self.assertEqual([call(self.usage_message),
call("next-action: error: argument -n/--number: invalid int value: 'not_a_number'\n")],
mock_stderr_write.call_args_list)
+
+ @patch.object(sys, "argv", ["next-action", "--all"])
+ def test_all_actions(self):
+ """ Test that --all option also sets the number of actions to show to a very big number. """
+ self.assertTrue(parse_arguments().all)
+ self.assertEqual(sys.maxsize, parse_arguments().number)
+
+ @patch.object(sys, "argv", ["next-action", "--all", "--number", "3"])
+ @patch.object(sys.stderr, "write")
+ def test_all_and_number(self, mock_stderr_write):
+ """ Test that the argument parser exits if the both --all and --number are used. """
+ os.environ['COLUMNS'] = "120" # Fake that the terminal is wide enough.
+ self.assertRaises(SystemExit, parse_arguments)
+ self.assertEqual([call(self.usage_message),
+ call("next-action: error: argument -n/--number: not allowed with argument -a/--all\n")],
+ mock_stderr_write.call_args_list)
diff --git a/tests/unittests/test_cli.py b/tests/unittests/test_cli.py
index 8f8e68f..1b80920 100644
--- a/tests/unittests/test_cli.py
+++ b/tests/unittests/test_cli.py
@@ -59,7 +59,7 @@ class CLITest(unittest.TestCase):
""" Test the help message. """
os.environ['COLUMNS'] = "120" # Fake that the terminal is wide enough.
self.assertRaises(SystemExit, next_action)
- self.assertEqual(call("""usage: next-action [-h] [--version] [-f FILE] [-n N] [@CONTEXT [@CONTEXT ...]] \
+ self.assertEqual(call("""usage: next-action [-h] [--version] [-f FILE] [-n N | -a] [@CONTEXT [@CONTEXT ...]] \
[+PROJECT [+PROJECT ...]]
Show the next action in your todo.txt
@@ -73,6 +73,7 @@ optional arguments:
--version show program's version number and exit
-f FILE, --file FILE filename of the todo.txt file to read (default: todo.txt)
-n N, --number N number of next actions to show (default: 1)
+ -a, --all show all next actions (default: False)
"""),
mock_stdout_write.call_args_list[0])
|
Allow for showing all (next) actions
```console
$ next-action --all
(A) World peace
(B) End hunger
(C) Call mom @home
Make a pizza @home
```
|
0.0
|
41a4b998821978a9a7ed832d8b6865a8e07a46c1
|
[
"tests/unittests/test_arguments.py::ArgumentParserTest::test_all_actions"
] |
[
"tests/unittests/test_arguments.py::ArgumentParserTest::test_contexts_and_projects",
"tests/unittests/test_arguments.py::ArgumentParserTest::test_default_filename",
"tests/unittests/test_arguments.py::ArgumentParserTest::test_default_number",
"tests/unittests/test_arguments.py::ArgumentParserTest::test_filename_argument",
"tests/unittests/test_arguments.py::ArgumentParserTest::test_long_filename_argument",
"tests/unittests/test_arguments.py::ArgumentParserTest::test_multiple_contexts",
"tests/unittests/test_arguments.py::ArgumentParserTest::test_multiple_projects",
"tests/unittests/test_arguments.py::ArgumentParserTest::test_no_context",
"tests/unittests/test_arguments.py::ArgumentParserTest::test_number",
"tests/unittests/test_arguments.py::ArgumentParserTest::test_one_context",
"tests/unittests/test_arguments.py::ArgumentParserTest::test_one_project",
"tests/unittests/test_cli.py::CLITest::test_context",
"tests/unittests/test_cli.py::CLITest::test_empty_task_file",
"tests/unittests/test_cli.py::CLITest::test_ignore_empty_lines",
"tests/unittests/test_cli.py::CLITest::test_missing_file",
"tests/unittests/test_cli.py::CLITest::test_number",
"tests/unittests/test_cli.py::CLITest::test_one_task",
"tests/unittests/test_cli.py::CLITest::test_project",
"tests/unittests/test_cli.py::CLITest::test_version"
] |
{
"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-05-12 22:00:47+00:00
|
apache-2.0
| 2,378 |
|
fniessink__next-action-39
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 5353797..b08b416 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,12 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/)
and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html).
+## [0.1.0] - 2018-05-13
+
+### Added
+
+- Take due date into account when determining the next action. Tasks due earlier take precedence. Closes #33.
+
## [0.0.9] - 2018-05-13
### Added
diff --git a/README.md b/README.md
index 3a98d93..beca8e8 100644
--- a/README.md
+++ b/README.md
@@ -7,7 +7,7 @@
[](https://www.codacy.com/app/frank_10/next-action?utm_source=github.com&utm_medium=referral&utm_content=fniessink/next-action&utm_campaign=Badge_Grade)
[](https://www.codacy.com/app/frank_10/next-action?utm_source=github.com&utm_medium=referral&utm_content=fniessink/next-action&utm_campaign=Badge_Coverage)
-Determine the next action to work on from a list of actions in a todo.txt file. *Next-action* is pre-alpha-stage at the moment, so its functionality is still rather limited.
+Determine the next action to work on from a list of actions in a todo.txt file. *Next-action* is alpha-stage at the moment, so its functionality is still rather limited.
Don't know what *Todo.txt* is? See <https://github.com/todotxt/todo.txt> for the *Todo.txt* specification.
@@ -50,7 +50,7 @@ $ next-action
(A) Call mom @phone
```
-The next action is determined using priority. Creation date is considered after priority, with older tasks getting precedence over newer tasks.
+The next action is determined using priority. Due date is considered after priority, with tasks due earlier getting precedence over tasks due later. Creation date is considered after due date, with older tasks getting precedence over newer tasks.
Completed tasks (~~`x This is a completed task`~~) and tasks with a creation date in the future (`9999-01-01 Start preparing for five-digit years`) are not considered when determining the next action.
@@ -97,7 +97,7 @@ $ next-action --all @store
Note again that completed tasks and task with a future creation date are never shown since they can't be a next action.
-*Next-action* being still pre-alpha-stage, this is it for the moment. Stay tuned for more options.
+*Next-action* being still alpha-stage, this is it for the moment. Stay tuned for more options.
## Develop
diff --git a/next_action/__init__.py b/next_action/__init__.py
index f916b9e..9aa288e 100644
--- a/next_action/__init__.py
+++ b/next_action/__init__.py
@@ -1,4 +1,4 @@
""" Main Next-action package. """
__title__ = "next-action"
-__version__ = "0.0.9"
+__version__ = "0.1.0"
diff --git a/next_action/pick_action.py b/next_action/pick_action.py
index a950112..444f65a 100644
--- a/next_action/pick_action.py
+++ b/next_action/pick_action.py
@@ -8,7 +8,7 @@ from .todotxt import Task
def sort_key(task: Task) -> Tuple[str, datetime.date]:
""" Return the sort key for a task. """
- return (task.priority() or "ZZZ", task.creation_date() or datetime.date.max)
+ return (task.priority() or "ZZZ", task.due_date() or datetime.date.max, task.creation_date() or datetime.date.max)
def next_actions(tasks: Sequence[Task], contexts: Set[str] = None, projects: Set[str] = None) -> Sequence[Task]:
@@ -19,5 +19,5 @@ def next_actions(tasks: Sequence[Task], contexts: Set[str] = None, projects: Set
tasks_in_context = filter(lambda task: contexts <= task.contexts() if contexts else True, actionable_tasks)
# Next, select the tasks that belong to at least one of the given projects, if any
tasks_in_project = filter(lambda task: projects & task.projects() if projects else True, tasks_in_context)
- # Finally, sort by priority and creation date
+ # Finally, sort by priority, due date and creation date
return sorted(tasks_in_project, key=sort_key)
diff --git a/next_action/todotxt/task.py b/next_action/todotxt/task.py
index 6ea1319..0ee3042 100644
--- a/next_action/todotxt/task.py
+++ b/next_action/todotxt/task.py
@@ -3,10 +3,14 @@
import datetime
import re
from typing import Optional, Set
+from typing.re import Match # pylint: disable=import-error
class Task(object):
""" A task from a line in a todo.txt file. """
+
+ iso_date_reg_exp = r"(\d{4})-(\d{1,2})-(\d{1,2})"
+
def __init__(self, todo_txt: str) -> None:
self.text = todo_txt
@@ -28,13 +32,13 @@ class Task(object):
def creation_date(self) -> Optional[datetime.date]:
""" Return the creation date of the task. """
- match = re.match(r"(?:\([A-Z]\) )?(\d{4})-(\d{1,2})-(\d{1,2})", self.text)
- if match:
- try:
- return datetime.date(*(int(group) for group in match.groups()))
- except ValueError:
- pass
- return None
+ match = re.match(r"(?:\([A-Z]\) )?{0}\b".format(self.iso_date_reg_exp), self.text)
+ return self.__create_date(match)
+
+ def due_date(self) -> Optional[datetime.date]:
+ """ Return the due date of the task. """
+ match = re.search(r"\bdue:{0}\b".format(self.iso_date_reg_exp), self.text)
+ return self.__create_date(match)
def is_completed(self) -> bool:
""" Return whether the task is completed or not. """
@@ -48,3 +52,13 @@ class Task(object):
def __prefixed_items(self, prefix: str) -> Set[str]:
""" Return the prefixed items in the task. """
return {match.group(1) for match in re.finditer(" {0}([^ ]+)".format(prefix), self.text)}
+
+ @staticmethod
+ def __create_date(match: Match) -> Optional[datetime.date]:
+ """ Create a date from the match, if possible. """
+ if match:
+ try:
+ return datetime.date(*(int(group) for group in match.groups()))
+ except ValueError:
+ pass
+ return None
diff --git a/setup.py b/setup.py
index bdbb6cd..67b4fd0 100644
--- a/setup.py
+++ b/setup.py
@@ -24,7 +24,7 @@ and more.""",
},
test_suite="tests",
classifiers=[
- "Development Status :: 2 - Pre-Alpha",
+ "Development Status :: 3 - Alpha",
"Environment :: Console",
"Intended Audience :: End Users/Desktop",
"License :: OSI Approved :: Apache Software License",
|
fniessink/next-action
|
e145fa742fb415e26ec78bff558a359e2022729e
|
diff --git a/tests/unittests/test_pick_action.py b/tests/unittests/test_pick_action.py
index 163b4aa..afd7844 100644
--- a/tests/unittests/test_pick_action.py
+++ b/tests/unittests/test_pick_action.py
@@ -94,3 +94,17 @@ class PickActionTest(unittest.TestCase):
older_task = todotxt.Task("2017-01-01 Task 3")
self.assertEqual([priority, older_task, newer_task],
pick_action.next_actions([priority, newer_task, older_task]))
+
+ def test_due_dates(self):
+ """ Test that a task with an earlier due date takes precedence. """
+ no_due_date = todotxt.Task("Task 1")
+ earlier_task = todotxt.Task("Task 2 due:2018-02-02")
+ later_task = todotxt.Task("Task 3 due:2019-01-01")
+ self.assertEqual([earlier_task, later_task, no_due_date],
+ pick_action.next_actions([no_due_date, later_task, earlier_task]))
+
+ def test_due_and_creation_dates(self):
+ """ Test that a task with a due date takes precedence over creation date. """
+ task1 = todotxt.Task("2018-1-1 Task 1")
+ task2 = todotxt.Task("Task 2 due:2018-1-1")
+ self.assertEqual([task2, task1], pick_action.next_actions([task1, task2]))
diff --git a/tests/unittests/todotxt/test_task.py b/tests/unittests/todotxt/test_task.py
index a0b1bf9..a6fa2b8 100644
--- a/tests/unittests/todotxt/test_task.py
+++ b/tests/unittests/todotxt/test_task.py
@@ -95,6 +95,10 @@ class CreationDateTest(unittest.TestCase):
""" Test an invalid creation date. """
self.assertEqual(None, todotxt.Task("2018-14-02 Todo").creation_date())
+ def test_no_space_after(self):
+ """ Test a creation date without a word boundary. """
+ self.assertEqual(None, todotxt.Task("2018-10-10Todo").creation_date())
+
def test_single_digits(self):
""" Test a creation date with single digits for day and/or month. """
self.assertEqual(datetime.date(2018, 12, 3), todotxt.Task("(B) 2018-12-3 Todo").creation_date())
@@ -106,6 +110,33 @@ class CreationDateTest(unittest.TestCase):
self.assertTrue(todotxt.Task("9999-01-01 Prepare for five-digit years").is_future())
+class DueDateTest(unittest.TestCase):
+ """ Unit tests for the due date of tasks. """
+
+ def test_no_due_date(self):
+ """ Test that tasks have no due date by default. """
+ self.assertEqual(None, todotxt.Task("Todo").due_date())
+
+ def test_due_date(self):
+ """ Test a valid due date. """
+ self.assertEqual(datetime.date(2018, 1, 2), todotxt.Task("Todo due:2018-01-02").due_date())
+
+ def test_invalid_date(self):
+ """ Test an invalid due date. """
+ self.assertEqual(None, todotxt.Task("Todo due:2018-01-32").due_date())
+
+ def test_no_space_after(self):
+ """ Test a due date without a word boundary following it. """
+ self.assertEqual(None, todotxt.Task("Todo due:2018-01-023").due_date())
+
+ def test_single_digits(self):
+ """ Test a due date with single digits for day and/or month. """
+ self.assertEqual(datetime.date(2018, 12, 3), todotxt.Task("(B) due:2018-12-3 Todo").due_date())
+ self.assertEqual(datetime.date(2018, 1, 13), todotxt.Task("(B) due:2018-1-13 Todo").due_date())
+ self.assertEqual(datetime.date(2018, 1, 1), todotxt.Task("(B) due:2018-1-1 Todo").due_date())
+
+
+
class TaskCompletionTest(unittest.TestCase):
""" Unit tests for the completion status of tasks. """
|
Take due date into account when determining next action
Due dates are not part of the todo.txt spec, but are usually added using the key:value pattern, e.g.:
`Pay taxes due:2018-05-01`
|
0.0
|
e145fa742fb415e26ec78bff558a359e2022729e
|
[
"tests/unittests/test_pick_action.py::PickActionTest::test_due_and_creation_dates",
"tests/unittests/test_pick_action.py::PickActionTest::test_due_dates",
"tests/unittests/todotxt/test_task.py::CreationDateTest::test_no_space_after",
"tests/unittests/todotxt/test_task.py::DueDateTest::test_due_date",
"tests/unittests/todotxt/test_task.py::DueDateTest::test_invalid_date",
"tests/unittests/todotxt/test_task.py::DueDateTest::test_no_due_date",
"tests/unittests/todotxt/test_task.py::DueDateTest::test_no_space_after",
"tests/unittests/todotxt/test_task.py::DueDateTest::test_single_digits"
] |
[
"tests/unittests/test_pick_action.py::PickActionTest::test_context",
"tests/unittests/test_pick_action.py::PickActionTest::test_contexts",
"tests/unittests/test_pick_action.py::PickActionTest::test_creation_dates",
"tests/unittests/test_pick_action.py::PickActionTest::test_higher_prio_goes_first",
"tests/unittests/test_pick_action.py::PickActionTest::test_ignore_completed_task",
"tests/unittests/test_pick_action.py::PickActionTest::test_ignore_future_task",
"tests/unittests/test_pick_action.py::PickActionTest::test_ignore_these_tasks",
"tests/unittests/test_pick_action.py::PickActionTest::test_multiple_tasks",
"tests/unittests/test_pick_action.py::PickActionTest::test_no_tasks",
"tests/unittests/test_pick_action.py::PickActionTest::test_one_task",
"tests/unittests/test_pick_action.py::PickActionTest::test_priority_and_creation_date",
"tests/unittests/test_pick_action.py::PickActionTest::test_project",
"tests/unittests/test_pick_action.py::PickActionTest::test_project_and_context",
"tests/unittests/todotxt/test_task.py::TodoTest::test_task_repr",
"tests/unittests/todotxt/test_task.py::TodoTest::test_task_text",
"tests/unittests/todotxt/test_task.py::TodoContextTest::test_no_context",
"tests/unittests/todotxt/test_task.py::TodoContextTest::test_no_space_before_at_sign",
"tests/unittests/todotxt/test_task.py::TodoContextTest::test_one_context",
"tests/unittests/todotxt/test_task.py::TodoContextTest::test_two_contexts",
"tests/unittests/todotxt/test_task.py::TaskProjectTest::test_no_projects",
"tests/unittests/todotxt/test_task.py::TaskProjectTest::test_no_space_before_at_sign",
"tests/unittests/todotxt/test_task.py::TaskProjectTest::test_one_project",
"tests/unittests/todotxt/test_task.py::TaskProjectTest::test_two_projects",
"tests/unittests/todotxt/test_task.py::TaskPriorityTest::test_faulty_priorities",
"tests/unittests/todotxt/test_task.py::TaskPriorityTest::test_no_priority",
"tests/unittests/todotxt/test_task.py::TaskPriorityTest::test_priorities",
"tests/unittests/todotxt/test_task.py::CreationDateTest::test_creation_date",
"tests/unittests/todotxt/test_task.py::CreationDateTest::test_creation_date_after_priority",
"tests/unittests/todotxt/test_task.py::CreationDateTest::test_invalid_creation_date",
"tests/unittests/todotxt/test_task.py::CreationDateTest::test_is_future_task",
"tests/unittests/todotxt/test_task.py::CreationDateTest::test_no_creation_date",
"tests/unittests/todotxt/test_task.py::CreationDateTest::test_single_digits",
"tests/unittests/todotxt/test_task.py::TaskCompletionTest::test_completed",
"tests/unittests/todotxt/test_task.py::TaskCompletionTest::test_not_completed",
"tests/unittests/todotxt/test_task.py::TaskCompletionTest::test_space_after_x",
"tests/unittests/todotxt/test_task.py::TaskCompletionTest::test_x_must_be_lowercase"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2018-05-13 20:52:13+00:00
|
apache-2.0
| 2,379 |
|
fniessink__next-action-55
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e0174c6..e107c92 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,16 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/)
and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html).
+## [Unreleased]
+
+### Added
+
+- The `--file` argument accepts `-` to read input from standard input. Closes #42.
+
+### Changed
+
+- Give consistent error message when files can't be opened. Fixes #54.
+
## [0.2.1] - 2018-05-16
### Changed
diff --git a/README.md b/README.md
index 25fc8eb..e759dae 100644
--- a/README.md
+++ b/README.md
@@ -27,26 +27,26 @@ Don't know what *Todo.txt* is? See <https://github.com/todotxt/todo.txt> for the
```console
$ next-action --help
-usage: next-action [-h] [--version] [-f <todo.txt>] [-n <number> | -a] [<context|project> ...]
+usage: next-action [-h] [--version] [-f <filename>] [-n <number> | -a] [<context|project> ...]
-Show the next action in your todo.txt. The next action is selected from the tasks in the todo.txt
-file based on priority, due date, creation date, and supplied filters.
+Show the next action in your todo.txt. The next action is selected from the tasks in the todo.txt file based on
+priority, due date, creation date, and supplied filters.
optional arguments:
-h, --help show this help message and exit
--version show program's version number and exit
- -f <todo.txt>, --file <todo.txt>
- todo.txt file to read; argument can be repeated to read tasks from multiple
- todo.txt files (default: ['todo.txt'])
+ -f <filename>, --file <filename>
+ filename of todo.txt file to read; can be - to read from standard input; argument can be
+ repeated to read tasks from multiple todo.txt files (default: ['todo.txt'])
-n <number>, --number <number>
number of next actions to show (default: 1)
-a, --all show all next actions (default: False)
optional context and project arguments; these can be repeated:
- @<context> context the next action must have (default: None)
- +<project> project the next action must be part of (default: None)
- -@<context> context the next action must not have (default: None)
- -+<project> project the next action must not be part of (default: None)
+ @<context> context the next action must have
+ +<project> project the next action must be part of
+ -@<context> context the next action must not have
+ -+<project> project the next action must not be part of
```
Assuming your todo.txt file is in the current folder, running *Next-action* without arguments will show the next action you should do. Given this [todo.txt](todo.txt), calling mom would be the next action:
diff --git a/next_action/arguments/__init__.py b/next_action/arguments/__init__.py
index 73eb785..45faa29 100644
--- a/next_action/arguments/__init__.py
+++ b/next_action/arguments/__init__.py
@@ -4,7 +4,7 @@ import argparse
import os
import shutil
import sys
-from typing import Dict, List, Set
+from typing import cast, Dict, List, Set, Tuple
from .arguments import Arguments
from .parser import build_parser, parse_remaining_args
@@ -15,8 +15,8 @@ def parse_arguments() -> Arguments:
# Ensure that the help info is printed using all columns available
os.environ['COLUMNS'] = str(shutil.get_terminal_size().columns)
default_filenames = ["todo.txt"]
- arguments = Arguments(default_filenames)
parser = build_parser(default_filenames)
+ arguments = Arguments(parser, default_filenames)
namespace, remaining = parser.parse_known_args()
parse_remaining_args(parser, remaining, namespace)
arguments.filenames = namespace.filenames
diff --git a/next_action/arguments/arguments.py b/next_action/arguments/arguments.py
index e06f4d5..afbe5ac 100644
--- a/next_action/arguments/arguments.py
+++ b/next_action/arguments/arguments.py
@@ -1,12 +1,14 @@
""" Argument data class for transfering command line arguments. """
+import argparse
import sys
from typing import List, Set
class Arguments(object):
""" Argument data class. """
- def __init__(self, default_filenames: List[str]) -> None:
+ def __init__(self, parser: argparse.ArgumentParser, default_filenames: List[str]) -> None:
+ self.parser = parser
self.__default_filenames = default_filenames
self.__filenames: List[str] = []
self.__filters: List[Set[str]] = []
diff --git a/next_action/arguments/parser.py b/next_action/arguments/parser.py
index 18afb99..0d3ed9d 100644
--- a/next_action/arguments/parser.py
+++ b/next_action/arguments/parser.py
@@ -12,7 +12,7 @@ def build_parser(default_filenames: List[str]) -> argparse.ArgumentParser:
description="Show the next action in your todo.txt. The next action is selected from the tasks in the todo.txt \
file based on priority, due date, creation date, and supplied filters.",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
- usage="%(prog)s [-h] [--version] [-f <todo.txt>] [-n <number> | -a] [<context|project> ...]")
+ usage="%(prog)s [-h] [--version] [-f <filename>] [-n <number> | -a] [<context|project> ...]")
add_optional_arguments(parser, default_filenames)
add_positional_arguments(parser)
return parser
@@ -23,8 +23,9 @@ def add_optional_arguments(parser: argparse.ArgumentParser, default_filenames: L
parser.add_argument(
"--version", action="version", version="%(prog)s {0}".format(next_action.__version__))
parser.add_argument(
- "-f", "--file", action="append", dest="filenames", metavar="<todo.txt>", default=default_filenames, type=str,
- help="todo.txt file to read; argument can be repeated to read tasks from multiple todo.txt files")
+ "-f", "--file", action="append", dest="filenames", metavar="<filename>", default=default_filenames, type=str,
+ help="filename of todo.txt file to read; can be - to read from standard input; argument can be repeated to "
+ "read tasks from multiple todo.txt files")
number = parser.add_mutually_exclusive_group()
number.add_argument(
"-n", "--number", metavar="<number>", help="number of next actions to show", type=int, default=1)
diff --git a/next_action/cli.py b/next_action/cli.py
index 8e9888a..03cda4c 100644
--- a/next_action/cli.py
+++ b/next_action/cli.py
@@ -1,5 +1,7 @@
""" Entry point for Next-action's command-line interface. """
+import fileinput
+
from next_action.arguments import parse_arguments
from next_action.pick_action import next_actions
from next_action.todotxt import read_todotxt_file
@@ -14,13 +16,10 @@ def next_action() -> None:
3) determine the next action(s) and display them.
"""
arguments = parse_arguments()
- tasks = []
- for filename in arguments.filenames:
- try:
- todotxt_file = open(filename, "r")
- except FileNotFoundError:
- print("Can't find {0}".format(filename))
- return
- tasks.extend(read_todotxt_file(todotxt_file))
+ try:
+ with fileinput.input(arguments.filenames) as todotxt_file:
+ tasks = read_todotxt_file(todotxt_file)
+ except OSError as reason:
+ arguments.parser.error("can't open file: {0}".format(reason))
actions = next_actions(tasks, *arguments.filters)
print("\n".join(action.text for action in actions[:arguments.number]) if actions else "Nothing to do!")
diff --git a/next_action/todotxt/__init__.py b/next_action/todotxt/__init__.py
index 3faed18..1b2b424 100644
--- a/next_action/todotxt/__init__.py
+++ b/next_action/todotxt/__init__.py
@@ -8,4 +8,4 @@ from .task import Task
def read_todotxt_file(todoxt_file: IO[str]) -> List[Task]:
""" Read tasks from a Todo.txt file. """
with todoxt_file:
- return [Task(line.strip()) for line in todoxt_file.readlines() if line.strip()]
+ return [Task(line.strip()) for line in todoxt_file if line.strip()]
|
fniessink/next-action
|
56fd078f158b0b278b8c8b39cd4b5dd314760a32
|
diff --git a/tests/unittests/test_arguments.py b/tests/unittests/test_arguments.py
index 626f557..7dc6ce6 100644
--- a/tests/unittests/test_arguments.py
+++ b/tests/unittests/test_arguments.py
@@ -8,7 +8,7 @@ from unittest.mock import patch, call
from next_action.arguments import parse_arguments
-USAGE_MESSAGE = "usage: next-action [-h] [--version] [-f <todo.txt>] [-n <number> | -a] [<context|project> ...]\n"
+USAGE_MESSAGE = "usage: next-action [-h] [--version] [-f <filename>] [-n <number> | -a] [<context|project> ...]\n"
class NoArgumentTest(unittest.TestCase):
diff --git a/tests/unittests/test_cli.py b/tests/unittests/test_cli.py
index 80b4a5f..299b65d 100644
--- a/tests/unittests/test_cli.py
+++ b/tests/unittests/test_cli.py
@@ -8,12 +8,14 @@ from unittest.mock import patch, mock_open, call
from next_action.cli import next_action
from next_action import __version__
+from .test_arguments import USAGE_MESSAGE
+
class CLITest(unittest.TestCase):
""" Unit tests for the command-line interface. """
@patch.object(sys, "argv", ["next-action"])
- @patch("next_action.cli.open", mock_open(read_data=""))
+ @patch("fileinput.open", mock_open(read_data=""))
@patch.object(sys.stdout, "write")
def test_empty_task_file(self, mock_stdout_write):
""" Test the response when the task file is empty. """
@@ -21,7 +23,7 @@ class CLITest(unittest.TestCase):
self.assertEqual([call("Nothing to do!"), call("\n")], mock_stdout_write.call_args_list)
@patch.object(sys, "argv", ["next-action"])
- @patch("next_action.cli.open", mock_open(read_data="Todo\n"))
+ @patch("fileinput.open", mock_open(read_data="Todo\n"))
@patch.object(sys.stdout, "write")
def test_one_task(self, mock_stdout_write):
""" Test the response when the task file has one task. """
@@ -29,7 +31,7 @@ class CLITest(unittest.TestCase):
self.assertEqual([call("Todo"), call("\n")], mock_stdout_write.call_args_list)
@patch.object(sys, "argv", ["next-action", "@work"])
- @patch("next_action.cli.open", mock_open(read_data="Todo @home\nTodo @work\n"))
+ @patch("fileinput.open", mock_open(read_data="Todo @home\nTodo @work\n"))
@patch.object(sys.stdout, "write")
def test_context(self, mock_stdout_write):
""" Test the response when the user passes a context. """
@@ -37,7 +39,7 @@ class CLITest(unittest.TestCase):
self.assertEqual([call("Todo @work"), call("\n")], mock_stdout_write.call_args_list)
@patch.object(sys, "argv", ["next-action", "+DogHouse"])
- @patch("next_action.cli.open", mock_open(read_data="Walk the dog @home\nBuy wood +DogHouse\n"))
+ @patch("fileinput.open", mock_open(read_data="Walk the dog @home\nBuy wood +DogHouse\n"))
@patch.object(sys.stdout, "write")
def test_project(self, mock_stdout_write):
""" Test the response when the user passes a project. """
@@ -45,13 +47,14 @@ class CLITest(unittest.TestCase):
self.assertEqual([call("Buy wood +DogHouse"), call("\n")], mock_stdout_write.call_args_list)
@patch.object(sys, "argv", ["next-action"])
- @patch("next_action.cli.open")
- @patch.object(sys.stdout, "write")
- def test_missing_file(self, mock_stdout_write, mock_file_open):
+ @patch("fileinput.open")
+ @patch.object(sys.stderr, "write")
+ def test_missing_file(self, mock_stderr_write, mock_file_open):
""" Test the response when the task file can't be found. """
- mock_file_open.side_effect = FileNotFoundError
- next_action()
- self.assertEqual([call("Can't find todo.txt"), call("\n")], mock_stdout_write.call_args_list)
+ mock_file_open.side_effect = OSError("some problem")
+ self.assertRaises(SystemExit, next_action)
+ self.assertEqual([call(USAGE_MESSAGE), call("next-action: error: can't open file: some problem\n")],
+ mock_stderr_write.call_args_list)
@patch.object(sys, "argv", ["next-action", "--help"])
@patch.object(sys.stdout, "write")
@@ -59,8 +62,7 @@ class CLITest(unittest.TestCase):
""" Test the help message. """
os.environ['COLUMNS'] = "120" # Fake that the terminal is wide enough.
self.assertRaises(SystemExit, next_action)
- self.assertEqual(call("""usage: next-action [-h] [--version] [-f <todo.txt>] [-n <number> | -a] \
-[<context|project> ...]
+ self.assertEqual(call("""usage: next-action [-h] [--version] [-f <filename>] [-n <number> | -a] [<context|project> ...]
Show the next action in your todo.txt. The next action is selected from the tasks in the todo.txt file based on
priority, due date, creation date, and supplied filters.
@@ -68,9 +70,9 @@ priority, due date, creation date, and supplied filters.
optional arguments:
-h, --help show this help message and exit
--version show program's version number and exit
- -f <todo.txt>, --file <todo.txt>
- todo.txt file to read; argument can be repeated to read tasks from multiple todo.txt files
- (default: ['todo.txt'])
+ -f <filename>, --file <filename>
+ filename of todo.txt file to read; can be - to read from standard input; argument can be
+ repeated to read tasks from multiple todo.txt files (default: ['todo.txt'])
-n <number>, --number <number>
number of next actions to show (default: 1)
-a, --all show all next actions (default: False)
@@ -91,7 +93,7 @@ optional context and project arguments; these can be repeated:
self.assertEqual([call("next-action {0}\n".format(__version__))], mock_stdout_write.call_args_list)
@patch.object(sys, "argv", ["next-action", "--number", "2"])
- @patch("next_action.cli.open", mock_open(read_data="Walk the dog @home\n(A) Buy wood +DogHouse\n(B) Call mom\n"))
+ @patch("fileinput.open", mock_open(read_data="Walk the dog @home\n(A) Buy wood +DogHouse\n(B) Call mom\n"))
@patch.object(sys.stdout, "write")
def test_number(self, mock_stdout_write):
""" Test that the number of next actions can be specified. """
@@ -99,9 +101,18 @@ optional context and project arguments; these can be repeated:
self.assertEqual([call("(A) Buy wood +DogHouse\n(B) Call mom"), call("\n")], mock_stdout_write.call_args_list)
@patch.object(sys, "argv", ["next-action", "--number", "3"])
- @patch("next_action.cli.open", mock_open(read_data="\nWalk the dog @home\n \n(B) Call mom\n"))
+ @patch("fileinput.open", mock_open(read_data="\nWalk the dog @home\n \n(B) Call mom\n"))
@patch.object(sys.stdout, "write")
def test_ignore_empty_lines(self, mock_stdout_write):
""" Test that empty lines in the todo.txt file are ignored. """
next_action()
self.assertEqual([call("(B) Call mom\nWalk the dog @home"), call("\n")], mock_stdout_write.call_args_list)
+
+ @patch.object(sys, "argv", ["next-action", "--file", "-"])
+ @patch.object(sys.stdin, "readline")
+ @patch.object(sys.stdout, "write")
+ def test_reading_stdin(self, mock_stdout_write, mock_stdin_readline):
+ """ Test that tasks can be read from stdin works. """
+ mock_stdin_readline.side_effect = ["(B) Call mom\n", "Walk the dog\n", StopIteration]
+ next_action()
+ self.assertEqual([call("(B) Call mom"), call("\n")], mock_stdout_write.call_args_list)
|
Add option to read todo.txt from stdin
```console
$ cat todo.txt | next-action -
Buy newspaper
```
Use the fileinput module for iterating over the files, including stdin.
|
0.0
|
56fd078f158b0b278b8c8b39cd4b5dd314760a32
|
[
"tests/unittests/test_arguments.py::FilterArgumentTest::test_empty_context",
"tests/unittests/test_arguments.py::FilterArgumentTest::test_empty_excluded_project",
"tests/unittests/test_arguments.py::FilterArgumentTest::test_empty_project",
"tests/unittests/test_arguments.py::FilterArgumentTest::test_faulty_option",
"tests/unittests/test_arguments.py::FilterArgumentTest::test_include_exclude_context",
"tests/unittests/test_arguments.py::FilterArgumentTest::test_include_exclude_project",
"tests/unittests/test_arguments.py::FilterArgumentTest::test_invalid_extra_argument",
"tests/unittests/test_arguments.py::NumberTest::test_all_and_number",
"tests/unittests/test_arguments.py::NumberTest::test_faulty_number",
"tests/unittests/test_cli.py::CLITest::test_context",
"tests/unittests/test_cli.py::CLITest::test_empty_task_file",
"tests/unittests/test_cli.py::CLITest::test_help",
"tests/unittests/test_cli.py::CLITest::test_ignore_empty_lines",
"tests/unittests/test_cli.py::CLITest::test_missing_file",
"tests/unittests/test_cli.py::CLITest::test_number",
"tests/unittests/test_cli.py::CLITest::test_one_task",
"tests/unittests/test_cli.py::CLITest::test_project",
"tests/unittests/test_cli.py::CLITest::test_reading_stdin"
] |
[
"tests/unittests/test_arguments.py::NoArgumentTest::test_filename",
"tests/unittests/test_arguments.py::NoArgumentTest::test_filters",
"tests/unittests/test_arguments.py::FilenameTest::test__add_filename_twice",
"tests/unittests/test_arguments.py::FilenameTest::test_add_default_filename",
"tests/unittests/test_arguments.py::FilenameTest::test_default_and_non_default",
"tests/unittests/test_arguments.py::FilenameTest::test_filename_argument",
"tests/unittests/test_arguments.py::FilenameTest::test_long_filename_argument",
"tests/unittests/test_arguments.py::FilterArgumentTest::test_contexts_and_projects",
"tests/unittests/test_arguments.py::FilterArgumentTest::test_exclude_context",
"tests/unittests/test_arguments.py::FilterArgumentTest::test_exclude_project",
"tests/unittests/test_arguments.py::FilterArgumentTest::test_multiple_contexts",
"tests/unittests/test_arguments.py::FilterArgumentTest::test_multiple_projects",
"tests/unittests/test_arguments.py::FilterArgumentTest::test_one_context",
"tests/unittests/test_arguments.py::FilterArgumentTest::test_one_project",
"tests/unittests/test_arguments.py::NumberTest::test_all_actions",
"tests/unittests/test_arguments.py::NumberTest::test_default_number",
"tests/unittests/test_arguments.py::NumberTest::test_number",
"tests/unittests/test_cli.py::CLITest::test_version"
] |
{
"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-05-18 21:56:01+00:00
|
apache-2.0
| 2,380 |
|
fniessink__next-action-56
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index cae04b8..aba1ba2 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,12 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/)
and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html).
+## [Unreleased]
+
+### Changed
+
+- If no file is specified, *Next-action* tries to read the todo.txt in the user's home folder. Closes #4.
+
## [0.3.0] - 2018-05-19
### Added
diff --git a/README.md b/README.md
index 8e9e88d..4a0f179 100644
--- a/README.md
+++ b/README.md
@@ -37,7 +37,7 @@ optional arguments:
--version show program's version number and exit
-f <filename>, --file <filename>
filename of todo.txt file to read; can be - to read from standard input; argument can be
- repeated to read tasks from multiple todo.txt files (default: ['todo.txt'])
+ repeated to read tasks from multiple todo.txt files (default: ['~/todo.txt'])
-n <number>, --number <number>
number of next actions to show (default: 1)
-a, --all show all next actions (default: False)
@@ -49,7 +49,7 @@ optional context and project arguments; these can be repeated:
-+<project> project the next action must not be part of
```
-Assuming your todo.txt file is in the current folder, running *Next-action* without arguments will show the next action you should do. Given this [todo.txt](todo.txt), calling mom would be the next action:
+Assuming your todo.txt file is your home folder, running *Next-action* without arguments will show the next action you should do. Given this [todo.txt](todo.txt), calling mom would be the next action:
```console
$ next-action
diff --git a/next_action/arguments/__init__.py b/next_action/arguments/__init__.py
index 45faa29..2389d2f 100644
--- a/next_action/arguments/__init__.py
+++ b/next_action/arguments/__init__.py
@@ -14,7 +14,7 @@ def parse_arguments() -> Arguments:
""" Build the argument parser, paerse the command line arguments, and post-process them. """
# Ensure that the help info is printed using all columns available
os.environ['COLUMNS'] = str(shutil.get_terminal_size().columns)
- default_filenames = ["todo.txt"]
+ default_filenames = ["~/todo.txt"]
parser = build_parser(default_filenames)
arguments = Arguments(parser, default_filenames)
namespace, remaining = parser.parse_known_args()
diff --git a/next_action/arguments/arguments.py b/next_action/arguments/arguments.py
index afbe5ac..384e841 100644
--- a/next_action/arguments/arguments.py
+++ b/next_action/arguments/arguments.py
@@ -1,6 +1,7 @@
""" Argument data class for transfering command line arguments. """
import argparse
+import os.path
import sys
from typing import List, Set
@@ -28,7 +29,7 @@ class Arguments(object):
for default_filename in self.__default_filenames:
filenames.remove(default_filename)
# Remove duplicate filenames while maintaining order.
- self.__filenames = list(dict.fromkeys(filenames))
+ self.__filenames = [os.path.expanduser(filename) for filename in list(dict.fromkeys(filenames))]
def show_all(self, show_all: bool) -> None:
""" If the user wants to see all next actions, set the number to something big. """
diff --git a/update_readme.py b/update_readme.py
index c86bcb1..96b8da3 100644
--- a/update_readme.py
+++ b/update_readme.py
@@ -18,7 +18,7 @@ def update_readme():
in_console_section = False
elif line.startswith("$ "):
print(line)
- command = line[2:].split(" ")
+ command = line[2:].split(" ") + ["--file", "todo.txt"]
command_output = subprocess.run(command, stdout=subprocess.PIPE, universal_newlines=True)
print(command_output.stdout.rstrip())
elif not in_console_section:
|
fniessink/next-action
|
663a557773123886a51e1657a6f8fe81550006dd
|
diff --git a/tests/unittests/test_arguments.py b/tests/unittests/test_arguments.py
index 7dc6ce6..4c7bbf9 100644
--- a/tests/unittests/test_arguments.py
+++ b/tests/unittests/test_arguments.py
@@ -22,7 +22,7 @@ class NoArgumentTest(unittest.TestCase):
@patch.object(sys, "argv", ["next-action"])
def test_filename(self):
""" Test that the argument parser returns the default filename if the user doesn't pass one. """
- self.assertEqual(["todo.txt"], parse_arguments().filenames)
+ self.assertEqual([os.path.expanduser("~/todo.txt")], parse_arguments().filenames)
class FilenameTest(unittest.TestCase):
diff --git a/tests/unittests/test_cli.py b/tests/unittests/test_cli.py
index 99da454..0cabed3 100644
--- a/tests/unittests/test_cli.py
+++ b/tests/unittests/test_cli.py
@@ -73,7 +73,7 @@ optional arguments:
--version show program's version number and exit
-f <filename>, --file <filename>
filename of todo.txt file to read; can be - to read from standard input; argument can be
- repeated to read tasks from multiple todo.txt files (default: ['todo.txt'])
+ repeated to read tasks from multiple todo.txt files (default: ['~/todo.txt'])
-n <number>, --number <number>
number of next actions to show (default: 1)
-a, --all show all next actions (default: False)
diff --git a/tests/unittests/test_pick_action.py b/tests/unittests/test_pick_action.py
index 82cbc42..8fec9cc 100644
--- a/tests/unittests/test_pick_action.py
+++ b/tests/unittests/test_pick_action.py
@@ -145,4 +145,4 @@ class IgnoredTasksTest(unittest.TestCase):
completed_task1 = todotxt.Task("x Completed")
completed_task2 = todotxt.Task("x Completed too")
future_task = todotxt.Task("(A) 9999-01-01 Start preparing for five-digit years")
- self.assertEqual([], pick_action.next_actions([completed_task1, completed_task2, future_task]))
\ No newline at end of file
+ self.assertEqual([], pick_action.next_actions([completed_task1, completed_task2, future_task]))
|
Make the "todo.txt" in the user's home folder the default todo.txt to read
|
0.0
|
663a557773123886a51e1657a6f8fe81550006dd
|
[
"tests/unittests/test_arguments.py::NoArgumentTest::test_filename",
"tests/unittests/test_cli.py::CLITest::test_help"
] |
[
"tests/unittests/test_arguments.py::NoArgumentTest::test_filters",
"tests/unittests/test_arguments.py::FilenameTest::test__add_filename_twice",
"tests/unittests/test_arguments.py::FilenameTest::test_add_default_filename",
"tests/unittests/test_arguments.py::FilenameTest::test_default_and_non_default",
"tests/unittests/test_arguments.py::FilenameTest::test_filename_argument",
"tests/unittests/test_arguments.py::FilenameTest::test_long_filename_argument",
"tests/unittests/test_arguments.py::FilterArgumentTest::test_contexts_and_projects",
"tests/unittests/test_arguments.py::FilterArgumentTest::test_empty_context",
"tests/unittests/test_arguments.py::FilterArgumentTest::test_empty_excluded_project",
"tests/unittests/test_arguments.py::FilterArgumentTest::test_empty_project",
"tests/unittests/test_arguments.py::FilterArgumentTest::test_exclude_context",
"tests/unittests/test_arguments.py::FilterArgumentTest::test_exclude_project",
"tests/unittests/test_arguments.py::FilterArgumentTest::test_faulty_option",
"tests/unittests/test_arguments.py::FilterArgumentTest::test_include_exclude_context",
"tests/unittests/test_arguments.py::FilterArgumentTest::test_include_exclude_project",
"tests/unittests/test_arguments.py::FilterArgumentTest::test_invalid_extra_argument",
"tests/unittests/test_arguments.py::FilterArgumentTest::test_multiple_contexts",
"tests/unittests/test_arguments.py::FilterArgumentTest::test_multiple_projects",
"tests/unittests/test_arguments.py::FilterArgumentTest::test_one_context",
"tests/unittests/test_arguments.py::FilterArgumentTest::test_one_project",
"tests/unittests/test_arguments.py::NumberTest::test_all_actions",
"tests/unittests/test_arguments.py::NumberTest::test_all_and_number",
"tests/unittests/test_arguments.py::NumberTest::test_default_number",
"tests/unittests/test_arguments.py::NumberTest::test_faulty_number",
"tests/unittests/test_arguments.py::NumberTest::test_number",
"tests/unittests/test_cli.py::CLITest::test_context",
"tests/unittests/test_cli.py::CLITest::test_empty_task_file",
"tests/unittests/test_cli.py::CLITest::test_ignore_empty_lines",
"tests/unittests/test_cli.py::CLITest::test_missing_file",
"tests/unittests/test_cli.py::CLITest::test_number",
"tests/unittests/test_cli.py::CLITest::test_one_task",
"tests/unittests/test_cli.py::CLITest::test_project",
"tests/unittests/test_cli.py::CLITest::test_reading_stdin",
"tests/unittests/test_cli.py::CLITest::test_version",
"tests/unittests/test_pick_action.py::PickActionTest::test_creation_dates",
"tests/unittests/test_pick_action.py::PickActionTest::test_due_and_creation_dates",
"tests/unittests/test_pick_action.py::PickActionTest::test_due_dates",
"tests/unittests/test_pick_action.py::PickActionTest::test_higher_prio_goes_first",
"tests/unittests/test_pick_action.py::PickActionTest::test_multiple_tasks",
"tests/unittests/test_pick_action.py::PickActionTest::test_no_tasks",
"tests/unittests/test_pick_action.py::PickActionTest::test_one_task",
"tests/unittests/test_pick_action.py::PickActionTest::test_priority_and_creation_date",
"tests/unittests/test_pick_action.py::FilterTasksTest::test_context",
"tests/unittests/test_pick_action.py::FilterTasksTest::test_contexts",
"tests/unittests/test_pick_action.py::FilterTasksTest::test_excluded_context",
"tests/unittests/test_pick_action.py::FilterTasksTest::test_excluded_contexts",
"tests/unittests/test_pick_action.py::FilterTasksTest::test_excluded_project",
"tests/unittests/test_pick_action.py::FilterTasksTest::test_excluded_projects",
"tests/unittests/test_pick_action.py::FilterTasksTest::test_not_excluded_context",
"tests/unittests/test_pick_action.py::FilterTasksTest::test_not_excluded_project",
"tests/unittests/test_pick_action.py::FilterTasksTest::test_project",
"tests/unittests/test_pick_action.py::FilterTasksTest::test_project_and_context",
"tests/unittests/test_pick_action.py::IgnoredTasksTest::test_ignore_completed_task",
"tests/unittests/test_pick_action.py::IgnoredTasksTest::test_ignore_future_task",
"tests/unittests/test_pick_action.py::IgnoredTasksTest::test_ignore_these_tasks"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2018-05-19 11:58:35+00:00
|
apache-2.0
| 2,381 |
|
fniessink__next-action-58
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 4f75f42..c4ec0b5 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,12 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/)
and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html).
+## [Unreleased]
+
+### Added
+
+- Other properties being equal, task with more projects get precedence over tasks with fewer projects when selecting the next action. Closes #57.
+
## [0.4.0] - 2018-05-19
### Changed
diff --git a/README.md b/README.md
index 4a0f179..2337d3d 100644
--- a/README.md
+++ b/README.md
@@ -29,8 +29,9 @@ Don't know what *Todo.txt* is? See <https://github.com/todotxt/todo.txt> for the
$ next-action --help
usage: next-action [-h] [--version] [-f <filename>] [-n <number> | -a] [<context|project> ...]
-Show the next action in your todo.txt. The next action is selected from the tasks in the todo.txt file based on
-priority, due date, creation date, and supplied filters.
+Show the next action in your todo.txt. The next action is selected from the tasks in the todo.txt file based on task
+properties such as priority, due date, and creation date. Limit the tasks from which the next action is selected by
+specifying contexts the tasks must have and/or projects the tasks must belong to.
optional arguments:
-h, --help show this help message and exit
@@ -56,7 +57,7 @@ $ next-action
(A) Call mom @phone
```
-The next action is determined using priority. Due date is considered after priority, with tasks due earlier getting precedence over tasks due later. Creation date is considered after due date, with older tasks getting precedence over newer tasks.
+The next action is determined using priority. Due date is considered after priority, with tasks due earlier getting precedence over tasks due later. Creation date is considered after due date, with older tasks getting precedence over newer tasks. FInally, tasks that belong to more projects get precedence over tasks that belong to fewer projects.
Completed tasks (~~`x This is a completed task`~~) and tasks with a creation date in the future (`9999-01-01 Start preparing for five-digit years`) are not considered when determining the next action.
diff --git a/next_action/arguments/parser.py b/next_action/arguments/parser.py
index 0d3ed9d..a53589e 100644
--- a/next_action/arguments/parser.py
+++ b/next_action/arguments/parser.py
@@ -10,7 +10,9 @@ def build_parser(default_filenames: List[str]) -> argparse.ArgumentParser:
""" Create the arguments parsers. """
parser = argparse.ArgumentParser(
description="Show the next action in your todo.txt. The next action is selected from the tasks in the todo.txt \
- file based on priority, due date, creation date, and supplied filters.",
+ file based on task properties such as priority, due date, and creation date. Limit the tasks from \
+ which the next action is selected by specifying contexts the tasks must have and/or projects the \
+ tasks must belong to.",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
usage="%(prog)s [-h] [--version] [-f <filename>] [-n <number> | -a] [<context|project> ...]")
add_optional_arguments(parser, default_filenames)
diff --git a/next_action/pick_action.py b/next_action/pick_action.py
index 2542cfb..71646d4 100644
--- a/next_action/pick_action.py
+++ b/next_action/pick_action.py
@@ -6,9 +6,10 @@ from typing import Set, Sequence, Tuple
from .todotxt import Task
-def sort_key(task: Task) -> Tuple[str, datetime.date, datetime.date]:
+def sort_key(task: Task) -> Tuple[str, datetime.date, datetime.date, int]:
""" Return the sort key for a task. """
- return (task.priority() or "ZZZ", task.due_date() or datetime.date.max, task.creation_date() or datetime.date.max)
+ return (task.priority() or "ZZZ", task.due_date() or datetime.date.max, task.creation_date() or datetime.date.max,
+ -len(task.projects()))
def next_actions(tasks: Sequence[Task], contexts: Set[str] = None, projects: Set[str] = None,
|
fniessink/next-action
|
59b44d490e41069dad67aea493337747864d639c
|
diff --git a/tests/unittests/test_cli.py b/tests/unittests/test_cli.py
index 0cabed3..1352148 100644
--- a/tests/unittests/test_cli.py
+++ b/tests/unittests/test_cli.py
@@ -65,8 +65,9 @@ class CLITest(unittest.TestCase):
self.assertEqual(call("""\
usage: next-action [-h] [--version] [-f <filename>] [-n <number> | -a] [<context|project> ...]
-Show the next action in your todo.txt. The next action is selected from the tasks in the todo.txt file based on
-priority, due date, creation date, and supplied filters.
+Show the next action in your todo.txt. The next action is selected from the tasks in the todo.txt file based on task
+properties such as priority, due date, and creation date. Limit the tasks from which the next action is selected by
+specifying contexts the tasks must have and/or projects the tasks must belong to.
optional arguments:
-h, --help show this help message and exit
diff --git a/tests/unittests/test_pick_action.py b/tests/unittests/test_pick_action.py
index 8fec9cc..8ccd64b 100644
--- a/tests/unittests/test_pick_action.py
+++ b/tests/unittests/test_pick_action.py
@@ -61,6 +61,18 @@ class PickActionTest(unittest.TestCase):
task2 = todotxt.Task("Task 2 due:2018-1-1")
self.assertEqual([task2, task1], pick_action.next_actions([task1, task2]))
+ def test_project(self):
+ """ Test that a task with a project takes precedence over a task without a project. """
+ task1 = todotxt.Task("Task 1")
+ task2 = todotxt.Task("Task 2 +Project")
+ self.assertEqual([task2, task1], pick_action.next_actions([task1, task2]))
+
+ def test_projects(self):
+ """ Test that a task with more projects takes precedence over a task with less projects. """
+ task1 = todotxt.Task("Task 1 +Project")
+ task2 = todotxt.Task("Task 2 +Project1 +Project2")
+ self.assertEqual([task2, task1], pick_action.next_actions([task1, task2]))
+
class FilterTasksTest(unittest.TestCase):
""" Test that the tasks from which the next action is picked, can be filtered. """
|
When picking the next action, give priority to tasks that belong to a project
|
0.0
|
59b44d490e41069dad67aea493337747864d639c
|
[
"tests/unittests/test_cli.py::CLITest::test_help",
"tests/unittests/test_pick_action.py::PickActionTest::test_project",
"tests/unittests/test_pick_action.py::PickActionTest::test_projects"
] |
[
"tests/unittests/test_cli.py::CLITest::test_context",
"tests/unittests/test_cli.py::CLITest::test_empty_task_file",
"tests/unittests/test_cli.py::CLITest::test_ignore_empty_lines",
"tests/unittests/test_cli.py::CLITest::test_missing_file",
"tests/unittests/test_cli.py::CLITest::test_number",
"tests/unittests/test_cli.py::CLITest::test_one_task",
"tests/unittests/test_cli.py::CLITest::test_project",
"tests/unittests/test_cli.py::CLITest::test_reading_stdin",
"tests/unittests/test_cli.py::CLITest::test_version",
"tests/unittests/test_pick_action.py::PickActionTest::test_creation_dates",
"tests/unittests/test_pick_action.py::PickActionTest::test_due_and_creation_dates",
"tests/unittests/test_pick_action.py::PickActionTest::test_due_dates",
"tests/unittests/test_pick_action.py::PickActionTest::test_higher_prio_goes_first",
"tests/unittests/test_pick_action.py::PickActionTest::test_multiple_tasks",
"tests/unittests/test_pick_action.py::PickActionTest::test_no_tasks",
"tests/unittests/test_pick_action.py::PickActionTest::test_one_task",
"tests/unittests/test_pick_action.py::PickActionTest::test_priority_and_creation_date",
"tests/unittests/test_pick_action.py::FilterTasksTest::test_context",
"tests/unittests/test_pick_action.py::FilterTasksTest::test_contexts",
"tests/unittests/test_pick_action.py::FilterTasksTest::test_excluded_context",
"tests/unittests/test_pick_action.py::FilterTasksTest::test_excluded_contexts",
"tests/unittests/test_pick_action.py::FilterTasksTest::test_excluded_project",
"tests/unittests/test_pick_action.py::FilterTasksTest::test_excluded_projects",
"tests/unittests/test_pick_action.py::FilterTasksTest::test_not_excluded_context",
"tests/unittests/test_pick_action.py::FilterTasksTest::test_not_excluded_project",
"tests/unittests/test_pick_action.py::FilterTasksTest::test_project",
"tests/unittests/test_pick_action.py::FilterTasksTest::test_project_and_context",
"tests/unittests/test_pick_action.py::IgnoredTasksTest::test_ignore_completed_task",
"tests/unittests/test_pick_action.py::IgnoredTasksTest::test_ignore_future_task",
"tests/unittests/test_pick_action.py::IgnoredTasksTest::test_ignore_these_tasks"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2018-05-19 16:35:02+00:00
|
apache-2.0
| 2,382 |
|
fniessink__next-action-74
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d6fd7c7..7768ac2 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.
### Added
- Option to not read a configuration file. Closes #71.
+- Option to write a default configuration file. Closes #68.
## [0.7.0] - 2018-05-23
diff --git a/README.md b/README.md
index 8ff4108..762ffb6 100644
--- a/README.md
+++ b/README.md
@@ -39,6 +39,7 @@ optional arguments:
-c <config.cfg>, --config-file <config.cfg>
filename of configuration file to read (default: ~/.next-action.cfg)
-C, --no-config-file don't read the configuration file
+ --write-config-file generate a sample configuration file and exit
-f <todo.txt>, --file <todo.txt>
filename of todo.txt file to read; can be '-' to read from standard input; argument can be
repeated to read tasks from multiple todo.txt files (default: ~/todo.txt)
@@ -121,7 +122,20 @@ Note again that completed tasks and task with a future creation date are never s
### Configuring *Next-action*
-Instead of specifying which todo.txt files to read on the command-line, you can also configure this in a configuration file. By default, *Next-action* tries to read a file called [.next-action.cfg](https://raw.githubusercontent.com/fniessink/next-action/master/docs/.next-action.cfg) in your home folder, but you can tell it to read another configuration file:
+In addition to specifying options on the command-line, you can also configure options in a configuration file. By default, *Next-action* tries to read a file called [.next-action.cfg](https://raw.githubusercontent.com/fniessink/next-action/master/docs/.next-action.cfg) in your home folder.
+
+To get started, you can tell *Next-action* to generate a configuration file with the default options:
+
+```console
+$ next-action --write-config-file
+# Configuration file for Next-action. Edit the settings below as you like.
+file: ~/todo.txt
+number: 1
+```
+
+To make this the configuration that *Next-action* reads by default, redirect the output to `~/.next-action.cfg` like this: `next-action --write-config-file > ~/.next-action.cfg`.
+
+If you want to use a configuration file that is not in the default location (`~/.next-action.cfg`), you'll need to explicitly tell *Next-action* its location:
```console
$ next-action --config-file docs/.next-action.cfg
@@ -175,9 +189,9 @@ To run the unit tests:
```console
$ python -m unittest
-.......................................................................................................................
+........................................................................................................................
----------------------------------------------------------------------
-Ran 119 tests in 0.168s
+Ran 120 tests in 0.346s
OK
```
diff --git a/docs/update_readme.py b/docs/update_readme.py
index 5333ee9..b8de9af 100644
--- a/docs/update_readme.py
+++ b/docs/update_readme.py
@@ -19,7 +19,7 @@ def update_readme():
elif line.startswith("$ "):
print(line)
command = line[2:].split(" ")
- if command[0] == "next-action":
+ if command[0] == "next-action" and "--write-config-file" not in command:
command.extend(["--config", "docs/.next-action.cfg"])
command_output = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
check=True, universal_newlines=True)
diff --git a/next_action/arguments/parser.py b/next_action/arguments/parser.py
index 3c349f6..604915c 100644
--- a/next_action/arguments/parser.py
+++ b/next_action/arguments/parser.py
@@ -4,6 +4,8 @@ import argparse
import sys
from typing import List
+import yaml
+
import next_action
from .config import read_config_file, validate_config_file
@@ -32,6 +34,8 @@ class NextActionArgumentParser(argparse.ArgumentParser):
help="filename of configuration file to read (default: %(default)s)")
config_file.add_argument(
"-C", "--no-config-file", help="don't read the configuration file", action="store_true")
+ config_file.add_argument(
+ "--write-config-file", help="generate a sample configuration file and exit", action="store_true")
self.add_argument(
"-f", "--file", action="append", metavar="<todo.txt>", default=default_filenames[:], type=str,
help="filename of todo.txt file to read; can be '-' to read from standard input; argument can be "
@@ -70,6 +74,8 @@ class NextActionArgumentParser(argparse.ArgumentParser):
self.parse_remaining_args(remaining, namespace)
if not namespace.no_config_file:
self.process_config_file(namespace)
+ if namespace.write_config_file:
+ self.write_config_file()
return namespace
def parse_remaining_args(self, remaining: List[str], namespace: argparse.Namespace) -> None:
@@ -102,6 +108,13 @@ class NextActionArgumentParser(argparse.ArgumentParser):
number = sys.maxsize if config.get("all", False) else config.get("number", 1)
setattr(namespace, "number", number)
+ def write_config_file(self) -> None:
+ """ Generate a configuration file on standard out and exi. """
+ intro = "# Configuration file for Next-action. Edit the settings below as you like.\n"
+ config = yaml.dump(dict(file="~/todo.txt", number=1), default_flow_style=False)
+ sys.stdout.write(intro + config)
+ self.exit()
+
def arguments_not_specified(self, namespace: argparse.Namespace, *arguments: str) -> bool:
""" Return whether the arguments were not specified on the command line. """
return all([getattr(namespace, argument) == self.get_default(argument) for argument in arguments])
|
fniessink/next-action
|
6e69cacd6b944eec7be0489e9f4bf9442802c5ea
|
diff --git a/tests/unittests/arguments/test_config.py b/tests/unittests/arguments/test_config.py
index e5bae6c..775e336 100644
--- a/tests/unittests/arguments/test_config.py
+++ b/tests/unittests/arguments/test_config.py
@@ -88,6 +88,16 @@ class ConfigFileTest(unittest.TestCase):
parse_arguments()
self.assertEqual([], mock_file_open.call_args_list)
+ @patch.object(sys, "argv", ["next-action", "--write-config-file"])
+ @patch.object(config, "open", mock_open(read_data=""))
+ @patch.object(sys.stdout, "write")
+ def test_write_config(self, mock_stdout_write):
+ """ Test that a config file can be written to stdout. """
+ self.assertRaises(SystemExit, parse_arguments)
+ expected = "# Configuration file for Next-action. Edit the settings below as you like.\n"
+ expected += "file: ~/todo.txt\nnumber: 1\n"
+ self.assertEqual([call(expected)], mock_stdout_write.call_args_list)
+
class FilenameTest(unittest.TestCase):
""" Unit tests for the config file parameter. """
diff --git a/tests/unittests/test_cli.py b/tests/unittests/test_cli.py
index 754fe21..0eca016 100644
--- a/tests/unittests/test_cli.py
+++ b/tests/unittests/test_cli.py
@@ -77,6 +77,7 @@ optional arguments:
-c <config.cfg>, --config-file <config.cfg>
filename of configuration file to read (default: ~/.next-action.cfg)
-C, --no-config-file don't read the configuration file
+ --write-config-file generate a sample configuration file and exit
-f <todo.txt>, --file <todo.txt>
filename of todo.txt file to read; can be '-' to read from standard input; argument can be
repeated to read tasks from multiple todo.txt files (default: ~/todo.txt)
|
Option to write out a default configuration file
|
0.0
|
6e69cacd6b944eec7be0489e9f4bf9442802c5ea
|
[
"tests/unittests/arguments/test_config.py::ConfigFileTest::test_write_config",
"tests/unittests/test_cli.py::CLITest::test_help"
] |
[
"tests/unittests/arguments/test_config.py::ConfigFileTest::test_empty_file",
"tests/unittests/arguments/test_config.py::ConfigFileTest::test_error_opening",
"tests/unittests/arguments/test_config.py::ConfigFileTest::test_error_parsing",
"tests/unittests/arguments/test_config.py::ConfigFileTest::test_file_not_found",
"tests/unittests/arguments/test_config.py::ConfigFileTest::test_invalid_document",
"tests/unittests/arguments/test_config.py::ConfigFileTest::test_missing_default_config",
"tests/unittests/arguments/test_config.py::ConfigFileTest::test_no_file_key",
"tests/unittests/arguments/test_config.py::ConfigFileTest::test_skip_config",
"tests/unittests/arguments/test_config.py::FilenameTest::test_cli_takes_precedence",
"tests/unittests/arguments/test_config.py::FilenameTest::test_invalid_filename",
"tests/unittests/arguments/test_config.py::FilenameTest::test_valid_and_invalid",
"tests/unittests/arguments/test_config.py::FilenameTest::test_valid_file",
"tests/unittests/arguments/test_config.py::FilenameTest::test_valid_files",
"tests/unittests/arguments/test_config.py::NumberTest::test_all_and_number",
"tests/unittests/arguments/test_config.py::NumberTest::test_all_false",
"tests/unittests/arguments/test_config.py::NumberTest::test_all_true",
"tests/unittests/arguments/test_config.py::NumberTest::test_argument_all_overrides",
"tests/unittests/arguments/test_config.py::NumberTest::test_argument_nr_overrides",
"tests/unittests/arguments/test_config.py::NumberTest::test_cli_takes_precedence",
"tests/unittests/arguments/test_config.py::NumberTest::test_invalid_number",
"tests/unittests/arguments/test_config.py::NumberTest::test_valid_number",
"tests/unittests/arguments/test_config.py::NumberTest::test_zero",
"tests/unittests/test_cli.py::CLITest::test_context",
"tests/unittests/test_cli.py::CLITest::test_empty_task_file",
"tests/unittests/test_cli.py::CLITest::test_ignore_empty_lines",
"tests/unittests/test_cli.py::CLITest::test_missing_file",
"tests/unittests/test_cli.py::CLITest::test_number",
"tests/unittests/test_cli.py::CLITest::test_one_task",
"tests/unittests/test_cli.py::CLITest::test_project",
"tests/unittests/test_cli.py::CLITest::test_reading_stdin",
"tests/unittests/test_cli.py::CLITest::test_version"
] |
{
"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-05-24 15:52:48+00:00
|
apache-2.0
| 2,383 |
|
fniessink__next-action-88
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f38a53a..60da2e1 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,12 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/)
and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html).
+## [Unreleased]
+
+### Removed
+
+- The `--no-config-file` option was removed. To not read any configuration file, use the `--config-file` option without specifying a configuration filename.
+
## [0.12.0] - 2018-05-28
### Added
diff --git a/README.md b/README.md
index 2e858c4..07408b3 100644
--- a/README.md
+++ b/README.md
@@ -15,14 +15,15 @@ Don't know what *Todo.txt* is? See <https://github.com/todotxt/todo.txt> for the
## Table of contents
- - [Demo](#demo)
- - [Installation](#installation)
- - [Usage](#usage)
- - [Limiting the tasks from which next actions are selected](#limiting-the-tasks-from-which-next-actions-are-selected)
- - [Showing more than one next action](#showing-more-than-one-next-action)
- - [Styling the output](#styling-the-output)
- - [Configuring *Next-action*](#configuring-next-action)
- - [Develop](#develop)
+- [Demo](#demo)
+- [Installation](#installation)
+- [Usage](#usage)
+ - [Limiting the tasks from which next actions are selected](#limiting-the-tasks-from-which-next-actions-are-selected)
+ - [Showing more than one next action](#showing-more-than-one-next-action)
+ - [Styling the output](#styling-the-output)
+ - [Configuring *Next-action*](#configuring-next-action)
+- [Develop](#develop)
+
## Demo

@@ -37,7 +38,7 @@ Don't know what *Todo.txt* is? See <https://github.com/todotxt/todo.txt> for the
```console
$ next-action --help
-usage: next-action [-h] [--version] [-c <config.cfg> | -C] [-f <todo.txt>] [-n <number> | -a] [-o] [-p [<priority>]]
+usage: next-action [-h] [--version] [-c [<config.cfg>]] [-f <todo.txt>] [-n <number> | -a] [-o] [-p [<priority>]]
[<context|project> ...]
Show the next action in your todo.txt. The next action is selected from the tasks in the todo.txt file based on task
@@ -48,9 +49,9 @@ optional arguments:
-h, --help show this help message and exit
--version show program's version number and exit
--write-config-file generate a sample configuration file and exit
- -c <config.cfg>, --config-file <config.cfg>
- filename of configuration file to read (default: ~/.next-action.cfg)
- -C, --no-config-file don't read the configuration file
+ -c [<config.cfg>], --config-file [<config.cfg>]
+ filename of configuration file to read (default: ~/.next-action.cfg); omit filename to not
+ read any configuration file
-f <todo.txt>, --file <todo.txt>
filename of todo.txt file to read; can be '-' to read from standard input; argument can be
repeated to read tasks from multiple todo.txt files (default: ~/todo.txt)
@@ -175,13 +176,15 @@ style: default
To make this the configuration that *Next-action* reads by default, redirect the output to `~/.next-action.cfg` like this: `next-action --write-config-file > ~/.next-action.cfg`.
-If you want to use a configuration file that is not in the default location (`~/.next-action.cfg`), you'll need to explicitly tell *Next-action* its location:
+If you want to use a configuration file that is not in the default location (`~/.next-action.cfg`), you'll need to explicitly specify its location:
```console
$ next-action --config-file docs/.next-action.cfg
(A) Call mom @phone
```
+To skip reading the default configuration file, and also not read an alternative configuration file, use the `--config-file` option without arguments.
+
The configuration file format is [YAML](http://yaml.org). The options currently supported are which todo.txt files must be read, how many next actions should be shown, and the styling.
#### Configuring a default todo.txt
@@ -253,7 +256,7 @@ To run the unit tests:
$ python -m unittest
...............................................................................................................................................
----------------------------------------------------------------------
-Ran 143 tests in 0.461s
+Ran 143 tests in 0.420s
OK
```
diff --git a/docs/update_readme.py b/docs/update_readme.py
index 86a3553..3c77201 100644
--- a/docs/update_readme.py
+++ b/docs/update_readme.py
@@ -21,7 +21,7 @@ def create_toc(lines, toc_header, min_level=2, max_level=3):
level = line.count("#", 0, 6)
if level < min_level or level > max_level or line.startswith(toc_header):
continue
- indent = (level - 1) * 2
+ indent = (level - min_level) * 2
title = line.split(" ", 1)[1].rstrip()
slug = title.lower().replace(" ", "-").replace("*", "").replace(".", "")
result.append("{0}- [{1}](#{2})".format(" " * indent, title, slug))
@@ -68,17 +68,16 @@ class StateMachine(object):
def print_toc(self, line):
""" Print the table of contents. """
print(self.toc)
- if line.startswith(" "):
+ if "- [" in line:
return self.in_old_toc
print(line)
return self.default
def in_old_toc(self, line):
""" Skip the old table of contents. """
- if line.startswith(" "):
+ if "- [" in line:
return self.in_old_toc
- if line:
- print(line)
+ print(line)
return self.default
diff --git a/next_action/arguments/parser.py b/next_action/arguments/parser.py
index fec3e3a..52dc719 100644
--- a/next_action/arguments/parser.py
+++ b/next_action/arguments/parser.py
@@ -22,7 +22,7 @@ class NextActionArgumentParser(argparse.ArgumentParser):
"todo.txt file based on task properties such as priority, due date, and creation date. Limit "
"the tasks from which the next action is selected by specifying contexts the tasks must have "
"and/or projects the tasks must belong to.",
- usage=textwrap.fill("next-action [-h] [--version] [-c <config.cfg> | -C] [-f <todo.txt>] "
+ usage=textwrap.fill("next-action [-h] [--version] [-c [<config.cfg>]] [-f <todo.txt>] "
"[-n <number> | -a] [-o] [-p [<priority>]] [<context|project> ...]",
width=shutil.get_terminal_size().columns - len("usage: ")))
self.__default_filenames = ["~/todo.txt"]
@@ -37,10 +37,9 @@ class NextActionArgumentParser(argparse.ArgumentParser):
config_file.add_argument(
"--write-config-file", help="generate a sample configuration file and exit", action="store_true")
config_file.add_argument(
- "-c", "--config-file", metavar="<config.cfg>", type=str, default="~/.next-action.cfg",
- help="filename of configuration file to read (default: %(default)s)")
- config_file.add_argument(
- "-C", "--no-config-file", help="don't read the configuration file", action="store_true")
+ "-c", "--config-file", metavar="<config.cfg>", type=str, default="~/.next-action.cfg", nargs="?",
+ help="filename of configuration file to read (default: %(default)s); omit filename to not read any "
+ "configuration file")
self.add_argument(
"-f", "--file", action="append", metavar="<todo.txt>", default=self.__default_filenames[:], type=str,
help="filename of todo.txt file to read; can be '-' to read from standard input; argument can be "
@@ -86,7 +85,7 @@ class NextActionArgumentParser(argparse.ArgumentParser):
""" Parse the command-line arguments. """
namespace, remaining = self.parse_known_args(args, namespace)
self.parse_remaining_args(remaining, namespace)
- if not namespace.no_config_file:
+ if getattr(namespace, "config_file", self.get_default("config_file")) is not None:
self.process_config_file(namespace)
if namespace.write_config_file:
write_config_file()
|
fniessink/next-action
|
b9bfd4e21bd2df93dc35dca32a467626b739540b
|
diff --git a/tests/unittests/arguments/test_config.py b/tests/unittests/arguments/test_config.py
index d7e02d2..6f126d8 100644
--- a/tests/unittests/arguments/test_config.py
+++ b/tests/unittests/arguments/test_config.py
@@ -85,7 +85,7 @@ class ConfigFileTest(ConfigTestCase):
self.assertEqual([call(USAGE_MESSAGE), call("next-action: error: can't open file: some problem\n")],
mock_stderr_write.call_args_list)
- @patch.object(sys, "argv", ["next-action", "--no-config-file"])
+ @patch.object(sys, "argv", ["next-action", "--config-file"])
@patch.object(config, "open")
def test_skip_config(self, mock_file_open):
""" Test that the config file is not read if the user doesn't want to. """
diff --git a/tests/unittests/arguments/test_parser.py b/tests/unittests/arguments/test_parser.py
index 20358f6..6a262af 100644
--- a/tests/unittests/arguments/test_parser.py
+++ b/tests/unittests/arguments/test_parser.py
@@ -10,7 +10,7 @@ from next_action.arguments import config, parse_arguments
USAGE_MESSAGE = textwrap.fill(
- "usage: next-action [-h] [--version] [-c <config.cfg> | -C] [-f <todo.txt>] [-n <number> | -a] [-o] "
+ "usage: next-action [-h] [--version] [-c [<config.cfg>]] [-f <todo.txt>] [-n <number> | -a] [-o] "
"[-p [<priority>]] [<context|project> ...]", 120) + "\n"
diff --git a/tests/unittests/test_cli.py b/tests/unittests/test_cli.py
index 4778730..f26c609 100644
--- a/tests/unittests/test_cli.py
+++ b/tests/unittests/test_cli.py
@@ -65,7 +65,7 @@ class CLITest(unittest.TestCase):
os.environ['COLUMNS'] = "120" # Fake that the terminal is wide enough.
self.assertRaises(SystemExit, next_action)
self.assertEqual(call("""\
-usage: next-action [-h] [--version] [-c <config.cfg> | -C] [-f <todo.txt>] [-n <number> | -a] [-o] [-p [<priority>]]
+usage: next-action [-h] [--version] [-c [<config.cfg>]] [-f <todo.txt>] [-n <number> | -a] [-o] [-p [<priority>]]
[<context|project> ...]
Show the next action in your todo.txt. The next action is selected from the tasks in the todo.txt file based on task
@@ -76,9 +76,9 @@ optional arguments:
-h, --help show this help message and exit
--version show program's version number and exit
--write-config-file generate a sample configuration file and exit
- -c <config.cfg>, --config-file <config.cfg>
- filename of configuration file to read (default: ~/.next-action.cfg)
- -C, --no-config-file don't read the configuration file
+ -c [<config.cfg>], --config-file [<config.cfg>]
+ filename of configuration file to read (default: ~/.next-action.cfg); omit filename to not
+ read any configuration file
-f <todo.txt>, --file <todo.txt>
filename of todo.txt file to read; can be '-' to read from standard input; argument can be
repeated to read tasks from multiple todo.txt files (default: ~/todo.txt)
|
Merge --config and --no-config options by making the config argument optional
|
0.0
|
b9bfd4e21bd2df93dc35dca32a467626b739540b
|
[
"tests/unittests/arguments/test_config.py::ConfigFileTest::test_error_opening",
"tests/unittests/arguments/test_config.py::ConfigFileTest::test_error_parsing",
"tests/unittests/arguments/test_config.py::ConfigFileTest::test_file_not_found",
"tests/unittests/arguments/test_config.py::ConfigFileTest::test_invalid_document",
"tests/unittests/arguments/test_config.py::ConfigFileTest::test_no_file_key",
"tests/unittests/arguments/test_config.py::ConfigFileTest::test_skip_config",
"tests/unittests/arguments/test_config.py::FilenameTest::test_invalid_filename",
"tests/unittests/arguments/test_config.py::FilenameTest::test_valid_and_invalid",
"tests/unittests/arguments/test_config.py::NumberTest::test_all_and_number",
"tests/unittests/arguments/test_config.py::NumberTest::test_all_false",
"tests/unittests/arguments/test_config.py::NumberTest::test_invalid_number",
"tests/unittests/arguments/test_config.py::NumberTest::test_zero",
"tests/unittests/arguments/test_config.py::ConfigStyleTest::test_invalid_style",
"tests/unittests/arguments/test_config.py::PriorityTest::test_invalid_priority",
"tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_empty_context",
"tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_empty_excluded_project",
"tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_empty_project",
"tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_faulty_option",
"tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_include_exclude_context",
"tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_include_exclude_project",
"tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_invalid_extra_argument",
"tests/unittests/arguments/test_parser.py::NumberTest::test_all_and_number",
"tests/unittests/arguments/test_parser.py::NumberTest::test_faulty_number",
"tests/unittests/test_cli.py::CLITest::test_missing_file"
] |
[
"tests/unittests/arguments/test_config.py::ConfigFileTest::test_empty_file",
"tests/unittests/arguments/test_config.py::ConfigFileTest::test_missing_default_config",
"tests/unittests/arguments/test_config.py::ConfigFileTest::test_write_config",
"tests/unittests/arguments/test_config.py::FilenameTest::test_cli_takes_precedence",
"tests/unittests/arguments/test_config.py::FilenameTest::test_valid_file",
"tests/unittests/arguments/test_config.py::FilenameTest::test_valid_files",
"tests/unittests/arguments/test_config.py::NumberTest::test_all_true",
"tests/unittests/arguments/test_config.py::NumberTest::test_argument_all_overrides",
"tests/unittests/arguments/test_config.py::NumberTest::test_argument_nr_overrides",
"tests/unittests/arguments/test_config.py::NumberTest::test_cli_takes_precedence",
"tests/unittests/arguments/test_config.py::NumberTest::test_valid_number",
"tests/unittests/arguments/test_config.py::ConfigStyleTest::test_override_style",
"tests/unittests/arguments/test_config.py::ConfigStyleTest::test_valid_style",
"tests/unittests/arguments/test_config.py::PriorityTest::test_cancel_priority",
"tests/unittests/arguments/test_config.py::PriorityTest::test_override_priority",
"tests/unittests/arguments/test_config.py::PriorityTest::test_valid_priority",
"tests/unittests/arguments/test_parser.py::NoArgumentTest::test_filename",
"tests/unittests/arguments/test_parser.py::NoArgumentTest::test_filters",
"tests/unittests/arguments/test_parser.py::NoArgumentTest::test_style",
"tests/unittests/arguments/test_parser.py::FilenameTest::test__add_filename_twice",
"tests/unittests/arguments/test_parser.py::FilenameTest::test_add_default_filename",
"tests/unittests/arguments/test_parser.py::FilenameTest::test_default_and_non_default",
"tests/unittests/arguments/test_parser.py::FilenameTest::test_filename_argument",
"tests/unittests/arguments/test_parser.py::FilenameTest::test_long_filename_argument",
"tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_contexts_and_projects",
"tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_exclude_context",
"tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_exclude_project",
"tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_multiple_contexts",
"tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_multiple_projects",
"tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_one_context",
"tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_one_project",
"tests/unittests/arguments/test_parser.py::NumberTest::test_all_actions",
"tests/unittests/arguments/test_parser.py::NumberTest::test_default_number",
"tests/unittests/arguments/test_parser.py::NumberTest::test_number",
"tests/unittests/test_cli.py::CLITest::test_context",
"tests/unittests/test_cli.py::CLITest::test_empty_task_file",
"tests/unittests/test_cli.py::CLITest::test_ignore_empty_lines",
"tests/unittests/test_cli.py::CLITest::test_number",
"tests/unittests/test_cli.py::CLITest::test_one_task",
"tests/unittests/test_cli.py::CLITest::test_project",
"tests/unittests/test_cli.py::CLITest::test_reading_stdin",
"tests/unittests/test_cli.py::CLITest::test_show_all_actions",
"tests/unittests/test_cli.py::CLITest::test_version"
] |
{
"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-05-30 18:26:43+00:00
|
apache-2.0
| 2,384 |
|
fniessink__next-action-89
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 60da2e1..838c5c0 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,9 +7,13 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.
## [Unreleased]
-### Removed
+### Added
+
+- Using the `--style` option without arguments ignores the style specified in the configuration file, if any. Closes #83.
+
+### Changed
-- The `--no-config-file` option was removed. To not read any configuration file, use the `--config-file` option without specifying a configuration filename.
+- The `--no-config-file` option was removed. To not read any configuration file, use the `--config-file` option without specifying a configuration filename. Closes #82.
## [0.12.0] - 2018-05-28
diff --git a/README.md b/README.md
index 07408b3..653b98d 100644
--- a/README.md
+++ b/README.md
@@ -38,8 +38,8 @@ Don't know what *Todo.txt* is? See <https://github.com/todotxt/todo.txt> for the
```console
$ next-action --help
-usage: next-action [-h] [--version] [-c [<config.cfg>]] [-f <todo.txt>] [-n <number> | -a] [-o] [-p [<priority>]]
-[<context|project> ...]
+usage: next-action [-h] [--version] [-c [<config.cfg>]] [-f <todo.txt>] [-n <number> | -a] [-o] [-p [<priority>]] [-s
+[<style>]] [<context|project> ...]
Show the next action in your todo.txt. The next action is selected from the tasks in the todo.txt file based on task
properties such as priority, due date, and creation date. Limit the tasks from which the next action is selected by
@@ -61,7 +61,7 @@ optional arguments:
-o, --overdue show only overdue next actions
-p [<priority>], --priority [<priority>]
minimum priority (A-Z) of next actions to show (default: None)
- -s <style>, --style <style>
+ -s [<style>], --style [<style>]
colorize the output; available styles: abap, algol, algol_nu, arduino, autumn, borland, bw,
colorful, default, emacs, friendly, fruity, igor, lovelace, manni, monokai, murphy, native,
paraiso-dark, paraiso-light, pastie, perldoc, rainbow_dash, rrt, tango, trac, vim, vs, xcode
@@ -160,6 +160,8 @@ The next actions can be colorized using the `--style` argument. Run `next-action
When you've decided on a style you prefer, it makes sense to configure the style in the configuration file. See the section below on how to configure *Next-action*.
+Not passing an argument to `--style` cancels the style that is configured in the configuration file, if any.
+
### Configuring *Next-action*
In addition to specifying options on the command-line, you can also configure options in a configuration file. By default, *Next-action* tries to read a file called [.next-action.cfg](https://raw.githubusercontent.com/fniessink/next-action/master/docs/.next-action.cfg) in your home folder.
@@ -254,9 +256,9 @@ To run the unit tests:
```console
$ python -m unittest
-...............................................................................................................................................
+................................................................................................................................................
----------------------------------------------------------------------
-Ran 143 tests in 0.420s
+Ran 144 tests in 0.426s
OK
```
diff --git a/next_action/arguments/parser.py b/next_action/arguments/parser.py
index 52dc719..8966b0a 100644
--- a/next_action/arguments/parser.py
+++ b/next_action/arguments/parser.py
@@ -23,7 +23,7 @@ class NextActionArgumentParser(argparse.ArgumentParser):
"the tasks from which the next action is selected by specifying contexts the tasks must have "
"and/or projects the tasks must belong to.",
usage=textwrap.fill("next-action [-h] [--version] [-c [<config.cfg>]] [-f <todo.txt>] "
- "[-n <number> | -a] [-o] [-p [<priority>]] [<context|project> ...]",
+ "[-n <number> | -a] [-o] [-p [<priority>]] [-s [<style>]] [<context|project> ...]",
width=shutil.get_terminal_size().columns - len("usage: ")))
self.__default_filenames = ["~/todo.txt"]
self.add_optional_arguments()
@@ -56,7 +56,7 @@ class NextActionArgumentParser(argparse.ArgumentParser):
help="minimum priority (A-Z) of next actions to show (default: %(default)s)")
styles = sorted(list(get_all_styles()))
self.add_argument(
- "-s", "--style", metavar="<style>", choices=styles, default=None,
+ "-s", "--style", metavar="<style>", choices=styles, default=None, nargs="?",
help="colorize the output; available styles: {0} (default: %(default)s)".format(", ".join(styles)))
def add_positional_arguments(self) -> None:
|
fniessink/next-action
|
212cdfe8673e4c4438a8b7de1a8df67da326281a
|
diff --git a/tests/unittests/arguments/test_config.py b/tests/unittests/arguments/test_config.py
index 6f126d8..2efa764 100644
--- a/tests/unittests/arguments/test_config.py
+++ b/tests/unittests/arguments/test_config.py
@@ -240,6 +240,12 @@ class ConfigStyleTest(ConfigTestCase):
""" Test that a command line style overrides the style in the config file. """
self.assertEqual("vim", parse_arguments()[1].style)
+ @patch.object(sys, "argv", ["next-action", "--style"])
+ @patch.object(config, "open", mock_open(read_data="style: default"))
+ def test_cancel_style(self):
+ """ Test that --style without style cancels the style in the config file. """
+ self.assertEqual(None, parse_arguments()[1].style)
+
@patch.object(sys, "argv", ["next-action"])
@patch.object(config, "open", mock_open(read_data="style: invalid_style"))
@patch.object(sys.stderr, "write")
diff --git a/tests/unittests/arguments/test_parser.py b/tests/unittests/arguments/test_parser.py
index 6a262af..f9eebd5 100644
--- a/tests/unittests/arguments/test_parser.py
+++ b/tests/unittests/arguments/test_parser.py
@@ -11,7 +11,7 @@ from next_action.arguments import config, parse_arguments
USAGE_MESSAGE = textwrap.fill(
"usage: next-action [-h] [--version] [-c [<config.cfg>]] [-f <todo.txt>] [-n <number> | -a] [-o] "
- "[-p [<priority>]] [<context|project> ...]", 120) + "\n"
+ "[-p [<priority>]] [-s [<style>]] [<context|project> ...]", 120) + "\n"
class ParserTestCase(unittest.TestCase):
diff --git a/tests/unittests/test_cli.py b/tests/unittests/test_cli.py
index f26c609..b477698 100644
--- a/tests/unittests/test_cli.py
+++ b/tests/unittests/test_cli.py
@@ -65,8 +65,8 @@ class CLITest(unittest.TestCase):
os.environ['COLUMNS'] = "120" # Fake that the terminal is wide enough.
self.assertRaises(SystemExit, next_action)
self.assertEqual(call("""\
-usage: next-action [-h] [--version] [-c [<config.cfg>]] [-f <todo.txt>] [-n <number> | -a] [-o] [-p [<priority>]]
-[<context|project> ...]
+usage: next-action [-h] [--version] [-c [<config.cfg>]] [-f <todo.txt>] [-n <number> | -a] [-o] [-p [<priority>]] [-s
+[<style>]] [<context|project> ...]
Show the next action in your todo.txt. The next action is selected from the tasks in the todo.txt file based on task
properties such as priority, due date, and creation date. Limit the tasks from which the next action is selected by
@@ -88,7 +88,7 @@ optional arguments:
-o, --overdue show only overdue next actions
-p [<priority>], --priority [<priority>]
minimum priority (A-Z) of next actions to show (default: None)
- -s <style>, --style <style>
+ -s [<style>], --style [<style>]
colorize the output; available styles: abap, algol, algol_nu, arduino, autumn, borland, bw,
colorful, default, emacs, friendly, fruity, igor, lovelace, manni, monokai, murphy, native,
paraiso-dark, paraiso-light, pastie, perldoc, rainbow_dash, rrt, tango, trac, vim, vs, xcode
|
Make it possible to overwrite the style in the configuration file by not passing a style to the --style argument
|
0.0
|
212cdfe8673e4c4438a8b7de1a8df67da326281a
|
[
"tests/unittests/arguments/test_config.py::ConfigFileTest::test_error_opening",
"tests/unittests/arguments/test_config.py::ConfigFileTest::test_error_parsing",
"tests/unittests/arguments/test_config.py::ConfigFileTest::test_file_not_found",
"tests/unittests/arguments/test_config.py::ConfigFileTest::test_invalid_document",
"tests/unittests/arguments/test_config.py::ConfigFileTest::test_no_file_key",
"tests/unittests/arguments/test_config.py::FilenameTest::test_invalid_filename",
"tests/unittests/arguments/test_config.py::FilenameTest::test_valid_and_invalid",
"tests/unittests/arguments/test_config.py::NumberTest::test_all_and_number",
"tests/unittests/arguments/test_config.py::NumberTest::test_all_false",
"tests/unittests/arguments/test_config.py::NumberTest::test_invalid_number",
"tests/unittests/arguments/test_config.py::NumberTest::test_zero",
"tests/unittests/arguments/test_config.py::ConfigStyleTest::test_cancel_style",
"tests/unittests/arguments/test_config.py::ConfigStyleTest::test_invalid_style",
"tests/unittests/arguments/test_config.py::PriorityTest::test_invalid_priority",
"tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_empty_context",
"tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_empty_excluded_project",
"tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_empty_project",
"tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_faulty_option",
"tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_include_exclude_context",
"tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_include_exclude_project",
"tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_invalid_extra_argument",
"tests/unittests/arguments/test_parser.py::NumberTest::test_all_and_number",
"tests/unittests/arguments/test_parser.py::NumberTest::test_faulty_number",
"tests/unittests/test_cli.py::CLITest::test_missing_file"
] |
[
"tests/unittests/arguments/test_config.py::ConfigFileTest::test_empty_file",
"tests/unittests/arguments/test_config.py::ConfigFileTest::test_missing_default_config",
"tests/unittests/arguments/test_config.py::ConfigFileTest::test_skip_config",
"tests/unittests/arguments/test_config.py::ConfigFileTest::test_write_config",
"tests/unittests/arguments/test_config.py::FilenameTest::test_cli_takes_precedence",
"tests/unittests/arguments/test_config.py::FilenameTest::test_valid_file",
"tests/unittests/arguments/test_config.py::FilenameTest::test_valid_files",
"tests/unittests/arguments/test_config.py::NumberTest::test_all_true",
"tests/unittests/arguments/test_config.py::NumberTest::test_argument_all_overrides",
"tests/unittests/arguments/test_config.py::NumberTest::test_argument_nr_overrides",
"tests/unittests/arguments/test_config.py::NumberTest::test_cli_takes_precedence",
"tests/unittests/arguments/test_config.py::NumberTest::test_valid_number",
"tests/unittests/arguments/test_config.py::ConfigStyleTest::test_override_style",
"tests/unittests/arguments/test_config.py::ConfigStyleTest::test_valid_style",
"tests/unittests/arguments/test_config.py::PriorityTest::test_cancel_priority",
"tests/unittests/arguments/test_config.py::PriorityTest::test_override_priority",
"tests/unittests/arguments/test_config.py::PriorityTest::test_valid_priority",
"tests/unittests/arguments/test_parser.py::NoArgumentTest::test_filename",
"tests/unittests/arguments/test_parser.py::NoArgumentTest::test_filters",
"tests/unittests/arguments/test_parser.py::NoArgumentTest::test_style",
"tests/unittests/arguments/test_parser.py::FilenameTest::test__add_filename_twice",
"tests/unittests/arguments/test_parser.py::FilenameTest::test_add_default_filename",
"tests/unittests/arguments/test_parser.py::FilenameTest::test_default_and_non_default",
"tests/unittests/arguments/test_parser.py::FilenameTest::test_filename_argument",
"tests/unittests/arguments/test_parser.py::FilenameTest::test_long_filename_argument",
"tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_contexts_and_projects",
"tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_exclude_context",
"tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_exclude_project",
"tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_multiple_contexts",
"tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_multiple_projects",
"tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_one_context",
"tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_one_project",
"tests/unittests/arguments/test_parser.py::NumberTest::test_all_actions",
"tests/unittests/arguments/test_parser.py::NumberTest::test_default_number",
"tests/unittests/arguments/test_parser.py::NumberTest::test_number",
"tests/unittests/test_cli.py::CLITest::test_context",
"tests/unittests/test_cli.py::CLITest::test_empty_task_file",
"tests/unittests/test_cli.py::CLITest::test_ignore_empty_lines",
"tests/unittests/test_cli.py::CLITest::test_number",
"tests/unittests/test_cli.py::CLITest::test_one_task",
"tests/unittests/test_cli.py::CLITest::test_project",
"tests/unittests/test_cli.py::CLITest::test_reading_stdin",
"tests/unittests/test_cli.py::CLITest::test_show_all_actions",
"tests/unittests/test_cli.py::CLITest::test_version"
] |
{
"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-05-30 19:29:27+00:00
|
apache-2.0
| 2,385 |
|
fniessink__next-action-93
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 4622239..c5192b7 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,12 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/)
and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html).
+## [Unreleased]
+
+### Added
+
+- The due date argument to `--due` is now optional. Closes #92.
+
## [0.14.1] - 2018-06-01
### Fixed
diff --git a/README.md b/README.md
index 42a13a2..ad017f2 100644
--- a/README.md
+++ b/README.md
@@ -40,8 +40,8 @@ Don't know what *Todo.txt* is? See <https://github.com/todotxt/todo.txt> for the
```console
$ next-action --help
-usage: next-action [-h] [--version] [-c [<config.cfg>]] [-f <todo.txt>] [-n <number> | -a] [-d <due date>]
-[-o] [-p [<priority>]] [-s [<style>]] [<context|project> ...]
+usage: next-action [-h] [--version] [-c [<config.cfg>]] [-f <todo.txt>] [-n <number> | -a] [-d [<due date>] |
+-o] [-p [<priority>]] [-s [<style>]] [<context|project> ...]
Show the next action in your todo.txt. The next action is selected from the tasks in the todo.txt file based
on task properties such as priority, due date, and creation date. Limit the tasks from which the next action
@@ -60,8 +60,9 @@ optional arguments:
-n <number>, --number <number>
number of next actions to show (default: 1)
-a, --all show all next actions
- -d <due date>, --due <due date>
- show only next actions due on or before the date
+ -d [<due date>], --due [<due date>]
+ show only next actions with a due date; if a date is given, show only next actions
+ due on or before that date
-o, --overdue show only overdue next actions
-p [<priority>], --priority [<priority>]
minimum priority (A-Z) of next actions to show (default: None)
@@ -91,6 +92,8 @@ Completed tasks (~~`x This is a completed task`~~) and tasks with a creation dat
### Limiting the tasks from which next actions are selected
+#### By contexts and/or projects
+
You can limit the tasks from which *Next-action* picks the next action by passing contexts and/or projects:
```console
@@ -123,11 +126,20 @@ $ next-action -+PaintHouse @store
(G) Buy wood for new +DogHouse @store
```
-To limit the the tasks from which the next action is selected to actions with a due date, specify a due date:
+#### By due date
+
+To limit the the tasks from which the next action is selected to actions with a due date, use the `--due` option:
```console
-$ next-action @home --due june
-Pay invoice @home due:2018-06-28
+$ next-action @home --due
+(K) Pay July invoice @home due:2018-07-28
+```
+
+Add a due date to select a next action from tasks due on or before that date:
+
+```console
+$ next-action @home --due "june 2018"
+(L) Pay June invoice @home due:2018-06-28
```
To make sure you have no overdue actions, or work on overdue actions first, limit the tasks from which the next action is selected to overdue actions:
@@ -137,6 +149,8 @@ $ next-action --overdue
Buy flowers due:2018-02-14
```
+#### By priority
+
To make sure you work on important tasks rather than urgent tasks, you can make sure the tasks from which the next action is selected have at least a minimum priority:
```console
@@ -271,9 +285,9 @@ To run the unit tests:
```console
$ python -m unittest
-.......................................................................................................................................................
+.........................................................................................................................................................
----------------------------------------------------------------------
-Ran 151 tests in 0.587s
+Ran 153 tests in 0.548s
OK
```
diff --git a/docs/todo.txt b/docs/todo.txt
index 9e3f99c..06842c9 100644
--- a/docs/todo.txt
+++ b/docs/todo.txt
@@ -5,6 +5,7 @@
Get rid of old +DogHouse @home
Borrow ladder from the neighbors +PaintHouse @home
Buy flowers due:2018-02-14
-Pay invoice @home due:2018-06-28
+(L) Pay June invoice @home due:2018-06-28
+(K) Pay July invoice @home due:2018-07-28
x This is a completed task
9999-01-01 Start preparing for five-digit years
diff --git a/docs/update_readme.py b/docs/update_readme.py
index 591c40a..6d5d826 100644
--- a/docs/update_readme.py
+++ b/docs/update_readme.py
@@ -1,12 +1,13 @@
""" Insert the output of console commands into the README.md file. """
import os
+import shlex
import subprocess # nosec
def do_command(line):
""" Run the command on the line and return its stdout and stderr. """
- command = line[2:].split(" ")
+ command = shlex.split(line[2:])
if command[0] == "next-action" and "--write-config-file" not in command:
command.extend(["--config", "docs/.next-action.cfg"])
command_output = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
diff --git a/next_action/arguments/parser.py b/next_action/arguments/parser.py
index cd6fec0..953b952 100644
--- a/next_action/arguments/parser.py
+++ b/next_action/arguments/parser.py
@@ -25,7 +25,7 @@ class NextActionArgumentParser(argparse.ArgumentParser):
"the tasks from which the next action is selected by specifying contexts the tasks must have "
"and/or projects the tasks must belong to.",
usage=textwrap.fill("next-action [-h] [--version] [-c [<config.cfg>]] [-f <todo.txt>] "
- "[-n <number> | -a] [-d <due date>] [-o] [-p [<priority>]] [-s [<style>]] "
+ "[-n <number> | -a] [-d [<due date>] | -o] [-p [<priority>]] [-s [<style>]] "
"[<context|project> ...]",
width=shutil.get_terminal_size().columns - len("usage: ")))
self.__default_filenames = ["~/todo.txt"]
@@ -55,8 +55,9 @@ class NextActionArgumentParser(argparse.ArgumentParser):
"-a", "--all", help="show all next actions", action="store_const", dest="number", const=sys.maxsize)
date = self.add_mutually_exclusive_group()
date.add_argument(
- "-d", "--due", metavar="<due date>", type=date_type,
- help="show only next actions due on or before the date")
+ "-d", "--due", metavar="<due date>", type=date_type, nargs="?", const=datetime.date.max,
+ help="show only next actions with a due date; if a date is given, show only next actions due on or "
+ "before that date")
date.add_argument("-o", "--overdue", help="show only overdue next actions", action="store_true")
self.add_argument(
"-p", "--priority", metavar="<priority>", choices=string.ascii_uppercase, nargs="?",
|
fniessink/next-action
|
4af7c956d738e25f879ceb9da77bfb393fcb9713
|
diff --git a/tests/unittests/arguments/test_parser.py b/tests/unittests/arguments/test_parser.py
index aa5dfc4..403c66e 100644
--- a/tests/unittests/arguments/test_parser.py
+++ b/tests/unittests/arguments/test_parser.py
@@ -11,7 +11,7 @@ from next_action.arguments import config, parse_arguments
USAGE_MESSAGE = textwrap.fill(
- "usage: next-action [-h] [--version] [-c [<config.cfg>]] [-f <todo.txt>] [-n <number> | -a] [-d <due date>] [-o] "
+ "usage: next-action [-h] [--version] [-c [<config.cfg>]] [-f <todo.txt>] [-n <number> | -a] [-d [<due date>] | -o] "
"[-p [<priority>]] [-s [<style>]] [<context|project> ...]", 120) + "\n"
@@ -221,6 +221,11 @@ class DueDateTest(ParserTestCase):
""" Test that the default value for due date is None. """
self.assertEqual(None, parse_arguments()[1].due)
+ @patch.object(sys, "argv", ["next-action", "--due"])
+ def test_no_due_date(self):
+ """ Test that the due date is the max date if the user doesn't specify a date. """
+ self.assertEqual(datetime.date.max, parse_arguments()[1].due)
+
@patch.object(sys, "argv", ["next-action", "--due", "2018-01-01"])
def test_due_date(self):
""" Test that the default value for due date is None. """
diff --git a/tests/unittests/test_cli.py b/tests/unittests/test_cli.py
index 388ff6f..8148d29 100644
--- a/tests/unittests/test_cli.py
+++ b/tests/unittests/test_cli.py
@@ -65,7 +65,7 @@ class CLITest(unittest.TestCase):
os.environ['COLUMNS'] = "120" # Fake that the terminal is wide enough.
self.assertRaises(SystemExit, next_action)
self.assertEqual(call("""\
-usage: next-action [-h] [--version] [-c [<config.cfg>]] [-f <todo.txt>] [-n <number> | -a] [-d <due date>] [-o] [-p
+usage: next-action [-h] [--version] [-c [<config.cfg>]] [-f <todo.txt>] [-n <number> | -a] [-d [<due date>] | -o] [-p
[<priority>]] [-s [<style>]] [<context|project> ...]
Show the next action in your todo.txt. The next action is selected from the tasks in the todo.txt file based on task
@@ -85,8 +85,9 @@ optional arguments:
-n <number>, --number <number>
number of next actions to show (default: 1)
-a, --all show all next actions
- -d <due date>, --due <due date>
- show only next actions due on or before the date
+ -d [<due date>], --due [<due date>]
+ show only next actions with a due date; if a date is given, show only next actions due on or
+ before that date
-o, --overdue show only overdue next actions
-p [<priority>], --priority [<priority>]
minimum priority (A-Z) of next actions to show (default: None)
diff --git a/tests/unittests/test_pick_action.py b/tests/unittests/test_pick_action.py
index 5874fb8..05d4db5 100644
--- a/tests/unittests/test_pick_action.py
+++ b/tests/unittests/test_pick_action.py
@@ -205,6 +205,15 @@ class DueTasks(PickActionTestCase):
self.namespace.due = datetime.date(2000, 1, 1)
self.assertEqual([overdue], pick_action.next_actions([no_duedate, future_duedate, overdue], self.namespace))
+ def test_any_due_tasks(self):
+ """ Test that tasks that are not due are filtered. """
+ no_duedate = todotxt.Task("Task")
+ future_duedate = todotxt.Task("Task due:9999-01-01")
+ overdue = todotxt.Task("Task due:2000-01-01")
+ self.namespace.due = datetime.date.max
+ self.assertEqual([overdue, future_duedate],
+ pick_action.next_actions([no_duedate, future_duedate, overdue], self.namespace))
+
class MinimimPriorityTest(PickActionTest):
""" Unit test for the mininum priority filter. """
|
Make --due argument optional to pick next action from tasks with any due date
|
0.0
|
4af7c956d738e25f879ceb9da77bfb393fcb9713
|
[
"tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_empty_context",
"tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_empty_excluded_project",
"tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_empty_project",
"tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_faulty_option",
"tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_include_exclude_context",
"tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_include_exclude_project",
"tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_invalid_extra_argument",
"tests/unittests/arguments/test_parser.py::NumberTest::test_all_and_number",
"tests/unittests/arguments/test_parser.py::NumberTest::test_faulty_number",
"tests/unittests/arguments/test_parser.py::DueDateTest::test_faulty_date",
"tests/unittests/arguments/test_parser.py::DueDateTest::test_invalid_date",
"tests/unittests/arguments/test_parser.py::DueDateTest::test_no_due_date",
"tests/unittests/arguments/test_parser.py::DueDateTest::test_too_long",
"tests/unittests/test_cli.py::CLITest::test_missing_file"
] |
[
"tests/unittests/arguments/test_parser.py::NoArgumentTest::test_filename",
"tests/unittests/arguments/test_parser.py::NoArgumentTest::test_filters",
"tests/unittests/arguments/test_parser.py::NoArgumentTest::test_style",
"tests/unittests/arguments/test_parser.py::FilenameTest::test__add_filename_twice",
"tests/unittests/arguments/test_parser.py::FilenameTest::test_add_default_filename",
"tests/unittests/arguments/test_parser.py::FilenameTest::test_default_and_non_default",
"tests/unittests/arguments/test_parser.py::FilenameTest::test_filename_argument",
"tests/unittests/arguments/test_parser.py::FilenameTest::test_long_filename_argument",
"tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_contexts_and_projects",
"tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_exclude_context",
"tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_exclude_project",
"tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_multiple_contexts",
"tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_multiple_projects",
"tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_one_context",
"tests/unittests/arguments/test_parser.py::FilterArgumentTest::test_one_project",
"tests/unittests/arguments/test_parser.py::NumberTest::test_all_actions",
"tests/unittests/arguments/test_parser.py::NumberTest::test_default_number",
"tests/unittests/arguments/test_parser.py::NumberTest::test_number",
"tests/unittests/arguments/test_parser.py::DueDateTest::test_default",
"tests/unittests/arguments/test_parser.py::DueDateTest::test_due_date",
"tests/unittests/test_cli.py::CLITest::test_context",
"tests/unittests/test_cli.py::CLITest::test_empty_task_file",
"tests/unittests/test_cli.py::CLITest::test_ignore_empty_lines",
"tests/unittests/test_cli.py::CLITest::test_number",
"tests/unittests/test_cli.py::CLITest::test_one_task",
"tests/unittests/test_cli.py::CLITest::test_project",
"tests/unittests/test_cli.py::CLITest::test_reading_stdin",
"tests/unittests/test_cli.py::CLITest::test_show_all_actions",
"tests/unittests/test_cli.py::CLITest::test_version",
"tests/unittests/test_pick_action.py::PickActionTest::test_creation_dates",
"tests/unittests/test_pick_action.py::PickActionTest::test_due_and_creation_dates",
"tests/unittests/test_pick_action.py::PickActionTest::test_due_dates",
"tests/unittests/test_pick_action.py::PickActionTest::test_higher_prio_goes_first",
"tests/unittests/test_pick_action.py::PickActionTest::test_multiple_tasks",
"tests/unittests/test_pick_action.py::PickActionTest::test_no_tasks",
"tests/unittests/test_pick_action.py::PickActionTest::test_one_task",
"tests/unittests/test_pick_action.py::PickActionTest::test_priority_and_creation_date",
"tests/unittests/test_pick_action.py::PickActionTest::test_project",
"tests/unittests/test_pick_action.py::PickActionTest::test_projects",
"tests/unittests/test_pick_action.py::FilterTasksTest::test_context",
"tests/unittests/test_pick_action.py::FilterTasksTest::test_contexts",
"tests/unittests/test_pick_action.py::FilterTasksTest::test_excluded_context",
"tests/unittests/test_pick_action.py::FilterTasksTest::test_excluded_contexts",
"tests/unittests/test_pick_action.py::FilterTasksTest::test_excluded_project",
"tests/unittests/test_pick_action.py::FilterTasksTest::test_excluded_projects",
"tests/unittests/test_pick_action.py::FilterTasksTest::test_not_excluded_context",
"tests/unittests/test_pick_action.py::FilterTasksTest::test_not_excluded_project",
"tests/unittests/test_pick_action.py::FilterTasksTest::test_project",
"tests/unittests/test_pick_action.py::FilterTasksTest::test_project_and_context",
"tests/unittests/test_pick_action.py::IgnoredTasksTest::test_ignore_completed_task",
"tests/unittests/test_pick_action.py::IgnoredTasksTest::test_ignore_future_task",
"tests/unittests/test_pick_action.py::IgnoredTasksTest::test_ignore_these_tasks",
"tests/unittests/test_pick_action.py::OverdueTasks::test_overdue_tasks",
"tests/unittests/test_pick_action.py::DueTasks::test_any_due_tasks",
"tests/unittests/test_pick_action.py::DueTasks::test_due_tasks",
"tests/unittests/test_pick_action.py::MinimimPriorityTest::test_creation_dates",
"tests/unittests/test_pick_action.py::MinimimPriorityTest::test_due_and_creation_dates",
"tests/unittests/test_pick_action.py::MinimimPriorityTest::test_due_dates",
"tests/unittests/test_pick_action.py::MinimimPriorityTest::test_higher_prio_goes_first",
"tests/unittests/test_pick_action.py::MinimimPriorityTest::test_multiple_tasks",
"tests/unittests/test_pick_action.py::MinimimPriorityTest::test_no_tasks",
"tests/unittests/test_pick_action.py::MinimimPriorityTest::test_one_task",
"tests/unittests/test_pick_action.py::MinimimPriorityTest::test_priority",
"tests/unittests/test_pick_action.py::MinimimPriorityTest::test_priority_and_creation_date",
"tests/unittests/test_pick_action.py::MinimimPriorityTest::test_project",
"tests/unittests/test_pick_action.py::MinimimPriorityTest::test_projects"
] |
{
"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-06-01 21:51:44+00:00
|
apache-2.0
| 2,386 |
|
fniessink__next-action-99
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 7db5eed..d3ce3c0 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,12 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/)
and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html).
+## [Unrelease]
+
+### Fixed
+
+- Include reference parameter into standard configuration file. Fixes #98.
+
## [0.16.0] - 2018-06-03
### Added
diff --git a/next_action/arguments/config.py b/next_action/arguments/config.py
index 243e787..6c6acdc 100644
--- a/next_action/arguments/config.py
+++ b/next_action/arguments/config.py
@@ -29,7 +29,8 @@ def read_config_file(filename: str, default_filename: str, error: Callable[[str]
def write_config_file() -> None:
""" Generate a configuration file on standard out. """
intro = "# Configuration file for Next-action. Edit the settings below as you like.\n"
- config = yaml.dump(dict(file="~/todo.txt", number=1, style="default"), default_flow_style=False)
+ config = yaml.dump(dict(file="~/todo.txt", number=1, reference="multiple", style="default"),
+ default_flow_style=False)
sys.stdout.write(intro + config)
|
fniessink/next-action
|
ccfac4290ac360ea795bdc5b71d8574152af99aa
|
diff --git a/tests/unittests/arguments/test_config.py b/tests/unittests/arguments/test_config.py
index fcdf588..8eb5728 100644
--- a/tests/unittests/arguments/test_config.py
+++ b/tests/unittests/arguments/test_config.py
@@ -99,7 +99,7 @@ class ConfigFileTest(ConfigTestCase):
""" Test that a config file can be written to stdout. """
self.assertRaises(SystemExit, parse_arguments)
expected = "# Configuration file for Next-action. Edit the settings below as you like.\n"
- expected += "file: ~/todo.txt\nnumber: 1\nstyle: default\n"
+ expected += "file: ~/todo.txt\nnumber: 1\nreference: multiple\nstyle: default\n"
self.assertEqual([call(expected)], mock_stdout_write.call_args_list)
|
Add `--reference` to standard configuration file
|
0.0
|
ccfac4290ac360ea795bdc5b71d8574152af99aa
|
[
"tests/unittests/arguments/test_config.py::ConfigFileTest::test_write_config"
] |
[
"tests/unittests/arguments/test_config.py::ConfigFileTest::test_empty_file",
"tests/unittests/arguments/test_config.py::ConfigFileTest::test_error_opening",
"tests/unittests/arguments/test_config.py::ConfigFileTest::test_error_parsing",
"tests/unittests/arguments/test_config.py::ConfigFileTest::test_file_not_found",
"tests/unittests/arguments/test_config.py::ConfigFileTest::test_invalid_document",
"tests/unittests/arguments/test_config.py::ConfigFileTest::test_missing_default_config",
"tests/unittests/arguments/test_config.py::ConfigFileTest::test_no_file_key",
"tests/unittests/arguments/test_config.py::ConfigFileTest::test_skip_config",
"tests/unittests/arguments/test_config.py::FilenameTest::test_cli_takes_precedence",
"tests/unittests/arguments/test_config.py::FilenameTest::test_invalid_filename",
"tests/unittests/arguments/test_config.py::FilenameTest::test_valid_and_invalid",
"tests/unittests/arguments/test_config.py::FilenameTest::test_valid_file",
"tests/unittests/arguments/test_config.py::FilenameTest::test_valid_files",
"tests/unittests/arguments/test_config.py::NumberTest::test_all_and_number",
"tests/unittests/arguments/test_config.py::NumberTest::test_all_false",
"tests/unittests/arguments/test_config.py::NumberTest::test_all_true",
"tests/unittests/arguments/test_config.py::NumberTest::test_argument_all_overrides",
"tests/unittests/arguments/test_config.py::NumberTest::test_argument_nr_overrides",
"tests/unittests/arguments/test_config.py::NumberTest::test_cli_takes_precedence",
"tests/unittests/arguments/test_config.py::NumberTest::test_invalid_number",
"tests/unittests/arguments/test_config.py::NumberTest::test_valid_number",
"tests/unittests/arguments/test_config.py::NumberTest::test_zero",
"tests/unittests/arguments/test_config.py::ConfigStyleTest::test_cancel_style",
"tests/unittests/arguments/test_config.py::ConfigStyleTest::test_invalid_style",
"tests/unittests/arguments/test_config.py::ConfigStyleTest::test_override_style",
"tests/unittests/arguments/test_config.py::ConfigStyleTest::test_valid_style",
"tests/unittests/arguments/test_config.py::PriorityTest::test_cancel_priority",
"tests/unittests/arguments/test_config.py::PriorityTest::test_invalid_priority",
"tests/unittests/arguments/test_config.py::PriorityTest::test_override_priority",
"tests/unittests/arguments/test_config.py::PriorityTest::test_valid_priority",
"tests/unittests/arguments/test_config.py::ReferenceTest::test_invalid_priority",
"tests/unittests/arguments/test_config.py::ReferenceTest::test_override",
"tests/unittests/arguments/test_config.py::ReferenceTest::test_valid_reference"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2018-06-03 21:52:07+00:00
|
apache-2.0
| 2,387 |
|
fnl__syntok-17
|
diff --git a/syntok/tokenizer.py b/syntok/tokenizer.py
index e27a705..edb3f7f 100644
--- a/syntok/tokenizer.py
+++ b/syntok/tokenizer.py
@@ -221,7 +221,7 @@ class Tokenizer:
yield Token(prefix, word[remainder:mo.start() - 1], offset + remainder)
prefix = ""
- yield Token(prefix, "not" if self.replace_not_contraction else 'n' + mo.group(0), offset + mo.start())
+ yield Token(prefix, "not" if self.replace_not_contraction else 'n' + mo.group(0), offset + mo.start() - 1)
return ""
yield Token(prefix, word[remainder:mo.start()], offset + remainder)
|
fnl/syntok
|
10ee9b1525a513ae0fb08762b91beb24a26389ca
|
diff --git a/syntok/tokenizer_test.py b/syntok/tokenizer_test.py
index e40a032..dbb3cbe 100644
--- a/syntok/tokenizer_test.py
+++ b/syntok/tokenizer_test.py
@@ -91,6 +91,23 @@ class TestTokenizer(TestCase):
self.assertListEqual(s(result), ["\U0001F64C", ".", "A"])
self.assertListEqual([t.offset for t in result], [0, 1, 2]) # requires Py3.3+
+ def test_apostrophe_offset_without_replace_not_contraction(self):
+ # NOTE: in this case nothing is replaced, so the offsets should remain identical
+ # to those in the original text
+ text = "don't"
+ self.tokenizer = Tokenizer(replace_not_contraction=False)
+ result = self.tokenizer.split(text)
+ self.assertListEqual([t.offset for t in result], [0, 2])
+
+ def test_apostrophe_offset_with_replace_not_contraction(self):
+ # NOTE: in this case, "n't" is replaced with "not", so a space is introduced.
+ # e.g. "don't" -> "do not", "can't" -> "can not"
+ text = "don't"
+ self.tokenizer = Tokenizer(replace_not_contraction=True)
+ result = self.tokenizer.split(text)
+ self.assertListEqual([t.offset for t in result], [0, 2])
+ self.assertListEqual([t.value for t in result], ["do", "not"])
+
class TestToText(TestCase):
|
Bug in not-contraction handling code
Hi,
Thanks for the great library! I think I ran into a weird edge-case wrt not-contraction handling code. If I use the following example:
```python
from syntok.tokenizer import Tokenizer
tok = Tokenizer(replace_not_contraction=False)
tok.split("n't")
```
The output is `[<Token '' : "n't" @ 1>]`. Something is going wrong in the offset calculation there, that 1 should be a 0... The real example this came from is a sentence in the AIDA dataset, `" Falling share prices in New York do n't hurt Mexico as long as it happens gradually , as earlier this week`.
I see the same with "don't": `[<Token '' : 'do' @ 0>, <Token '' : "n't" @ 3>]`, that 3 should be 2 no?
Would love to hear your thoughts, not sure how to fix this neatly yet.
|
0.0
|
10ee9b1525a513ae0fb08762b91beb24a26389ca
|
[
"syntok/tokenizer_test.py::TestTokenizer::test_apostrophe_offset_with_replace_not_contraction",
"syntok/tokenizer_test.py::TestTokenizer::test_apostrophe_offset_without_replace_not_contraction"
] |
[
"syntok/tokenizer_test.py::TestTokenizer::test_apostrophes",
"syntok/tokenizer_test.py::TestTokenizer::test_clean_text",
"syntok/tokenizer_test.py::TestTokenizer::test_clean_text_Unicode",
"syntok/tokenizer_test.py::TestTokenizer::test_emit_dash",
"syntok/tokenizer_test.py::TestTokenizer::test_emit_underscore",
"syntok/tokenizer_test.py::TestTokenizer::test_hyphens",
"syntok/tokenizer_test.py::TestTokenizer::test_inner_ellipsis",
"syntok/tokenizer_test.py::TestTokenizer::test_lines",
"syntok/tokenizer_test.py::TestTokenizer::test_nonword_high_prefix",
"syntok/tokenizer_test.py::TestTokenizer::test_nonword_prefix",
"syntok/tokenizer_test.py::TestTokenizer::test_spacing_prefix",
"syntok/tokenizer_test.py::TestTokenizer::test_split_camel_case",
"syntok/tokenizer_test.py::TestTokenizer::test_split_dot",
"syntok/tokenizer_test.py::TestToText::test_lines",
"syntok/tokenizer_test.py::TestToText::test_lines_emit_and_do_not_replace"
] |
{
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
}
|
2021-12-17 09:09:53+00:00
|
mit
| 2,388 |
|
fnl__syntok-24
|
diff --git a/syntok/_segmentation_states.py b/syntok/_segmentation_states.py
index b94668b..bc01c02 100644
--- a/syntok/_segmentation_states.py
+++ b/syntok/_segmentation_states.py
@@ -76,7 +76,6 @@ class State(metaclass=ABCMeta):
univ Univ Urt vda Vda vol Vol vs vta zB zit zzgl
Mon lun Tue mar Wed mie mié Thu jue Fri vie Sat sab Sun dom
""".split()
- + list(months)
)
"""Abbreviations with no dots inside."""
@@ -188,14 +187,13 @@ class State(metaclass=ABCMeta):
return not self.is_empty and self.__queue[0].value.isnumeric()
@property
- def next_is_alphanumeric(self) -> bool:
+ def next_is_alphanumeric_containing_numeric_char(self) -> bool:
if self.is_empty:
return False
v = self.__queue[0].value
return (
any(c.isnumeric() for c in v)
- and any(c.isalpha() for c in v)
and v.isalnum()
)
@@ -389,7 +387,7 @@ class State(metaclass=ABCMeta):
):
return self
- elif token_before == "no" and self.next_is_alphanumeric:
+ elif token_before in ("no", "No", "NO") and self.next_is_alphanumeric_containing_numeric_char:
return self
elif self.next_is_numeric and self.next_has_no_spacing:
@@ -408,6 +406,9 @@ class State(metaclass=ABCMeta):
elif token_before.isnumeric() and self.next_is_month_abbreviation:
return self
+ elif token_before in State.months and self.next_is_numeric:
+ return self
+
elif "." in token_before and token_after != ".":
return self
|
fnl/syntok
|
d023b5c41ec1594b3c5be3abd95788db96ef5e9a
|
diff --git a/syntok/segmenter_test.py b/syntok/segmenter_test.py
index 48e59c3..60aa0eb 100644
--- a/syntok/segmenter_test.py
+++ b/syntok/segmenter_test.py
@@ -87,6 +87,7 @@ This is a sentence terminal ellipsis...
This is another sentence terminal ellipsis....
An easy to handle G. species mention.
Am 13. Jän. 2006 war es regnerisch.
+And on Jan. 22, 2022 it was, too.
(Phil. 4:8)
(Oh. Again!)
Syntok even handles bible quotes!
@@ -144,6 +145,7 @@ In line with the literature on DLB.
This is verse 14;45 in the test;
Splitting on semi-colons.
The discovery of low-mass nulceli (AGN; NGC 4395 and POX 52; Filippenko & Sargent 1989; Kunth et al. 1987) triggered a quest; it has yielded today more than 500 sources.
+The Company is the No. 2 and No. 3 largest chain in the U.S. and Canada, respectively, by number of stores.
Always last, clear closing example."""
SENTENCES = OSPL.split("\n")
@@ -276,6 +278,22 @@ class TestSegmenter(TestCase):
result = segmenter.split(iter(tokens))
self.assertEqual([tokens[:sep], tokens[sep:]], result)
+ def test_sentences_ending_with_false_positive_month_abbreviation_1(self):
+ tokens = Tokenizer().split(
+ "Some of the cookies are essential for parts of the site to operate and have already been set. You may delete and block all cookies from this site, but if you do, parts of the site may not work."
+ )
+ sep = 19
+ result = segmenter.split(iter(tokens))
+ self.assertEqual([tokens[:sep], tokens[sep:]], result)
+
+ def test_sentences_ending_with_false_positive_month_abbreviation_2(self):
+ tokens = Tokenizer().split(
+ "The sharpshooter appears to be checked out on his Kings experience, and an argument could easily be raised that he should have been moved two years ago. Now, his $23 million salary will be a tough pill for teams to swallow, even if there is decent chance of a solid bounce-back year at a new destination."
+ )
+ sep = 29
+ result = segmenter.split(iter(tokens))
+ self.assertEqual([tokens[:sep], tokens[sep:]], result)
+
def test_sentences_with_enumerations(self):
tokens = Tokenizer().split("1. This goes first. 2. And here thereafter.")
sep = 6
@@ -378,9 +396,7 @@ class TestSegmenter(TestCase):
self.assertEqual([tokens], result)
def test_do_not_split_bible_citation(self):
- tokens = Tokenizer().split(
- "This is a bible quote? (Phil. 4:8) Yes, it is!"
- )
+ tokens = Tokenizer().split("This is a bible quote? (Phil. 4:8) Yes, it is!")
result = segmenter.split(iter(tokens))
self.assertEqual(len(result[0]), 6)
self.assertEqual(len(result[1]), 5)
@@ -463,12 +479,16 @@ class TestSegmenter(TestCase):
self.assertEqual([tokens], result)
def test_no_split_on_strange_text(self):
- tokens = Tokenizer().split("Four patients (67%) with an average response of 3.3 mos. (range 6 wks. to 12 mos.)")
+ tokens = Tokenizer().split(
+ "Four patients (67%) with an average response of 3.3 mos. (range 6 wks. to 12 mos.)"
+ )
result = segmenter.split(iter(tokens))
self.assertEqual([tokens], result)
def test_no_split_on_strange_text2(self):
- tokens = Tokenizer().split("Packed cells (PRBC) for less than 20,000 thousand/micro.L, repsectively.")
+ tokens = Tokenizer().split(
+ "Packed cells (PRBC) for less than 20,000 thousand/micro.L, repsectively."
+ )
result = segmenter.split(iter(tokens))
self.assertEqual([tokens], result)
|
Under-splitting on "set." and "ago."
Syntok did not split:
> Some of the cookies are essential for parts of the site to operate and have already been set. You may delete and block all cookies from this site, but if you do, parts of the site may not work.
and:
> The sharpshooter appears to be checked out on his Kings experience, and an argument could easily be raised that he should have been moved two years ago. Now, his $23 million salary will be a tough pill for teams to swallow, even if there is decent chance of a solid bounce-back year at a new destination.
Because those are the official abbreviations for two Spanish months (septiembre and agosto).
|
0.0
|
d023b5c41ec1594b3c5be3abd95788db96ef5e9a
|
[
"syntok/segmenter_test.py::TestSegmenter::test_segmenter",
"syntok/segmenter_test.py::TestSegmenter::test_sentences_ending_with_false_positive_month_abbreviation_1",
"syntok/segmenter_test.py::TestSegmenter::test_sentences_ending_with_false_positive_month_abbreviation_2"
] |
[
"syntok/segmenter_test.py::TestSegmenter::test_abbreviation_followed_by_large_number",
"syntok/segmenter_test.py::TestSegmenter::test_abbreviation_followed_by_parenthesis",
"syntok/segmenter_test.py::TestSegmenter::test_abbreviation_no_followed_by_alnum_token",
"syntok/segmenter_test.py::TestSegmenter::test_brackets_before_the_terminal",
"syntok/segmenter_test.py::TestSegmenter::test_do_not_split_bible_citation",
"syntok/segmenter_test.py::TestSegmenter::test_do_not_split_short_text_inside_parenthesis",
"syntok/segmenter_test.py::TestSegmenter::test_do_not_split_short_text_inside_parenthesis3",
"syntok/segmenter_test.py::TestSegmenter::test_do_not_split_short_text_inside_parenthesis4",
"syntok/segmenter_test.py::TestSegmenter::test_empty",
"syntok/segmenter_test.py::TestSegmenter::test_no_split_on_strange_text",
"syntok/segmenter_test.py::TestSegmenter::test_no_split_on_strange_text2",
"syntok/segmenter_test.py::TestSegmenter::test_no_split_on_strange_text3",
"syntok/segmenter_test.py::TestSegmenter::test_no_split_with_simple_inner_bracketed_text",
"syntok/segmenter_test.py::TestSegmenter::test_one_token",
"syntok/segmenter_test.py::TestSegmenter::test_one_word_sentences",
"syntok/segmenter_test.py::TestSegmenter::test_sentence_ends_in_abbreviation",
"syntok/segmenter_test.py::TestSegmenter::test_sentence_ends_in_single_letter_and_starts_with_starter_word",
"syntok/segmenter_test.py::TestSegmenter::test_sentence_marker_after_abbreviation",
"syntok/segmenter_test.py::TestSegmenter::test_sentence_with_abbreviation_indictated_by_punctuation",
"syntok/segmenter_test.py::TestSegmenter::test_sentence_with_abbreviation_with_dot",
"syntok/segmenter_test.py::TestSegmenter::test_sentence_with_single_letter_abbreviation",
"syntok/segmenter_test.py::TestSegmenter::test_sentence_with_single_letter_at_end",
"syntok/segmenter_test.py::TestSegmenter::test_sentence_with_single_quotes",
"syntok/segmenter_test.py::TestSegmenter::test_sentences_with_Roman_enumerations",
"syntok/segmenter_test.py::TestSegmenter::test_sentences_with_enumerations",
"syntok/segmenter_test.py::TestSegmenter::test_sentences_with_letter_enumerations",
"syntok/segmenter_test.py::TestSegmenter::test_sentences_with_nasty_abbreviations",
"syntok/segmenter_test.py::TestSegmenter::test_sentences_with_nasty_special_abbreviations",
"syntok/segmenter_test.py::TestSegmenter::test_sentences_with_simple_abbreviations",
"syntok/segmenter_test.py::TestSegmenter::test_sentences_with_special_abbreviations",
"syntok/segmenter_test.py::TestSegmenter::test_simple",
"syntok/segmenter_test.py::TestSegmenter::test_split_long_text_inside_parenthesis",
"syntok/segmenter_test.py::TestSegmenter::test_split_long_text_inside_parenthesis2",
"syntok/segmenter_test.py::TestSegmenter::test_split_self_standing_parenthesis",
"syntok/segmenter_test.py::TestSegmenter::test_split_sentence_with_parenthesis_at_start",
"syntok/segmenter_test.py::TestSegmenter::test_split_with_a_simple_parenthesis_structure",
"syntok/segmenter_test.py::TestSegmenter::test_split_with_complex_parenthesis_structure",
"syntok/segmenter_test.py::TestSegmenter::test_split_with_complext_abbreviation_pattern",
"syntok/segmenter_test.py::TestSegmenter::test_split_with_dot_following_abbreviation",
"syntok/segmenter_test.py::TestSegmenter::test_two_exclamations",
"syntok/segmenter_test.py::TestSegmenter::test_two_questions",
"syntok/segmenter_test.py::TestSegmenter::test_two_sentences",
"syntok/segmenter_test.py::TestSegmenter::test_two_sentences_with_parenthesis_in_first",
"syntok/segmenter_test.py::TestSegmenter::test_two_sentences_with_parenthesis_in_second",
"syntok/segmenter_test.py::TestSegmenter::test_two_sentences_with_quotes_and_prenthesis_in_both",
"syntok/segmenter_test.py::TestSegmenter::test_two_sentences_with_quotes_in_both",
"syntok/segmenter_test.py::TestSegmenter::test_two_sentences_with_quotes_in_first",
"syntok/segmenter_test.py::TestSegmenter::test_two_sentences_with_quotes_in_second",
"syntok/segmenter_test.py::TestSegmenter::test_two_tokens",
"syntok/segmenter_test.py::TestPreprocess::test_preprocess",
"syntok/segmenter_test.py::TestPreprocess::test_preprocess_with_offsets",
"syntok/segmenter_test.py::TestAnalyze::test_analyze",
"syntok/segmenter_test.py::TestProcess::test_process"
] |
{
"failed_lite_validators": [
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-02-28 15:45:20+00:00
|
mit
| 2,389 |
|
fonttools__openstep-plist-24
|
diff --git a/src/openstep_plist/__main__.py b/src/openstep_plist/__main__.py
index 673128b..9165225 100755
--- a/src/openstep_plist/__main__.py
+++ b/src/openstep_plist/__main__.py
@@ -37,6 +37,9 @@ def main(args=None):
"-j", "--json", help="use json to serialize", action="store_true", default=False
)
parser.add_argument("-i", "--indent", help="indentation level", type=int, default=2)
+ parser.add_argument(
+ "--no-escape-newlines", dest="escape_newlines", action="store_false"
+ )
args = parser.parse_args(args)
if not args.glyphs:
@@ -58,7 +61,11 @@ def main(args=None):
if args.glyphs:
from glyphsLib.writer import dump
else:
- dump = partial(openstep_plist.dump, indent=args.indent)
+ dump = partial(
+ openstep_plist.dump,
+ indent=args.indent,
+ escape_newlines=args.escape_newlines,
+ )
with open(args.infile, "r", encoding="utf-8") as fp:
data = parse(fp)
diff --git a/src/openstep_plist/writer.pyx b/src/openstep_plist/writer.pyx
index 46a693e..ffbb98b 100644
--- a/src/openstep_plist/writer.pyx
+++ b/src/openstep_plist/writer.pyx
@@ -117,6 +117,7 @@ cdef class Writer:
cdef unicode indent
cdef int current_indent_level
cdef bint single_line_tuples
+ cdef bint escape_newlines
def __cinit__(
self,
@@ -124,10 +125,12 @@ cdef class Writer:
int float_precision=6,
indent=None,
bint single_line_tuples=False,
+ bint escape_newlines=True,
):
self.dest = new vector[Py_UCS4]()
self.unicode_escape = unicode_escape
self.float_precision = float_precision
+ self.escape_newlines = escape_newlines
if indent is not None:
if isinstance(indent, basestring):
@@ -225,14 +228,17 @@ cdef class Writer:
unsigned long ch
Py_ssize_t base_length = dest.size()
Py_ssize_t new_length = 0
+ bint escape_newlines = self.escape_newlines
while curr < end:
ch = curr[0]
- if ch == c'\t' or ch == c' ':
+ if ch == c'\t' or ch == c' ' or (ch == c'\n' and not escape_newlines):
new_length += 1
elif (
- ch == c'\n' or ch == c'\\' or ch == c'"' or ch == c'\a'
+ ch == c'\\' or ch == c'"' or ch == c'\a'
or ch == c'\b' or ch == c'\v' or ch == c'\f' or ch == c'\r'
+ ) or (
+ ch == c'\n' and escape_newlines
):
new_length += 2
else:
@@ -258,10 +264,10 @@ cdef class Writer:
curr = s
while curr < end:
ch = curr[0]
- if ch == c'\t' or ch == c' ':
+ if ch == c'\t' or ch == c' ' or (ch == c'\n' and not escape_newlines):
ptr[0] = ch
ptr += 1
- elif ch == c'\n':
+ elif ch == c'\n' and escape_newlines:
ptr[0] = c'\\'; ptr[1] = c'n'; ptr += 2
elif ch == c'\a':
ptr[0] = c'\\'; ptr[1] = c'a'; ptr += 2
@@ -584,24 +590,26 @@ cdef class Writer:
def dumps(obj, bint unicode_escape=True, int float_precision=6, indent=None,
- single_line_tuples=False):
+ bint single_line_tuples=False, bint escape_newlines=True):
w = Writer(
unicode_escape=unicode_escape,
float_precision=float_precision,
indent=indent,
single_line_tuples=single_line_tuples,
+ escape_newlines=escape_newlines,
)
w.write(obj)
return w.getvalue()
def dump(obj, fp, bint unicode_escape=True, int float_precision=6, indent=None,
- single_line_tuples=False):
+ bint single_line_tuples=False, bint escape_newlines=True):
w = Writer(
unicode_escape=unicode_escape,
float_precision=float_precision,
indent=indent,
single_line_tuples=single_line_tuples,
+ escape_newlines=escape_newlines,
)
w.write(obj)
w.dump(fp)
|
fonttools/openstep-plist
|
c9acd408ba3a374ba41dd62f595f43fa2e5bfa6f
|
diff --git a/tests/test_writer.py b/tests/test_writer.py
index 3197766..8306bde 100644
--- a/tests/test_writer.py
+++ b/tests/test_writer.py
@@ -4,6 +4,7 @@ import openstep_plist
from openstep_plist.writer import Writer, string_needs_quotes
from io import StringIO, BytesIO
from collections import OrderedDict
+from textwrap import dedent
import string
import random
import pytest
@@ -57,6 +58,11 @@ class TestWriter(object):
w.write(string)
assert w.getvalue() == expected
+ def test_quoted_string_dont_escape_newlines(self):
+ w = Writer(escape_newlines=False)
+ w.write("a\n\n\nbc")
+ assert w.getvalue() == '"a\n\n\nbc"'
+
def test_quoted_string_no_unicode_escape(self):
w = Writer(unicode_escape=False)
w.write("\u0410") == 3
@@ -211,17 +217,36 @@ def test_dumps():
'{a = 1; b = 3; "c d" = (33, 44); '
"e = (<66676869 6C6D6E6F>, <70717273 7475767A>);}"
)
+ assert openstep_plist.dumps(
+ {
+ "features": dedent(
+ """\
+ sub periodcentered by periodcentered.case;
+ sub bullet by bullet.case;
+ """
+ ),
+ },
+ escape_newlines=False,
+ ) == (
+ '{features = "sub periodcentered by periodcentered.case;\n'
+ 'sub bullet by bullet.case;\n'
+ '";}'
+ )
def test_dump():
- plist = [1, b"2", {3: (4, "5", "\U0001F4A9")}]
+ plist = [1, b"2", {3: (4, "5\n6", "\U0001F4A9")}]
fp = StringIO()
openstep_plist.dump(plist, fp)
- assert fp.getvalue() == '(1, <32>, {"3" = (4, "5", "\\UD83D\\UDCA9");})'
+ assert fp.getvalue() == '(1, <32>, {"3" = (4, "5\\n6", "\\UD83D\\UDCA9");})'
fp = BytesIO()
openstep_plist.dump(plist, fp, unicode_escape=False)
- assert fp.getvalue() == b'(1, <32>, {"3" = (4, "5", "\xf0\x9f\x92\xa9");})'
+ assert fp.getvalue() == b'(1, <32>, {"3" = (4, "5\\n6", "\xf0\x9f\x92\xa9");})'
+
+ fp = BytesIO()
+ openstep_plist.dump(plist, fp, escape_newlines=False, unicode_escape=False)
+ assert fp.getvalue() == b'(1, <32>, {"3" = (4, "5\n6", "\xf0\x9f\x92\xa9");})'
with pytest.raises(AttributeError):
openstep_plist.dump(plist, object())
|
[writer] add option to not escape newline characters
as @arrowtype noted in
https://github.com/googlefonts/glyphsLib/issues/953#issuecomment-1789998384
|
0.0
|
c9acd408ba3a374ba41dd62f595f43fa2e5bfa6f
|
[
"tests/test_writer.py::test_string_needs_quotes[{-True]"
] |
[
"tests/test_writer.py::TestWriter::test_simple",
"tests/test_writer.py::TestWriter::test_None",
"tests/test_writer.py::TestWriter::test_unquoted_string",
"tests/test_writer.py::TestWriter::test_quoted_string[-\"\"]",
"tests/test_writer.py::TestWriter::test_quoted_string[\\t-\"\\t\"]",
"tests/test_writer.py::TestWriter::test_quoted_string[\\n\\x07\\x08\\x0b\\x0c\\r-\"\\\\n\\\\a\\\\b\\\\v\\\\f\\\\r\"]",
"tests/test_writer.py::TestWriter::test_quoted_string[\\\\-\"\\\\\\\\\"]",
"tests/test_writer.py::TestWriter::test_quoted_string[\"-\"\\\\\"\"]",
"tests/test_writer.py::TestWriter::test_quoted_string[\\x00\\x01\\x02\\x03\\x04\\x05\\x06-\"\\\\000\\\\001\\\\002\\\\003\\\\004\\\\005\\\\006\"]",
"tests/test_writer.py::TestWriter::test_quoted_string[\\x0e\\x0f\\x10\\x11\\x12\\x13-\"\\\\016\\\\017\\\\020\\\\021\\\\022\\\\023\"]",
"tests/test_writer.py::TestWriter::test_quoted_string[\\x14\\x15\\x16\\x17\\x18\\x19-\"\\\\024\\\\025\\\\026\\\\027\\\\030\\\\031\"]",
"tests/test_writer.py::TestWriter::test_quoted_string[\\x1a\\x1b\\x1c\\x1d\\x1e\\x1f\\x7f-\"\\\\032\\\\033\\\\034\\\\035\\\\036\\\\037\\\\177\"]",
"tests/test_writer.py::TestWriter::test_quoted_string[\\x80\\x81\\x9e\\x9f\\xa0-\"\\\\U0080\\\\U0081\\\\U009E\\\\U009F\\\\U00A0\"]",
"tests/test_writer.py::TestWriter::test_quoted_string[\\U0001f4a9-\"\\\\UD83D\\\\UDCA9\"]",
"tests/test_writer.py::TestWriter::test_quoted_string[1-\"1\"]",
"tests/test_writer.py::TestWriter::test_quoted_string[1.1-\"1.1\"]",
"tests/test_writer.py::TestWriter::test_quoted_string[-23-\"-23\"]",
"tests/test_writer.py::TestWriter::test_quoted_string[-23yyy-\"-23yyy\"]",
"tests/test_writer.py::TestWriter::test_quoted_string[--\"-\"]",
"tests/test_writer.py::TestWriter::test_quoted_string[-a--\"-a-\"]",
"tests/test_writer.py::TestWriter::test_quoted_string_no_unicode_escape",
"tests/test_writer.py::TestWriter::test_int[0-0]",
"tests/test_writer.py::TestWriter::test_int[1-1]",
"tests/test_writer.py::TestWriter::test_int[123-123]",
"tests/test_writer.py::TestWriter::test_int[9223372036854775807-9223372036854775807]",
"tests/test_writer.py::TestWriter::test_int[9223372036854775808-9223372036854775808]",
"tests/test_writer.py::TestWriter::test_float[0.0-0]",
"tests/test_writer.py::TestWriter::test_float[1.0-1]",
"tests/test_writer.py::TestWriter::test_float[123.456-123.456]",
"tests/test_writer.py::TestWriter::test_float[0.01-0.01]",
"tests/test_writer.py::TestWriter::test_float[0.001-0.001]",
"tests/test_writer.py::TestWriter::test_float[0.0001-0.0001]",
"tests/test_writer.py::TestWriter::test_float[1e-05-0.00001]",
"tests/test_writer.py::TestWriter::test_float[1e-06-0.000001]",
"tests/test_writer.py::TestWriter::test_float[1e-07-0]",
"tests/test_writer.py::TestWriter::test_float_precision",
"tests/test_writer.py::TestWriter::test_data[\\x00-<00>]",
"tests/test_writer.py::TestWriter::test_data[\\x00\\x01-<0001>]",
"tests/test_writer.py::TestWriter::test_data[\\x00\\x01\\x02-<000102>]",
"tests/test_writer.py::TestWriter::test_data[\\x00\\x01\\x02\\x03-<00010203>]",
"tests/test_writer.py::TestWriter::test_data[\\x00\\x01\\x02\\x03\\x04-<00010203",
"tests/test_writer.py::TestWriter::test_data[\\x00\\x01\\x02\\x03\\x04\\x05-<00010203",
"tests/test_writer.py::TestWriter::test_data[\\x00\\x01\\x02\\x03\\x04\\x05\\x06-<00010203",
"tests/test_writer.py::TestWriter::test_data[\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07-<00010203",
"tests/test_writer.py::TestWriter::test_data[\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08-<00010203",
"tests/test_writer.py::TestWriter::test_data[\\t\\n\\x0b\\x0c\\r\\x0e\\x0f\\x10\\x11-<090A0B0C",
"tests/test_writer.py::TestWriter::test_bool",
"tests/test_writer.py::TestWriter::test_array[array0-()-()]",
"tests/test_writer.py::TestWriter::test_array[array1-()-()]",
"tests/test_writer.py::TestWriter::test_array[array2-(1)-(\\n",
"tests/test_writer.py::TestWriter::test_array[array3-(1,",
"tests/test_writer.py::TestWriter::test_array[array4-(1.2,",
"tests/test_writer.py::TestWriter::test_array[array5-(1,",
"tests/test_writer.py::TestWriter::test_array[array6-(<61>,",
"tests/test_writer.py::TestWriter::test_array[array7-({a",
"tests/test_writer.py::TestWriter::test_dictionary[dictionary0-{}-{}]",
"tests/test_writer.py::TestWriter::test_dictionary[dictionary1-{}-{}]",
"tests/test_writer.py::TestWriter::test_dictionary[dictionary2-{a",
"tests/test_writer.py::TestWriter::test_dictionary[dictionary3-{\"1\"",
"tests/test_writer.py::TestWriter::test_dictionary[dictionary4-{abc",
"tests/test_writer.py::TestWriter::test_dictionary[dictionary5-{z",
"tests/test_writer.py::TestWriter::test_type_error",
"tests/test_writer.py::test_string_needs_quotes[ABCDEFGHIJKLMNOPQRSTUVWXYZ-False]",
"tests/test_writer.py::test_string_needs_quotes[abcdefghijklmnopqrstuvwxyz-False]",
"tests/test_writer.py::test_string_needs_quotes[a0123456789-False]",
"tests/test_writer.py::test_string_needs_quotes[.appVersion-False]",
"tests/test_writer.py::test_string_needs_quotes[_private-False]",
"tests/test_writer.py::test_string_needs_quotes[$PWD-False]",
"tests/test_writer.py::test_string_needs_quotes[1zzz-False]",
"tests/test_writer.py::test_string_needs_quotes[192.168.1.1-False]",
"tests/test_writer.py::test_string_needs_quotes[0-True]",
"tests/test_writer.py::test_string_needs_quotes[1-True]",
"tests/test_writer.py::test_string_needs_quotes[2-True]",
"tests/test_writer.py::test_string_needs_quotes[3-True]",
"tests/test_writer.py::test_string_needs_quotes[4-True]",
"tests/test_writer.py::test_string_needs_quotes[5-True]",
"tests/test_writer.py::test_string_needs_quotes[6-True]",
"tests/test_writer.py::test_string_needs_quotes[7-True]",
"tests/test_writer.py::test_string_needs_quotes[8-True]",
"tests/test_writer.py::test_string_needs_quotes[9-True]",
"tests/test_writer.py::test_string_needs_quotes[-True]",
"tests/test_writer.py::test_string_needs_quotes[--True]",
"tests/test_writer.py::test_string_needs_quotes[A-Z-True]",
"tests/test_writer.py::test_string_needs_quotes[hello",
"tests/test_writer.py::test_string_needs_quotes[\\\\backslash-True]",
"tests/test_writer.py::test_string_needs_quotes[http://github.com-True]",
"tests/test_writer.py::test_single_line_tuples"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2023-11-02 13:34:42+00:00
|
mit
| 2,390 |
|
fonttools__openstep-plist-7
|
diff --git a/src/openstep_plist/writer.pyx b/src/openstep_plist/writer.pyx
index b0b9034..b6cc262 100644
--- a/src/openstep_plist/writer.pyx
+++ b/src/openstep_plist/writer.pyx
@@ -114,9 +114,14 @@ cdef class Writer:
cdef int float_precision
cdef unicode indent
cdef int current_indent_level
+ cdef bint single_line_tuples
def __cinit__(
- self, bint unicode_escape=True, int float_precision=6, indent=None
+ self,
+ bint unicode_escape=True,
+ int float_precision=6,
+ indent=None,
+ bint single_line_tuples=False,
):
self.dest = array.clone(unicode_array_template, 0, zero=False)
self.unicode_escape = unicode_escape
@@ -129,6 +134,7 @@ cdef class Writer:
self.indent = ' ' * indent
else:
self.indent = None
+ self.single_line_tuples = single_line_tuples
self.current_indent_level = 0
def getvalue(self):
@@ -433,7 +439,7 @@ cdef class Writer:
count = 1
indent = self.indent
- if indent is not None:
+ if indent is not None and not self.single_line_tuples:
self.current_indent_level += 1
newline_indent = '\n' + self.current_indent_level * indent
indent_length = PyUnicode_GET_SIZE(newline_indent)
@@ -450,10 +456,13 @@ cdef class Writer:
count += 2
else:
dest.append(',')
+ if self.single_line_tuples:
+ dest.append(' ')
+ count += 1
array.extend_buffer(dest, <char*>indent_chars, indent_length)
count += 1 + indent_length
- if indent is not None:
+ if indent is not None and not self.single_line_tuples:
self.current_indent_level -= 1
newline_indent = '\n' + self.current_indent_level * indent
indent_length = PyUnicode_GET_SIZE(newline_indent)
@@ -594,21 +603,25 @@ cdef class Writer:
return count
-def dumps(obj, bint unicode_escape=True, int float_precision=6, indent=None):
+def dumps(obj, bint unicode_escape=True, int float_precision=6, indent=None,
+ single_line_tuples=False):
w = Writer(
unicode_escape=unicode_escape,
float_precision=float_precision,
indent=indent,
+ single_line_tuples=single_line_tuples,
)
w.write(obj)
return w.getvalue()
-def dump(obj, fp, bint unicode_escape=True, int float_precision=6, indent=None):
+def dump(obj, fp, bint unicode_escape=True, int float_precision=6, indent=None,
+ single_line_tuples=False):
w = Writer(
unicode_escape=unicode_escape,
float_precision=float_precision,
indent=indent,
+ single_line_tuples=single_line_tuples,
)
w.write(obj)
w.dump(fp)
|
fonttools/openstep-plist
|
0e58a15b8690969c5a9301cc03d3bd2ffb0f8166
|
diff --git a/tests/test_writer.py b/tests/test_writer.py
index aafa043..77deabc 100644
--- a/tests/test_writer.py
+++ b/tests/test_writer.py
@@ -269,3 +269,25 @@ invalid_unquoted_chars = [
)
def test_string_needs_quotes(string, expected):
assert string_needs_quotes(string) is expected
+
+
+def test_single_line_tuples():
+ assert openstep_plist.dumps({"a": 1, "b": (2, 3), "c": "Hello"}, indent=0) == (
+ """{
+a = 1;
+b = (
+2,
+3
+);
+c = Hello;
+}"""
+ )
+ assert openstep_plist.dumps(
+ {"a": 1, "b": (2, 3), "c": "Hello"}, indent=0, single_line_tuples=True
+ ) == (
+ """{
+a = 1;
+b = (2, 3);
+c = Hello;
+}"""
+ )
|
Support Glyphs-style "tuples"
Glyphs 3 plist files have "tuples" which appear on a single line even when other lines are separated/indented. The easiest way to support this would be to remove the `if indent is not None...` blocks from `write_array_from_tuple`. However, this may have Unintended Consequences.
|
0.0
|
0e58a15b8690969c5a9301cc03d3bd2ffb0f8166
|
[
"tests/test_writer.py::test_string_needs_quotes[/-True]"
] |
[
"tests/test_writer.py::TestWriter::test_simple",
"tests/test_writer.py::TestWriter::test_None",
"tests/test_writer.py::TestWriter::test_unquoted_string",
"tests/test_writer.py::TestWriter::test_quoted_string[-\"\"]",
"tests/test_writer.py::TestWriter::test_quoted_string[\\t-\"\\t\"]",
"tests/test_writer.py::TestWriter::test_quoted_string[\\n\\x07\\x08\\x0b\\x0c\\r-\"\\\\n\\\\a\\\\b\\\\v\\\\f\\\\r\"]",
"tests/test_writer.py::TestWriter::test_quoted_string[\\\\-\"\\\\\\\\\"]",
"tests/test_writer.py::TestWriter::test_quoted_string[\"-\"\\\\\"\"]",
"tests/test_writer.py::TestWriter::test_quoted_string[\\x00\\x01\\x02\\x03\\x04\\x05\\x06-\"\\\\000\\\\001\\\\002\\\\003\\\\004\\\\005\\\\006\"]",
"tests/test_writer.py::TestWriter::test_quoted_string[\\x0e\\x0f\\x10\\x11\\x12\\x13-\"\\\\016\\\\017\\\\020\\\\021\\\\022\\\\023\"]",
"tests/test_writer.py::TestWriter::test_quoted_string[\\x14\\x15\\x16\\x17\\x18\\x19-\"\\\\024\\\\025\\\\026\\\\027\\\\030\\\\031\"]",
"tests/test_writer.py::TestWriter::test_quoted_string[\\x1a\\x1b\\x1c\\x1d\\x1e\\x1f\\x7f-\"\\\\032\\\\033\\\\034\\\\035\\\\036\\\\037\\\\177\"]",
"tests/test_writer.py::TestWriter::test_quoted_string[\\x80\\x81\\x9e\\x9f\\xa0-\"\\\\U0080\\\\U0081\\\\U009E\\\\U009F\\\\U00A0\"]",
"tests/test_writer.py::TestWriter::test_quoted_string[\\U0001f4a9-\"\\\\UD83D\\\\UDCA9\"]",
"tests/test_writer.py::TestWriter::test_quoted_string[1-\"1\"]",
"tests/test_writer.py::TestWriter::test_quoted_string[1.1-\"1.1\"]",
"tests/test_writer.py::TestWriter::test_quoted_string[-23-\"-23\"]",
"tests/test_writer.py::TestWriter::test_quoted_string[-23yyy-\"-23yyy\"]",
"tests/test_writer.py::TestWriter::test_quoted_string[--\"-\"]",
"tests/test_writer.py::TestWriter::test_quoted_string[-a--\"-a-\"]",
"tests/test_writer.py::TestWriter::test_quoted_string_no_unicode_escape",
"tests/test_writer.py::TestWriter::test_int[0-0]",
"tests/test_writer.py::TestWriter::test_int[1-1]",
"tests/test_writer.py::TestWriter::test_int[123-123]",
"tests/test_writer.py::TestWriter::test_int[9223372036854775807-9223372036854775807]",
"tests/test_writer.py::TestWriter::test_int[9223372036854775808-9223372036854775808]",
"tests/test_writer.py::TestWriter::test_float[0.0-0]",
"tests/test_writer.py::TestWriter::test_float[1.0-1]",
"tests/test_writer.py::TestWriter::test_float[123.456-123.456]",
"tests/test_writer.py::TestWriter::test_float[0.01-0.01]",
"tests/test_writer.py::TestWriter::test_float[0.001-0.001]",
"tests/test_writer.py::TestWriter::test_float[0.0001-0.0001]",
"tests/test_writer.py::TestWriter::test_float[1e-05-0.00001]",
"tests/test_writer.py::TestWriter::test_float[1e-06-0.000001]",
"tests/test_writer.py::TestWriter::test_float[1e-07-0]",
"tests/test_writer.py::TestWriter::test_float_precision",
"tests/test_writer.py::TestWriter::test_data[\\x00-<00>]",
"tests/test_writer.py::TestWriter::test_data[\\x00\\x01-<0001>]",
"tests/test_writer.py::TestWriter::test_data[\\x00\\x01\\x02-<000102>]",
"tests/test_writer.py::TestWriter::test_data[\\x00\\x01\\x02\\x03-<00010203>]",
"tests/test_writer.py::TestWriter::test_data[\\x00\\x01\\x02\\x03\\x04-<00010203",
"tests/test_writer.py::TestWriter::test_data[\\x00\\x01\\x02\\x03\\x04\\x05-<00010203",
"tests/test_writer.py::TestWriter::test_data[\\x00\\x01\\x02\\x03\\x04\\x05\\x06-<00010203",
"tests/test_writer.py::TestWriter::test_data[\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07-<00010203",
"tests/test_writer.py::TestWriter::test_data[\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08-<00010203",
"tests/test_writer.py::TestWriter::test_data[\\t\\n\\x0b\\x0c\\r\\x0e\\x0f\\x10\\x11-<090A0B0C",
"tests/test_writer.py::TestWriter::test_bool",
"tests/test_writer.py::TestWriter::test_array[array0-()-()]",
"tests/test_writer.py::TestWriter::test_array[array1-()-()]",
"tests/test_writer.py::TestWriter::test_array[array2-(1)-(\\n",
"tests/test_writer.py::TestWriter::test_array[array3-(1,",
"tests/test_writer.py::TestWriter::test_array[array4-(1.2,",
"tests/test_writer.py::TestWriter::test_array[array5-(1,",
"tests/test_writer.py::TestWriter::test_array[array6-(<61>,",
"tests/test_writer.py::TestWriter::test_array[array7-({a",
"tests/test_writer.py::TestWriter::test_dictionary[dictionary0-{}-{}]",
"tests/test_writer.py::TestWriter::test_dictionary[dictionary1-{}-{}]",
"tests/test_writer.py::TestWriter::test_dictionary[dictionary2-{a",
"tests/test_writer.py::TestWriter::test_dictionary[dictionary3-{\"1\"",
"tests/test_writer.py::TestWriter::test_dictionary[dictionary4-{abc",
"tests/test_writer.py::TestWriter::test_dictionary[dictionary5-{z",
"tests/test_writer.py::TestWriter::test_type_error",
"tests/test_writer.py::test_dumps",
"tests/test_writer.py::test_dump",
"tests/test_writer.py::test_string_needs_quotes[ABCDEFGHIJKLMNOPQRSTUVWXYZ-False]",
"tests/test_writer.py::test_string_needs_quotes[abcdefghijklmnopqrstuvwxyz-False]",
"tests/test_writer.py::test_string_needs_quotes[a0123456789-False]",
"tests/test_writer.py::test_string_needs_quotes[.appVersion-False]",
"tests/test_writer.py::test_string_needs_quotes[_private-False]",
"tests/test_writer.py::test_string_needs_quotes[$PWD-False]",
"tests/test_writer.py::test_string_needs_quotes[1zzz-False]",
"tests/test_writer.py::test_string_needs_quotes[192.168.1.1-False]",
"tests/test_writer.py::test_string_needs_quotes[0-True]",
"tests/test_writer.py::test_string_needs_quotes[1-True]",
"tests/test_writer.py::test_string_needs_quotes[2-True]",
"tests/test_writer.py::test_string_needs_quotes[3-True]",
"tests/test_writer.py::test_string_needs_quotes[4-True]",
"tests/test_writer.py::test_string_needs_quotes[5-True]",
"tests/test_writer.py::test_string_needs_quotes[6-True]",
"tests/test_writer.py::test_string_needs_quotes[7-True]",
"tests/test_writer.py::test_string_needs_quotes[8-True]",
"tests/test_writer.py::test_string_needs_quotes[9-True]",
"tests/test_writer.py::test_string_needs_quotes[-True]",
"tests/test_writer.py::test_string_needs_quotes[--True]",
"tests/test_writer.py::test_string_needs_quotes[A-Z-True]",
"tests/test_writer.py::test_string_needs_quotes[hello",
"tests/test_writer.py::test_string_needs_quotes[\\\\backslash-True]",
"tests/test_writer.py::test_string_needs_quotes[http://github.com-True]"
] |
{
"failed_lite_validators": [
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-03-01 21:03:17+00:00
|
mit
| 2,391 |
|
fonttools__ufoLib2-246
|
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 4f90292..7142d15 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -53,11 +53,14 @@ jobs:
run: pip install tox coverage
- name: Run Tox
run: tox -e py-cov
- - name: Re-run Tox (without cattrs)
+ - name: Re-run Tox without cattrs
if: startsWith(matrix.platform, 'ubuntu-latest') && startsWith(matrix.python-version, '3.10')
run: |
- .tox/py-cov/bin/pip uninstall -y cattrs
- tox -e py-cov --skip-pkg-install
+ tox -e py-nocattrs
+ - name: Re-run Tox without msgpack
+ if: startsWith(matrix.platform, 'ubuntu-latest') && startsWith(matrix.python-version, '3.10')
+ run: |
+ tox -e py-nomsgpack
- name: Produce coverage files
run: |
coverage combine
diff --git a/src/ufoLib2/errors.py b/src/ufoLib2/errors.py
index 292b963..6ace0c5 100644
--- a/src/ufoLib2/errors.py
+++ b/src/ufoLib2/errors.py
@@ -1,5 +1,17 @@
from __future__ import annotations
+from typing import Any
+
class Error(Exception):
"""The base exception for ufoLib2."""
+
+
+class ExtrasNotInstalledError(Error):
+ """The extras required for this feature are not installed."""
+
+ def __init__(self, extras: str) -> None:
+ super().__init__(f"Extras not installed: ufoLib2[{extras}]")
+
+ def __call__(self, *args: Any, **kwargs: Any) -> None:
+ raise self
diff --git a/src/ufoLib2/serde/__init__.py b/src/ufoLib2/serde/__init__.py
index 0573abb..2659e9b 100644
--- a/src/ufoLib2/serde/__init__.py
+++ b/src/ufoLib2/serde/__init__.py
@@ -4,6 +4,7 @@ from functools import partialmethod
from importlib import import_module
from typing import IO, Any, AnyStr, Callable, Type
+from ufoLib2.errors import ExtrasNotInstalledError
from ufoLib2.typing import PathLike, T
_SERDE_FORMATS_ = ("json", "msgpack")
@@ -75,12 +76,9 @@ def serde(cls: Type[T]) -> Type[T]:
try:
serde_submodule = import_module(f"ufoLib2.serde.{fmt}")
- except ImportError as e:
- exc = e
-
- def raise_error(*args: Any, **kwargs: Any) -> None:
- raise exc
-
+ except ImportError as exc:
+ raise_error = ExtrasNotInstalledError(fmt)
+ raise_error.__cause__ = exc
for method in ("loads", "load", "dumps", "dump"):
setattr(cls, f"{fmt}_{method}", raise_error)
else:
diff --git a/tox.ini b/tox.ini
index e55a83b..d34ec05 100644
--- a/tox.ini
+++ b/tox.ini
@@ -7,6 +7,9 @@ deps =
-r requirements.txt
-r requirements-dev.txt
commands =
+ nocattrs: pip uninstall -y cattrs
+ noorjson: pip uninstall -y orjson
+ nomsgpack: pip uninstall -y msgpack
cov: coverage run --parallel-mode -m pytest {posargs}
!cov: pytest {posargs}
|
fonttools/ufoLib2
|
c7281e7197491175ebcbfd7784c74748fc469e29
|
diff --git a/tests/serde/test_json.py b/tests/serde/test_json.py
index 67cdab8..53388a9 100644
--- a/tests/serde/test_json.py
+++ b/tests/serde/test_json.py
@@ -20,6 +20,8 @@ def test_dumps_loads(
) -> None:
if not have_orjson:
monkeypatch.setattr(ufoLib2.serde.json, "have_orjson", have_orjson)
+ else:
+ pytest.importorskip("orjson")
font = ufo_UbuTestData
data = font.json_dumps() # type: ignore
@@ -82,6 +84,7 @@ def test_dump_load(
@pytest.mark.parametrize("indent", [1, 3], ids=["indent-1", "indent-3"])
def test_indent_not_2_orjson(indent: int) -> None:
+ pytest.importorskip("orjson")
with pytest.raises(ValueError):
ufoLib2.serde.json.dumps(None, indent=indent)
diff --git a/tests/serde/test_msgpack.py b/tests/serde/test_msgpack.py
index 886582f..78f717c 100644
--- a/tests/serde/test_msgpack.py
+++ b/tests/serde/test_msgpack.py
@@ -1,12 +1,14 @@
from pathlib import Path
-import msgpack # type: ignore
import pytest
import ufoLib2.objects
# isort: off
pytest.importorskip("cattrs")
+pytest.importorskip("msgpack")
+
+import msgpack # type: ignore # noqa
import ufoLib2.serde.msgpack # noqa: E402
diff --git a/tests/serde/test_serde.py b/tests/serde/test_serde.py
index f45e210..7fe0be6 100644
--- a/tests/serde/test_serde.py
+++ b/tests/serde/test_serde.py
@@ -1,20 +1,37 @@
import importlib
-import sys
from typing import Any, Dict, List
import pytest
from attrs import define
import ufoLib2.objects
+from ufoLib2.errors import ExtrasNotInstalledError
from ufoLib2.serde import _SERDE_FORMATS_, serde
+cattrs = None
+try:
+ import cattrs # type: ignore
+except ImportError:
+ pass
-def test_raise_import_error(monkeypatch: Any) -> None:
- # pretend we can't import the module (e.g. msgpack not installed)
- monkeypatch.setitem(sys.modules, "ufoLib2.serde.msgpack", None)
- with pytest.raises(ImportError, match="ufoLib2.serde.msgpack"):
- importlib.import_module("ufoLib2.serde.msgpack")
+msgpack = None
+try:
+ import msgpack # type: ignore
+except ImportError:
+ pass
+
+
+EXTRAS_REQUIREMENTS = {
+ "json": ["cattrs"],
+ "msgpack": ["cattrs", "msgpack"],
+}
+
+
+def assert_extras_not_installed(extras: str, missing_dependency: str) -> None:
+ # sanity check that the dependency is not installed
+ with pytest.raises(ImportError, match=missing_dependency):
+ importlib.import_module(missing_dependency)
@serde
@define
@@ -24,10 +41,28 @@ def test_raise_import_error(monkeypatch: Any) -> None:
foo = Foo(1)
- with pytest.raises(ImportError, match="ufoLib2.serde.msgpack"):
- # since the method is only added dynamically at runtime, mypy complains that
- # "Foo" has no attribute "msgpack_dumps" -- so I shut it up
- foo.msgpack_dumps() # type: ignore
+ with pytest.raises(
+ ExtrasNotInstalledError, match=rf"Extras not installed: ufoLib2\[{extras}\]"
+ ) as exc_info:
+ dumps_method = getattr(foo, f"{extras}_dumps")
+ dumps_method()
+
+ assert isinstance(exc_info.value.__cause__, ModuleNotFoundError)
+
+
[email protected](cattrs is not None, reason="cattrs installed, not applicable")
+def test_json_cattrs_not_installed() -> None:
+ assert_extras_not_installed("json", "cattrs")
+
+
[email protected](cattrs is not None, reason="cattrs installed, not applicable")
+def test_msgpack_cattrs_not_installed() -> None:
+ assert_extras_not_installed("msgpack", "cattrs")
+
+
[email protected](msgpack is not None, reason="msgpack installed, not applicable")
+def test_msgpack_not_installed() -> None:
+ assert_extras_not_installed("msgpack", "msgpack")
BASIC_EMPTY_OBJECTS: List[Dict[str, Any]] = [
@@ -61,9 +96,8 @@ assert {d["class_name"] for d in BASIC_EMPTY_OBJECTS} == set(ufoLib2.objects.__a
ids=lambda x: x["class_name"], # type: ignore
)
def test_serde_all_objects(fmt: str, object_info: Dict[str, Any]) -> None:
- if fmt in ("json", "msgpack"):
- # skip these format tests if cattrs is not installed
- pytest.importorskip("cattrs")
+ for req in EXTRAS_REQUIREMENTS[fmt]:
+ pytest.importorskip(req)
klass = getattr(ufoLib2.objects, object_info["class_name"])
loads = getattr(klass, f"{fmt}_loads")
|
msgpack also required for json output
This code triggers a msgpack import (neither json nor msgpack extra is installed):
```py
ufo = Font.open("some.ufo")
ufo.json_dump("a.json")
```
Can't even seem to catch it using `except Exception as e` in `def serde`. A missing cattrs import ends the script as well.
|
0.0
|
c7281e7197491175ebcbfd7784c74748fc469e29
|
[
"tests/serde/test_json.py::test_dumps_loads[no-orjson]",
"tests/serde/test_json.py::test_dumps_loads[with-orjson]",
"tests/serde/test_json.py::test_dump_load[no-sort-keys-no-indent-no-orjson]",
"tests/serde/test_json.py::test_dump_load[no-sort-keys-no-indent-with-orjson]",
"tests/serde/test_json.py::test_dump_load[no-sort-keys-indent-2-no-orjson]",
"tests/serde/test_json.py::test_dump_load[no-sort-keys-indent-2-with-orjson]",
"tests/serde/test_json.py::test_dump_load[sort-keys-no-indent-no-orjson]",
"tests/serde/test_json.py::test_dump_load[sort-keys-no-indent-with-orjson]",
"tests/serde/test_json.py::test_dump_load[sort-keys-indent-2-no-orjson]",
"tests/serde/test_json.py::test_dump_load[sort-keys-indent-2-with-orjson]",
"tests/serde/test_json.py::test_indent_not_2_orjson[indent-1]",
"tests/serde/test_json.py::test_indent_not_2_orjson[indent-3]",
"tests/serde/test_json.py::test_not_allow_bytes",
"tests/serde/test_msgpack.py::test_dumps_loads",
"tests/serde/test_msgpack.py::test_dump_load",
"tests/serde/test_msgpack.py::test_allow_bytes",
"tests/serde/test_serde.py::test_serde_all_objects[Anchor-json]",
"tests/serde/test_serde.py::test_serde_all_objects[Anchor-msgpack]",
"tests/serde/test_serde.py::test_serde_all_objects[Component-json]",
"tests/serde/test_serde.py::test_serde_all_objects[Component-msgpack]",
"tests/serde/test_serde.py::test_serde_all_objects[Contour-json]",
"tests/serde/test_serde.py::test_serde_all_objects[Contour-msgpack]",
"tests/serde/test_serde.py::test_serde_all_objects[DataSet-json]",
"tests/serde/test_serde.py::test_serde_all_objects[DataSet-msgpack]",
"tests/serde/test_serde.py::test_serde_all_objects[Features-json]",
"tests/serde/test_serde.py::test_serde_all_objects[Features-msgpack]",
"tests/serde/test_serde.py::test_serde_all_objects[Font-json]",
"tests/serde/test_serde.py::test_serde_all_objects[Font-msgpack]",
"tests/serde/test_serde.py::test_serde_all_objects[Glyph-json]",
"tests/serde/test_serde.py::test_serde_all_objects[Glyph-msgpack]",
"tests/serde/test_serde.py::test_serde_all_objects[Guideline-json]",
"tests/serde/test_serde.py::test_serde_all_objects[Guideline-msgpack]",
"tests/serde/test_serde.py::test_serde_all_objects[Image-json]",
"tests/serde/test_serde.py::test_serde_all_objects[Image-msgpack]",
"tests/serde/test_serde.py::test_serde_all_objects[ImageSet-json]",
"tests/serde/test_serde.py::test_serde_all_objects[ImageSet-msgpack]",
"tests/serde/test_serde.py::test_serde_all_objects[Info-json]",
"tests/serde/test_serde.py::test_serde_all_objects[Info-msgpack]",
"tests/serde/test_serde.py::test_serde_all_objects[Kerning-json]",
"tests/serde/test_serde.py::test_serde_all_objects[Kerning-msgpack]",
"tests/serde/test_serde.py::test_serde_all_objects[Layer-json]",
"tests/serde/test_serde.py::test_serde_all_objects[Layer-msgpack]",
"tests/serde/test_serde.py::test_serde_all_objects[LayerSet-json]",
"tests/serde/test_serde.py::test_serde_all_objects[LayerSet-msgpack]",
"tests/serde/test_serde.py::test_serde_all_objects[Lib-json]",
"tests/serde/test_serde.py::test_serde_all_objects[Lib-msgpack]",
"tests/serde/test_serde.py::test_serde_all_objects[Point-json]",
"tests/serde/test_serde.py::test_serde_all_objects[Point-msgpack]"
] |
[] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-11-06 13:06:49+00:00
|
apache-2.0
| 2,392 |
|
fortran-lang__fortls-306
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 935d35c..68b380a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -18,6 +18,9 @@
### Changed
+- Changed `--incl_suffixes` option to faithfully match the suffixes that are
+ provided in the option, without performing any type of modification.
+ ([#300](https://github.com/fortran-lang/fortls/issues/300))
- Changed the completion signature to include the full Markdown documentation
for the completion item.
([#219](https://github.com/fortran-lang/fortls/issues/219))
diff --git a/docs/options.rst b/docs/options.rst
index 91ceb82..c532741 100644
--- a/docs/options.rst
+++ b/docs/options.rst
@@ -102,11 +102,15 @@ incl_suffixes
.. code-block:: json
{
- "incl_suffixes": [".h", ".FYP"]
+ "incl_suffixes": [".h", ".FYP", "inc"]
}
``fortls`` will parse only files with ``incl_suffixes`` extensions found in
-``source_dirs``. By default ``incl_suffixes`` are defined as
+``source_dirs``. Using the above example, ``fortls`` will match files by the
+``file.h`` and ``file.FYP``, but not ``file.fyp`` or ``filefyp``.
+It will also match ``file.inc`` and ``fileinc`` but not ``file.inc2``.
+
+By default, ``incl_suffixes`` are defined as
.F .f .F03 .f03 .F05 .f05 .F08 .f08 .F18 .f18 .F77 .f77 .F90 .f90 .F95 .f95 .FOR .for .FPP .fpp.
Additional source file extensions can be defined in ``incl_suffixes``.
diff --git a/fortls/fortls.schema.json b/fortls/fortls.schema.json
index 695c963..f6a8c09 100644
--- a/fortls/fortls.schema.json
+++ b/fortls/fortls.schema.json
@@ -61,7 +61,7 @@
},
"incl_suffixes": {
"title": "Incl Suffixes",
- "description": "Consider additional file extensions to the default (default: F,F77,F90,F95,F03,F08,FOR,FPP (lower & upper casing))",
+ "description": "Consider additional file extensions to the default (default: .F, .F77, .F90, .F95, .F03, .F08, .FOR, .FPP (lower & upper casing))",
"default": [],
"type": "array",
"items": {},
diff --git a/fortls/interface.py b/fortls/interface.py
index ac136aa..05cc8c1 100644
--- a/fortls/interface.py
+++ b/fortls/interface.py
@@ -126,7 +126,7 @@ def cli(name: str = "fortls") -> argparse.ArgumentParser:
metavar="SUFFIXES",
help=(
"Consider additional file extensions to the default (default: "
- "F,F77,F90,F95,F03,F08,FOR,FPP (lower & upper casing))"
+ ".F, .F77, .F90, .F95, .F03, .F08, .FOR, .FPP (lower & upper casing))"
),
)
group.add_argument(
diff --git a/fortls/langserver.py b/fortls/langserver.py
index f98ebb6..33dc6c3 100644
--- a/fortls/langserver.py
+++ b/fortls/langserver.py
@@ -61,7 +61,7 @@ from fortls.objects import (
get_use_tree,
)
from fortls.parse_fortran import FortranFile, get_line_context
-from fortls.regex_patterns import src_file_exts
+from fortls.regex_patterns import create_src_file_exts_str
from fortls.version import __version__
# Global regexes
@@ -89,7 +89,9 @@ class LangServer:
self.sync_type: int = 2 if self.incremental_sync else 1
self.post_messages = []
- self.FORTRAN_SRC_EXT_REGEX: Pattern[str] = src_file_exts(self.incl_suffixes)
+ self.FORTRAN_SRC_EXT_REGEX: Pattern[str] = create_src_file_exts_str(
+ self.incl_suffixes
+ )
# Intrinsic (re-loaded during initialize)
(
self.statements,
@@ -1569,7 +1571,7 @@ class LangServer:
self.source_dirs = set(config_dict.get("source_dirs", self.source_dirs))
self.incl_suffixes = set(config_dict.get("incl_suffixes", self.incl_suffixes))
# Update the source file REGEX
- self.FORTRAN_SRC_EXT_REGEX = src_file_exts(self.incl_suffixes)
+ self.FORTRAN_SRC_EXT_REGEX = create_src_file_exts_str(self.incl_suffixes)
self.excl_suffixes = set(config_dict.get("excl_suffixes", self.excl_suffixes))
def _load_config_file_general(self, config_dict: dict) -> None:
diff --git a/fortls/regex_patterns.py b/fortls/regex_patterns.py
index 80a793e..6f59040 100644
--- a/fortls/regex_patterns.py
+++ b/fortls/regex_patterns.py
@@ -149,30 +149,63 @@ class FortranRegularExpressions:
OBJBREAK: Pattern = compile(r"[\/\-(.,+*<>=$: ]", I)
-def src_file_exts(input_exts: list[str] = []) -> Pattern[str]:
- """Create a REGEX for which file extensions the Language Server should parse
- Default extensions are
- F F03 F05 F08 F18 F77 F90 F95 FOR FPP f f03 f05 f08 f18 f77 f90 f95 for fpp
+# TODO: use this in the main code
+def create_src_file_exts_regex(input_exts: list[str] = []) -> Pattern[str]:
+ r"""Create a REGEX for which sources the Language Server should parse.
+
+ Default extensions are (case insensitive):
+ F F03 F05 F08 F18 F77 F90 F95 FOR FPP
Parameters
----------
input_exts : list[str], optional
- Additional Fortran, by default []
+ Additional list of file extensions to parse, in Python REGEX format
+ that means special characters must be escaped
+ , by default []
+
+ Examples
+ --------
+ >>> regex = create_src_file_exts_regex([r"\.fypp", r"\.inc"])
+ >>> regex.search("test.fypp")
+ <re.Match object; span=(4, 9), match='.fypp'>
+ >>> regex.search("test.inc")
+ <re.Match object; span=(4, 8), match='.inc'>
+
+ >>> regex = create_src_file_exts_regex([r"\.inc.*"])
+ >>> regex.search("test.inc.1")
+ <re.Match object; span=(4, 10), match='.inc.1'>
+
+ Invalid regex expressions will cause the function to revert to the default
+ extensions
+
+ >>> regex = create_src_file_exts_regex(["*.inc"])
+ >>> regex.search("test.inc") is None
+ True
Returns
-------
Pattern[str]
- A compiled regular expression, by default
- '.(F|F03|F05|F08|F18|F77|F90|F95|FOR|FPP|f|f03|f05|f08|f18|f77|f90|f95|for|fpp)?'
+ A compiled regular expression for matching file extensions
"""
- EXTS = ["", "77", "90", "95", "03", "05", "08", "18", "OR", "PP"]
- FORTRAN_FILE_EXTS = []
- for e in EXTS:
- FORTRAN_FILE_EXTS.extend([f"F{e}".upper(), f"f{e}".lower()])
- # Add the custom extensions for the server to parse
- for e in input_exts:
- if e.startswith("."):
- FORTRAN_FILE_EXTS.append(e.replace(".", ""))
- # Cast into a set to ensure uniqueness of extensions & sort for consistency
- # Create a regular expression from this
- return compile(rf"\.({'|'.join(sorted(set(FORTRAN_FILE_EXTS)))})?$")
+ import re
+
+ DEFAULT = r"\.[fF](77|90|95|03|05|08|18|[oO][rR]|[pP]{2})?"
+ EXPRESSIONS = [DEFAULT]
+ try:
+ EXPRESSIONS.extend(input_exts)
+ # Add its expression as an OR and force they match the end of the string
+ return re.compile(rf"(({'$)|('.join(EXPRESSIONS)}$))")
+ except re.error:
+ # TODO: Add a warning to the logger
+ return re.compile(rf"({DEFAULT}$)")
+
+
+def create_src_file_exts_str(input_exts: list[str] = []) -> Pattern[str]:
+ """This is a version of create_src_file_exts_regex that takes a list
+ sanitises the list of input_exts before compiling the regex.
+ For more info see create_src_file_exts_regex
+ """
+ import re
+
+ input_exts = [re.escape(ext) for ext in input_exts]
+ return create_src_file_exts_regex(input_exts)
diff --git a/setup.cfg b/setup.cfg
index d9651b2..e6c8048 100644
--- a/setup.cfg
+++ b/setup.cfg
@@ -62,7 +62,7 @@ dev =
black
isort
pre-commit
- pydantic
+ pydantic==1.9.1
docs =
sphinx >= 4.0.0
sphinx-argparse
|
fortran-lang/fortls
|
351ae01969042eaf9bcf29fa1d2a4b9556bd20b3
|
diff --git a/test/test_regex_patterns.py b/test/test_regex_patterns.py
new file mode 100644
index 0000000..0b08b6d
--- /dev/null
+++ b/test/test_regex_patterns.py
@@ -0,0 +1,45 @@
+from __future__ import annotations
+
+import pytest
+
+from fortls.regex_patterns import create_src_file_exts_regex
+
+
[email protected](
+ "input_exts, input_files, matches",
+ [
+ (
+ [],
+ [
+ "test.f",
+ "test.F",
+ "test.f90",
+ "test.F90",
+ "test.f03",
+ "test.F03",
+ "test.f18",
+ "test.F18",
+ "test.f77",
+ "test.F77",
+ "test.f95",
+ "test.F95",
+ "test.for",
+ "test.FOR",
+ "test.fpp",
+ "test.FPP",
+ ],
+ [True] * 16,
+ ),
+ ([], ["test.ff", "test.f901", "test.f90.ff"], [False, False, False]),
+ ([r"\.inc"], ["test.inc", "testinc", "test.inc2"], [True, False, False]),
+ (["inc.*"], ["test.inc", "testinc", "test.inc2"], [True, True, True]),
+ ],
+)
+def test_src_file_exts(
+ input_exts: list[str],
+ input_files: list[str],
+ matches: list[bool],
+):
+ regex = create_src_file_exts_regex(input_exts)
+ results = [bool(regex.search(file)) for file in input_files]
+ assert results == matches
|
`incl_suffixes` ignored if they do not start with a dot
**Describe the bug**
If I pass include suffixes via `--incl_suffixes` to fortls that do not start with a dot, they are simply ignored, with no warning whatsoever. This is especially surprising, since the description of the setting in the Modern Fortran VS Code extension lists the defaults without dots (see [package.json#L443](https://github.com/fortran-lang/vscode-fortran-support/blob/b35cbf5732102e54dc9a8b01a3853a10f11727d2/package.json#L443C100-L443C129))
**To Reproduce**
Having a source repository with
```
<root>
|- main.f90
|- subdir
|- include.inc
```
running `python -m fortls --debug_rootpath=C:\source\test-fortls --incl_suffixes inc`
gives
```
Testing "initialize" request:
Root = "C:\source\test-fortls"
[INFO - 12:03:10] fortls - Fortran Language Server 2.13.1.dev172+gc04d2ab.d20230629 Initialized
Successful!
Source directories:
C:\source\test-fortls
```
but running `python -m fortls --debug_rootpath=C:\source\test-fortls --incl_suffixes .inc`
gives the correct:
```
Testing "initialize" request:
Root = "C:\source\test-fortls"
[INFO - 12:03:13] fortls - Fortran Language Server 2.13.1.dev172+gc04d2ab.d20230629 Initialized
Successful!
Source directories:
C:\source\test-fortls\subdir
C:\source\test-fortls
```
**Expected behavior**
In the order of my personal preference:
1. It should not matter whether I pass the include suffixes with or without a dot in the beginning
2. **OR** I should get a warning when a passed argument is incorrect and ignored
3. **OR** The documentation should at least very explicitly state that a dot in the beginning is a mandatory requirement.
|
0.0
|
351ae01969042eaf9bcf29fa1d2a4b9556bd20b3
|
[
"test/test_regex_patterns.py::test_src_file_exts[input_exts0-input_files0-matches0]",
"test/test_regex_patterns.py::test_src_file_exts[input_exts1-input_files1-matches1]",
"test/test_regex_patterns.py::test_src_file_exts[input_exts2-input_files2-matches2]",
"test/test_regex_patterns.py::test_src_file_exts[input_exts3-input_files3-matches3]"
] |
[] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2023-07-14 21:59:46+00:00
|
mit
| 2,393 |
|
frankV__flask-sendgrid-4
|
diff --git a/README.md b/README.md
index e91d349..75ad0ea 100755
--- a/README.md
+++ b/README.md
@@ -13,22 +13,18 @@ Installation
Usage
-----
- from flask.ext.sendgrid import FlaskSendGrid
+ from flask.ext.sendgrid import SendGrid
app = Flask(__name__)
app.config['SENDGRID_API_KEY'] = 'your api key'
app.config['SENDGRID_DEFAULT_FROM'] = '[email protected]'
- sendgrid = FlaskSendGrid(app)
+ sendgrid = SendGrid(app)
sendgrid.send_email(
from_email='[email protected]',
- subject='Subject',
- template_id='some_id',
- substitutions={ ':name': 'Peter Piper' },
- to=[{'email': '[email protected]'}, {'email': '[email protected]'}],
- text='Hello World'
+ subject='Subject'
+ to_email='[email protected]',
+ text='Body',
)
-Using templates (`template_id` and `substitutions`) is purely optional.
-
For additional information about mail parameters: [SendGrid Web API Mail](https://sendgrid.com/docs/API_Reference/Web_API/mail.html#parameters-mail)
diff --git a/flask_sendgrid.py b/flask_sendgrid.py
index c6178a0..84003a8 100755
--- a/flask_sendgrid.py
+++ b/flask_sendgrid.py
@@ -1,7 +1,8 @@
-import sendgrid
+from sendgrid import SendGridAPIClient
+from sendgrid.helpers.mail import Mail, Email, Content
-class FlaskSendGrid(object):
+class SendGrid(object):
app = None
api_key = None
default_from = None
@@ -15,32 +16,31 @@ class FlaskSendGrid(object):
self.api_key = app.config['SENDGRID_API_KEY']
self.default_from = app.config['SENDGRID_DEFAULT_FROM']
- def send_email(self, **opts):
- if not opts.get('from_email', None) and not self.default_from:
- raise ValueError('No from email or default_from was configured')
+ def send_email(self, to_email, subject, from_email=None,
+ html=None, text=None):
+ if not any([from_email, self.default_from]):
+ raise ValueError("Missing from email and no default.")
+ if not any([html, text]):
+ raise ValueError("Missing html or text.")
- client = sendgrid.SendGridClient(self.api_key)
- message = sendgrid.Mail()
+ sg = SendGridAPIClient(apikey=self.api_key)
- for _ in opts['to']:
- message.add_to(_['email'])
+ mail = Mail(
+ from_email=Email(from_email or self.default_from),
+ subject=subject,
+ to_email=Email(to_email),
+ content=Content("text/html", html) if html
+ else Content("text/plain", text),
+ )
+
+ return sg.client.mail.send.post(request_body=mail.get())
# Use a template if specified.
# See https://github.com/sendgrid/sendgrid-python/blob/master/examples/example_v2.py
- if opts.get('template_id', None):
- message.add_filter('templates', 'enable', '1')
- message.add_filter('templates', 'template_id', opts['template_id'])
-
- substitutions = opts.get('substitutions', dict()).items()
- for key, value in substitutions:
- message.add_substitution(key, value)
-
- message.set_from(opts.get('from_email', None) or self.default_from)
- message.set_subject(opts['subject'])
-
- if opts.get('html', None):
- message.set_html(opts['html'])
- elif opts.get('text', None):
- message.set_html(opts['text'])
+# if opts.get('template_id', None):
+# message.add_filter('templates', 'enable', '1')
+# message.add_filter('templates', 'template_id', opts['template_id'])
- return client.send(message)
+# substitutions = opts.get('substitutions', dict()).items()
+# for key, value in substitutions:
+# message.add_substitution(key, value)
diff --git a/setup.py b/setup.py
index ff333b5..cafcfcd 100755
--- a/setup.py
+++ b/setup.py
@@ -26,8 +26,9 @@ Usage
sendgrid = SendGrid(app)
sendgrid.send_email(
from_email='[email protected]',
- to=[{'email': '[email protected]'}],
- text='Hello World'
+ subject='Subject'
+ to_email='[email protected]',
+ text='Body',
)
"""
@@ -48,7 +49,7 @@ setup(
py_modules=['flask_sendgrid'],
zip_safe=False,
platforms='any',
- install_requires=['Flask', 'SendGrid'],
+ install_requires=['Flask', 'SendGrid~=3.0'],
classifiers=[
'Development Status :: 3 - Alpha',
'Environment :: Web Environment',
|
frankV/flask-sendgrid
|
0eb1939b84a263b5c733bc03a922f439e24bbf0e
|
diff --git a/tests.py b/tests.py
index 6e1b643..2e55a73 100755
--- a/tests.py
+++ b/tests.py
@@ -1,6 +1,6 @@
import unittest
from mock import MagicMock
-from flask_sendgrid import FlaskSendGrid
+from flask_sendgrid import SendGrid
# Set up test API key for emails
app = MagicMock()
@@ -10,18 +10,18 @@ app.config['SENDGRID_API_KEY'] = '12345'
app.config['SENDGRID_DEFAULT_FROM'] = 'from'
-class FlaskSendGridTest(unittest.TestCase):
+class SendGridTest(unittest.TestCase):
def setUp(self):
- self.mail = FlaskSendGrid(app)
+ self.mail = SendGrid(app)
def test_get_api_key(self):
self.assertEqual(self.mail.api_key, app.config['SENDGRID_API_KEY'])
def test_fails_no_key(self):
- mail = FlaskSendGrid()
+ mail = SendGrid()
self.assertRaises(ValueError, mail.send_email)
def test_fails_no_sender(self):
- mail = FlaskSendGrid()
+ mail = SendGrid()
self.assertRaises(ValueError, mail.send_email, key='ABCDEFG')
|
AttributeError: module 'sendgrid' has no attribute 'SendGridClient'
This library doesn't seem to work with any versions of https://github.com/sendgrid/sendgrid-python released in the past year or so. `SendGridClient` was renamed to `SendGridAPIClient`.
|
0.0
|
0eb1939b84a263b5c733bc03a922f439e24bbf0e
|
[
"tests.py::SendGridTest::test_get_api_key"
] |
[] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2016-12-31 09:00:34+00:00
|
mit
| 2,394 |
|
frankie567__httpx-oauth-274
|
diff --git a/docs/oauth2.md b/docs/oauth2.md
index dbb7178..35f0ce1 100644
--- a/docs/oauth2.md
+++ b/docs/oauth2.md
@@ -123,6 +123,23 @@ A utility method is provided to quickly determine if the token is still valid or
We provide several ready-to-use clients for widely used services with configured endpoints and specificites took into account.
+### Discord
+
+Contributed by [William Hatcher](https://github.com/williamhatcher)
+
+```py
+from httpx_oauth.clients.discord import DiscordOAuth2
+
+client = DiscordOAuth2("CLIENT_ID", "CLIENT_SECRET")
+```
+
+* ✅ `refresh_token`
+* ✅ `revoke_token`
+
+!!! warning "Warning about get_id_email()"
+ Email is optional for Discord accounts. This method will error if the user does not have a verified email address.
+ Furthermore, you should always make sure to include `identify`, and `email` in your scopes. (This is the default)
+
### Facebook
```py
diff --git a/httpx_oauth/clients/discord.py b/httpx_oauth/clients/discord.py
new file mode 100644
index 0000000..fe3473f
--- /dev/null
+++ b/httpx_oauth/clients/discord.py
@@ -0,0 +1,53 @@
+from typing import Any, Dict, List, Optional, Tuple, cast
+
+from httpx_oauth.errors import GetIdEmailError
+from httpx_oauth.oauth2 import BaseOAuth2
+
+AUTHORIZE_ENDPOINT = "https://discord.com/api/oauth2/authorize"
+ACCESS_TOKEN_ENDPOINT = "https://discord.com/api/oauth2/token"
+REVOKE_TOKEN_ENDPOINT = "https://discord.com/api/oauth2/token/revoke"
+BASE_SCOPES = ("identify", "email")
+PROFILE_ENDPOINT = "https://discord.com/api/users/@me"
+
+
+class DiscordOAuth2(BaseOAuth2[Dict[str, Any]]):
+ def __init__(
+ self,
+ client_id: str,
+ client_secret: str,
+ scopes: Optional[List[str]] = BASE_SCOPES,
+ name: str = "discord",
+ ):
+ super().__init__(
+ client_id,
+ client_secret,
+ AUTHORIZE_ENDPOINT,
+ ACCESS_TOKEN_ENDPOINT,
+ ACCESS_TOKEN_ENDPOINT,
+ REVOKE_TOKEN_ENDPOINT,
+ name=name,
+ base_scopes=scopes,
+ )
+
+ async def get_id_email(self, token: str) -> Tuple[str, str]:
+ async with self.get_httpx_client() as client:
+ response = await client.get(
+ PROFILE_ENDPOINT,
+ headers={**self.request_headers, "Authorization": f"Bearer {token}"},
+ )
+
+ if response.status_code >= 400:
+ raise GetIdEmailError(response.json())
+
+ data = cast(Dict[str, Any], response.json())
+
+ user_id = data["id"]
+
+ if 'verified' not in data or 'email' not in data: # No email on discord account
+ raise GetIdEmailError({'error': 'Email not provided'})
+ elif not data['verified']: # Email present, but not verified
+ raise GetIdEmailError({'error': 'Email not verified'})
+ else:
+ user_email = data["email"]
+
+ return user_id, user_email
|
frankie567/httpx-oauth
|
b06a32050c8a1dbb409d9d4b956fe1120879df1d
|
diff --git a/tests/test_clients_discord.py b/tests/test_clients_discord.py
new file mode 100644
index 0000000..87c432e
--- /dev/null
+++ b/tests/test_clients_discord.py
@@ -0,0 +1,116 @@
+import re
+
+import pytest
+import respx
+from httpx import Response
+
+from httpx_oauth.clients.discord import DiscordOAuth2, PROFILE_ENDPOINT
+from httpx_oauth.errors import GetIdEmailError
+
+client = DiscordOAuth2("CLIENT_ID", "CLIENT_SECRET")
+
+
+def test_discord_oauth2():
+ assert client.authorize_endpoint == "https://discord.com/api/oauth2/authorize"
+ assert client.access_token_endpoint == "https://discord.com/api/oauth2/token"
+ assert client.refresh_token_endpoint == "https://discord.com/api/oauth2/token"
+ assert client.revoke_token_endpoint == "https://discord.com/api/oauth2/token/revoke"
+ assert client.base_scopes == ("identify", "email")
+ assert client.name == "discord"
+
+
+profile_verified_email_response = {
+ "id": "80351110224678912",
+ "username": "Nelly",
+ "discriminator": "1337",
+ "avatar": "8342729096ea3675442027381ff50dfe",
+ "verified": True,
+ "email": "[email protected]",
+ "flags": 64,
+ "banner": "06c16474723fe537c283b8efa61a30c8",
+ "accent_color": 16711680,
+ "premium_type": 1,
+ "public_flags": 64
+}
+
+profile_no_email_response = {
+ "id": "80351110224678912",
+ "username": "Nelly",
+ "discriminator": "1337",
+ "avatar": "8342729096ea3675442027381ff50dfe",
+ "flags": 64,
+ "banner": "06c16474723fe537c283b8efa61a30c8",
+ "accent_color": 16711680,
+ "premium_type": 1,
+ "public_flags": 64
+}
+
+profile_not_verified_email_response = {
+ "id": "80351110224678912",
+ "username": "Nelly",
+ "discriminator": "1337",
+ "avatar": "8342729096ea3675442027381ff50dfe",
+ "verified": False,
+ "email": "[email protected]",
+ "flags": 64,
+ "banner": "06c16474723fe537c283b8efa61a30c8",
+ "accent_color": 16711680,
+ "premium_type": 1,
+ "public_flags": 64
+}
+
+
+class TestDiscordGetIdEmail:
+ @pytest.mark.asyncio
+ @respx.mock
+ async def test_success(self, get_respx_call_args):
+ request = respx.get(re.compile(f"^{PROFILE_ENDPOINT}")).mock(
+ return_value=Response(200, json=profile_verified_email_response)
+ )
+
+ user_id, user_email = await client.get_id_email("TOKEN")
+ _, headers, _ = await get_respx_call_args(request)
+
+ assert headers["Authorization"] == "Bearer TOKEN"
+ assert headers["Accept"] == "application/json"
+ assert user_id == "80351110224678912"
+ assert user_email == "[email protected]"
+
+ @pytest.mark.asyncio
+ @respx.mock
+ async def test_error(self):
+ respx.get(re.compile(f"^{PROFILE_ENDPOINT}")).mock(
+ return_value=Response(400, json={"error": "message"})
+ )
+
+ with pytest.raises(GetIdEmailError) as excinfo:
+ await client.get_id_email("TOKEN")
+
+ assert type(excinfo.value.args[0]) == dict
+ assert excinfo.value.args[0] == {"error": "message"}
+
+ @pytest.mark.asyncio
+ @respx.mock
+ async def test_no_email_error(self):
+ respx.get(re.compile(f"^{PROFILE_ENDPOINT}$")).mock(
+ return_value=Response(200, json=profile_no_email_response)
+ )
+
+ with pytest.raises(GetIdEmailError) as excinfo:
+ await client.get_id_email("TOKEN")
+
+ assert type(excinfo.value.args[0]) == dict
+ assert excinfo.value.args[0] == {"error": "Email not provided"}
+
+ @pytest.mark.asyncio
+ @respx.mock
+ async def test_email_not_verified_error(self):
+ respx.get(re.compile(f"^{PROFILE_ENDPOINT}$")).mock(
+ return_value=Response(200, json=profile_not_verified_email_response)
+ )
+
+ with pytest.raises(GetIdEmailError) as excinfo:
+ await client.get_id_email("TOKEN")
+
+ assert type(excinfo.value.args[0]) == dict
+ assert excinfo.value.args[0] == {"error": "Email not verified"}
|
Provide Discord OAuth2 implementation
I may work on this at some point if I understand the lib well enough.
In any case, I appreciate all the work that is put into httpx-oauth :D
|
0.0
|
b06a32050c8a1dbb409d9d4b956fe1120879df1d
|
[
"tests/test_clients_discord.py::test_discord_oauth2",
"tests/test_clients_discord.py::TestDiscordGetIdEmail::test_success",
"tests/test_clients_discord.py::TestDiscordGetIdEmail::test_error",
"tests/test_clients_discord.py::TestDiscordGetIdEmail::test_no_email_error",
"tests/test_clients_discord.py::TestDiscordGetIdEmail::test_email_not_verified_error"
] |
[] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_added_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-06-29 22:51:03+00:00
|
mit
| 2,395 |
|
freelawproject__courts-db-25
|
diff --git a/courts_db/__init__.py b/courts_db/__init__.py
index c4c8c76..3bf78dc 100644
--- a/courts_db/__init__.py
+++ b/courts_db/__init__.py
@@ -7,7 +7,7 @@ from __future__ import (
import re
from datetime import datetime
-from typing import List
+from typing import List, Optional
import six
@@ -48,7 +48,9 @@ def __getattr__(name):
return value
-def find_court_ids_by_name(court_str: str, bankruptcy: bool) -> List[str]:
+def find_court_ids_by_name(
+ court_str: str, bankruptcy: Optional[bool], location: Optional[str]
+) -> List[str]:
"""Find court IDs with our courts-db regex list
:param court_str: test string
@@ -63,7 +65,10 @@ def find_court_ids_by_name(court_str: str, bankruptcy: bool) -> List[str]:
court_matches = set()
matches = []
- for regex, court_id, court_name, court_type in regexes:
+ for regex, court_id, court_name, court_type, court_location in regexes:
+ # If location provided - check if overlapped.
+ if location and court_location != location:
+ continue
# Filter gathered regexes by bankruptcy flag.
if bankruptcy is True:
if court_type != "bankruptcy":
@@ -158,7 +163,11 @@ def find_court_by_id(court_id):
def find_court(
- court_str, bankruptcy=None, date_found=None, strict_dates=False
+ court_str: str,
+ bankruptcy: Optional[bool] = None,
+ date_found: Optional[datetime] = None,
+ strict_dates: Optional[bool] = False,
+ location: Optional[str] = None,
):
"""Finds a list of court ID for a given string and parameters
@@ -166,11 +175,12 @@ def find_court(
:param bankruptcy: Tells function to exclude or include bankruptcy cases
:param date_found: Date object
:param strict_dates: Boolean that helps tell the sytsem how to handle
+ :param location: Where the court is located.
null dates in courts-db
:return: List of court IDs if any
"""
court_str = strip_punc(court_str)
- matches = find_court_ids_by_name(court_str, bankruptcy)
+ matches = find_court_ids_by_name(court_str, bankruptcy, location)
if bankruptcy is not None:
matches = filter_courts_by_bankruptcy(
matches=matches, bankruptcy=bankruptcy
diff --git a/courts_db/data/courts.json b/courts_db/data/courts.json
index c4b3392..3d7153c 100644
--- a/courts_db/data/courts.json
+++ b/courts_db/data/courts.json
@@ -9794,6 +9794,72 @@
"location": "Michigan",
"citation_string": "Mich."
},
+ {
+ "regex": [],
+ "name_abbreviation": "Michigan Cir. Ct.",
+ "dates": [
+ {
+ "start": null,
+ "end": null
+ }
+ ],
+ "name": "Michigan Circuit Court",
+ "level": "gjc",
+ "case_types": [],
+ "jurisdiction": "M.I.",
+ "system": "state",
+ "examples": [],
+ "type": "trial",
+ "id": "micirct",
+ "location": "Michigan",
+ "citation_string": "Michigan Cir. Ct."
+ },
+ {
+ "regex": [],
+ "name_abbreviation": "Mich. 37th Cir.",
+ "dates": [
+ {
+ "start": null,
+ "end": null
+ }
+ ],
+ "name": "Circuit Court of the 37th Circuit of Michigan",
+ "level": "gjc",
+ "case_types": [],
+ "jurisdiction": "M.I.",
+ "system": "state",
+ "examples": [],
+ "type": "trial",
+ "id": "micirct37",
+ "group_id": "micirct",
+ "location": "Michigan",
+ "citation_string": "Mich. 37th Cir."
+ },
+ {
+ "regex": [
+ "Calhoun County Circuit Court"
+ ],
+ "name_abbreviation": "Michigan Cir. Ct., Calhoun Cty.",
+ "dates": [
+ {
+ "start": null,
+ "end": null
+ }
+ ],
+ "name": "Circuit Court of the 37th Circuit of Michigan, Calhoun County",
+ "level": "gjc",
+ "case_types": [],
+ "jurisdiction": "M.I.",
+ "system": "state",
+ "examples": [
+ "Calhoun County Circuit Court"
+ ],
+ "type": "trial",
+ "id": "micirct37cal",
+ "group_id": "micirct37",
+ "location": "Michigan",
+ "citation_string": "Mich. 37th Cir., Calhoun Cty."
+ },
{
"regex": [
"${wd} ${mi}",
diff --git a/courts_db/utils.py b/courts_db/utils.py
index 31ee234..ef984f2 100644
--- a/courts_db/utils.py
+++ b/courts_db/utils.py
@@ -71,6 +71,14 @@ def gather_regexes(courts):
for court in courts:
for reg_str in court["regex"]:
regex = re.compile(reg_str, (re.I | re.U))
- regexes.append((regex, court["id"], court["name"], court["type"]))
+ regexes.append(
+ (
+ regex,
+ court["id"],
+ court["name"],
+ court["type"],
+ court.get("location"),
+ )
+ )
return regexes
|
freelawproject/courts-db
|
389eb63535f696866ddc51b82dda6abc38bce0ed
|
diff --git a/tests.py b/tests.py
index 6ec3dd6..cd590e3 100644
--- a/tests.py
+++ b/tests.py
@@ -49,6 +49,34 @@ class DataTest(CourtsDBTestCase):
)
print("√")
+ def test_location_filter(self):
+ """Can we use location to filter properly"""
+
+ court_ids = find_court("Calhoun County Circuit Court")
+ self.assertEqual(
+ court_ids,
+ ["flacirct14cal", "micirct37cal"],
+ msg="Court filtering failed",
+ )
+
+ florida_court_ids = find_court(
+ "Calhoun County Circuit Court", location="Florida"
+ )
+ self.assertEqual(
+ ["flacirct14cal"],
+ florida_court_ids,
+ msg="Florida county court not found",
+ )
+
+ michigan_court_ids = find_court(
+ "Calhoun County Circuit Court", location="Michigan"
+ )
+ self.assertEqual(
+ ["micirct37cal"],
+ michigan_court_ids,
+ msg="Michican county court not found",
+ )
+
class ExamplesTest(CourtsDBTestCase):
def test_all_non_bankruptcy_examples(self):
|
Need jurisdiction/location flag
We need to add a jurisdiction/location flag to differentiate between all the small local level courts in the Harvard dataset.
For example, testing against all courts - we have the following results.
```
Testing Calhoun County Circuit Court ... Mich. ['flacirct14cal']
Testing Calhoun County Circuit Court ... Fla. ['flacirct14cal']
```
Calhoun County Circuit Court for Michigan hasn't been added yet - so it clearly assumed that the court str was from Calhoun County Florida.
|
0.0
|
389eb63535f696866ddc51b82dda6abc38bce0ed
|
[
"tests.py::DataTest::test_location_filter"
] |
[
"tests.py::DataTest::test_all_example",
"tests.py::DataTest::test_unicode_handling",
"tests.py::ExamplesTest::test_all_non_bankruptcy_examples",
"tests.py::ExamplesTest::test_bankruptcy_examples",
"tests.py::JsonTest::test_json",
"tests.py::LazyLoadTest::test_lazy_load"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-09-07 16:43:05+00:00
|
bsd-2-clause
| 2,396 |
|
frictionlessdata__frictionless-py-525
|
diff --git a/frictionless/query.py b/frictionless/query.py
index 3315f852..247992c2 100644
--- a/frictionless/query.py
+++ b/frictionless/query.py
@@ -170,11 +170,11 @@ class Query(Metadata):
"properties": {
"pickFields": {"type": "array"},
"skipFields": {"type": "array"},
- "limitFields": {"type": "number"},
- "offsetFields": {"type": "number"},
+ "limitFields": {"type": "number", "minimum": 1},
+ "offsetFields": {"type": "number", "minimum": 1},
"pickRows": {"type": "array"},
"skipRows": {"type": "array"},
- "limitRows": {"type": "number"},
- "offsetRows": {"type": "number"},
+ "limitRows": {"type": "number", "minimum": 1},
+ "offsetRows": {"type": "number", "minimum": 1},
},
}
|
frictionlessdata/frictionless-py
|
30a44b05388f9def41a0c5ea009aa900a5aaf574
|
diff --git a/tests/test_table.py b/tests/test_table.py
index 97d23601..f269c50c 100644
--- a/tests/test_table.py
+++ b/tests/test_table.py
@@ -851,6 +851,50 @@ def test_table_limit_offset_rows():
assert table.read_data() == [["3", "c"], ["4", "d"]]
+def test_table_limit_fields_error_zero_issue_521():
+ source = "data/long.csv"
+ query = Query(limit_fields=0)
+ table = Table(source, query=query)
+ with pytest.raises(exceptions.FrictionlessException) as excinfo:
+ table.open()
+ error = excinfo.value.error
+ assert error.code == "query-error"
+ assert error.note.count('minimum of 1" at "limitFields')
+
+
+def test_table_offset_fields_error_zero_issue_521():
+ source = "data/long.csv"
+ query = Query(offset_fields=0)
+ table = Table(source, query=query)
+ with pytest.raises(exceptions.FrictionlessException) as excinfo:
+ table.open()
+ error = excinfo.value.error
+ assert error.code == "query-error"
+ assert error.note.count('minimum of 1" at "offsetFields')
+
+
+def test_table_limit_rows_error_zero_issue_521():
+ source = "data/long.csv"
+ query = Query(limit_rows=0)
+ table = Table(source, query=query)
+ with pytest.raises(exceptions.FrictionlessException) as excinfo:
+ table.open()
+ error = excinfo.value.error
+ assert error.code == "query-error"
+ assert error.note.count('minimum of 1" at "limitRows')
+
+
+def test_table_offset_rows_error_zero_issue_521():
+ source = "data/long.csv"
+ query = Query(offset_rows=0)
+ table = Table(source, query=query)
+ with pytest.raises(exceptions.FrictionlessException) as excinfo:
+ table.open()
+ error = excinfo.value.error
+ assert error.code == "query-error"
+ assert error.note.count('minimum of 1" at "offsetRows')
+
+
# Header
|
Query(limit_rows=0) doesn't limit rows
# Overview
From here - https://github.com/frictionlessdata/frictionless-py/issues/516. Also the same must be for limit_fields
|
0.0
|
30a44b05388f9def41a0c5ea009aa900a5aaf574
|
[
"tests/test_table.py::test_table_limit_fields_error_zero_issue_521",
"tests/test_table.py::test_table_offset_fields_error_zero_issue_521",
"tests/test_table.py::test_table_limit_rows_error_zero_issue_521",
"tests/test_table.py::test_table_offset_rows_error_zero_issue_521"
] |
[
"tests/test_table.py::test_table",
"tests/test_table.py::test_table_read_data",
"tests/test_table.py::test_table_data_stream",
"tests/test_table.py::test_table_data_stream_iterate",
"tests/test_table.py::test_table_read_rows",
"tests/test_table.py::test_table_row_stream",
"tests/test_table.py::test_table_row_stream_iterate",
"tests/test_table.py::test_table_row_stream_error_cells",
"tests/test_table.py::test_table_row_stream_blank_cells",
"tests/test_table.py::test_table_empty",
"tests/test_table.py::test_table_without_rows",
"tests/test_table.py::test_table_without_headers",
"tests/test_table.py::test_table_error_read_closed",
"tests/test_table.py::test_table_source_error_data",
"tests/test_table.py::test_table_scheme_file",
"tests/test_table.py::test_table_scheme_stream",
"tests/test_table.py::test_table_scheme_text",
"tests/test_table.py::test_table_scheme_error_bad_scheme",
"tests/test_table.py::test_table_scheme_error_bad_scheme_and_format",
"tests/test_table.py::test_table_scheme_error_file_not_found",
"tests/test_table.py::test_table_scheme_error_file_not_found_bad_format",
"tests/test_table.py::test_table_scheme_error_file_not_found_bad_compression",
"tests/test_table.py::test_table_format_csv",
"tests/test_table.py::test_table_format_ndjson",
"tests/test_table.py::test_table_format_xls",
"tests/test_table.py::test_table_format_xlsx",
"tests/test_table.py::test_table_format_error_bad_format",
"tests/test_table.py::test_table_format_error_non_matching_format",
"tests/test_table.py::test_table_hashing",
"tests/test_table.py::test_table_hashing_provided",
"tests/test_table.py::test_table_hashing_error_bad_hashing",
"tests/test_table.py::test_table_encoding",
"tests/test_table.py::test_table_encoding_explicit_utf8",
"tests/test_table.py::test_table_encoding_explicit_latin1",
"tests/test_table.py::test_table_encoding_utf_16",
"tests/test_table.py::test_table_encoding_error_bad_encoding",
"tests/test_table.py::test_table_encoding_error_non_matching_encoding",
"tests/test_table.py::test_table_compression_local_csv_zip",
"tests/test_table.py::test_table_compression_local_csv_zip_multiple_files",
"tests/test_table.py::test_table_compression_local_csv_zip_multiple_files_compression_path",
"tests/test_table.py::test_table_compression_local_csv_zip_multiple_open",
"tests/test_table.py::test_table_compression_local_csv_gz",
"tests/test_table.py::test_table_compression_filelike_csv_zip",
"tests/test_table.py::test_table_compression_filelike_csv_gz",
"tests/test_table.py::test_table_compression_error_bad",
"tests/test_table.py::test_table_compression_error_invalid_zip",
"tests/test_table.py::test_table_compression_error_invalid_gz",
"tests/test_table.py::test_table_control",
"tests/test_table.py::test_table_control_bad_property",
"tests/test_table.py::test_table_dialect",
"tests/test_table.py::test_table_dialect_csv_delimiter",
"tests/test_table.py::test_table_dialect_json_property",
"tests/test_table.py::test_table_dialect_bad_property",
"tests/test_table.py::test_table_dialect_header_case_default",
"tests/test_table.py::test_table_dialect_header_case_is_false",
"tests/test_table.py::test_table_pick_fields",
"tests/test_table.py::test_table_pick_fields_position",
"tests/test_table.py::test_table_pick_fields_regex",
"tests/test_table.py::test_table_pick_fields_position_and_prefix",
"tests/test_table.py::test_table_skip_fields",
"tests/test_table.py::test_table_skip_fields_position",
"tests/test_table.py::test_table_skip_fields_regex",
"tests/test_table.py::test_table_skip_fields_position_and_prefix",
"tests/test_table.py::test_table_skip_fields_blank_header",
"tests/test_table.py::test_table_skip_fields_blank_header_notation",
"tests/test_table.py::test_table_skip_fields_keyed_source",
"tests/test_table.py::test_table_limit_fields",
"tests/test_table.py::test_table_offset_fields",
"tests/test_table.py::test_table_limit_offset_fields",
"tests/test_table.py::test_table_pick_rows",
"tests/test_table.py::test_table_pick_rows_number",
"tests/test_table.py::test_table_pick_rows_regex",
"tests/test_table.py::test_table_skip_rows",
"tests/test_table.py::test_table_skip_rows_excel_empty_column",
"tests/test_table.py::test_table_skip_rows_with_headers",
"tests/test_table.py::test_table_skip_rows_with_headers_example_from_readme",
"tests/test_table.py::test_table_skip_rows_regex",
"tests/test_table.py::test_table_skip_rows_preset",
"tests/test_table.py::test_table_limit_rows",
"tests/test_table.py::test_table_offset_rows",
"tests/test_table.py::test_table_limit_offset_rows",
"tests/test_table.py::test_table_header",
"tests/test_table.py::test_table_header_unicode",
"tests/test_table.py::test_table_header_stream_context_manager",
"tests/test_table.py::test_table_header_inline",
"tests/test_table.py::test_table_header_json_keyed",
"tests/test_table.py::test_table_header_inline_keyed",
"tests/test_table.py::test_table_header_inline_keyed_headers_is_none",
"tests/test_table.py::test_table_header_xlsx_multiline",
"tests/test_table.py::test_table_header_csv_multiline_headers_join",
"tests/test_table.py::test_table_header_csv_multiline_headers_duplicates",
"tests/test_table.py::test_table_header_strip_and_non_strings",
"tests/test_table.py::test_table_schema",
"tests/test_table.py::test_table_schema_provided",
"tests/test_table.py::test_table_sync_schema",
"tests/test_table.py::test_table_schema_patch_schema",
"tests/test_table.py::test_table_schema_patch_schema_missing_values",
"tests/test_table.py::test_table_schema_infer_type",
"tests/test_table.py::test_table_schema_infer_names",
"tests/test_table.py::test_table_schema_lookup_foreign_keys",
"tests/test_table.py::test_table_schema_lookup_foreign_keys_error",
"tests/test_table.py::test_table_stats_hash",
"tests/test_table.py::test_table_stats_hash_md5",
"tests/test_table.py::test_table_stats_hash_sha1",
"tests/test_table.py::test_table_stats_hash_sha256",
"tests/test_table.py::test_table_stats_hash_sha512",
"tests/test_table.py::test_table_stats_hash_compressed",
"tests/test_table.py::test_table_stats_bytes",
"tests/test_table.py::test_table_stats_bytes_compressed",
"tests/test_table.py::test_table_stats_fields",
"tests/test_table.py::test_table_stats_rows",
"tests/test_table.py::test_table_stats_rows_significant",
"tests/test_table.py::test_table_reopen",
"tests/test_table.py::test_table_reopen_and_infer_volume",
"tests/test_table.py::test_table_reopen_generator",
"tests/test_table.py::test_table_write",
"tests/test_table.py::test_table_write_format_error_bad_format",
"tests/test_table.py::test_table_integrity_onerror",
"tests/test_table.py::test_table_integrity_onerror_header_warn",
"tests/test_table.py::test_table_integrity_onerror_header_raise",
"tests/test_table.py::test_table_integrity_onerror_row_warn",
"tests/test_table.py::test_table_integrity_onerror_row_raise",
"tests/test_table.py::test_table_integrity_unique",
"tests/test_table.py::test_table_integrity_unique_error",
"tests/test_table.py::test_table_integrity_primary_key",
"tests/test_table.py::test_table_integrity_primary_key_error",
"tests/test_table.py::test_table_integrity_foreign_keys",
"tests/test_table.py::test_table_integrity_foreign_keys_error",
"tests/test_table.py::test_table_reset_on_close_issue_190",
"tests/test_table.py::test_table_skip_blank_at_the_end_issue_bco_dmo_33",
"tests/test_table.py::test_table_not_existent_local_file_with_no_format_issue_287",
"tests/test_table.py::test_table_skip_rows_non_string_cell_issue_320",
"tests/test_table.py::test_table_skip_rows_non_string_cell_issue_322"
] |
{
"failed_lite_validators": [
"has_short_problem_statement"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-11-11 09:11:32+00:00
|
mit
| 2,397 |
|
frictionlessdata__frictionless-py-527
|
diff --git a/frictionless/validate/inquiry.py b/frictionless/validate/inquiry.py
index 4136259b..8e570d92 100644
--- a/frictionless/validate/inquiry.py
+++ b/frictionless/validate/inquiry.py
@@ -9,7 +9,7 @@ from .. import exceptions
@Report.from_validate
-def validate_inquiry(source):
+def validate_inquiry(source, *, nopool=False):
"""Validate inquiry
API | Usage
@@ -18,6 +18,7 @@ def validate_inquiry(source):
Parameters:
source (dict|str): an inquiry descriptor
+ nopool? (bool): disable multiprocessing
Returns:
Report: validation report
@@ -44,13 +45,14 @@ def validate_inquiry(source):
continue
tasks.append(task)
- # Validate task
- if len(tasks) == 1:
- report = validate(**helpers.create_options(tasks[0]))
- reports.append(report)
+ # Validate sequentially
+ if len(tasks) == 1 or nopool:
+ for task in tasks:
+ report = validate(**helpers.create_options(task))
+ reports.append(report)
- # Validate tasks
- if len(tasks) > 1:
+ # Validate in-parallel
+ else:
with Pool() as pool:
reports.extend(pool.map(partial(helpers.apply_function, validate), tasks))
diff --git a/frictionless/validate/package.py b/frictionless/validate/package.py
index ebea2872..0fd8c9a9 100644
--- a/frictionless/validate/package.py
+++ b/frictionless/validate/package.py
@@ -8,7 +8,13 @@ from .. import exceptions
@Report.from_validate
def validate_package(
- source, basepath=None, trusted=False, noinfer=False, nolookup=False, **options
+ source,
+ basepath=None,
+ trusted=False,
+ noinfer=False,
+ nolookup=False,
+ nopool=False,
+ **options
):
"""Validate package
@@ -22,6 +28,7 @@ def validate_package(
trusted? (bool): don't raise an exception on unsafe paths
noinfer? (bool): don't call `package.infer`
nolookup? (bool): don't read lookup tables skipping integrity checks
+ nopool? (bool): disable multiprocessing
**options (dict): options for every extracted table
Returns:
@@ -62,7 +69,7 @@ def validate_package(
# Validate inquiry
inquiry = Inquiry(descriptor)
- report = validate_inquiry(inquiry)
+ report = validate_inquiry(inquiry, nopool=nopool)
# Return report
return Report(time=timer.time, errors=report["errors"], tables=report["tables"])
|
frictionlessdata/frictionless-py
|
38002600c959bbe2863d533177d56a9df89c9fbd
|
diff --git a/tests/validate/test_inquiry.py b/tests/validate/test_inquiry.py
index 38a4a976..2340deb3 100644
--- a/tests/validate/test_inquiry.py
+++ b/tests/validate/test_inquiry.py
@@ -101,3 +101,20 @@ def test_validate_with_multiple_packages():
[3, 3, None, "primary-key-error"],
[4, 4, None, "blank-row"],
]
+
+
+def test_validate_with_multiple_packages_with_nopool():
+ report = validate(
+ {
+ "tasks": [
+ {"source": "data/package/datapackage.json"},
+ {"source": "data/invalid/datapackage.json"},
+ ]
+ },
+ nopool=True,
+ )
+ assert report.flatten(["tablePosition", "rowPosition", "fieldPosition", "code"]) == [
+ [3, 3, None, "blank-row"],
+ [3, 3, None, "primary-key-error"],
+ [4, 4, None, "blank-row"],
+ ]
diff --git a/tests/validate/test_package.py b/tests/validate/test_package.py
index 5dd51144..299497a8 100644
--- a/tests/validate/test_package.py
+++ b/tests/validate/test_package.py
@@ -146,6 +146,15 @@ def test_validate_package_dialect_header_false():
assert report.valid
+def test_validate_with_nopool():
+ report = validate("data/invalid/datapackage.json", nopool=True)
+ assert report.flatten(["tablePosition", "rowPosition", "fieldPosition", "code"]) == [
+ [1, 3, None, "blank-row"],
+ [1, 3, None, "primary-key-error"],
+ [2, 4, None, "blank-row"],
+ ]
+
+
# Checksum
DESCRIPTOR_SH = {
|
Multiprocessing introduces high overhead for small validation jobs
# Overview
Validation can now be done on just metadata and table headers, so migrating `goodtables-pandas` should now be very straightforward. Thank you. (see https://github.com/frictionlessdata/frictionless-py/issues/503, closed by #514 and #515)
```python
from frictionless import validate, Query
validate(..., query=Query(limit_rows=1), nolookup=True, noinfer=True)
```
*NOTE: `limit_rows=1` because `Query(limit_rows=0)` queries all rows, rather than no rows.*
However, I wanted to point out that with the validation process so reduced, the use of `multiprocessing.Pool` introduces a significant overhead. My test package with three resources takes 1.2 s, instead of just 0.2 s if I replace:
https://github.com/frictionlessdata/frictionless-py/blob/09cc98e1966d6f97f4eecb47757f45f8a946c5e7/frictionless/validate/inquiry.py#L54-L55
with:
```python
for task in tasks:
reports.append(validate(**task))
```
So it may be worth considering a global or local configuration to set the max number of threads (threads > 1) or disable parallel processing altogether (threads == 1).
---
Please preserve this line to notify @roll (lead of this repository)
|
0.0
|
38002600c959bbe2863d533177d56a9df89c9fbd
|
[
"tests/validate/test_inquiry.py::test_validate_with_multiple_packages_with_nopool",
"tests/validate/test_package.py::test_validate_with_nopool"
] |
[
"tests/validate/test_inquiry.py::test_validate",
"tests/validate/test_package.py::test_validate",
"tests/validate/test_package.py::test_validate_invalid_descriptor_path",
"tests/validate/test_package.py::test_validate_invalid_package",
"tests/validate/test_package.py::test_validate_invalid_package_noinfer",
"tests/validate/test_package.py::test_validate_invalid_table",
"tests/validate/test_package.py::test_validate_package_dialect_header_false",
"tests/validate/test_package.py::test_validate_checksum",
"tests/validate/test_package.py::test_validate_checksum_invalid",
"tests/validate/test_package.py::test_validate_checksum_size",
"tests/validate/test_package.py::test_validate_checksum_size_invalid",
"tests/validate/test_package.py::test_validate_checksum_hash",
"tests/validate/test_package.py::test_check_file_checksum_hash_invalid",
"tests/validate/test_package.py::test_check_file_checksum_hash_not_supported_algorithm",
"tests/validate/test_package.py::test_validate_package_invalid_json_issue_192",
"tests/validate/test_package.py::test_composite_primary_key_unique_issue_215",
"tests/validate/test_package.py::test_composite_primary_key_not_unique_issue_215",
"tests/validate/test_package.py::test_validate_geopoint_required_constraint_issue_231",
"tests/validate/test_package.py::test_validate_package_number_test_issue_232",
"tests/validate/test_package.py::test_validate_package_with_schema_issue_348"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-11-12 08:16:27+00:00
|
mit
| 2,398 |
|
frictionlessdata__frictionless-py-548
|
diff --git a/data/Table With Data.csv b/data/Table With Data.csv
new file mode 100644
index 00000000..6d09540e
--- /dev/null
+++ b/data/Table With Data.csv
@@ -0,0 +1,3 @@
+id,name
+1,english
+2,中国人
diff --git a/frictionless/helpers.py b/frictionless/helpers.py
index 97445639..67885215 100644
--- a/frictionless/helpers.py
+++ b/frictionless/helpers.py
@@ -9,6 +9,7 @@ import chardet
import tempfile
import datetime
import stringcase
+from slugify import slugify
from inspect import signature
from importlib import import_module
from urllib.parse import urlparse, parse_qs
@@ -136,13 +137,14 @@ def compile_regex(items):
return result
-# TODO: use slugify
def detect_name(source):
+ name = "memory"
if isinstance(source, str) and "\n" not in source:
- return os.path.splitext(os.path.basename(source))[0]
- if isinstance(source, list) and source and isinstance(source[0], str):
- return os.path.splitext(os.path.basename(source[0]))[0]
- return "memory"
+ name = os.path.splitext(os.path.basename(source))[0]
+ elif isinstance(source, list) and source and isinstance(source[0], str):
+ name = os.path.splitext(os.path.basename(source[0]))[0]
+ name = slugify(name).lower()
+ return name
def detect_basepath(descriptor):
|
frictionlessdata/frictionless-py
|
e813a8e1249aa47d0b776c78f543fb1d6b52eaed
|
diff --git a/tests/test_resource.py b/tests/test_resource.py
index d85951fa..6cbed497 100644
--- a/tests/test_resource.py
+++ b/tests/test_resource.py
@@ -606,6 +606,13 @@ def test_resource_infer_from_path():
assert resource.path == "data/table.csv"
+def test_resource_infer_not_slugified_name_issue_531():
+ resource = Resource()
+ resource.infer("data/Table With Data.csv")
+ assert resource.metadata_valid
+ assert resource.name == "table-with-data"
+
+
# Import/Export
|
Resource names coming from 'infer' should not retain uppercase characters
# Overview
In working on a dataset where some of the filenames contain uppercase characters, I see that those characters are retained in the resource names when one processes them with `infer`.
For example, `RAW_input_stream_1.csv` will be given a resource name of `RAW_input_stream_1`. This violates the JSONschema, which allows only lowercase letters: `^([-a-z0-9._/])+$`
---
Please preserve this line to notify @roll (lead of this repository)
|
0.0
|
e813a8e1249aa47d0b776c78f543fb1d6b52eaed
|
[
"tests/test_resource.py::test_resource_infer_not_slugified_name_issue_531"
] |
[
"tests/test_resource.py::test_resource",
"tests/test_resource.py::test_resource_from_dict",
"tests/test_resource.py::test_resource_from_path",
"tests/test_resource.py::test_resource_from_path_error_bad_path",
"tests/test_resource.py::test_resource_from_zip",
"tests/test_resource.py::test_resource_source_non_tabular",
"tests/test_resource.py::test_resource_source_non_tabular_error_bad_path",
"tests/test_resource.py::test_resource_source_path",
"tests/test_resource.py::test_resource_source_path_and_basepath",
"tests/test_resource.py::test_resource_source_path_error_bad_path",
"tests/test_resource.py::test_resource_source_path_error_bad_path_not_safe_absolute",
"tests/test_resource.py::test_resource_source_path_error_bad_path_not_safe_traversing",
"tests/test_resource.py::test_resource_source_data",
"tests/test_resource.py::test_resource_source_path_and_data",
"tests/test_resource.py::test_resource_source_no_path_and_no_data",
"tests/test_resource.py::test_resource_dialect",
"tests/test_resource.py::test_resource_dialect_header_false",
"tests/test_resource.py::test_resource_dialect_from_path",
"tests/test_resource.py::test_resource_dialect_from_path_error_path_not_safe",
"tests/test_resource.py::test_resource_respect_query_set_after_creation_issue_503",
"tests/test_resource.py::test_resource_schema",
"tests/test_resource.py::test_resource_schema_source_data",
"tests/test_resource.py::test_resource_schema_from_path",
"tests/test_resource.py::test_resource_schema_from_path_with_basepath",
"tests/test_resource.py::test_resource_schema_from_path_error_bad_path",
"tests/test_resource.py::test_resource_schema_from_path_error_path_not_safe",
"tests/test_resource.py::test_resource_expand",
"tests/test_resource.py::test_resource_expand_with_dialect",
"tests/test_resource.py::test_resource_expand_with_schema",
"tests/test_resource.py::test_resource_write",
"tests/test_resource.py::test_resource_infer",
"tests/test_resource.py::test_resource_infer_source_non_tabular",
"tests/test_resource.py::test_resource_infer_from_path",
"tests/test_resource.py::test_resource_to_copy",
"tests/test_resource.py::test_resource_to_json",
"tests/test_resource.py::test_resource_to_yaml",
"tests/test_resource.py::test_resource_to_zip",
"tests/test_resource.py::test_resource_to_zip_source_inline",
"tests/test_resource.py::test_resource_to_table",
"tests/test_resource.py::test_resource_to_table_source_data",
"tests/test_resource.py::test_resource_to_table_source_non_tabular",
"tests/test_resource.py::test_resource_to_table_respect_query_issue_503",
"tests/test_resource.py::test_resource_source_multipart",
"tests/test_resource.py::test_resource_source_multipart_error_bad_path",
"tests/test_resource.py::test_resource_source_multipart_error_bad_path_not_safe_absolute",
"tests/test_resource.py::test_resource_source_multipart_error_bad_path_not_safe_traversing",
"tests/test_resource.py::test_resource_source_multipart_infer",
"tests/test_resource.py::test_resource_integrity_onerror",
"tests/test_resource.py::test_resource_integrity_onerror_header_warn",
"tests/test_resource.py::test_resource_integrity_onerror_header_raise",
"tests/test_resource.py::test_resource_integrity_onerror_row_warn",
"tests/test_resource.py::test_resource_integrity_onerror_row_raise",
"tests/test_resource.py::test_resource_integrity_foreign_keys",
"tests/test_resource.py::test_resource_integrity_foreign_keys_invalid",
"tests/test_resource.py::test_resource_integrity_read_lookup",
"tests/test_resource.py::test_resource_relative_parent_path_with_trusted_option_issue_171",
"tests/test_resource.py::test_resource_preserve_format_from_descriptor_on_infer_issue_188"
] |
{
"failed_lite_validators": [
"has_added_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-11-25 09:19:34+00:00
|
mit
| 2,399 |
|
fronzbot__blinkpy-104
|
diff --git a/.gitignore b/.gitignore
index 0bd45aa..9a182cc 100644
--- a/.gitignore
+++ b/.gitignore
@@ -10,3 +10,4 @@ dist/*
.sh
build/*
docs/_build
+*.log
diff --git a/blinkpy/blinkpy.py b/blinkpy/blinkpy.py
index e5fe32c..7124f1a 100644
--- a/blinkpy/blinkpy.py
+++ b/blinkpy/blinkpy.py
@@ -21,7 +21,7 @@ from blinkpy.helpers.util import (
create_session, BlinkURLHandler,
BlinkAuthenticationException)
from blinkpy.helpers.constants import (
- BLINK_URL, LOGIN_URL, LOGIN_BACKUP_URL)
+ BLINK_URL, LOGIN_URL, LOGIN_BACKUP_URL, PROJECT_URL)
REFRESH_RATE = 30
@@ -146,8 +146,7 @@ class Blink():
if all_networks:
_LOGGER.error(("More than one unboarded network. "
"Platform may not work as intended. "
- "Please open an issue on "
- "https://github.com/fronzbot/blinkpy."))
+ "Please open an issue on %s"), PROJECT_URL)
def refresh(self, force_cache=False):
"""
diff --git a/blinkpy/camera.py b/blinkpy/camera.py
index cb2666e..d36a5da 100644
--- a/blinkpy/camera.py
+++ b/blinkpy/camera.py
@@ -162,8 +162,8 @@ class BlinkCamera():
else:
self.motion_detected = False
except KeyError:
- _LOGGER.warning("Could not extract clip info from camera %s",
- self.name)
+ _LOGGER.info("Could not extract clip info from camera %s",
+ self.name)
def image_to_file(self, path):
"""
@@ -187,6 +187,9 @@ class BlinkCamera():
"""
_LOGGER.debug("Writing video from %s to %s", self.name, path)
response = self._cached_video
+ if response is None:
+ _LOGGER.error("No saved video exist for %s.", self.name)
+ return
with open(path, 'wb') as vidfile:
copyfileobj(response.raw, vidfile)
diff --git a/blinkpy/helpers/util.py b/blinkpy/helpers/util.py
index 23fb58d..253220e 100644
--- a/blinkpy/helpers/util.py
+++ b/blinkpy/helpers/util.py
@@ -2,7 +2,7 @@
import logging
from requests import Request, Session, exceptions
-from blinkpy.helpers.constants import BLINK_URL
+from blinkpy.helpers.constants import BLINK_URL, PROJECT_URL
import blinkpy.helpers.errors as ERROR
@@ -17,7 +17,7 @@ def create_session():
def attempt_reauthorization(blink):
"""Attempt to refresh auth token and links."""
- _LOGGER.debug("Auth token expired, attempting reauthorization.")
+ _LOGGER.info("Auth token expired, attempting reauthorization.")
headers = blink.get_auth_token()
return headers
@@ -48,20 +48,25 @@ def http_req(blink, url='http://example.com', data=None, headers=None,
try:
response = blink.session.send(prepped, stream=stream)
+ if json_resp and 'code' in response.json():
+ if is_retry:
+ _LOGGER.error(("Cannot obtain new token for server auth. "
+ "Please report this issue on %s"), PROJECT_URL)
+ return None
+ else:
+ headers = attempt_reauthorization(blink)
+ return http_req(blink, url=url, data=data, headers=headers,
+ reqtype=reqtype, stream=stream,
+ json_resp=json_resp, is_retry=True)
except (exceptions.ConnectionError, exceptions.Timeout):
- _LOGGER.error("Cannot connect to server. Possible outage.")
- return None
-
- if json_resp and 'code' in response.json():
- if is_retry:
- _LOGGER.error("Cannot authenticate with server.")
- raise BlinkAuthenticationException(
- (response.json()['code'], response.json()['message']))
- else:
+ _LOGGER.error("Cannot connect to server with url %s.", url)
+ if not is_retry:
headers = attempt_reauthorization(blink)
return http_req(blink, url=url, data=data, headers=headers,
reqtype=reqtype, stream=stream,
json_resp=json_resp, is_retry=True)
+ _LOGGER.error("Possible issue with Blink servers.")
+ return None
if json_resp:
return response.json()
|
fronzbot/blinkpy
|
0781d79ca7e4e2327d699ed33d9bf190485c370c
|
diff --git a/tests/test_api.py b/tests/test_api.py
index d50a64e..103367d 100644
--- a/tests/test_api.py
+++ b/tests/test_api.py
@@ -1,6 +1,7 @@
"""Test various api functions."""
import unittest
+from unittest import mock
from blinkpy import api
from blinkpy.blinkpy import Blink
from blinkpy.helpers.util import create_session
@@ -20,13 +21,21 @@ class TestBlinkAPI(unittest.TestCase):
"""Tear down blink module."""
self.blink = None
- def test_http_req_connect_error(self):
+ @mock.patch('blinkpy.blinkpy.Blink.get_auth_token')
+ def test_http_req_connect_error(self, mock_auth):
"""Test http_get error condition."""
- expected = ("ERROR:blinkpy.helpers.util:"
- "Cannot connect to server. Possible outage.")
+ mock_auth.return_value = {'foo': 'bar'}
+ firstlog = ("ERROR:blinkpy.helpers.util:"
+ "Cannot connect to server with url {}").format(
+ 'http://notreal.fake.')
+ nextlog = ("INFO:blinkpy.helpers.util:"
+ "Auth token expired, attempting reauthorization.")
+ lastlog = ("ERROR:blinkpy.helpers.util:"
+ "Possible issue with Blink servers.")
+ expected = [firstlog, nextlog, firstlog, lastlog]
with self.assertLogs() as getlog:
api.http_get(self.blink, 'http://notreal.fake')
with self.assertLogs() as postlog:
api.http_post(self.blink, 'http://notreal.fake')
- self.assertEqual(getlog.output, [expected])
- self.assertEqual(postlog.output, [expected])
+ self.assertEqual(getlog.output, expected)
+ self.assertEqual(postlog.output, expected)
diff --git a/tests/test_blinkpy.py b/tests/test_blinkpy.py
index 0f5dadd..577d177 100644
--- a/tests/test_blinkpy.py
+++ b/tests/test_blinkpy.py
@@ -14,6 +14,7 @@ from blinkpy.sync_module import BlinkSyncModule
from blinkpy.helpers.util import (
http_req, create_session, BlinkAuthenticationException,
BlinkException, BlinkURLHandler)
+from blinkpy.helpers.constants import PROJECT_URL
import tests.mock_responses as mresp
USERNAME = 'foobar'
@@ -77,11 +78,15 @@ class TestBlinkSetup(unittest.TestCase):
def test_bad_request(self, mock_sess):
"""Check that we raise an Exception with a bad request."""
self.blink.session = create_session()
+ explog = ("ERROR:blinkpy.helpers.util:"
+ "Cannot obtain new token for server auth. "
+ "Please report this issue on {}").format(PROJECT_URL)
with self.assertRaises(BlinkException):
http_req(self.blink, reqtype='bad')
- with self.assertRaises(BlinkAuthenticationException):
+ with self.assertLogs() as logrecord:
http_req(self.blink, reqtype='post', is_retry=True)
+ self.assertEqual(logrecord.output, [explog])
def test_authentication(self, mock_sess):
"""Check that we can authenticate Blink up properly."""
|
When no cameras on server, issue 'info' rather than 'warning' in log
**Describe the bug**
When a camera has no saved videos on the server, we print a 'Warning' to the log. This really should be an 'Info' statement instead (line 165 of `blinkpy.cameras`)
**`blinkpy` version:** 0.10.0
**Log Output/Additional Information**
If using home-assistant, please paste the output of the log showing your error below. If not, please include any additional useful information.
```
2018-10-18 15:04:24 WARNING (SyncWorker_7) [blinkpy.camera] Could not extract clip info from camera Blink 3
```
|
0.0
|
0781d79ca7e4e2327d699ed33d9bf190485c370c
|
[
"tests/test_api.py::TestBlinkAPI::test_http_req_connect_error",
"tests/test_blinkpy.py::TestBlinkSetup::test_bad_request"
] |
[
"tests/test_blinkpy.py::TestBlinkSetup::test_authentication",
"tests/test_blinkpy.py::TestBlinkSetup::test_initialization",
"tests/test_blinkpy.py::TestBlinkSetup::test_manual_login",
"tests/test_blinkpy.py::TestBlinkSetup::test_multiple_networks",
"tests/test_blinkpy.py::TestBlinkSetup::test_no_auth_header",
"tests/test_blinkpy.py::TestBlinkSetup::test_no_credentials",
"tests/test_blinkpy.py::TestBlinkSetup::test_reauthorization_attempt",
"tests/test_blinkpy.py::TestBlinkSetup::test_throttle"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2018-10-18 17:00:23+00:00
|
mit
| 2,400 |
|
fronzbot__blinkpy-135
|
diff --git a/blinkpy/camera.py b/blinkpy/camera.py
index 992310b..8c0eb5b 100644
--- a/blinkpy/camera.py
+++ b/blinkpy/camera.py
@@ -24,6 +24,7 @@ class BlinkCamera():
self.battery_voltage = None
self.clip = None
self.temperature = None
+ self.temperature_calibrated = None
self.battery_state = None
self.motion_detected = None
self.wifi_strength = None
@@ -40,6 +41,7 @@ class BlinkCamera():
'serial': self.serial,
'temperature': self.temperature,
'temperature_c': self.temperature_c,
+ 'temperature_calibrated': self.temperature_calibrated,
'battery': self.battery,
'thumbnail': self.thumbnail,
'video': self.clip,
@@ -104,6 +106,15 @@ class BlinkCamera():
self.temperature = config['temperature']
self.wifi_strength = config['wifi_strength']
+ # Retrieve calibrated temperature from special endpoint
+ resp = api.request_camera_sensors(self.sync.blink,
+ self.network_id,
+ self.camera_id)
+ try:
+ self.temperature_calibrated = resp['temp']
+ except KeyError:
+ _LOGGER.error("Could not retrieve calibrated temperature.")
+
# Check if thumbnail exists in config, if not try to
# get it from the homescreen info in teh sync module
# otherwise set it to None and log an error
diff --git a/blinkpy/helpers/constants.py b/blinkpy/helpers/constants.py
index a801f5f..3eb1d82 100644
--- a/blinkpy/helpers/constants.py
+++ b/blinkpy/helpers/constants.py
@@ -45,10 +45,10 @@ PYPI_URL = 'https://pypi.python.org/pypi/{}'.format(PROJECT_PACKAGE_NAME)
URLS
'''
BLINK_URL = 'immedia-semi.com'
-LOGIN_URL = 'https://prod.' + BLINK_URL + '/login'
-LOGIN_BACKUP_URL = 'https://rest.piri/' + BLINK_URL + '/login'
-BASE_URL = 'https://prod.' + BLINK_URL
-DEFAULT_URL = 'prod.' + BLINK_URL
+DEFAULT_URL = "{}.{}".format('prod', BLINK_URL)
+BASE_URL = "https://{}".format(DEFAULT_URL)
+LOGIN_URL = "{}/login".format(BASE_URL)
+LOGIN_BACKUP_URL = "https://{}.{}/login".format('rest.piri', BLINK_URL)
'''
Dictionaries
|
fronzbot/blinkpy
|
04c2be9087b3d5be80c40f9020406db946962772
|
diff --git a/tests/test_cameras.py b/tests/test_cameras.py
index d3ffccb..a340228 100644
--- a/tests/test_cameras.py
+++ b/tests/test_cameras.py
@@ -98,6 +98,7 @@ class TestBlinkCameraSetup(unittest.TestCase):
self.camera.last_record = ['1']
self.camera.sync.all_clips = {'new': {'1': '/test.mp4'}}
mock_sess.side_effect = [
+ mresp.MockResponse({'temp': 71}, 200),
'test',
'foobar'
]
@@ -110,6 +111,7 @@ class TestBlinkCameraSetup(unittest.TestCase):
self.assertEqual(self.camera.battery, 50)
self.assertEqual(self.camera.temperature, 68)
self.assertEqual(self.camera.temperature_c, 20)
+ self.assertEqual(self.camera.temperature_calibrated, 71)
self.assertEqual(self.camera.wifi_strength, 4)
self.assertEqual(self.camera.thumbnail,
'https://rest.test.immedia-semi.com/thumb.jpg')
@@ -120,7 +122,11 @@ class TestBlinkCameraSetup(unittest.TestCase):
def test_thumbnail_not_in_info(self, mock_sess):
"""Test that we grab thumbanil if not in camera_info."""
- mock_sess.side_effect = ['foobar', 'barfoo']
+ mock_sess.side_effect = [
+ mresp.MockResponse({'temp': 71}, 200),
+ 'foobar',
+ 'barfoo'
+ ]
self.camera.last_record = ['1']
self.camera.sync.record_dates['new'] = ['1']
self.camera.sync.all_clips = {'new': {'1': '/test.mp4'}}
@@ -175,7 +181,8 @@ class TestBlinkCameraSetup(unittest.TestCase):
self.assertEqual(self.camera.thumbnail, None)
self.assertEqual(
logrecord.output,
- ["ERROR:blinkpy.camera:Could not find thumbnail for camera new"]
+ ["ERROR:blinkpy.camera:Could not retrieve calibrated temperature.",
+ "ERROR:blinkpy.camera:Could not find thumbnail for camera new"]
)
def test_no_video_clips(self, mock_sess):
|
Backup login url incorrect
**Describe the bug**
Backup login url in the `helpers/constants.py` module contains errant `/` instead of `.`. Should be `rest.piri.` instead of `rest.piri/`
**To Reproduce**
Steps to reproduce the behavior:
1. Fail with LOGIN_URL
2. BACKUP_LOGIN_URL will fail because of incorrect format
**`blinkpy` version:** 0.11.0
|
0.0
|
04c2be9087b3d5be80c40f9020406db946962772
|
[
"tests/test_cameras.py::TestBlinkCameraSetup::test_camera_update",
"tests/test_cameras.py::TestBlinkCameraSetup::test_no_thumbnails"
] |
[
"tests/test_cameras.py::TestBlinkCameraSetup::test_check_for_motion",
"tests/test_cameras.py::TestBlinkCameraSetup::test_max_motion_clips",
"tests/test_cameras.py::TestBlinkCameraSetup::test_no_video_clips",
"tests/test_cameras.py::TestBlinkCameraSetup::test_thumbnail_not_in_info"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2019-01-02 16:47:03+00:00
|
mit
| 2,401 |
|
fronzbot__blinkpy-143
|
diff --git a/blinkpy/api.py b/blinkpy/api.py
index f9db8df..723c069 100644
--- a/blinkpy/api.py
+++ b/blinkpy/api.py
@@ -3,7 +3,7 @@
import logging
from json import dumps
import blinkpy.helpers.errors as ERROR
-from blinkpy.helpers.util import http_req, BlinkException
+from blinkpy.helpers.util import http_req, get_time, BlinkException
from blinkpy.helpers.constants import DEFAULT_URL
_LOGGER = logging.getLogger(__name__)
@@ -96,9 +96,11 @@ def request_video_count(blink, headers):
return http_get(blink, url)
-def request_videos(blink, page=0):
+def request_videos(blink, time=None, page=0):
"""Perform a request for videos."""
- url = "{}/api/v2/videos/page/{}".format(blink.urls.base_url, page)
+ timestamp = get_time(time)
+ url = "{}/api/v2/videos/changed?since={}&page/{}".format(
+ blink.urls.base_url, timestamp, page)
return http_get(blink, url)
diff --git a/blinkpy/blinkpy.py b/blinkpy/blinkpy.py
index 7285465..c6de470 100644
--- a/blinkpy/blinkpy.py
+++ b/blinkpy/blinkpy.py
@@ -166,6 +166,9 @@ class Blink():
for sync_name, sync_module in self.sync.items():
_LOGGER.debug("Attempting refresh of sync %s", sync_name)
sync_module.refresh(force_cache=force_cache)
+ if not force_cache:
+ # Prevents rapid clearing of motion detect property
+ self.last_refresh = int(time.time())
def check_if_ok_to_update(self):
"""Check if it is ok to perform an http request."""
@@ -174,7 +177,6 @@ class Blink():
if last_refresh is None:
last_refresh = 0
if current_time >= (last_refresh + self.refresh_rate):
- self.last_refresh = current_time
return True
return False
diff --git a/blinkpy/camera.py b/blinkpy/camera.py
index 8c0eb5b..7991a91 100644
--- a/blinkpy/camera.py
+++ b/blinkpy/camera.py
@@ -6,8 +6,6 @@ from blinkpy import api
_LOGGER = logging.getLogger(__name__)
-MAX_CLIPS = 5
-
class BlinkCamera():
"""Class to initialize individual camera."""
@@ -28,7 +26,7 @@ class BlinkCamera():
self.battery_state = None
self.motion_detected = None
self.wifi_strength = None
- self.last_record = []
+ self.last_record = None
self._cached_image = None
self._cached_video = None
@@ -128,12 +126,15 @@ class BlinkCamera():
new_thumbnail = "{}{}.jpg".format(self.sync.urls.base_url,
thumb_addr)
- # Check if a new motion clip has been recorded
- # check_for_motion_method sets motion_detected variable
- self.check_for_motion()
+ try:
+ self.motion_detected = self.sync.motion[self.name]
+ except KeyError:
+ self.motion_detected = False
+
clip_addr = None
- if self.last_record:
- clip_addr = self.sync.all_clips[self.name][self.last_record[0]]
+ if self.name in self.sync.last_record:
+ clip_addr = self.sync.last_record[self.name]['clip']
+ self.last_record = self.sync.last_record[self.name]['time']
self.clip = "{}{}".format(self.sync.urls.base_url,
clip_addr)
@@ -158,25 +159,6 @@ class BlinkCamera():
stream=True,
json=False)
- def check_for_motion(self):
- """Check if motion detected.."""
- try:
- records = sorted(self.sync.record_dates[self.name])
- new_clip = records.pop()
- if new_clip not in self.last_record and self.last_record:
- self.motion_detected = True
- self.last_record.insert(0, new_clip)
- if len(self.last_record) > MAX_CLIPS:
- self.last_record.pop()
- elif not self.last_record:
- self.last_record.insert(0, new_clip)
- self.motion_detected = False
- else:
- self.motion_detected = False
- except KeyError:
- _LOGGER.info("Could not extract clip info from camera %s",
- self.name)
-
def image_to_file(self, path):
"""
Write image to file.
diff --git a/blinkpy/helpers/constants.py b/blinkpy/helpers/constants.py
index 3eb1d82..9ebcf7d 100644
--- a/blinkpy/helpers/constants.py
+++ b/blinkpy/helpers/constants.py
@@ -54,3 +54,8 @@ LOGIN_BACKUP_URL = "https://{}.{}/login".format('rest.piri', BLINK_URL)
Dictionaries
'''
ONLINE = {'online': True, 'offline': False}
+
+'''
+OTHER
+'''
+TIMESTAMP_FORMAT = '%Y-%m-%dT%H:%M:%S%Z'
diff --git a/blinkpy/helpers/util.py b/blinkpy/helpers/util.py
index 4bcc497..6e14cc5 100644
--- a/blinkpy/helpers/util.py
+++ b/blinkpy/helpers/util.py
@@ -1,14 +1,22 @@
"""Useful functions for blinkpy."""
import logging
+import time
from requests import Request, Session, exceptions
-from blinkpy.helpers.constants import BLINK_URL
+from blinkpy.helpers.constants import BLINK_URL, TIMESTAMP_FORMAT
import blinkpy.helpers.errors as ERROR
_LOGGER = logging.getLogger(__name__)
+def get_time(time_to_convert=None):
+ """Create blink-compatible timestamp."""
+ if time_to_convert is None:
+ time_to_convert = time.time()
+ return time.strftime(TIMESTAMP_FORMAT, time.localtime(time_to_convert))
+
+
def merge_dicts(dict_a, dict_b):
"""Merge two dictionaries into one."""
duplicates = [val for val in dict_a if val in dict_b]
diff --git a/blinkpy/sync_module.py b/blinkpy/sync_module.py
index 75c02c1..9e5bc42 100644
--- a/blinkpy/sync_module.py
+++ b/blinkpy/sync_module.py
@@ -32,11 +32,10 @@ class BlinkSyncModule():
self.summary = None
self.homescreen = None
self.network_info = None
- self.record_dates = {}
- self.videos = {}
self.events = []
self.cameras = CaseInsensitiveDict({})
- self.all_clips = {}
+ self.motion = {}
+ self.last_record = {}
@property
def attributes(self):
@@ -85,22 +84,17 @@ class BlinkSyncModule():
self.status = self.summary['status']
self.events = self.get_events()
-
self.homescreen = api.request_homescreen(self.blink)
-
self.network_info = api.request_network_status(self.blink,
self.network_id)
+ self.check_new_videos()
camera_info = self.get_camera_info()
for camera_config in camera_info:
name = camera_config['name']
self.cameras[name] = BlinkCamera(self)
-
- self.videos = self.get_videos()
- for camera_config in camera_info:
- name = camera_config['name']
- if name in self.cameras:
- self.cameras[name].update(camera_config, force_cache=True)
+ self.motion[name] = False
+ self.cameras[name].update(camera_config, force_cache=True)
def get_events(self):
"""Retrieve events from server."""
@@ -115,73 +109,38 @@ class BlinkSyncModule():
def refresh(self, force_cache=False):
"""Get all blink cameras and pulls their most recent status."""
self.events = self.get_events()
- self.videos = self.get_videos()
self.homescreen = api.request_homescreen(self.blink)
self.network_info = api.request_network_status(self.blink,
self.network_id)
camera_info = self.get_camera_info()
+ self.check_new_videos()
for camera_config in camera_info:
name = camera_config['name']
self.cameras[name].update(camera_config, force_cache=force_cache)
- def get_videos(self, start_page=0, end_page=1):
- """
- Retrieve last recorded videos per camera.
-
- :param start_page: Page to start reading from on blink servers
- (defaults to 0)
- :param end_page: Page to stop reading from (defaults to 1)
- """
- videos = list()
- all_dates = dict()
-
- for page_num in range(start_page, end_page + 1):
- this_page = api.request_videos(self.blink, page=page_num)
- if not this_page:
- break
- elif 'message' in this_page:
- _LOGGER.warning("Could not retrieve videos. Message: %s",
- this_page['message'])
- break
-
- videos.append(this_page)
- _LOGGER.debug("Getting videos from page %s through %s",
- start_page,
- end_page)
- for page in videos:
- for entry in page:
- try:
- camera_name = entry['camera_name']
- clip_addr = entry['address']
- thumb_addr = entry['thumbnail']
- except TypeError:
- _LOGGER.warning("Could not extract video information.")
- break
- clip_date = clip_addr.split('_')[-6:]
- clip_date = '_'.join(clip_date)
- clip_date = clip_date.split('.')[0]
- try:
- self.all_clips[camera_name][clip_date] = clip_addr
- except KeyError:
- self.all_clips[camera_name] = {clip_date: clip_addr}
-
- if camera_name not in all_dates:
- all_dates[camera_name] = list()
- all_dates[camera_name].append(clip_date)
- try:
- self.videos[camera_name].append(
- {
- 'clip': clip_addr,
- 'thumb': thumb_addr,
- }
- )
- except KeyError:
- self.videos[camera_name] = [
- {
- 'clip': clip_addr,
- 'thumb': thumb_addr,
- }
- ]
- self.record_dates = all_dates
- _LOGGER.debug("Retrieved a total of %s records", len(all_dates))
- return self.videos
+ def check_new_videos(self):
+ """Check if new videos since last refresh."""
+ resp = api.request_videos(self.blink,
+ time=self.blink.last_refresh,
+ page=0)
+
+ for camera in self.cameras.keys():
+ self.motion[camera] = False
+
+ try:
+ info = resp['videos']
+ except (KeyError, TypeError):
+ _LOGGER.warning("Could not check for motion. Response: %s", resp)
+ return False
+
+ for entry in info:
+ try:
+ name = entry['camera_name']
+ clip = entry['address']
+ timestamp = entry['created_at']
+ self.motion[name] = True
+ self.last_record[name] = {'clip': clip, 'time': timestamp}
+ except KeyError:
+ _LOGGER.debug("No new videos since last refresh.")
+
+ return True
|
fronzbot/blinkpy
|
66a66c9bd301d17c65dbe4d850c5804f0eceda0e
|
diff --git a/tests/test_blinkpy.py b/tests/test_blinkpy.py
index 6676fbd..001c200 100644
--- a/tests/test_blinkpy.py
+++ b/tests/test_blinkpy.py
@@ -138,9 +138,13 @@ class TestBlinkSetup(unittest.TestCase):
now = self.blink.refresh_rate + 1
mock_time.return_value = now
self.assertEqual(self.blink.last_refresh, None)
- result = self.blink.check_if_ok_to_update()
+ self.assertEqual(self.blink.check_if_ok_to_update(), True)
+ self.assertEqual(self.blink.last_refresh, None)
+ with mock.patch('blinkpy.sync_module.BlinkSyncModule.refresh',
+ return_value=True):
+ self.blink.refresh()
+
self.assertEqual(self.blink.last_refresh, now)
- self.assertEqual(result, True)
self.assertEqual(self.blink.check_if_ok_to_update(), False)
self.assertEqual(self.blink.last_refresh, now)
diff --git a/tests/test_cameras.py b/tests/test_cameras.py
index a340228..aae0b5d 100644
--- a/tests/test_cameras.py
+++ b/tests/test_cameras.py
@@ -11,7 +11,7 @@ from unittest import mock
from blinkpy import blinkpy
from blinkpy.helpers.util import create_session, BlinkURLHandler
from blinkpy.sync_module import BlinkSyncModule
-from blinkpy.camera import BlinkCamera, MAX_CLIPS
+from blinkpy.camera import BlinkCamera
import tests.mock_responses as mresp
USERNAME = 'foobar'
@@ -55,32 +55,6 @@ class TestBlinkCameraSetup(unittest.TestCase):
"""Clean up after test."""
self.blink = None
- def test_check_for_motion(self, mock_sess):
- """Test check for motion function."""
- self.assertEqual(self.camera.last_record, [])
- self.assertEqual(self.camera.motion_detected, None)
- self.camera.sync.record_dates = {'foobar': [1, 3, 2, 4]}
- self.camera.check_for_motion()
- self.assertEqual(self.camera.last_record, [4])
- self.assertEqual(self.camera.motion_detected, False)
- self.camera.sync.record_dates = {'foobar': [7, 1, 3, 4]}
- self.camera.check_for_motion()
- self.assertEqual(self.camera.last_record, [7, 4])
- self.assertEqual(self.camera.motion_detected, True)
- self.camera.check_for_motion()
- self.assertEqual(self.camera.last_record, [7, 4])
- self.assertEqual(self.camera.motion_detected, False)
-
- def test_max_motion_clips(self, mock_sess):
- """Test that we only maintain certain number of records."""
- for i in range(0, MAX_CLIPS):
- self.camera.last_record.append(i)
- self.camera.sync.record_dates['foobar'] = [MAX_CLIPS+2]
- self.assertEqual(len(self.camera.last_record), MAX_CLIPS)
- self.camera.check_for_motion()
- self.assertEqual(self.camera.motion_detected, True)
- self.assertEqual(len(self.camera.last_record), MAX_CLIPS)
-
def test_camera_update(self, mock_sess):
"""Test that we can properly update camera properties."""
config = {
@@ -96,7 +70,12 @@ class TestBlinkCameraSetup(unittest.TestCase):
'thumbnail': '/thumb',
}
self.camera.last_record = ['1']
- self.camera.sync.all_clips = {'new': {'1': '/test.mp4'}}
+ self.camera.sync.last_record = {
+ 'new': {
+ 'clip': '/test.mp4',
+ 'time': '1970-01-01T00:00:00'
+ }
+ }
mock_sess.side_effect = [
mresp.MockResponse({'temp': 71}, 200),
'test',
@@ -128,8 +107,12 @@ class TestBlinkCameraSetup(unittest.TestCase):
'barfoo'
]
self.camera.last_record = ['1']
- self.camera.sync.record_dates['new'] = ['1']
- self.camera.sync.all_clips = {'new': {'1': '/test.mp4'}}
+ self.camera.sync.last_record = {
+ 'new': {
+ 'clip': '/test.mp4',
+ 'time': '1970-01-01T00:00:00'
+ }
+ }
config = {
'name': 'new',
'camera_id': 1234,
@@ -159,8 +142,6 @@ class TestBlinkCameraSetup(unittest.TestCase):
"""Tests that thumbnail is 'None' if none found."""
mock_sess.return_value = 'foobar'
self.camera.last_record = ['1']
- self.camera.sync.record_dates['new'] = ['1']
- self.camera.sync.all_clips = {'new': {'1': '/test.mp4'}}
config = {
'name': 'new',
'camera_id': 1234,
@@ -179,6 +160,7 @@ class TestBlinkCameraSetup(unittest.TestCase):
with self.assertLogs() as logrecord:
self.camera.update(config)
self.assertEqual(self.camera.thumbnail, None)
+ self.assertEqual(self.camera.last_record, ['1'])
self.assertEqual(
logrecord.output,
["ERROR:blinkpy.camera:Could not retrieve calibrated temperature.",
diff --git a/tests/test_sync_module.py b/tests/test_sync_module.py
index 7c623d1..f1a5848 100644
--- a/tests/test_sync_module.py
+++ b/tests/test_sync_module.py
@@ -42,40 +42,47 @@ class TestBlinkSyncModule(unittest.TestCase):
mock_resp.return_value = {'devicestatus': True}
self.assertEqual(self.blink.sync['test'].get_camera_info(), True)
- def test_get_videos_one_page(self, mock_resp):
- """Test video access."""
- mock_resp.return_value = [
- {
- 'camera_name': 'foobar',
- 'address': '/test/clip_1900_01_01_12_00_00AM.mp4',
- 'thumbnail': '/test/thumb'
- }
- ]
- expected_videos = {'foobar': [
- {'clip': '/test/clip_1900_01_01_12_00_00AM.mp4',
- 'thumb': '/test/thumb'}]}
- expected_recs = {'foobar': ['1900_01_01_12_00_00AM']}
- expected_clips = {'foobar': {
- '1900_01_01_12_00_00AM': '/test/clip_1900_01_01_12_00_00AM.mp4'}}
- self.blink.sync['test'].get_videos(start_page=0, end_page=0)
- self.assertEqual(self.blink.sync['test'].videos, expected_videos)
- self.assertEqual(self.blink.sync['test'].record_dates, expected_recs)
- self.assertEqual(self.blink.sync['test'].all_clips, expected_clips)
+ def test_check_new_videos(self, mock_resp):
+ """Test recent video response."""
+ mock_resp.return_value = {
+ 'videos': [{
+ 'camera_name': 'foo',
+ 'address': '/foo/bar.mp4',
+ 'created_at': '1970-01-01T00:00:00+0:00'
+ }]
+ }
+ sync_module = self.blink.sync['test']
+ sync_module.cameras = {'foo': None}
+ self.assertEqual(sync_module.motion, {})
+ self.assertTrue(sync_module.check_new_videos())
+ self.assertEqual(sync_module.last_record['foo'],
+ {'clip': '/foo/bar.mp4',
+ 'time': '1970-01-01T00:00:00+0:00'})
+ self.assertEqual(sync_module.motion, {'foo': True})
+ mock_resp.return_value = {'videos': []}
+ self.assertTrue(sync_module.check_new_videos())
+ self.assertEqual(sync_module.motion, {'foo': False})
+ self.assertEqual(sync_module.last_record['foo'],
+ {'clip': '/foo/bar.mp4',
+ 'time': '1970-01-01T00:00:00+0:00'})
- def test_get_videos_multi_page(self, mock_resp):
- """Test video access with multiple pages."""
- mock_resp.return_value = [
- {
- 'camera_name': 'test',
- 'address': '/foo/bar_1900_01_01_12_00_00AM.mp4',
- 'thumbnail': '/foobar'
- }
- ]
- self.blink.sync['test'].get_videos()
- self.assertEqual(mock_resp.call_count, 2)
- mock_resp.reset_mock()
- self.blink.sync['test'].get_videos(start_page=0, end_page=9)
- self.assertEqual(mock_resp.call_count, 10)
+ def test_check_new_videos_failed(self, mock_resp):
+ """Test method when response is unexpected."""
+ mock_resp.side_effect = [None, 'just a string', {}]
+ sync_module = self.blink.sync['test']
+ sync_module.cameras = {'foo': None}
+
+ sync_module.motion['foo'] = True
+ self.assertFalse(sync_module.check_new_videos())
+ self.assertFalse(sync_module.motion['foo'])
+
+ sync_module.motion['foo'] = True
+ self.assertFalse(sync_module.check_new_videos())
+ self.assertFalse(sync_module.motion['foo'])
+
+ sync_module.motion['foo'] = True
+ self.assertFalse(sync_module.check_new_videos())
+ self.assertFalse(sync_module.motion['foo'])
def test_sync_start(self, mock_resp):
"""Test sync start function."""
@@ -88,9 +95,8 @@ class TestBlinkSyncModule(unittest.TestCase):
{'event': True},
{},
{},
- {'devicestatus': {}},
None,
- None
+ {'devicestatus': {}},
]
self.blink.sync['test'].start()
self.assertEqual(self.blink.sync['test'].name, 'test')
|
Video endpoint not working
**Describe the bug**
Video api endpoint changed
**To Reproduce**
Steps to reproduce the behavior:
1. Log in
2. Retrieve token and network ids
3. Attempt to get list of videos, platform throws exception and fails
**Expected behavior**
- Be able to extract videos from correct api endpoint
- do not stall platform initialization due to video api endpoint changing
**Home Assistant version (if applicable):** 0.85.1
**`blinkpy` version (not needed if filling out Home Assistant version):** 0.11.1
|
0.0
|
66a66c9bd301d17c65dbe4d850c5804f0eceda0e
|
[
"tests/test_blinkpy.py::TestBlinkSetup::test_throttle",
"tests/test_cameras.py::TestBlinkCameraSetup::test_camera_update",
"tests/test_cameras.py::TestBlinkCameraSetup::test_no_thumbnails",
"tests/test_cameras.py::TestBlinkCameraSetup::test_thumbnail_not_in_info",
"tests/test_sync_module.py::TestBlinkSyncModule::test_check_new_videos",
"tests/test_sync_module.py::TestBlinkSyncModule::test_check_new_videos_failed",
"tests/test_sync_module.py::TestBlinkSyncModule::test_sync_start"
] |
[
"tests/test_blinkpy.py::TestBlinkSetup::test_authentication",
"tests/test_blinkpy.py::TestBlinkSetup::test_bad_request",
"tests/test_blinkpy.py::TestBlinkSetup::test_initialization",
"tests/test_blinkpy.py::TestBlinkSetup::test_manual_login",
"tests/test_blinkpy.py::TestBlinkSetup::test_multiple_networks",
"tests/test_blinkpy.py::TestBlinkSetup::test_multiple_onboarded_networks",
"tests/test_blinkpy.py::TestBlinkSetup::test_no_auth_header",
"tests/test_blinkpy.py::TestBlinkSetup::test_no_credentials",
"tests/test_blinkpy.py::TestBlinkSetup::test_reauthorization_attempt",
"tests/test_blinkpy.py::TestBlinkSetup::test_sync_case_insensitive_dict",
"tests/test_cameras.py::TestBlinkCameraSetup::test_no_video_clips",
"tests/test_sync_module.py::TestBlinkSyncModule::test_get_camera_info",
"tests/test_sync_module.py::TestBlinkSyncModule::test_get_events"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2019-01-25 19:04:28+00:00
|
mit
| 2,402 |
|
fronzbot__blinkpy-174
|
diff --git a/blinkpy/camera.py b/blinkpy/camera.py
index 7b05b93..8b904f5 100644
--- a/blinkpy/camera.py
+++ b/blinkpy/camera.py
@@ -41,6 +41,7 @@ class BlinkCamera():
'temperature_c': self.temperature_c,
'temperature_calibrated': self.temperature_calibrated,
'battery': self.battery,
+ 'battery_voltage': self.battery_voltage,
'thumbnail': self.thumbnail,
'video': self.clip,
'motion_enabled': self.motion_enabled,
@@ -54,8 +55,8 @@ class BlinkCamera():
@property
def battery(self):
- """Return battery level as percentage."""
- return round(self.battery_voltage / 180 * 100)
+ """Return battery as string."""
+ return self.battery_state
@property
def temperature_c(self):
|
fronzbot/blinkpy
|
c10fb432f7703066ac8b503c0cbc15ac1034b4a1
|
diff --git a/tests/test_cameras.py b/tests/test_cameras.py
index 866a2a0..17f6f64 100644
--- a/tests/test_cameras.py
+++ b/tests/test_cameras.py
@@ -87,7 +87,7 @@ class TestBlinkCameraSetup(unittest.TestCase):
self.assertEqual(self.camera.network_id, '5678')
self.assertEqual(self.camera.serial, '12345678')
self.assertEqual(self.camera.motion_enabled, False)
- self.assertEqual(self.camera.battery, 50)
+ self.assertEqual(self.camera.battery, 'ok')
self.assertEqual(self.camera.temperature, 68)
self.assertEqual(self.camera.temperature_c, 20)
self.assertEqual(self.camera.temperature_calibrated, 71)
|
Battery percentage reported is incorrect
**Describe the bug**
The current way of calculating battery percentage is completely incorrect (I don't really know what I was thinking when I implemented it). It takes current battery voltage divided by what the voltage should be when full....which is not even close to the correct calculation.
**Possible solution**
I'm not sure we have any good hooks to calculate battery percentage, so we may just have to use the standard "OK" or "Replace" keywords, which suck but it is what it is. We can still, perhaps, report the battery voltage... but I'm not sure how useful that actually is.
|
0.0
|
c10fb432f7703066ac8b503c0cbc15ac1034b4a1
|
[
"tests/test_cameras.py::TestBlinkCameraSetup::test_camera_update"
] |
[
"tests/test_cameras.py::TestBlinkCameraSetup::test_no_thumbnails",
"tests/test_cameras.py::TestBlinkCameraSetup::test_no_video_clips",
"tests/test_cameras.py::TestBlinkCameraSetup::test_thumbnail_not_in_info"
] |
{
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
}
|
2019-05-18 16:43:23+00:00
|
mit
| 2,403 |
|
fronzbot__blinkpy-222
|
diff --git a/blinkpy/helpers/errors.py b/blinkpy/helpers/errors.py
index a3b89b3..b81404b 100644
--- a/blinkpy/helpers/errors.py
+++ b/blinkpy/helpers/errors.py
@@ -11,3 +11,5 @@ AUTH_TOKEN = (
"Authentication header incorrect. Are you sure you received your token?"
)
REQUEST = (4, "Cannot perform request (get/post type incorrect)")
+
+BLINK_ERRORS = [101, 400, 404]
diff --git a/blinkpy/helpers/util.py b/blinkpy/helpers/util.py
index 84e2816..cff1187 100644
--- a/blinkpy/helpers/util.py
+++ b/blinkpy/helpers/util.py
@@ -86,16 +86,21 @@ def http_req(blink, url='http://example.com', data=None, headers=None,
try:
response = blink.session.send(prepped, stream=stream)
if json_resp and 'code' in response.json():
- if is_retry:
+ resp_dict = response.json()
+ code = resp_dict['code']
+ message = resp_dict['message']
+ if is_retry and code in ERROR.BLINK_ERRORS:
_LOGGER.error("Cannot obtain new token for server auth.")
return None
- else:
+ elif code in ERROR.BLINK_ERRORS:
headers = attempt_reauthorization(blink)
if not headers:
raise exceptions.ConnectionError
return http_req(blink, url=url, data=data, headers=headers,
reqtype=reqtype, stream=stream,
json_resp=json_resp, is_retry=True)
+ _LOGGER.warning("Response from server: %s - %s", code, message)
+
except (exceptions.ConnectionError, exceptions.Timeout):
_LOGGER.info("Cannot connect to server with url %s.", url)
if not is_retry:
diff --git a/codecov.yml b/codecov.yml
new file mode 100644
index 0000000..631a790
--- /dev/null
+++ b/codecov.yml
@@ -0,0 +1,13 @@
+codecov:
+ branch: dev
+coverage:
+ status:
+ project:
+ default:
+ threshold: 0.02
+
+comment: true
+require_ci_to_pass: yes
+range: 65..90
+round: down
+precision: 1
diff --git a/tox.ini b/tox.ini
index f1b8dfc..1cb3c1f 100644
--- a/tox.ini
+++ b/tox.ini
@@ -8,7 +8,7 @@ setenv =
LANG=en_US.UTF-8
PYTHONPATH = {toxinidir}
commands =
- pytest --timeout=9 --durations=10
+ pytest --timeout=9 --durations=10 --cov=blinkpy --cov-report term-missing {posargs}
deps =
-r{toxinidir}/requirements.txt
-r{toxinidir}/requirements_test.txt
|
fronzbot/blinkpy
|
800ddeaf7abc9e0908cf4505afa9393dabbb9889
|
diff --git a/tests/test_blinkpy.py b/tests/test_blinkpy.py
index 613ac23..686641c 100644
--- a/tests/test_blinkpy.py
+++ b/tests/test_blinkpy.py
@@ -123,8 +123,8 @@ class TestBlinkSetup(unittest.TestCase):
def test_bad_request(self, mock_sess):
"""Check that we raise an Exception with a bad request."""
self.blink.session = create_session()
- explog = ("ERROR:blinkpy.helpers.util:"
- "Cannot obtain new token for server auth.")
+ explog = ("WARNING:blinkpy.helpers.util:"
+ "Response from server: 200 - foo")
with self.assertRaises(BlinkException):
http_req(self.blink, reqtype='bad')
|
No Cameras Enabled for Motion
**Describe the bug**
When arming or disarming the sync module, the message "No Cameras Enabled for Motion" is seen in the Blink app if there are no cameras enabled. This message is returned in the API but is not handled. Instead "Cannot obtain new token for server auth." is logged as an error and nothing is returned. The request does succeed though.
**To Reproduce**
Steps to reproduce the behavior:
1. Disable all individual cameras
2. Issue a request for the sync module to disarm
**Expected behavior**
The return in this case is: `{'message': 'No Cameras Enabled for Motion', 'code': 304}`. I would expect that this message is used as the display (info only) and that the return is as per a successful call.
**Home Assistant version (if applicable):** N/A
**`blinkpy` version (not needed if filling out Home Assistant version):** 0.14.2
|
0.0
|
800ddeaf7abc9e0908cf4505afa9393dabbb9889
|
[
"tests/test_blinkpy.py::TestBlinkSetup::test_bad_request"
] |
[
"tests/test_blinkpy.py::TestBlinkSetup::test_authentication",
"tests/test_blinkpy.py::TestBlinkSetup::test_cred_file",
"tests/test_blinkpy.py::TestBlinkSetup::test_exit_on_bad_json",
"tests/test_blinkpy.py::TestBlinkSetup::test_exit_on_missing_json",
"tests/test_blinkpy.py::TestBlinkSetup::test_get_cameras",
"tests/test_blinkpy.py::TestBlinkSetup::test_get_cameras_failure",
"tests/test_blinkpy.py::TestBlinkSetup::test_initialization",
"tests/test_blinkpy.py::TestBlinkSetup::test_manual_login",
"tests/test_blinkpy.py::TestBlinkSetup::test_multiple_networks",
"tests/test_blinkpy.py::TestBlinkSetup::test_multiple_onboarded_networks",
"tests/test_blinkpy.py::TestBlinkSetup::test_no_auth_header",
"tests/test_blinkpy.py::TestBlinkSetup::test_no_cred_file",
"tests/test_blinkpy.py::TestBlinkSetup::test_no_credentials",
"tests/test_blinkpy.py::TestBlinkSetup::test_reauthorization_attempt",
"tests/test_blinkpy.py::TestBlinkSetup::test_sync_case_insensitive_dict",
"tests/test_blinkpy.py::TestBlinkSetup::test_throttle",
"tests/test_blinkpy.py::TestBlinkSetup::test_unexpected_login"
] |
{
"failed_lite_validators": [
"has_added_files",
"has_many_modified_files",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-04-15 15:11:42+00:00
|
mit
| 2,404 |
|
fronzbot__blinkpy-268
|
diff --git a/blinkpy/auth.py b/blinkpy/auth.py
index 778daf3..2f07048 100644
--- a/blinkpy/auth.py
+++ b/blinkpy/auth.py
@@ -111,12 +111,14 @@ class Auth:
if not json_resp:
return response
- json_data = response.json()
try:
+ json_data = response.json()
if json_data["code"] in ERROR.BLINK_ERRORS:
raise exceptions.ConnectionError
except KeyError:
pass
+ except (AttributeError, ValueError):
+ raise BlinkBadResponse
return json_data
@@ -161,6 +163,8 @@ class Auth:
)
except (TokenRefreshFailed, LoginError):
_LOGGER.error("Endpoint %s failed. Unable to refresh login tokens", url)
+ except BlinkBadResponse:
+ _LOGGER.error("Expected json response, but received: %s", response)
_LOGGER.error("Endpoint %s failed", url)
return None
@@ -192,3 +196,7 @@ class TokenRefreshFailed(Exception):
class LoginError(Exception):
"""Class to throw failed login exception."""
+
+
+class BlinkBadResponse(Exception):
+ """Class to throw bad json response exception."""
|
fronzbot/blinkpy
|
bc85779272e17708f0f4f85d472ea458907bc4c9
|
diff --git a/tests/test_auth.py b/tests/test_auth.py
index 88f9d7d..8086267 100644
--- a/tests/test_auth.py
+++ b/tests/test_auth.py
@@ -3,7 +3,7 @@
import unittest
from unittest import mock
from requests import exceptions
-from blinkpy.auth import Auth, LoginError, TokenRefreshFailed
+from blinkpy.auth import Auth, LoginError, TokenRefreshFailed, BlinkBadResponse
import blinkpy.helpers.constants as const
import tests.mock_responses as mresp
@@ -100,6 +100,11 @@ class TestAuth(unittest.TestCase):
fake_resp = "foobar"
self.assertEqual(self.auth.validate_response(fake_resp, False), "foobar")
+ def test_response_bad_json(self):
+ """Check response when not json but expecting json."""
+ with self.assertRaises(BlinkBadResponse):
+ self.auth.validate_response(None, True)
+
def test_header(self):
"""Test header data."""
self.auth.token = "bar"
|
Trouble working with 0.16-RC0 - New Login Methods
Hi, I have the new RC up and running but seem to be having trouble getting it to work. I setup a new routine to basically get and generate a new credential file:
from blinkpy.blinkpy import Blink
from blinkpy.auth import Auth
from blinkpy.helpers.util import json_load
blink = Blink()
#auth = Auth(json_load("c:\Blinkpy\cred.json"))
auth = Auth({"username":"MY EMAIL", "password":"MY PASS"}, no_prompt=False)
blink.auth = auth
blink.start()
blink.save("C:\Blinkpy\cred.json")
On first run it works, I get a verification code, plug it in and my cred.json file is generated.
Then I go to run another method to enable/disable a bunch of cameras, like:
from blinkpy.blinkpy import Blink
from blinkpy.auth import Auth
from blinkpy.helpers.util import json_load
import time
blink = Blink()
auth = Auth(json_load("c:\Blinkpy\cred.json"))
blink.auth = auth
blink.start()
blink.save("C:\Blinkpy\cred.json") <- I also tried to save the cred file at the end, which way shoudl I do it?
blink.cameras["Garage"].set_motion_detect(enable=False)
time.sleep(4)
blink.cameras["Mud Room"].set_motion_detect(enable=False)
time.sleep(4)
blink.cameras["Kitchen"].set_motion_detect(enable=False)
time.sleep(4)
blink.cameras["Dining"].set_motion_detect(enable=False)
time.sleep(4)
... A bunch of other cameras.
It may work once but eventually fails on blink.start or on one of the camera commands to disable motion with:
C:\Blinkpy>python disable_inside.py
Traceback (most recent call last):
File "disable_inside.py", line 9, in <module>
blink.start()
File "C:\Python38\lib\site-packages\blinkpy\blinkpy.py", line 109, in start
return self.setup_post_verify()
File "C:\Python38\lib\site-packages\blinkpy\blinkpy.py", line 121, in setup_post_verify
self.setup_networks()
File "C:\Python38\lib\site-packages\blinkpy\blinkpy.py", line 176, in setup_networks
response = api.request_networks(self)
File "C:\Python38\lib\site-packages\blinkpy\api.py", line 62, in request_networks
return http_get(blink, url)
File "C:\Python38\lib\site-packages\blinkpy\api.py", line 272, in http_get
return blink.auth.query(
File "C:\Python38\lib\site-packages\blinkpy\auth.py", line 147, in query
return self.validate_response(response, json_resp)
File "C:\Python38\lib\site-packages\blinkpy\auth.py", line 114, in validate_response
json_data = response.json()
File "C:\Python38\lib\site-packages\requests\models.py", line 898, in json
return complexjson.loads(self.text, **kwargs)
File "C:\Python38\lib\json\__init__.py", line 357, in loads
return _default_decoder.decode(s)
File "C:\Python38\lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Python38\lib\json\decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
Then if I try to regenerate my cred file it will fail with "Cannot setup Blink platform", if I wait a while it eventually works then the process starts all over again, I get a good run, then it fails mid-stream, then I have to wait a while and regen my cred file.
Am I doing something wrong? Should I generate a cred file first (asking for the code from Blink), save the cred file, then reference it in my future runs? Also should I be resaving my cred file after each run?
Thanks for the help!
|
0.0
|
bc85779272e17708f0f4f85d472ea458907bc4c9
|
[
"tests/test_auth.py::TestAuth::test_bad_response_code",
"tests/test_auth.py::TestAuth::test_barebones_init",
"tests/test_auth.py::TestAuth::test_check_key_required",
"tests/test_auth.py::TestAuth::test_empty_init",
"tests/test_auth.py::TestAuth::test_full_init",
"tests/test_auth.py::TestAuth::test_good_response_code",
"tests/test_auth.py::TestAuth::test_header",
"tests/test_auth.py::TestAuth::test_header_no_token",
"tests/test_auth.py::TestAuth::test_login",
"tests/test_auth.py::TestAuth::test_login_bad_response",
"tests/test_auth.py::TestAuth::test_query_retry",
"tests/test_auth.py::TestAuth::test_refresh_token",
"tests/test_auth.py::TestAuth::test_refresh_token_failed",
"tests/test_auth.py::TestAuth::test_response_bad_json",
"tests/test_auth.py::TestAuth::test_response_not_json",
"tests/test_auth.py::TestAuth::test_send_auth_key",
"tests/test_auth.py::TestAuth::test_send_auth_key_fail"
] |
[] |
{
"failed_lite_validators": [
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-05-26 20:52:06+00:00
|
mit
| 2,405 |
|
fronzbot__blinkpy-272
|
diff --git a/blinkpy/blinkpy.py b/blinkpy/blinkpy.py
index 1d60d1e..671b380 100644
--- a/blinkpy/blinkpy.py
+++ b/blinkpy/blinkpy.py
@@ -152,7 +152,7 @@ class Blink:
{"name": camera["name"], "id": camera["id"]}
)
return all_cameras
- except KeyError:
+ except (KeyError, TypeError):
_LOGGER.error("Unable to retrieve cameras from response %s", response)
raise BlinkSetupError
@@ -176,7 +176,7 @@ class Blink:
response = api.request_networks(self)
try:
self.networks = response["summary"]
- except KeyError:
+ except (KeyError, TypeError):
raise BlinkSetupError
def setup_network_ids(self):
@@ -250,8 +250,8 @@ class Blink:
try:
result = response["media"]
if not result:
- raise IndexError
- except (KeyError, IndexError):
+ raise KeyError
+ except (KeyError, TypeError):
_LOGGER.info("No videos found on page %s. Exiting.", page)
break
diff --git a/blinkpy/sync_module.py b/blinkpy/sync_module.py
index 4d5fe9b..1b8d7cb 100644
--- a/blinkpy/sync_module.py
+++ b/blinkpy/sync_module.py
@@ -149,14 +149,11 @@ class BlinkSyncModule:
def get_network_info(self):
"""Retrieve network status."""
- is_errored = False
self.network_info = api.request_network_status(self.blink, self.network_id)
try:
- is_errored = self.network_info["network"]["sync_module_error"]
- except KeyError:
- is_errored = True
-
- if is_errored:
+ if self.network_info["network"]["sync_module_error"]:
+ raise KeyError
+ except (TypeError, KeyError):
self.available = False
return False
return True
|
fronzbot/blinkpy
|
38fed26742e56e97c90b5103d772a9ca45a1a967
|
diff --git a/tests/test_blinkpy.py b/tests/test_blinkpy.py
index 2d980ff..cd7279f 100644
--- a/tests/test_blinkpy.py
+++ b/tests/test_blinkpy.py
@@ -106,6 +106,9 @@ class TestBlinkSetup(unittest.TestCase):
mock_home.return_value = {}
with self.assertRaises(BlinkSetupError):
self.blink.setup_camera_list()
+ mock_home.return_value = None
+ with self.assertRaises(BlinkSetupError):
+ self.blink.setup_camera_list()
def test_setup_urls(self):
"""Check setup of URLS."""
@@ -132,6 +135,9 @@ class TestBlinkSetup(unittest.TestCase):
mock_networks.return_value = {}
with self.assertRaises(BlinkSetupError):
self.blink.setup_networks()
+ mock_networks.return_value = None
+ with self.assertRaises(BlinkSetupError):
+ self.blink.setup_networks()
@mock.patch("blinkpy.blinkpy.Auth.send_auth_key")
def test_setup_prompt_2fa(self, mock_key):
diff --git a/tests/test_sync_module.py b/tests/test_sync_module.py
index 6dbc04e..baf2bb1 100644
--- a/tests/test_sync_module.py
+++ b/tests/test_sync_module.py
@@ -78,7 +78,7 @@ class TestBlinkSyncModule(unittest.TestCase):
self.assertEqual(self.blink.sync["test"].get_camera_info("1234"), "foobar")
def test_get_camera_info_fail(self, mock_resp):
- """Test hadnling of failed get camera info function."""
+ """Test handling of failed get camera info function."""
mock_resp.return_value = None
self.assertEqual(self.blink.sync["test"].get_camera_info("1"), [])
mock_resp.return_value = {}
@@ -86,6 +86,24 @@ class TestBlinkSyncModule(unittest.TestCase):
mock_resp.return_value = {"camera": None}
self.assertEqual(self.blink.sync["test"].get_camera_info("1"), [])
+ def test_get_network_info(self, mock_resp):
+ """Test network retrieval."""
+ mock_resp.return_value = {"network": {"sync_module_error": False}}
+ self.assertTrue(self.blink.sync["test"].get_network_info())
+ mock_resp.return_value = {"network": {"sync_module_error": True}}
+ self.assertFalse(self.blink.sync["test"].get_network_info())
+
+ def test_get_network_info_failure(self, mock_resp):
+ """Test failed network retrieval."""
+ mock_resp.return_value = {}
+ self.blink.sync["test"].available = True
+ self.assertFalse(self.blink.sync["test"].get_network_info())
+ self.assertFalse(self.blink.sync["test"].available)
+ self.blink.sync["test"].available = True
+ mock_resp.return_value = None
+ self.assertFalse(self.blink.sync["test"].get_network_info())
+ self.assertFalse(self.blink.sync["test"].available)
+
def test_check_new_videos_startup(self, mock_resp):
"""Test that check_new_videos does not block startup."""
sync_module = self.blink.sync["test"]
|
'None' responses improperly handled
https://github.com/fronzbot/blinkpy/blob/38fed26742e56e97c90b5103d772a9ca45a1a967/blinkpy/blinkpy.py#L179
If a `None` response is received, need to catch a `TypeError` which seems to not be done anywhere. See also #267
|
0.0
|
38fed26742e56e97c90b5103d772a9ca45a1a967
|
[
"tests/test_blinkpy.py::TestBlinkSetup::test_setup_cameras_failure",
"tests/test_blinkpy.py::TestBlinkSetup::test_setup_networks_failure",
"tests/test_sync_module.py::TestBlinkSyncModule::test_get_network_info_failure"
] |
[
"tests/test_blinkpy.py::TestBlinkSetup::test_initialization",
"tests/test_blinkpy.py::TestBlinkSetup::test_merge_cameras",
"tests/test_blinkpy.py::TestBlinkSetup::test_multiple_networks",
"tests/test_blinkpy.py::TestBlinkSetup::test_multiple_onboarded_networks",
"tests/test_blinkpy.py::TestBlinkSetup::test_network_id_failure",
"tests/test_blinkpy.py::TestBlinkSetup::test_setup_cameras",
"tests/test_blinkpy.py::TestBlinkSetup::test_setup_networks",
"tests/test_blinkpy.py::TestBlinkSetup::test_setup_post_verify",
"tests/test_blinkpy.py::TestBlinkSetup::test_setup_post_verify_failure",
"tests/test_blinkpy.py::TestBlinkSetup::test_setup_prompt_2fa",
"tests/test_blinkpy.py::TestBlinkSetup::test_setup_urls",
"tests/test_blinkpy.py::TestBlinkSetup::test_setup_urls_failure",
"tests/test_blinkpy.py::TestBlinkSetup::test_sync_case_insensitive_dict",
"tests/test_blinkpy.py::TestBlinkSetup::test_throttle",
"tests/test_sync_module.py::TestBlinkSyncModule::test_bad_arm",
"tests/test_sync_module.py::TestBlinkSyncModule::test_bad_status",
"tests/test_sync_module.py::TestBlinkSyncModule::test_check_multiple_videos",
"tests/test_sync_module.py::TestBlinkSyncModule::test_check_new_videos",
"tests/test_sync_module.py::TestBlinkSyncModule::test_check_new_videos_failed",
"tests/test_sync_module.py::TestBlinkSyncModule::test_check_new_videos_old_date",
"tests/test_sync_module.py::TestBlinkSyncModule::test_check_new_videos_startup",
"tests/test_sync_module.py::TestBlinkSyncModule::test_check_no_motion_if_not_armed",
"tests/test_sync_module.py::TestBlinkSyncModule::test_get_camera_info",
"tests/test_sync_module.py::TestBlinkSyncModule::test_get_camera_info_fail",
"tests/test_sync_module.py::TestBlinkSyncModule::test_get_events",
"tests/test_sync_module.py::TestBlinkSyncModule::test_get_events_fail",
"tests/test_sync_module.py::TestBlinkSyncModule::test_get_network_info",
"tests/test_sync_module.py::TestBlinkSyncModule::test_missing_camera_info",
"tests/test_sync_module.py::TestBlinkSyncModule::test_summary_with_no_network_id",
"tests/test_sync_module.py::TestBlinkSyncModule::test_summary_with_only_network_id",
"tests/test_sync_module.py::TestBlinkSyncModule::test_sync_attributes",
"tests/test_sync_module.py::TestBlinkSyncModule::test_sync_start",
"tests/test_sync_module.py::TestBlinkSyncModule::test_unexpected_camera_info",
"tests/test_sync_module.py::TestBlinkSyncModule::test_unexpected_summary"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_issue_reference",
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-05-27 21:29:03+00:00
|
mit
| 2,406 |
|
fronzbot__blinkpy-274
|
diff --git a/blinkpy/auth.py b/blinkpy/auth.py
index 2f07048..b379406 100644
--- a/blinkpy/auth.py
+++ b/blinkpy/auth.py
@@ -5,7 +5,6 @@ from requests import Request, Session, exceptions
from blinkpy import api
from blinkpy.helpers import util
from blinkpy.helpers.constants import BLINK_URL, LOGIN_ENDPOINT
-from blinkpy.helpers import errors as ERROR
_LOGGER = logging.getLogger(__name__)
@@ -95,7 +94,10 @@ class Auth:
self.token = self.login_response["authtoken"]["authtoken"]
self.client_id = self.login_response["client"]["id"]
self.account_id = self.login_response["account"]["id"]
- except KeyError:
+ except LoginError:
+ _LOGGER.error("Login endpoint failed. Try again later.")
+ raise TokenRefreshFailed
+ except (TypeError, KeyError):
_LOGGER.error("Malformed login response: %s", self.login_response)
raise TokenRefreshFailed
return True
@@ -110,11 +112,12 @@ class Auth:
"""Check for valid response."""
if not json_resp:
return response
-
try:
- json_data = response.json()
- if json_data["code"] in ERROR.BLINK_ERRORS:
+ if response.status_code in [101, 401]:
+ raise UnauthorizedError
+ if response.status_code == 404:
raise exceptions.ConnectionError
+ json_data = response.json()
except KeyError:
pass
except (AttributeError, ValueError):
@@ -141,31 +144,42 @@ class Auth:
:param reqtype: Can be 'get' or 'post' (default: 'get')
:param stream: Stream response? True/FALSE
:param json_resp: Return JSON response? TRUE/False
- :param is_retry: Is this a retry attempt? True/FALSE
+ :param is_retry: Is this part of a re-auth attempt? True/FALSE
"""
req = self.prepare_request(url, headers, data, reqtype)
try:
response = self.session.send(req, stream=stream)
return self.validate_response(response, json_resp)
-
- except (exceptions.ConnectionError, exceptions.Timeout, TokenRefreshFailed):
+ except (exceptions.ConnectionError, exceptions.Timeout):
+ _LOGGER.error(
+ "Connection error. Endpoint %s possibly down or throttled. %s: %s",
+ url,
+ response.status_code,
+ response.reason,
+ )
+ except BlinkBadResponse:
+ _LOGGER.error(
+ "Expected json response from %s, but received: %s: %s",
+ url,
+ response.status_code,
+ response.reason,
+ )
+ except UnauthorizedError:
try:
if not is_retry:
self.refresh_token()
return self.query(
url=url,
data=data,
- headers=headers,
+ headers=self.header,
reqtype=reqtype,
stream=stream,
json_resp=json_resp,
is_retry=True,
)
- except (TokenRefreshFailed, LoginError):
- _LOGGER.error("Endpoint %s failed. Unable to refresh login tokens", url)
- except BlinkBadResponse:
- _LOGGER.error("Expected json response, but received: %s", response)
- _LOGGER.error("Endpoint %s failed", url)
+ _LOGGER.error("Unable to access %s after token refresh.", url)
+ except TokenRefreshFailed:
+ _LOGGER.error("Unable to refresh token.")
return None
def send_auth_key(self, blink, key):
@@ -200,3 +214,7 @@ class LoginError(Exception):
class BlinkBadResponse(Exception):
"""Class to throw bad json response exception."""
+
+
+class UnauthorizedError(Exception):
+ """Class to throw an unauthorized access error."""
diff --git a/blinkpy/blinkpy.py b/blinkpy/blinkpy.py
index 671b380..1d6d0f5 100644
--- a/blinkpy/blinkpy.py
+++ b/blinkpy/blinkpy.py
@@ -78,7 +78,6 @@ class Blink:
"""
if self.check_if_ok_to_update() or force:
if not self.available:
- self.auth.refresh_token()
self.setup_post_verify()
for sync_name, sync_module in self.sync.items():
diff --git a/blinkpy/helpers/errors.py b/blinkpy/helpers/errors.py
index 3f39086..e701f2c 100644
--- a/blinkpy/helpers/errors.py
+++ b/blinkpy/helpers/errors.py
@@ -12,4 +12,4 @@ AUTH_TOKEN = (
)
REQUEST = (4, "Cannot perform request (get/post type incorrect)")
-BLINK_ERRORS = [101, 400, 404]
+BLINK_ERRORS = [400, 404]
|
fronzbot/blinkpy
|
396824d38c3203e0a3fb29266204e369345367ee
|
diff --git a/tests/mock_responses.py b/tests/mock_responses.py
index 3981926..a789e80 100644
--- a/tests/mock_responses.py
+++ b/tests/mock_responses.py
@@ -9,6 +9,7 @@ class MockResponse:
self.json_data = json_data
self.status_code = status_code
self.raw_data = raw_data
+ self.reason = "foobar"
def json(self):
"""Return json data from get_request."""
diff --git a/tests/test_auth.py b/tests/test_auth.py
index 8086267..8ee18ce 100644
--- a/tests/test_auth.py
+++ b/tests/test_auth.py
@@ -3,7 +3,13 @@
import unittest
from unittest import mock
from requests import exceptions
-from blinkpy.auth import Auth, LoginError, TokenRefreshFailed, BlinkBadResponse
+from blinkpy.auth import (
+ Auth,
+ LoginError,
+ TokenRefreshFailed,
+ BlinkBadResponse,
+ UnauthorizedError,
+)
import blinkpy.helpers.constants as const
import tests.mock_responses as mresp
@@ -90,6 +96,10 @@ class TestAuth(unittest.TestCase):
with self.assertRaises(exceptions.ConnectionError):
self.auth.validate_response(fake_resp, True)
+ fake_resp = mresp.MockResponse({"code": 101}, 401)
+ with self.assertRaises(UnauthorizedError):
+ self.auth.validate_response(fake_resp, True)
+
def test_good_response_code(self):
"""Check good response code from server."""
fake_resp = mresp.MockResponse({"foo": "bar"}, 200)
@@ -133,6 +143,8 @@ class TestAuth(unittest.TestCase):
mock_req.return_value = fake_resp
with self.assertRaises(LoginError):
self.auth.login()
+ with self.assertRaises(TokenRefreshFailed):
+ self.auth.refresh_token()
@mock.patch("blinkpy.auth.Auth.login")
def test_refresh_token(self, mock_login):
@@ -197,10 +209,22 @@ class TestAuth(unittest.TestCase):
def test_query_retry(self, mock_refresh, mock_validate):
"""Check handling of request retry."""
self.auth.session = MockSession()
- mock_validate.side_effect = [TokenRefreshFailed, "foobar"]
+ mock_validate.side_effect = [UnauthorizedError, "foobar"]
mock_refresh.return_value = True
self.assertEqual(self.auth.query(url="http://example.com"), "foobar")
+ @mock.patch("blinkpy.auth.Auth.validate_response")
+ @mock.patch("blinkpy.auth.Auth.refresh_token")
+ def test_query_retry_failed(self, mock_refresh, mock_validate):
+ """Check handling of failed retry request."""
+ self.auth.seession = MockSession()
+ mock_validate.side_effect = [UnauthorizedError, BlinkBadResponse]
+ mock_refresh.return_value = True
+ self.assertEqual(self.auth.query(url="http://example.com"), None)
+
+ mock_validate.side_effect = [UnauthorizedError, TokenRefreshFailed]
+ self.assertEqual(self.auth.query(url="http://example.com"), None)
+
class MockSession:
"""Object to mock a session."""
|
Don't refresh tokens on failed request
**Describe the bug**
Old versions of the library required auth tokens to be refreshed every 24hrs. Logic was added to assume a failed request meant the token expired, so would log in again. The move to 2FA made this an obsolete method and, in fact, may be causing many issues for users.
**Expected behavior**
A failed request should simply be marked as failed and the `available` property set to `False`. Retry can be done at the `refresh()` method level or an independent script can just check the property and call the `blink.auth.refresh_token()` method if needed.
**`blinkpy` version:** 0.15.0
|
0.0
|
396824d38c3203e0a3fb29266204e369345367ee
|
[
"tests/test_auth.py::TestAuth::test_bad_response_code",
"tests/test_auth.py::TestAuth::test_barebones_init",
"tests/test_auth.py::TestAuth::test_check_key_required",
"tests/test_auth.py::TestAuth::test_empty_init",
"tests/test_auth.py::TestAuth::test_full_init",
"tests/test_auth.py::TestAuth::test_good_response_code",
"tests/test_auth.py::TestAuth::test_header",
"tests/test_auth.py::TestAuth::test_header_no_token",
"tests/test_auth.py::TestAuth::test_login",
"tests/test_auth.py::TestAuth::test_login_bad_response",
"tests/test_auth.py::TestAuth::test_query_retry",
"tests/test_auth.py::TestAuth::test_query_retry_failed",
"tests/test_auth.py::TestAuth::test_refresh_token",
"tests/test_auth.py::TestAuth::test_refresh_token_failed",
"tests/test_auth.py::TestAuth::test_response_bad_json",
"tests/test_auth.py::TestAuth::test_response_not_json",
"tests/test_auth.py::TestAuth::test_send_auth_key",
"tests/test_auth.py::TestAuth::test_send_auth_key_fail"
] |
[] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-05-27 23:08:02+00:00
|
mit
| 2,407 |
|
fronzbot__blinkpy-290
|
diff --git a/blinkpy/blinkpy.py b/blinkpy/blinkpy.py
index 9f98f14..6b904f5 100644
--- a/blinkpy/blinkpy.py
+++ b/blinkpy/blinkpy.py
@@ -23,7 +23,7 @@ from dateutil.parser import parse
from slugify import slugify
from blinkpy import api
-from blinkpy.sync_module import BlinkSyncModule
+from blinkpy.sync_module import BlinkSyncModule, BlinkOwl
from blinkpy.helpers import util
from blinkpy.helpers.constants import (
DEFAULT_MOTION_INTERVAL,
@@ -33,7 +33,6 @@ from blinkpy.helpers.constants import (
from blinkpy.helpers.constants import __version__
from blinkpy.auth import Auth, TokenRefreshFailed, LoginError
-
_LOGGER = logging.getLogger(__name__)
@@ -68,6 +67,7 @@ class Blink:
self.version = __version__
self.available = False
self.key_required = False
+ self.homescreen = {}
@util.Throttle(seconds=MIN_THROTTLE_TIME)
def refresh(self, force=False):
@@ -127,7 +127,9 @@ class Blink:
for name, network_id in networks.items():
sync_cameras = cameras.get(network_id, {})
self.setup_sync_module(name, network_id, sync_cameras)
- self.cameras = self.merge_cameras()
+
+ self.setup_owls()
+ self.cameras = self.merge_cameras()
self.available = True
self.key_required = False
@@ -138,6 +140,25 @@ class Blink:
self.sync[name] = BlinkSyncModule(self, name, network_id, cameras)
self.sync[name].start()
+ def setup_owls(self):
+ """Check for mini cameras."""
+ response = api.request_homescreen(self)
+ self.homescreen = response
+ network_list = []
+ try:
+ for owl in response["owls"]:
+ name = owl["name"]
+ network_id = owl["network_id"]
+ if owl["onboarded"]:
+ network_list.append(str(network_id))
+ self.sync[name] = BlinkOwl(self, name, network_id, owl)
+ self.sync[name].start()
+ except KeyError:
+ # No sync-less devices found
+ pass
+
+ self.network_ids.extend(network_list)
+
def setup_camera_list(self):
"""Create camera list for onboarded networks."""
all_cameras = {}
diff --git a/blinkpy/camera.py b/blinkpy/camera.py
index 0443dd5..4372e1d 100644
--- a/blinkpy/camera.py
+++ b/blinkpy/camera.py
@@ -112,18 +112,24 @@ class BlinkCamera:
def update(self, config, force_cache=False, **kwargs):
"""Update camera info."""
- # force = kwargs.pop('force', False)
- self.name = config["name"]
- self.camera_id = str(config["id"])
- self.network_id = str(config["network_id"])
- self.serial = config["serial"]
- self.motion_enabled = config["enabled"]
- self.battery_voltage = config["battery_voltage"]
- self.battery_state = config["battery_state"]
- self.temperature = config["temperature"]
- self.wifi_strength = config["wifi_strength"]
-
- # Retrieve calibrated temperature from special endpoint
+ self.extract_config_info(config)
+ self.get_sensor_info()
+ self.update_images(config, force_cache=force_cache)
+
+ def extract_config_info(self, config):
+ """Extract info from config."""
+ self.name = config.get("name", "unknown")
+ self.camera_id = str(config.get("id", "unknown"))
+ self.network_id = str(config.get("network_id", "unknown"))
+ self.serial = config.get("serial", None)
+ self.motion_enabled = config.get("enabled", "unknown")
+ self.battery_voltage = config.get("battery_voltage", None)
+ self.battery_state = config.get("battery_state", None)
+ self.temperature = config.get("temperature", None)
+ self.wifi_strength = config.get("wifi_strength", None)
+
+ def get_sensor_info(self):
+ """Retrieve calibrated temperatue from special endpoint."""
resp = api.request_camera_sensors(
self.sync.blink, self.network_id, self.camera_id
)
@@ -133,12 +139,11 @@ class BlinkCamera:
self.temperature_calibrated = self.temperature
_LOGGER.warning("Could not retrieve calibrated temperature.")
- # Check if thumbnail exists in config, if not try to
- # get it from the homescreen info in the sync module
- # otherwise set it to None and log an error
+ def update_images(self, config, force_cache=False):
+ """Update images for camera."""
new_thumbnail = None
thumb_addr = None
- if config["thumbnail"]:
+ if config.get("thumbnail", False):
thumb_addr = config["thumbnail"]
else:
_LOGGER.warning(
@@ -154,10 +159,12 @@ class BlinkCamera:
self.motion_detected = False
clip_addr = None
- if self.name in self.sync.last_record:
+ try:
clip_addr = self.sync.last_record[self.name]["clip"]
self.last_record = self.sync.last_record[self.name]["time"]
self.clip = f"{self.sync.urls.base_url}{clip_addr}"
+ except KeyError:
+ pass
# If the thumbnail or clip have changed, update the cache
update_cached_image = False
@@ -202,7 +209,8 @@ class BlinkCamera:
)
def video_to_file(self, path):
- """Write video to file.
+ """
+ Write video to file.
:param path: Path to write file
"""
@@ -213,3 +221,35 @@ class BlinkCamera:
return
with open(path, "wb") as vidfile:
copyfileobj(response.raw, vidfile)
+
+
+class BlinkCameraMini(BlinkCamera):
+ """Define a class for a Blink Mini camera."""
+
+ @property
+ def arm(self):
+ """Return camera arm status."""
+ return self.sync.arm
+
+ @arm.setter
+ def arm(self, value):
+ """Set camera arm status."""
+ self.sync.arm = value
+
+ def snap_picture(self):
+ """Snap picture for a blink mini camera."""
+ url = f"{self.sync.urls.base_url}/api/v1/accounts/{self.sync.blink.account_id}/networks/{self.network_id}/owls/{self.camera_id}/thumbnail"
+ return api.http_post(self.sync.blink, url)
+
+ def get_sensor_info(self):
+ """Get sensor info for blink mini camera."""
+
+ def get_liveview(self):
+ """Get liveview link."""
+ url = f"{self.sync.urls.base_url}/api/v1/accounts/{self.sync.blink.account_id}/networks/{self.network_id}/owls/{self.camera_id}/liveview"
+ response = api.http_post(self.sync.blink, url)
+ server = response["server"]
+ server_split = server.split(":")
+ server_split[0] = "rtsps"
+ link = "".join(server_split)
+ return link
diff --git a/blinkpy/sync_module.py b/blinkpy/sync_module.py
index f109212..77c1719 100644
--- a/blinkpy/sync_module.py
+++ b/blinkpy/sync_module.py
@@ -4,7 +4,7 @@ import logging
from requests.structures import CaseInsensitiveDict
from blinkpy import api
-from blinkpy.camera import BlinkCamera
+from blinkpy.camera import BlinkCamera, BlinkCameraMini
from blinkpy.helpers.util import time_to_seconds
from blinkpy.helpers.constants import ONLINE
@@ -78,23 +78,12 @@ class BlinkSyncModule:
@arm.setter
def arm(self, value):
"""Arm or disarm system."""
- if value:
- return api.request_system_arm(self.blink, self.network_id)
-
- return api.request_system_disarm(self.blink, self.network_id)
+ _LOGGER.warning("Arm/Disarm API for %s not currently implemented.", self.name)
def start(self):
"""Initialize the system."""
- response = api.request_syncmodule(self.blink, self.network_id)
- try:
- self.summary = response["syncmodule"]
- self.network_id = self.summary["network_id"]
- except (TypeError, KeyError):
- _LOGGER.error(
- ("Could not retrieve sync module information " "with response: %s"),
- response,
- exc_info=True,
- )
+ response = self.sync_initialize()
+ if not response:
return False
try:
@@ -108,24 +97,39 @@ class BlinkSyncModule:
is_ok = self.get_network_info()
self.check_new_videos()
+
+ if not is_ok or not self.update_cameras():
+ return False
+ self.available = True
+ return True
+
+ def sync_initialize(self):
+ """Initialize a sync module."""
+ response = api.request_syncmodule(self.blink, self.network_id)
+ try:
+ self.summary = response["syncmodule"]
+ self.network_id = self.summary["network_id"]
+ except (TypeError, KeyError):
+ _LOGGER.error(
+ "Could not retrieve sync module information with response: %s", response
+ )
+ return False
+ return response
+
+ def update_cameras(self, camera_type=BlinkCamera):
+ """Update cameras from server."""
try:
for camera_config in self.camera_list:
if "name" not in camera_config:
break
name = camera_config["name"]
- self.cameras[name] = BlinkCamera(self)
+ self.cameras[name] = camera_type(self)
self.motion[name] = False
camera_info = self.get_camera_info(camera_config["id"])
self.cameras[name].update(camera_info, force_cache=True, force=True)
except KeyError:
- _LOGGER.error(
- "Could not create cameras instances for %s", self.name, exc_info=True
- )
- return False
-
- if not is_ok:
+ _LOGGER.error("Could not create camera instances for %s", self.name)
return False
- self.available = True
return True
def get_events(self, **kwargs):
@@ -205,3 +209,86 @@ class BlinkSyncModule:
def check_new_video_time(self, timestamp):
"""Check if video has timestamp since last refresh."""
return time_to_seconds(timestamp) > self.blink.last_refresh
+
+
+class BlinkOwl(BlinkSyncModule):
+ """Representation of a sync-less device."""
+
+ def __init__(self, blink, name, network_id, response):
+ """Initialize a sync-less object."""
+ cameras = [{"name": name, "id": response["id"]}]
+ super().__init__(blink, name, network_id, cameras)
+ self.sync_id = response["id"]
+ self.serial = response["serial"]
+ self.status = response["enabled"]
+ if not self.serial:
+ self.serial = f"{network_id}-{self.sync_id}"
+
+ def sync_initialize(self):
+ """Initialize a sync-less module."""
+ self.summary = {
+ "id": self.sync_id,
+ "name": self.name,
+ "serial": self.serial,
+ "status": self.status,
+ "onboarded": True,
+ "account_id": self.blink.account_id,
+ "network_id": self.network_id,
+ }
+ return self.summary
+
+ def update_cameras(self, camera_type=BlinkCameraMini):
+ """Update sync-less cameras."""
+ return super().update_cameras(camera_type=BlinkCameraMini)
+
+ def get_camera_info(self, camera_id):
+ """Retrieve camera information."""
+ try:
+ for owl in self.blink.homescreen["owls"]:
+ if owl["name"] == self.name:
+ self.status = owl["enabled"]
+ return owl
+ except KeyError:
+ pass
+ return None
+
+ def get_network_info(self):
+ """Get network info for sync-less module."""
+ return True
+
+ @property
+ def network_info(self):
+ """Format owl response to resemble sync module."""
+ return {
+ "network": {
+ "id": self.network_id,
+ "name": self.name,
+ "armed": self.status,
+ "sync_module_error": False,
+ "account_id": self.blink.account_id,
+ }
+ }
+
+ @network_info.setter
+ def network_info(self, value):
+ """Set network_info property."""
+
+ @property
+ def arm(self):
+ """Return arm status."""
+ try:
+ return self.network_info["network"]["armed"]
+ except (KeyError, TypeError):
+ self.available = False
+ return None
+
+ @arm.setter
+ def arm(self, value):
+ """Arm or disarm camera."""
+ if value:
+ return api.request_motion_detection_enable(
+ self.blink, self.network_id, self.sync_id
+ )
+ return api.request_motion_detection_disable(
+ self.blink, self.network_id, self.sync_id
+ )
|
fronzbot/blinkpy
|
31de65f1553008296c0870aa6fdd9a00d7c4fc13
|
diff --git a/tests/test_blinkpy.py b/tests/test_blinkpy.py
index 9f551e9..bd93720 100644
--- a/tests/test_blinkpy.py
+++ b/tests/test_blinkpy.py
@@ -9,6 +9,7 @@ any communication related errors at startup.
import unittest
from unittest import mock
from blinkpy.blinkpy import Blink, BlinkSetupError
+from blinkpy.sync_module import BlinkOwl
from blinkpy.helpers.constants import __version__
@@ -160,10 +161,12 @@ class TestBlinkSetup(unittest.TestCase):
@mock.patch("blinkpy.blinkpy.Blink.setup_camera_list")
@mock.patch("blinkpy.api.request_networks")
- def test_setup_post_verify(self, mock_networks, mock_camera):
+ @mock.patch("blinkpy.blinkpy.Blink.setup_owls")
+ def test_setup_post_verify(self, mock_owl, mock_networks, mock_camera):
"""Test setup after verification."""
self.blink.available = False
self.blink.key_required = True
+ mock_owl.return_value = True
mock_networks.return_value = {
"summary": {"foo": {"onboarded": False, "name": "bar"}}
}
@@ -192,6 +195,44 @@ class TestBlinkSetup(unittest.TestCase):
self.assertEqual(combined["fizz"], "buzz")
self.assertEqual(combined["bar"], "foo")
+ @mock.patch("blinkpy.api.request_homescreen")
+ @mock.patch("blinkpy.blinkpy.BlinkOwl.start")
+ def test_initialize_blink_minis(self, mock_start, mock_home):
+ """Test blink mini initialization."""
+ mock_start.return_value = True
+ mock_home.return_value = {
+ "owls": [
+ {
+ "enabled": False,
+ "id": 1,
+ "name": "foo",
+ "network_id": 2,
+ "onboarded": True,
+ "status": "online",
+ "thumbnail": "/foo/bar",
+ "serial": "1234",
+ },
+ {
+ "enabled": True,
+ "id": 3,
+ "name": "bar",
+ "network_id": 4,
+ "onboarded": True,
+ "status": "online",
+ "thumbnail": "/foo/bar",
+ "serial": "abcd",
+ },
+ ]
+ }
+ self.blink.sync = {}
+ self.blink.setup_owls()
+ self.assertEqual(self.blink.sync["foo"].__class__, BlinkOwl)
+ self.assertEqual(self.blink.sync["bar"].__class__, BlinkOwl)
+ self.assertEqual(self.blink.sync["foo"].arm, False)
+ self.assertEqual(self.blink.sync["bar"].arm, True)
+ self.assertEqual(self.blink.sync["foo"].name, "foo")
+ self.assertEqual(self.blink.sync["bar"].name, "bar")
+
class MockSync:
"""Mock sync module class."""
diff --git a/tests/test_sync_module.py b/tests/test_sync_module.py
index baf2bb1..211cdb4 100644
--- a/tests/test_sync_module.py
+++ b/tests/test_sync_module.py
@@ -4,8 +4,8 @@ from unittest import mock
from blinkpy.blinkpy import Blink
from blinkpy.helpers.util import BlinkURLHandler
-from blinkpy.sync_module import BlinkSyncModule
-from blinkpy.camera import BlinkCamera
+from blinkpy.sync_module import BlinkSyncModule, BlinkOwl
+from blinkpy.camera import BlinkCamera, BlinkCameraMini
@mock.patch("blinkpy.auth.Auth.query")
@@ -275,3 +275,20 @@ class TestBlinkSyncModule(unittest.TestCase):
"""Test sync attributes."""
self.assertEqual(self.blink.sync["test"].attributes["name"], "test")
self.assertEqual(self.blink.sync["test"].attributes["network_id"], "1234")
+
+ def test_owl_start(self, mock_resp):
+ """Test owl camera instantiation."""
+ response = {
+ "name": "foo",
+ "id": 2,
+ "serial": "foobar123",
+ "enabled": True,
+ "network_id": 1,
+ "thumbnail": "/foo/bar",
+ }
+ self.blink.last_refresh = None
+ self.blink.homescreen = {"owls": [response]}
+ owl = BlinkOwl(self.blink, "foo", 1234, response)
+ self.assertTrue(owl.start())
+ self.assertTrue("foo" in owl.cameras)
+ self.assertEqual(owl.cameras["foo"].__class__, BlinkCameraMini)
|
Support for Mini
**Is your feature request related to a problem? Please describe.**
I tried the Home Assistant integration, but don't get any devices, so I don't think the mini is supported yet.
**Describe the solution you'd like**
Support for the Blink mini.
**Additional context**
https://www.amazon.com/stores/page/C5DECBBE-4F56-4C36-B933-E62144578691?channel=productmini
|
0.0
|
31de65f1553008296c0870aa6fdd9a00d7c4fc13
|
[
"tests/test_blinkpy.py::TestBlinkSetup::test_initialization",
"tests/test_blinkpy.py::TestBlinkSetup::test_initialize_blink_minis",
"tests/test_blinkpy.py::TestBlinkSetup::test_merge_cameras",
"tests/test_blinkpy.py::TestBlinkSetup::test_multiple_networks",
"tests/test_blinkpy.py::TestBlinkSetup::test_multiple_onboarded_networks",
"tests/test_blinkpy.py::TestBlinkSetup::test_network_id_failure",
"tests/test_blinkpy.py::TestBlinkSetup::test_setup_cameras",
"tests/test_blinkpy.py::TestBlinkSetup::test_setup_cameras_failure",
"tests/test_blinkpy.py::TestBlinkSetup::test_setup_networks",
"tests/test_blinkpy.py::TestBlinkSetup::test_setup_networks_failure",
"tests/test_blinkpy.py::TestBlinkSetup::test_setup_post_verify",
"tests/test_blinkpy.py::TestBlinkSetup::test_setup_post_verify_failure",
"tests/test_blinkpy.py::TestBlinkSetup::test_setup_prompt_2fa",
"tests/test_blinkpy.py::TestBlinkSetup::test_setup_urls",
"tests/test_blinkpy.py::TestBlinkSetup::test_setup_urls_failure",
"tests/test_blinkpy.py::TestBlinkSetup::test_sync_case_insensitive_dict",
"tests/test_blinkpy.py::TestBlinkSetup::test_throttle",
"tests/test_sync_module.py::TestBlinkSyncModule::test_bad_arm",
"tests/test_sync_module.py::TestBlinkSyncModule::test_bad_status",
"tests/test_sync_module.py::TestBlinkSyncModule::test_check_multiple_videos",
"tests/test_sync_module.py::TestBlinkSyncModule::test_check_new_videos",
"tests/test_sync_module.py::TestBlinkSyncModule::test_check_new_videos_failed",
"tests/test_sync_module.py::TestBlinkSyncModule::test_check_new_videos_old_date",
"tests/test_sync_module.py::TestBlinkSyncModule::test_check_new_videos_startup",
"tests/test_sync_module.py::TestBlinkSyncModule::test_check_no_motion_if_not_armed",
"tests/test_sync_module.py::TestBlinkSyncModule::test_get_camera_info",
"tests/test_sync_module.py::TestBlinkSyncModule::test_get_camera_info_fail",
"tests/test_sync_module.py::TestBlinkSyncModule::test_get_events",
"tests/test_sync_module.py::TestBlinkSyncModule::test_get_events_fail",
"tests/test_sync_module.py::TestBlinkSyncModule::test_get_network_info",
"tests/test_sync_module.py::TestBlinkSyncModule::test_get_network_info_failure",
"tests/test_sync_module.py::TestBlinkSyncModule::test_missing_camera_info",
"tests/test_sync_module.py::TestBlinkSyncModule::test_owl_start",
"tests/test_sync_module.py::TestBlinkSyncModule::test_summary_with_no_network_id",
"tests/test_sync_module.py::TestBlinkSyncModule::test_summary_with_only_network_id",
"tests/test_sync_module.py::TestBlinkSyncModule::test_sync_attributes",
"tests/test_sync_module.py::TestBlinkSyncModule::test_sync_start",
"tests/test_sync_module.py::TestBlinkSyncModule::test_unexpected_camera_info",
"tests/test_sync_module.py::TestBlinkSyncModule::test_unexpected_summary"
] |
[] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-06-09 04:27:21+00:00
|
mit
| 2,408 |
|
fronzbot__blinkpy-331
|
diff --git a/blinkpy/auth.py b/blinkpy/auth.py
index 7d72645..34c85bb 100644
--- a/blinkpy/auth.py
+++ b/blinkpy/auth.py
@@ -53,7 +53,7 @@ class Auth:
"""Return authorization header."""
if self.token is None:
return None
- return {"Host": self.host, "TOKEN_AUTH": self.token}
+ return {"TOKEN_AUTH": self.token}
def create_session(self):
"""Create a session for blink communication."""
diff --git a/blinkpy/helpers/constants.py b/blinkpy/helpers/constants.py
index a933607..775aa15 100644
--- a/blinkpy/helpers/constants.py
+++ b/blinkpy/helpers/constants.py
@@ -4,7 +4,7 @@ import os
MAJOR_VERSION = 0
MINOR_VERSION = 16
-PATCH_VERSION = "0-rc11"
+PATCH_VERSION = "0-rc12"
__version__ = f"{MAJOR_VERSION}.{MINOR_VERSION}.{PATCH_VERSION}"
|
fronzbot/blinkpy
|
77959d6d94a76eb12d494c6c9c0f91c51d6b2013
|
diff --git a/tests/test_auth.py b/tests/test_auth.py
index e1fae96..dc1b35c 100644
--- a/tests/test_auth.py
+++ b/tests/test_auth.py
@@ -128,8 +128,7 @@ class TestAuth(unittest.TestCase):
def test_header(self):
"""Test header data."""
self.auth.token = "bar"
- self.auth.host = "foo"
- expected_header = {"Host": "foo", "TOKEN_AUTH": "bar"}
+ expected_header = {"TOKEN_AUTH": "bar"}
self.assertDictEqual(self.auth.header, expected_header)
def test_header_no_token(self):
|
Error requesting networks
I have been running 0.15 for over a week now and no issues, but yesterday it started to error on self.get_networks()
```
Traceback (most recent call last):
File "scripts/grab-photo.py", line 9, in <module>
blink.start()
File "/var/services/homes/admin/.local/lib/python3.7/site-packages/blinkpy/blinkpy.py", line 135, in start
self.get_auth_token()
File "/var/services/homes/admin/.local/lib/python3.7/site-packages/blinkpy/blinkpy.py", line 176, in get_auth_token
self.setup_params(self.login_response)
File "/var/services/homes/admin/.local/lib/python3.7/site-packages/blinkpy/blinkpy.py", line 189, in setup_params
self.networks = self.get_networks()
File "/var/services/homes/admin/.local/lib/python3.7/site-packages/blinkpy/blinkpy.py", line 195, in get_networks
response = api.request_networks(self)
File "/var/services/homes/admin/.local/lib/python3.7/site-packages/blinkpy/api.py", line 82, in request_networks
return http_get(blink, url)
File "/var/services/homes/admin/.local/lib/python3.7/site-packages/blinkpy/api.py", line 301, in http_get
is_retry=is_retry,
File "/var/services/homes/admin/.local/lib/python3.7/site-packages/blinkpy/helpers/util.py", line 104, in http_req
if json_resp and "code" in response.json():
File "/var/services/homes/admin/.local/lib/python3.7/site-packages/requests/models.py", line 898, in json
return complexjson.loads(self.text, **kwargs)
File "/usr/local/python3/lib/python3.7/json/__init__.py", line 348, in loads
return _default_decoder.decode(s)
File "/usr/local/python3/lib/python3.7/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/local/python3/lib/python3.7/json/decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
```
I thought it might be the version, so I updated to the latest dev build. I had to enter in a new code but now i'm still getting a similar error:
```
Expected json response from https://rest-u003.immedia-semi.com/api/v3/accounts/XXXXX/homescreen, but received: 403: Forbidden
Enter code sent to [email protected]: XXXXXX
Traceback (most recent call last):
File "scripts/grab-photo2.py", line 13, in <module>
blink.start()
File "/var/services/homes/admin/.local/lib/python3.7/site-packages/blinkpy/blinkpy.py", line 114, in start
self.setup_prompt_2fa()
File "/var/services/homes/admin/.local/lib/python3.7/site-packages/blinkpy/blinkpy.py", line 121, in setup_prompt_2fa
result = self.auth.send_auth_key(self, pin)
File "/var/services/homes/admin/.local/lib/python3.7/site-packages/blinkpy/auth.py", line 207, in send_auth_key
json_resp = response.json()
File "/var/services/homes/admin/.local/lib/python3.7/site-packages/requests/models.py", line 898, in json
return complexjson.loads(self.text, **kwargs)
File "/usr/local/python3/lib/python3.7/json/__init__.py", line 348, in loads
return _default_decoder.decode(s)
File "/usr/local/python3/lib/python3.7/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/local/python3/lib/python3.7/json/decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
```
|
0.0
|
77959d6d94a76eb12d494c6c9c0f91c51d6b2013
|
[
"tests/test_auth.py::TestAuth::test_header"
] |
[
"tests/test_auth.py::TestAuth::test_bad_response_code",
"tests/test_auth.py::TestAuth::test_barebones_init",
"tests/test_auth.py::TestAuth::test_check_key_required",
"tests/test_auth.py::TestAuth::test_empty_init",
"tests/test_auth.py::TestAuth::test_full_init",
"tests/test_auth.py::TestAuth::test_good_response_code",
"tests/test_auth.py::TestAuth::test_header_no_token",
"tests/test_auth.py::TestAuth::test_login",
"tests/test_auth.py::TestAuth::test_login_bad_response",
"tests/test_auth.py::TestAuth::test_query_retry",
"tests/test_auth.py::TestAuth::test_query_retry_failed",
"tests/test_auth.py::TestAuth::test_refresh_token",
"tests/test_auth.py::TestAuth::test_refresh_token_failed",
"tests/test_auth.py::TestAuth::test_response_bad_json",
"tests/test_auth.py::TestAuth::test_response_not_json",
"tests/test_auth.py::TestAuth::test_send_auth_key",
"tests/test_auth.py::TestAuth::test_send_auth_key_fail"
] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-07-11 14:42:04+00:00
|
mit
| 2,409 |
|
fronzbot__blinkpy-401
|
diff --git a/blinkpy/blinkpy.py b/blinkpy/blinkpy.py
index 70abd8d..8205458 100644
--- a/blinkpy/blinkpy.py
+++ b/blinkpy/blinkpy.py
@@ -76,21 +76,22 @@ class Blink:
self.no_owls = no_owls
@util.Throttle(seconds=MIN_THROTTLE_TIME)
- def refresh(self, force=False):
+ def refresh(self, force=False, force_cache=False):
"""
Perform a system refresh.
- :param force: Force an update of the camera data
+ :param force: Used to override throttle, resets refresh
+ :param force_cache: Used to force update without overriding throttle
"""
- if self.check_if_ok_to_update() or force:
+ if self.check_if_ok_to_update() or force or force_cache:
if not self.available:
self.setup_post_verify()
self.get_homescreen()
for sync_name, sync_module in self.sync.items():
_LOGGER.debug("Attempting refresh of sync %s", sync_name)
- sync_module.refresh(force_cache=force)
- if not force:
+ sync_module.refresh(force_cache=(force or force_cache))
+ if not force_cache:
# Prevents rapid clearing of motion detect property
self.last_refresh = int(time.time())
return True
diff --git a/blinkpy/sync_module.py b/blinkpy/sync_module.py
index ad780a1..4e31756 100644
--- a/blinkpy/sync_module.py
+++ b/blinkpy/sync_module.py
@@ -145,7 +145,7 @@ class BlinkSyncModule:
for owl in self.blink.homescreen["owls"]:
if owl["name"] == name:
return owl
- except KeyError:
+ except (TypeError, KeyError):
pass
return None
@@ -270,7 +270,7 @@ class BlinkOwl(BlinkSyncModule):
if owl["name"] == self.name:
self.status = owl["enabled"]
return owl
- except KeyError:
+ except (TypeError, KeyError):
pass
return None
|
fronzbot/blinkpy
|
0842739197bd4d8dc0f9e4f50cfb304410bbfb81
|
diff --git a/tests/test_blink_functions.py b/tests/test_blink_functions.py
index 89a45dc..8a71294 100644
--- a/tests/test_blink_functions.py
+++ b/tests/test_blink_functions.py
@@ -5,29 +5,23 @@ import logging
from blinkpy import blinkpy
from blinkpy.sync_module import BlinkSyncModule
+from blinkpy.camera import BlinkCamera
from blinkpy.helpers.util import get_time, BlinkURLHandler
class MockSyncModule(BlinkSyncModule):
- """Mock http requests from sync module."""
+ """Mock blink sync module object."""
- def __init__(self, blink, header):
- """Create mock sync module instance."""
- super().__init__(blink, header, network_id=None, camera_list=None)
- self.blink = blink
- self.header = header
- self.return_value = None
- self.return_value2 = None
+ def get_network_info(self):
+ """Mock network info method."""
+ return True
- def http_get(self, url, stream=False, json=True):
- """Mock get request."""
- if stream and self.return_value2 is not None:
- return self.return_value2
- return self.return_value
- def http_post(self, url):
- """Mock post request."""
- return self.return_value
+class MockCamera(BlinkCamera):
+ """Mock blink camera object."""
+
+ def update(self, config, force_cache=False, **kwargs):
+ """Mock camera update method."""
class TestBlinkFunctions(unittest.TestCase):
@@ -121,3 +115,16 @@ class TestBlinkFunctions(unittest.TestCase):
with self.assertLogs() as dl_log:
blink.download_videos("/tmp", camera="bar", stop=2)
self.assertEqual(dl_log.output, expected_log)
+
+ @mock.patch("blinkpy.blinkpy.api.request_network_update")
+ @mock.patch("blinkpy.auth.Auth.query")
+ def test_refresh(self, mock_req, mock_update):
+ """Test ability to refresh system."""
+ mock_update.return_value = {"network": {"sync_module_error": False}}
+ mock_req.return_value = None
+ self.blink.last_refresh = 0
+ self.blink.available = True
+ self.blink.sync["foo"] = MockSyncModule(self.blink, "foo", 1, [])
+ self.blink.cameras = {"bar": MockCamera(self.blink.sync)}
+ self.blink.sync["foo"].cameras = self.blink.cameras
+ self.assertTrue(self.blink.refresh())
diff --git a/tests/test_blinkpy.py b/tests/test_blinkpy.py
index aed2edb..c632215 100644
--- a/tests/test_blinkpy.py
+++ b/tests/test_blinkpy.py
@@ -69,7 +69,7 @@ class TestBlinkSetup(unittest.TestCase):
with mock.patch(
"blinkpy.sync_module.BlinkSyncModule.refresh", return_value=True
), mock.patch("blinkpy.blinkpy.Blink.get_homescreen", return_value=True):
- self.blink.refresh()
+ self.blink.refresh(force=True)
self.assertEqual(self.blink.last_refresh, now)
self.assertEqual(self.blink.check_if_ok_to_update(), False)
|
Exception on blink.refresh
I'm attempting to automate capture from a Blink Mini camera but the `blink.refresh()` command always produces the following error:
```
blink.refresh()
File "/Users/lakario/Library/Python/3.8/lib/python/site-packages/blinkpy/helpers/util.py", line 144, in wrapper
result = method(*args, *kwargs)
File "/Users/lakario/Library/Python/3.8/lib/python/site-packages/blinkpy/blinkpy.py", line 92, in refresh
sync_module.refresh(force_cache=force)
File "/Users/lakario/Library/Python/3.8/lib/python/site-packages/blinkpy/sync_module.py", line 193, in refresh
camera_id, owl_info=self.get_owl_info(camera_name)
File "/Users/lakario/Library/Python/3.8/lib/python/site-packages/blinkpy/sync_module.py", line 145, in get_owl_info
for owl in self.blink.homescreen["owls"]:
TypeError: 'NoneType' object is not subscriptable
```
I worked my way back through the code and I was able to successfully refresh my "owl" (Mini camera) with the internal calls. It's not obvious why it doesn't work with the `blink.refresh()`.
```
camera_info=blink.sync['Home'].get_owl_info('Farm')
camera = blink.cameras['Farm']
camera.snap_picture()
blink.sync['Home'].cameras['Farm'].update(camera_info, force_cache=True)
```
Let me know if I can provide any extra info which will help.
|
0.0
|
0842739197bd4d8dc0f9e4f50cfb304410bbfb81
|
[
"tests/test_blink_functions.py::TestBlinkFunctions::test_refresh"
] |
[
"tests/test_blink_functions.py::TestBlinkFunctions::test_download_video_exit",
"tests/test_blink_functions.py::TestBlinkFunctions::test_merge_cameras",
"tests/test_blink_functions.py::TestBlinkFunctions::test_parse_camera_not_in_list",
"tests/test_blink_functions.py::TestBlinkFunctions::test_parse_downloaded_items",
"tests/test_blinkpy.py::TestBlinkSetup::test_blink_mini_attached_to_sync",
"tests/test_blinkpy.py::TestBlinkSetup::test_blink_mini_cameras_returned",
"tests/test_blinkpy.py::TestBlinkSetup::test_initialization",
"tests/test_blinkpy.py::TestBlinkSetup::test_initialize_blink_minis",
"tests/test_blinkpy.py::TestBlinkSetup::test_merge_cameras",
"tests/test_blinkpy.py::TestBlinkSetup::test_multiple_networks",
"tests/test_blinkpy.py::TestBlinkSetup::test_multiple_onboarded_networks",
"tests/test_blinkpy.py::TestBlinkSetup::test_network_id_failure",
"tests/test_blinkpy.py::TestBlinkSetup::test_setup_cameras",
"tests/test_blinkpy.py::TestBlinkSetup::test_setup_cameras_failure",
"tests/test_blinkpy.py::TestBlinkSetup::test_setup_networks",
"tests/test_blinkpy.py::TestBlinkSetup::test_setup_networks_failure",
"tests/test_blinkpy.py::TestBlinkSetup::test_setup_post_verify",
"tests/test_blinkpy.py::TestBlinkSetup::test_setup_post_verify_failure",
"tests/test_blinkpy.py::TestBlinkSetup::test_setup_prompt_2fa",
"tests/test_blinkpy.py::TestBlinkSetup::test_setup_urls",
"tests/test_blinkpy.py::TestBlinkSetup::test_setup_urls_failure",
"tests/test_blinkpy.py::TestBlinkSetup::test_sync_case_insensitive_dict",
"tests/test_blinkpy.py::TestBlinkSetup::test_throttle"
] |
{
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-11-23 03:32:04+00:00
|
mit
| 2,410 |
|
fronzbot__blinkpy-424
|
diff --git a/blinkpy/auth.py b/blinkpy/auth.py
index bc61387..c7e997b 100644
--- a/blinkpy/auth.py
+++ b/blinkpy/auth.py
@@ -58,7 +58,11 @@ class Auth:
"""Return authorization header."""
if self.token is None:
return None
- return {"TOKEN_AUTH": self.token, "user-agent": DEFAULT_USER_AGENT}
+ return {
+ "TOKEN_AUTH": self.token,
+ "user-agent": DEFAULT_USER_AGENT,
+ "content-type": "application/json",
+ }
def create_session(self, opts=None):
"""Create a session for blink communication."""
@@ -227,6 +231,9 @@ class Auth:
try:
json_resp = response.json()
blink.available = json_resp["valid"]
+ if not json_resp["valid"]:
+ _LOGGER.error(f"{json_resp['message']}")
+ return False
except (KeyError, TypeError):
_LOGGER.error("Did not receive valid response from server.")
return False
|
fronzbot/blinkpy
|
f6118ea4a7ef0d330754dda5ba6267f2797bb84d
|
diff --git a/tests/test_auth.py b/tests/test_auth.py
index c5c082b..45e6cff 100644
--- a/tests/test_auth.py
+++ b/tests/test_auth.py
@@ -128,7 +128,11 @@ class TestAuth(unittest.TestCase):
def test_header(self):
"""Test header data."""
self.auth.token = "bar"
- expected_header = {"TOKEN_AUTH": "bar", "user-agent": const.DEFAULT_USER_AGENT}
+ expected_header = {
+ "TOKEN_AUTH": "bar",
+ "user-agent": const.DEFAULT_USER_AGENT,
+ "content-type": "application/json",
+ }
self.assertDictEqual(self.auth.header, expected_header)
def test_header_no_token(self):
|
Video download problem - "Unauthorized Access","code":101
I have been using Blinkpy to download videos to my PC for almost a year. Last time that I was able to download the video files was about 4 weeks ago. Today when I was trying to download new video files since my last downloading, I found the sizes of the downloaded video files are all 1kB, obviously something was not right. When I open the video files they just have one line of ASCII text showing below:
{"message":"Unauthorized Access","code":101}
My user name and password should be correct because after the code:
>blink.auth = auth
>blink.start()
No error message is shown. If the password is not correct, the error message 'Login endpoint failed. Try again later.' will be shown.
Anybody know what is the csuse of this problem? Thank you.
|
0.0
|
f6118ea4a7ef0d330754dda5ba6267f2797bb84d
|
[
"tests/test_auth.py::TestAuth::test_header"
] |
[
"tests/test_auth.py::TestAuth::test_bad_response_code",
"tests/test_auth.py::TestAuth::test_barebones_init",
"tests/test_auth.py::TestAuth::test_check_key_required",
"tests/test_auth.py::TestAuth::test_custom_session_full",
"tests/test_auth.py::TestAuth::test_custom_session_partial",
"tests/test_auth.py::TestAuth::test_default_session",
"tests/test_auth.py::TestAuth::test_empty_init",
"tests/test_auth.py::TestAuth::test_full_init",
"tests/test_auth.py::TestAuth::test_good_response_code",
"tests/test_auth.py::TestAuth::test_header_no_token",
"tests/test_auth.py::TestAuth::test_login",
"tests/test_auth.py::TestAuth::test_login_bad_response",
"tests/test_auth.py::TestAuth::test_query_retry",
"tests/test_auth.py::TestAuth::test_query_retry_failed",
"tests/test_auth.py::TestAuth::test_refresh_token",
"tests/test_auth.py::TestAuth::test_refresh_token_failed",
"tests/test_auth.py::TestAuth::test_response_bad_json",
"tests/test_auth.py::TestAuth::test_response_not_json",
"tests/test_auth.py::TestAuth::test_send_auth_key",
"tests/test_auth.py::TestAuth::test_send_auth_key_fail"
] |
{
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
}
|
2021-02-05 15:13:24+00:00
|
mit
| 2,411 |
|
fronzbot__blinkpy-437
|
diff --git a/README.rst b/README.rst
index 32d867c..7fcd6d9 100644
--- a/README.rst
+++ b/README.rst
@@ -174,13 +174,13 @@ Similar methods exist for individual cameras:
Download videos
----------------
-You can also use this library to download all videos from the server. In order to do this, you must specify a ``path``. You may also specifiy a how far back in time to go to retrieve videos via the ``since=`` variable (a simple string such as ``"2017/09/21"`` is sufficient), as well as how many pages to traverse via the ``stop=`` variable. Note that by default, the library will search the first ten pages which is sufficient in most use cases. Additionally, you can specify one or more cameras via the ``camera=`` property. This can be a single string indicating the name of the camera, or a list of camera names. By default, it is set to the string ``'all'`` to grab videos from all cameras.
+You can also use this library to download all videos from the server. In order to do this, you must specify a ``path``. You may also specifiy a how far back in time to go to retrieve videos via the ``since=`` variable (a simple string such as ``"2017/09/21"`` is sufficient), as well as how many pages to traverse via the ``stop=`` variable. Note that by default, the library will search the first ten pages which is sufficient in most use cases. Additionally, you can specify one or more cameras via the ``camera=`` property. This can be a single string indicating the name of the camera, or a list of camera names. By default, it is set to the string ``'all'`` to grab videos from all cameras. If you are downloading many items, setting the ``delay`` parameter is advised in order to throttle sequential calls to the API. By default this is set to ``1`` but can be any integer representing the number of seconds to delay between calls.
-Example usage, which downloads all videos recorded since July 4th, 2018 at 9:34am to the ``/home/blink`` directory:
+Example usage, which downloads all videos recorded since July 4th, 2018 at 9:34am to the ``/home/blink`` directory with a 2s delay between calls:
.. code:: python
- blink.download_videos('/home/blink', since='2018/07/04 09:34')
+ blink.download_videos('/home/blink', since='2018/07/04 09:34', delay=2)
.. |Build Status| image:: https://github.com/fronzbot/blinkpy/workflows/build/badge.svg
diff --git a/blinkpy/blinkpy.py b/blinkpy/blinkpy.py
index 8205458..eda5eb3 100644
--- a/blinkpy/blinkpy.py
+++ b/blinkpy/blinkpy.py
@@ -264,7 +264,9 @@ class Blink:
"""Save login data to file."""
util.json_save(self.auth.login_attributes, file_name)
- def download_videos(self, path, since=None, camera="all", stop=10, debug=False):
+ def download_videos(
+ self, path, since=None, camera="all", stop=10, delay=1, debug=False
+ ):
"""
Download all videos from server since specified time.
@@ -275,6 +277,7 @@ class Blink:
:param camera: Camera name to retrieve. Defaults to "all".
Use a list for multiple cameras.
:param stop: Page to stop on (~25 items per page. Default page 10).
+ :param delay: Number of seconds to wait in between subsequent video downloads.
:param debug: Set to TRUE to prevent downloading of items.
Instead of downloading, entries will be printed to log.
"""
@@ -301,9 +304,9 @@ class Blink:
_LOGGER.info("No videos found on page %s. Exiting.", page)
break
- self._parse_downloaded_items(result, camera, path, debug)
+ self._parse_downloaded_items(result, camera, path, delay, debug)
- def _parse_downloaded_items(self, result, camera, path, debug):
+ def _parse_downloaded_items(self, result, camera, path, delay, debug):
"""Parse downloaded videos."""
for item in result:
try:
@@ -351,6 +354,8 @@ class Blink:
"Address: {address}, Filename: {filename}"
)
)
+ if delay > 0:
+ time.sleep(delay)
class BlinkSetupError(Exception):
|
fronzbot/blinkpy
|
3c5caae93f2a00eb09427d27747aa83ce91179e1
|
diff --git a/tests/test_blink_functions.py b/tests/test_blink_functions.py
index 8a71294..c4c7d7c 100644
--- a/tests/test_blink_functions.py
+++ b/tests/test_blink_functions.py
@@ -2,6 +2,7 @@
import unittest
from unittest import mock
import logging
+import time
from blinkpy import blinkpy
from blinkpy.sync_module import BlinkSyncModule
@@ -88,9 +89,33 @@ class TestBlinkFunctions(unittest.TestCase):
"DEBUG:blinkpy.blinkpy:foo: /bar.mp4 is marked as deleted.",
]
with self.assertLogs() as dl_log:
- blink.download_videos("/tmp", stop=2)
+ blink.download_videos("/tmp", stop=2, delay=0)
self.assertEqual(dl_log.output, expected_log)
+ @mock.patch("blinkpy.blinkpy.api.request_videos")
+ def test_parse_downloaded_throttle(self, mock_req):
+ """Test ability to parse downloaded items list."""
+ generic_entry = {
+ "created_at": "1970",
+ "device_name": "foo",
+ "deleted": False,
+ "media": "/bar.mp4",
+ }
+ result = [generic_entry]
+ mock_req.return_value = {"media": result}
+ self.blink.last_refresh = 0
+ start = time.time()
+ self.blink.download_videos("/tmp", stop=2, delay=0, debug=True)
+ now = time.time()
+ delta = now - start
+ self.assertTrue(delta < 0.1)
+
+ start = time.time()
+ self.blink.download_videos("/tmp", stop=2, delay=0.1, debug=True)
+ now = time.time()
+ delta = now - start
+ self.assertTrue(delta >= 0.1)
+
@mock.patch("blinkpy.blinkpy.api.request_videos")
def test_parse_camera_not_in_list(self, mock_req):
"""Test ability to parse downloaded items list."""
@@ -113,7 +138,7 @@ class TestBlinkFunctions(unittest.TestCase):
"DEBUG:blinkpy.blinkpy:Skipping videos for foo.",
]
with self.assertLogs() as dl_log:
- blink.download_videos("/tmp", camera="bar", stop=2)
+ blink.download_videos("/tmp", camera="bar", stop=2, delay=0)
self.assertEqual(dl_log.output, expected_log)
@mock.patch("blinkpy.blinkpy.api.request_network_update")
|
Add throttling to video downloads to mitigate risk of account suspension
Hi folks,
I would just like to inform you that Blink has suspended my account after using blinkpy-0.17.0 once to download my videos. I have downloaded my videos before using my own script based on the API calls used in blinkpy. Never had an issue (except API changes). Now Blink decides to lock out paying customers that need automation other than Alexa or IFTTT.
Thank you for your excellent work @fronzbot, it was really appreciated. But I think I am done with Blink now.
BR,
rbrtrs
|
0.0
|
3c5caae93f2a00eb09427d27747aa83ce91179e1
|
[
"tests/test_blink_functions.py::TestBlinkFunctions::test_parse_camera_not_in_list",
"tests/test_blink_functions.py::TestBlinkFunctions::test_parse_downloaded_items",
"tests/test_blink_functions.py::TestBlinkFunctions::test_parse_downloaded_throttle"
] |
[
"tests/test_blink_functions.py::TestBlinkFunctions::test_download_video_exit",
"tests/test_blink_functions.py::TestBlinkFunctions::test_merge_cameras",
"tests/test_blink_functions.py::TestBlinkFunctions::test_refresh"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-02-18 13:37:10+00:00
|
mit
| 2,412 |
|
fronzbot__blinkpy-526
|
diff --git a/blinkpy/blinkpy.py b/blinkpy/blinkpy.py
index eda5eb3..c316875 100644
--- a/blinkpy/blinkpy.py
+++ b/blinkpy/blinkpy.py
@@ -23,7 +23,7 @@ from dateutil.parser import parse
from slugify import slugify
from blinkpy import api
-from blinkpy.sync_module import BlinkSyncModule, BlinkOwl
+from blinkpy.sync_module import BlinkSyncModule, BlinkOwl, BlinkLotus
from blinkpy.helpers import util
from blinkpy.helpers.constants import (
DEFAULT_MOTION_INTERVAL,
@@ -180,6 +180,36 @@ class Blink:
self.network_ids.extend(network_list)
return camera_list
+ def setup_lotus(self):
+ """Check for doorbells cameras."""
+ network_list = []
+ camera_list = []
+ try:
+ for lotus in self.homescreen["doorbells"]:
+ name = lotus["name"]
+ network_id = str(lotus["network_id"])
+ if network_id in self.network_ids:
+ camera_list.append(
+ {
+ network_id: {
+ "name": name,
+ "id": network_id,
+ "type": "doorbell",
+ }
+ }
+ )
+ continue
+ if lotus["onboarded"]:
+ network_list.append(str(network_id))
+ self.sync[name] = BlinkLotus(self, name, network_id, lotus)
+ self.sync[name].start()
+ except KeyError:
+ # No sync-less devices found
+ pass
+
+ self.network_ids.extend(network_list)
+ return camera_list
+
def setup_camera_list(self):
"""Create camera list for onboarded networks."""
all_cameras = {}
@@ -194,9 +224,13 @@ class Blink:
{"name": camera["name"], "id": camera["id"]}
)
mini_cameras = self.setup_owls()
+ lotus_cameras = self.setup_lotus()
for camera in mini_cameras:
for network, camera_info in camera.items():
all_cameras[network].append(camera_info)
+ for camera in lotus_cameras:
+ for network, camera_info in camera.items():
+ all_cameras[network].append(camera_info)
return all_cameras
except (KeyError, TypeError):
_LOGGER.error("Unable to retrieve cameras from response %s", response)
diff --git a/blinkpy/camera.py b/blinkpy/camera.py
index 6c75296..29ceec8 100644
--- a/blinkpy/camera.py
+++ b/blinkpy/camera.py
@@ -273,3 +273,42 @@ class BlinkCameraMini(BlinkCamera):
server_split[0] = "rtsps:"
link = "".join(server_split)
return link
+
+
+class BlinkDoorbell(BlinkCamera):
+ """Define a class for a Blink Doorbell camera."""
+
+ def __init__(self, sync):
+ """Initialize a Blink Doorbell."""
+ super().__init__(sync)
+ self.camera_type = "doorbell"
+
+ @property
+ def arm(self):
+ """Return camera arm status."""
+ return self.sync.arm
+
+ @arm.setter
+ def arm(self, value):
+ """Set camera arm status."""
+ _LOGGER.warning(
+ "Individual camera motion detection enable/disable for Blink Doorbell is unsupported at this time."
+ )
+
+ def snap_picture(self):
+ """Snap picture for a blink doorbell camera."""
+ url = f"{self.sync.urls.base_url}/api/v1/accounts/{self.sync.blink.account_id}/networks/{self.network_id}/lotus/{self.camera_id}/thumbnail"
+ return api.http_post(self.sync.blink, url)
+
+ def get_sensor_info(self):
+ """Get sensor info for blink doorbell camera."""
+
+ def get_liveview(self):
+ """Get liveview link."""
+ url = f"{self.sync.urls.base_url}/api/v1/accounts/{self.sync.blink.account_id}/networks/{self.network_id}/lotus/{self.camera_id}/liveview"
+ response = api.http_post(self.sync.blink, url)
+ server = response["server"]
+ server_split = server.split(":")
+ server_split[0] = "rtsps:"
+ link = "".join(server_split)
+ return link
diff --git a/blinkpy/sync_module.py b/blinkpy/sync_module.py
index 4e31756..2730de5 100644
--- a/blinkpy/sync_module.py
+++ b/blinkpy/sync_module.py
@@ -4,7 +4,7 @@ import logging
from requests.structures import CaseInsensitiveDict
from blinkpy import api
-from blinkpy.camera import BlinkCamera, BlinkCameraMini
+from blinkpy.camera import BlinkCamera, BlinkCameraMini, BlinkDoorbell
from blinkpy.helpers.util import time_to_seconds
from blinkpy.helpers.constants import ONLINE
@@ -126,11 +126,14 @@ class BlinkSyncModule:
name = camera_config["name"]
self.motion[name] = False
owl_info = self.get_owl_info(name)
+ lotus_info = self.get_lotus_info(name)
if blink_camera_type == "mini":
camera_type = BlinkCameraMini
+ if blink_camera_type == "lotus":
+ camera_type = BlinkDoorbell
self.cameras[name] = camera_type(self)
camera_info = self.get_camera_info(
- camera_config["id"], owl_info=owl_info
+ camera_config["id"], owl_info=owl_info, lotus_info=lotus_info
)
self.cameras[name].update(camera_info, force_cache=True, force=True)
@@ -149,6 +152,16 @@ class BlinkSyncModule:
pass
return None
+ def get_lotus_info(self, name):
+ """Extract lotus information."""
+ try:
+ for doorbell in self.blink.homescreen["doorbells"]:
+ if doorbell["name"] == name:
+ return doorbell
+ except (TypeError, KeyError):
+ pass
+ return None
+
def get_events(self, **kwargs):
"""Retrieve events from server."""
force = kwargs.pop("force", False)
@@ -164,6 +177,9 @@ class BlinkSyncModule:
owl = kwargs.get("owl_info", None)
if owl is not None:
return owl
+ lotus = kwargs.get("lotus_info", None)
+ if lotus is not None:
+ return lotus
response = api.request_camera_info(self.blink, self.network_id, camera_id)
try:
return response["camera"][0]
@@ -190,7 +206,9 @@ class BlinkSyncModule:
for camera_name in self.cameras.keys():
camera_id = self.cameras[camera_name].camera_id
camera_info = self.get_camera_info(
- camera_id, owl_info=self.get_owl_info(camera_name)
+ camera_id,
+ owl_info=self.get_owl_info(camera_name),
+ lotus_info=self.get_lotus_info(camera_name),
)
self.cameras[camera_name].update(camera_info, force_cache=force_cache)
self.available = True
@@ -294,3 +312,66 @@ class BlinkOwl(BlinkSyncModule):
@network_info.setter
def network_info(self, value):
"""Set network_info property."""
+
+
+class BlinkLotus(BlinkSyncModule):
+ """Representation of a sync-less device."""
+
+ def __init__(self, blink, name, network_id, response):
+ """Initialize a sync-less object."""
+ cameras = [{"name": name, "id": response["id"]}]
+ super().__init__(blink, name, network_id, cameras)
+ self.sync_id = response["id"]
+ self.serial = response["serial"]
+ self.status = response["enabled"]
+ if not self.serial:
+ self.serial = f"{network_id}-{self.sync_id}"
+
+ def sync_initialize(self):
+ """Initialize a sync-less module."""
+ self.summary = {
+ "id": self.sync_id,
+ "name": self.name,
+ "serial": self.serial,
+ "status": self.status,
+ "onboarded": True,
+ "account_id": self.blink.account_id,
+ "network_id": self.network_id,
+ }
+ return self.summary
+
+ def update_cameras(self, camera_type=BlinkDoorbell):
+ """Update sync-less cameras."""
+ return super().update_cameras(camera_type=BlinkDoorbell)
+
+ def get_camera_info(self, camera_id, **kwargs):
+ """Retrieve camera information."""
+ try:
+ for doorbell in self.blink.homescreen["doorbells"]:
+ if doorbell["name"] == self.name:
+ self.status = doorbell["enabled"]
+ return doorbell
+ except (TypeError, KeyError):
+ pass
+ return None
+
+ def get_network_info(self):
+ """Get network info for sync-less module."""
+ return True
+
+ @property
+ def network_info(self):
+ """Format lotus response to resemble sync module."""
+ return {
+ "network": {
+ "id": self.network_id,
+ "name": self.name,
+ "armed": self.status,
+ "sync_module_error": False,
+ "account_id": self.blink.account_id,
+ }
+ }
+
+ @network_info.setter
+ def network_info(self, value):
+ """Set network_info property."""
|
fronzbot/blinkpy
|
43f048cf1320e47a66be5ff82b83c17c247c9dab
|
diff --git a/tests/test_blinkpy.py b/tests/test_blinkpy.py
index c632215..e884179 100644
--- a/tests/test_blinkpy.py
+++ b/tests/test_blinkpy.py
@@ -9,7 +9,7 @@ any communication related errors at startup.
import unittest
from unittest import mock
from blinkpy.blinkpy import Blink, BlinkSetupError
-from blinkpy.sync_module import BlinkOwl
+from blinkpy.sync_module import BlinkOwl, BlinkLotus
from blinkpy.helpers.constants import __version__
@@ -164,10 +164,12 @@ class TestBlinkSetup(unittest.TestCase):
@mock.patch("blinkpy.blinkpy.Blink.setup_camera_list")
@mock.patch("blinkpy.api.request_networks")
@mock.patch("blinkpy.blinkpy.Blink.setup_owls")
- def test_setup_post_verify(self, mock_owl, mock_networks, mock_camera):
+ @mock.patch("blinkpy.blinkpy.Blink.setup_lotus")
+ def test_setup_post_verify(self, mock_lotus, mock_owl, mock_networks, mock_camera):
"""Test setup after verification."""
self.blink.available = False
self.blink.key_required = True
+ mock_lotus.return_value = True
mock_owl.return_value = True
mock_networks.return_value = {
"summary": {"foo": {"onboarded": False, "name": "bar"}}
@@ -288,6 +290,96 @@ class TestBlinkSetup(unittest.TestCase):
result, {"1234": [{"name": "foo", "id": "1234", "type": "mini"}]}
)
+ @mock.patch("blinkpy.blinkpy.BlinkLotus.start")
+ def test_initialize_blink_doorbells(self, mock_start):
+ """Test blink doorbell initialization."""
+ mock_start.return_value = True
+ self.blink.homescreen = {
+ "doorbells": [
+ {
+ "enabled": False,
+ "id": 1,
+ "name": "foo",
+ "network_id": 2,
+ "onboarded": True,
+ "status": "online",
+ "thumbnail": "/foo/bar",
+ "serial": "1234",
+ },
+ {
+ "enabled": True,
+ "id": 3,
+ "name": "bar",
+ "network_id": 4,
+ "onboarded": True,
+ "status": "online",
+ "thumbnail": "/foo/bar",
+ "serial": "abcd",
+ },
+ ]
+ }
+ self.blink.sync = {}
+ self.blink.setup_lotus()
+ self.assertEqual(self.blink.sync["foo"].__class__, BlinkLotus)
+ self.assertEqual(self.blink.sync["bar"].__class__, BlinkLotus)
+ self.assertEqual(self.blink.sync["foo"].arm, False)
+ self.assertEqual(self.blink.sync["bar"].arm, True)
+ self.assertEqual(self.blink.sync["foo"].name, "foo")
+ self.assertEqual(self.blink.sync["bar"].name, "bar")
+
+ # def test_blink_doorbell_cameras_returned(self):
+ # """Test that blink doorbell cameras are found if attached to sync module."""
+ # self.blink.network_ids = ["1234"]
+ # self.blink.homescreen = {
+ # "doorbells": [
+ # {
+ # "id": 1,
+ # "name": "foo",
+ # "network_id": 1234,
+ # "onboarded": True,
+ # "enabled": True,
+ # "status": "online",
+ # "thumbnail": "/foo/bar",
+ # "serial": "abc123",
+ # }
+ # ]
+ # }
+ # result = self.blink.setup_lotus()
+ # self.assertEqual(self.blink.network_ids, ["1234"])
+ # self.assertEqual(
+ # result, [{"1234": {"name": "foo", "id": "1234", "type": "doorbell"}}]
+ # )
+
+ # self.blink.network_ids = []
+ # self.blink.get_homescreen()
+ # result = self.blink.setup_lotus()
+ # self.assertEqual(self.blink.network_ids, [])
+ # self.assertEqual(result, [])
+
+ @mock.patch("blinkpy.api.request_camera_usage")
+ def test_blink_doorbell_attached_to_sync(self, mock_usage):
+ """Test that blink doorbell cameras are properly attached to sync module."""
+ self.blink.network_ids = ["1234"]
+ self.blink.homescreen = {
+ "doorbells": [
+ {
+ "id": 1,
+ "name": "foo",
+ "network_id": 1234,
+ "onboarded": True,
+ "enabled": True,
+ "status": "online",
+ "thumbnail": "/foo/bar",
+ "serial": "abc123",
+ }
+ ]
+ }
+ mock_usage.return_value = {"networks": [{"cameras": [], "network_id": 1234}]}
+ result = self.blink.setup_camera_list()
+ self.assertEqual(
+ result, {"1234": [{"name": "foo", "id": "1234", "type": "doorbell"}]}
+ )
+
class MockSync:
"""Mock sync module class."""
diff --git a/tests/test_cameras.py b/tests/test_cameras.py
index 8cf7d76..e482a72 100644
--- a/tests/test_cameras.py
+++ b/tests/test_cameras.py
@@ -11,7 +11,7 @@ from unittest import mock
from blinkpy.blinkpy import Blink
from blinkpy.helpers.util import BlinkURLHandler
from blinkpy.sync_module import BlinkSyncModule
-from blinkpy.camera import BlinkCamera, BlinkCameraMini
+from blinkpy.camera import BlinkCamera, BlinkCameraMini, BlinkDoorbell
CAMERA_CFG = {
@@ -177,9 +177,20 @@ class TestBlinkCameraSetup(unittest.TestCase):
for key in attr:
self.assertEqual(attr[key], None)
+ def test_doorbell_missing_attributes(self, mock_resp):
+ """Test that attributes return None if missing."""
+ camera = BlinkDoorbell(self.blink.sync)
+ self.blink.sync.network_id = None
+ self.blink.sync.name = None
+ attr = camera.attributes
+ for key in attr:
+ self.assertEqual(attr[key], None)
+
def test_camera_stream(self, mock_resp):
"""Test that camera stream returns correct url."""
mock_resp.return_value = {"server": "rtsps://foo.bar"}
mini_camera = BlinkCameraMini(self.blink.sync["test"])
+ doorbell_camera = BlinkDoorbell(self.blink.sync["test"])
self.assertEqual(self.camera.get_liveview(), "rtsps://foo.bar")
self.assertEqual(mini_camera.get_liveview(), "rtsps://foo.bar")
+ self.assertEqual(doorbell_camera.get_liveview(), "rtsps://foo.bar")
diff --git a/tests/test_sync_module.py b/tests/test_sync_module.py
index fc18a51..67d5206 100644
--- a/tests/test_sync_module.py
+++ b/tests/test_sync_module.py
@@ -4,8 +4,8 @@ from unittest import mock
from blinkpy.blinkpy import Blink
from blinkpy.helpers.util import BlinkURLHandler
-from blinkpy.sync_module import BlinkSyncModule, BlinkOwl
-from blinkpy.camera import BlinkCamera, BlinkCameraMini
+from blinkpy.sync_module import BlinkSyncModule, BlinkOwl, BlinkLotus
+from blinkpy.camera import BlinkCamera, BlinkCameraMini, BlinkDoorbell
@mock.patch("blinkpy.auth.Auth.query")
@@ -292,3 +292,20 @@ class TestBlinkSyncModule(unittest.TestCase):
self.assertTrue(owl.start())
self.assertTrue("foo" in owl.cameras)
self.assertEqual(owl.cameras["foo"].__class__, BlinkCameraMini)
+
+ def test_lotus_start(self, mock_resp):
+ """Test doorbell instantiation."""
+ response = {
+ "name": "doo",
+ "id": 3,
+ "serial": "doobar123",
+ "enabled": True,
+ "network_id": 1,
+ "thumbnail": "/foo/bar",
+ }
+ self.blink.last_refresh = None
+ self.blink.homescreen = {"doorbells": [response]}
+ lotus = BlinkLotus(self.blink, "doo", 1234, response)
+ self.assertTrue(lotus.start())
+ self.assertTrue("doo" in lotus.cameras)
+ self.assertEqual(lotus.cameras["doo"].__class__, BlinkDoorbell)
|
Blink Video Doorbell Support
**Describe the bug**
Related to https://github.com/home-assistant/core/issues/58662
Blink recently introduced video doorbells. After installation of hardware and activation on my existing Blink local system, the Video Doorbell does not appear in Home Assistant. No errors were logged by the home assistant integration.
**To Reproduce**
Steps to reproduce the behavior:
1. Install video doorbell hardware.
2. Follow instruction in Blink Home Monitor to add to existing setup.
3. Once added, reload and re-install Blink Integration in Home Assistant.
4. Other Blink cameras appear normally (including Mini) but Video doorbell is not recognized at all.
**Expected behavior**
Would expect the video doorbell to appear with functionality similar to other Blink cameras.
**Home Assistant version (if applicable):** 2021.10.6
**Log Output/Additional Information**
If using home-assistant, please paste the output of the log showing your error below. If not, please include any additional useful information.
```
Integration logged no errors.
```
|
0.0
|
43f048cf1320e47a66be5ff82b83c17c247c9dab
|
[
"tests/test_blinkpy.py::TestBlinkSetup::test_blink_doorbell_attached_to_sync",
"tests/test_blinkpy.py::TestBlinkSetup::test_blink_mini_attached_to_sync",
"tests/test_blinkpy.py::TestBlinkSetup::test_blink_mini_cameras_returned",
"tests/test_blinkpy.py::TestBlinkSetup::test_initialization",
"tests/test_blinkpy.py::TestBlinkSetup::test_initialize_blink_doorbells",
"tests/test_blinkpy.py::TestBlinkSetup::test_initialize_blink_minis",
"tests/test_blinkpy.py::TestBlinkSetup::test_merge_cameras",
"tests/test_blinkpy.py::TestBlinkSetup::test_multiple_networks",
"tests/test_blinkpy.py::TestBlinkSetup::test_multiple_onboarded_networks",
"tests/test_blinkpy.py::TestBlinkSetup::test_network_id_failure",
"tests/test_blinkpy.py::TestBlinkSetup::test_setup_cameras",
"tests/test_blinkpy.py::TestBlinkSetup::test_setup_cameras_failure",
"tests/test_blinkpy.py::TestBlinkSetup::test_setup_networks",
"tests/test_blinkpy.py::TestBlinkSetup::test_setup_networks_failure",
"tests/test_blinkpy.py::TestBlinkSetup::test_setup_post_verify",
"tests/test_blinkpy.py::TestBlinkSetup::test_setup_post_verify_failure",
"tests/test_blinkpy.py::TestBlinkSetup::test_setup_prompt_2fa",
"tests/test_blinkpy.py::TestBlinkSetup::test_setup_urls",
"tests/test_blinkpy.py::TestBlinkSetup::test_setup_urls_failure",
"tests/test_blinkpy.py::TestBlinkSetup::test_sync_case_insensitive_dict",
"tests/test_blinkpy.py::TestBlinkSetup::test_throttle",
"tests/test_cameras.py::TestBlinkCameraSetup::test_camera_arm_status",
"tests/test_cameras.py::TestBlinkCameraSetup::test_camera_stream",
"tests/test_cameras.py::TestBlinkCameraSetup::test_camera_update",
"tests/test_cameras.py::TestBlinkCameraSetup::test_doorbell_missing_attributes",
"tests/test_cameras.py::TestBlinkCameraSetup::test_mini_missing_attributes",
"tests/test_cameras.py::TestBlinkCameraSetup::test_missing_attributes",
"tests/test_cameras.py::TestBlinkCameraSetup::test_motion_detection_enable_disable",
"tests/test_cameras.py::TestBlinkCameraSetup::test_no_thumbnails",
"tests/test_cameras.py::TestBlinkCameraSetup::test_no_video_clips",
"tests/test_sync_module.py::TestBlinkSyncModule::test_bad_arm",
"tests/test_sync_module.py::TestBlinkSyncModule::test_bad_status",
"tests/test_sync_module.py::TestBlinkSyncModule::test_check_multiple_videos",
"tests/test_sync_module.py::TestBlinkSyncModule::test_check_new_videos",
"tests/test_sync_module.py::TestBlinkSyncModule::test_check_new_videos_failed",
"tests/test_sync_module.py::TestBlinkSyncModule::test_check_new_videos_old_date",
"tests/test_sync_module.py::TestBlinkSyncModule::test_check_new_videos_startup",
"tests/test_sync_module.py::TestBlinkSyncModule::test_check_no_motion_if_not_armed",
"tests/test_sync_module.py::TestBlinkSyncModule::test_get_camera_info",
"tests/test_sync_module.py::TestBlinkSyncModule::test_get_camera_info_fail",
"tests/test_sync_module.py::TestBlinkSyncModule::test_get_events",
"tests/test_sync_module.py::TestBlinkSyncModule::test_get_events_fail",
"tests/test_sync_module.py::TestBlinkSyncModule::test_get_network_info",
"tests/test_sync_module.py::TestBlinkSyncModule::test_get_network_info_failure",
"tests/test_sync_module.py::TestBlinkSyncModule::test_lotus_start",
"tests/test_sync_module.py::TestBlinkSyncModule::test_missing_camera_info",
"tests/test_sync_module.py::TestBlinkSyncModule::test_owl_start",
"tests/test_sync_module.py::TestBlinkSyncModule::test_summary_with_no_network_id",
"tests/test_sync_module.py::TestBlinkSyncModule::test_summary_with_only_network_id",
"tests/test_sync_module.py::TestBlinkSyncModule::test_sync_attributes",
"tests/test_sync_module.py::TestBlinkSyncModule::test_sync_start",
"tests/test_sync_module.py::TestBlinkSyncModule::test_unexpected_camera_info",
"tests/test_sync_module.py::TestBlinkSyncModule::test_unexpected_summary"
] |
[] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-12-11 13:11:01+00:00
|
mit
| 2,413 |
|
frostming__marko-123
|
diff --git a/marko/block.py b/marko/block.py
index 22cf1c5..10a2b9d 100644
--- a/marko/block.py
+++ b/marko/block.py
@@ -8,7 +8,7 @@ from typing import Match, Optional, Tuple, Union, cast
from . import inline, patterns
from .element import Element
-from .helpers import Source, is_paired, normalize_label
+from .helpers import Source, is_paired, normalize_label, partition_by_spaces
from .parser import Parser
__all__ = (
@@ -231,7 +231,7 @@ class FencedCode(BlockElement):
prefix, leading, info = m.groups()
if leading[0] == "`" and "`" in info:
return None
- lang, extra = (info.split(None, 1) + [""] * 2)[:2]
+ lang, _, extra = partition_by_spaces(info)
cls._parse_info = prefix, leading, lang, extra
return m
@@ -374,7 +374,7 @@ class Paragraph(BlockElement):
return True
if parser.block_elements["List"].match(source):
result = parser.block_elements["ListItem"].parse_leading(
- source.next_line(), 0
+ source.next_line().rstrip(), 0
)
if lazy or (result[1][:-1] == "1" or result[1] in "*-+") and result[3]:
return True
@@ -501,13 +501,13 @@ class List(BlockElement):
class ListItem(BlockElement):
"""List item element. It can only be created by List.parse"""
- _parse_info = (0, "", 0, "")
+ _parse_info = (0, "", 0)
virtual = True
_tight = False
pattern = re.compile(r" {,3}(\d{1,9}[.)]|[*\-+])[ \t\n\r\f]")
def __init__(self) -> None:
- indent, bullet, mid, tail = self._parse_info
+ indent, bullet, mid = self._parse_info
self._prefix = " " * indent + re.escape(bullet) + " " * mid
self._second_prefix = " " * (len(bullet) + indent + (mid or 1))
@@ -515,18 +515,10 @@ class ListItem(BlockElement):
def parse_leading(cls, line: str, prefix_pos: int) -> Tuple[int, str, int, str]:
stripped_line = line[prefix_pos:].expandtabs(4).lstrip()
indent = len(line) - prefix_pos - len(stripped_line)
- temp = stripped_line.split(None, 1)
- bullet = temp[0]
- if len(temp) == 1:
- # Bare bullets (* \n)
- mid = 0
- tail = ""
- else:
- mid = len(stripped_line) - len("".join(temp))
- if mid > 4:
- # If indented more than 4 spaces, it should be a indented code block
- mid = 1
- tail = temp[1]
+ bullet, spaces, tail = partition_by_spaces(stripped_line)
+ mid = len(spaces)
+ if mid > 4:
+ mid = 1
return indent, bullet, mid, tail
@classmethod
@@ -540,7 +532,7 @@ class ListItem(BlockElement):
m = re.match(source.prefix, next_line)
if m is not None:
prefix_pos = m.end()
- indent, bullet, mid, tail = cls.parse_leading(next_line, prefix_pos) # type: ignore
+ indent, bullet, mid, _ = cls.parse_leading(next_line.rstrip(), prefix_pos) # type: ignore
parent = source.state
assert isinstance(parent, List)
if (
@@ -551,7 +543,7 @@ class ListItem(BlockElement):
return False
if not parent.ordered and bullet != parent.bullet:
return False
- cls._parse_info = (indent, bullet, mid, tail)
+ cls._parse_info = (indent, bullet, mid)
return True
@classmethod
diff --git a/marko/helpers.py b/marko/helpers.py
index acd09f0..1a27833 100644
--- a/marko/helpers.py
+++ b/marko/helpers.py
@@ -13,6 +13,7 @@ from typing import (
Match,
Optional,
Pattern,
+ Tuple,
Union,
)
@@ -187,6 +188,27 @@ def normalize_label(label: str) -> str:
return re.sub(r"\s+", " ", label).strip().casefold()
+def partition_by_spaces(text: str) -> Tuple[str, str, str]:
+ """Split the given text by spaces or tabs, and return a tuple of
+ (start, delimiter, remaining). If spaces are not found, the latter
+ two elements will be empty.
+ """
+ start = end = -1
+ for i, c in enumerate(text):
+ if c in " \t":
+ if start >= 0:
+ continue
+ start = i
+ elif start >= 0:
+ end = i
+ break
+ if start < 0:
+ return text, "", ""
+ if end < 0:
+ return text[:start], text[start:], ""
+ return text[:start], text[start:end], text[end:]
+
+
def load_extension_object(name: str) -> Callable:
"""Load extension object from a string.
First try `marko.ext.<name>` if possible
|
frostming/marko
|
f7dfd20d1106bef06e2b7513b15be70ef8786f0a
|
diff --git a/tests/test_helpers.py b/tests/test_helpers.py
index 3b472aa..ebefd36 100644
--- a/tests/test_helpers.py
+++ b/tests/test_helpers.py
@@ -57,3 +57,17 @@ def test_load_illegal_extension_object():
match="Module marko.block does not have 'make_extension' attributte",
):
helpers.load_extension_object("marko.block")()
+
+
[email protected](
+ "text, expected",
+ [
+ ("hello world", ("hello", " ", "world")),
+ ("hello", ("hello", "", "")),
+ ("hello ", ("hello", " ", "")),
+ (" hello", ("", " ", "hello")),
+ ("hello\t wor ld", ("hello", "\t ", "wor ld")),
+ ],
+)
+def test_partition_by_spaces(text, expected):
+ assert helpers.partition_by_spaces(text) == expected
diff --git a/tests/test_spec.py b/tests/test_spec.py
index 92c22a9..6a67e28 100644
--- a/tests/test_spec.py
+++ b/tests/test_spec.py
@@ -16,6 +16,11 @@ class TestCommonMark(SpecTestSuite):
)
self.assert_case(md, html)
+ def test_parse_nbsp_no_crash(self):
+ md = "- \xa0A"
+ html = "<ul>\n<li>A</li>\n</ul>"
+ self.assert_case(md, html)
+
TestCommonMark.load_spec("commonmark")
|
Crash when parsing "- {NBSP}A"
Code that crashes is:
~~~
parser = Markdown(Parser, MarkdownRenderer)
with open(src_file_path, "r") as txtFile:
result = parser.parse(txtFile.read())
~~~
Markdown file is:
~~~
- A
~~~
Note that there is a unicode character U+00A0 right before the `A` that is a NBSP (non-breaking space).
Crash is:
~~~
File "/Users/ericzinda/Enlistments/docsproto/env/lib/python3.7/site-packages/marko/__init__.py", line 120, in parse
return cast("Document", self.parser.parse(text))
File "/Users/ericzinda/Enlistments/docsproto/env/lib/python3.7/site-packages/marko/parser.py", line 65, in parse
return self.block_elements["Document"](source_or_text) # type: ignore
File "/Users/ericzinda/Enlistments/docsproto/env/lib/python3.7/site-packages/marko/block.py", line 91, in __init__
self.children = parser.parse(source) # type: ignore
File "/Users/ericzinda/Enlistments/docsproto/env/lib/python3.7/site-packages/marko/parser.py", line 72, in parse
result = ele_type.parse(source_or_text)
File "/Users/ericzinda/Enlistments/docsproto/env/lib/python3.7/site-packages/marko/block.py", line 474, in parse
el = parser.block_elements["ListItem"].parse(source) # type: ignore
File "/Users/ericzinda/Enlistments/docsproto/env/lib/python3.7/site-packages/marko/block.py", line 562, in parse
if not source.next_line().strip(): # type: ignore
AttributeError: 'NoneType' object has no attribute 'strip'
~~~
|
0.0
|
f7dfd20d1106bef06e2b7513b15be70ef8786f0a
|
[
"tests/test_helpers.py::test_partition_by_spaces[hello",
"tests/test_helpers.py::test_partition_by_spaces[hello-expected1]",
"tests/test_helpers.py::test_partition_by_spaces[",
"tests/test_helpers.py::test_partition_by_spaces[hello\\t",
"tests/test_spec.py::TestCommonMark::test_parse_nbsp_no_crash"
] |
[
"tests/test_helpers.py::test_is_paired[(hello(to)world)]",
"tests/test_helpers.py::test_is_paired[(hello\\\\)world)]",
"tests/test_helpers.py::test_is_paired[he\\\\(llo(world)]",
"tests/test_helpers.py::test_is_paired[]",
"tests/test_helpers.py::test_is_paired[hello",
"tests/test_helpers.py::test_is_paired[(hello),",
"tests/test_helpers.py::test_is_not_paired[(hello(toworld)]",
"tests/test_helpers.py::test_is_not_paired[(hello)world)]",
"tests/test_helpers.py::test_is_not_paired[(]",
"tests/test_helpers.py::test_source_no_state",
"tests/test_helpers.py::test_load_extension_object",
"tests/test_helpers.py::test_load_illegal_extension_object",
"tests/test_spec.py::TestCommonMark::test_mixed_tab_space_in_list_item",
"tests/test_spec.py::TestCommonMark::test_greedy_consume_prefix",
"tests/test_spec.py::TestCommonMark::test_tabs_001",
"tests/test_spec.py::TestCommonMark::test_tabs_002",
"tests/test_spec.py::TestCommonMark::test_tabs_003",
"tests/test_spec.py::TestCommonMark::test_tabs_004",
"tests/test_spec.py::TestCommonMark::test_tabs_005",
"tests/test_spec.py::TestCommonMark::test_tabs_006",
"tests/test_spec.py::TestCommonMark::test_tabs_007",
"tests/test_spec.py::TestCommonMark::test_tabs_008",
"tests/test_spec.py::TestCommonMark::test_tabs_009",
"tests/test_spec.py::TestCommonMark::test_tabs_010",
"tests/test_spec.py::TestCommonMark::test_tabs_011",
"tests/test_spec.py::TestCommonMark::test_backslash_escapes_001",
"tests/test_spec.py::TestCommonMark::test_backslash_escapes_002",
"tests/test_spec.py::TestCommonMark::test_backslash_escapes_003",
"tests/test_spec.py::TestCommonMark::test_backslash_escapes_004",
"tests/test_spec.py::TestCommonMark::test_backslash_escapes_005",
"tests/test_spec.py::TestCommonMark::test_backslash_escapes_006",
"tests/test_spec.py::TestCommonMark::test_backslash_escapes_007",
"tests/test_spec.py::TestCommonMark::test_backslash_escapes_008",
"tests/test_spec.py::TestCommonMark::test_backslash_escapes_009",
"tests/test_spec.py::TestCommonMark::test_backslash_escapes_010",
"tests/test_spec.py::TestCommonMark::test_backslash_escapes_011",
"tests/test_spec.py::TestCommonMark::test_backslash_escapes_012",
"tests/test_spec.py::TestCommonMark::test_backslash_escapes_013",
"tests/test_spec.py::TestCommonMark::test_entity_and_numeric_character_references_001",
"tests/test_spec.py::TestCommonMark::test_entity_and_numeric_character_references_002",
"tests/test_spec.py::TestCommonMark::test_entity_and_numeric_character_references_003",
"tests/test_spec.py::TestCommonMark::test_entity_and_numeric_character_references_004",
"tests/test_spec.py::TestCommonMark::test_entity_and_numeric_character_references_005",
"tests/test_spec.py::TestCommonMark::test_entity_and_numeric_character_references_006",
"tests/test_spec.py::TestCommonMark::test_entity_and_numeric_character_references_007",
"tests/test_spec.py::TestCommonMark::test_entity_and_numeric_character_references_008",
"tests/test_spec.py::TestCommonMark::test_entity_and_numeric_character_references_009",
"tests/test_spec.py::TestCommonMark::test_entity_and_numeric_character_references_010",
"tests/test_spec.py::TestCommonMark::test_entity_and_numeric_character_references_011",
"tests/test_spec.py::TestCommonMark::test_entity_and_numeric_character_references_012",
"tests/test_spec.py::TestCommonMark::test_entity_and_numeric_character_references_013",
"tests/test_spec.py::TestCommonMark::test_entity_and_numeric_character_references_014",
"tests/test_spec.py::TestCommonMark::test_entity_and_numeric_character_references_015",
"tests/test_spec.py::TestCommonMark::test_entity_and_numeric_character_references_016",
"tests/test_spec.py::TestCommonMark::test_entity_and_numeric_character_references_017",
"tests/test_spec.py::TestCommonMark::test_precedence_001",
"tests/test_spec.py::TestCommonMark::test_thematic_breaks_001",
"tests/test_spec.py::TestCommonMark::test_thematic_breaks_002",
"tests/test_spec.py::TestCommonMark::test_thematic_breaks_003",
"tests/test_spec.py::TestCommonMark::test_thematic_breaks_004",
"tests/test_spec.py::TestCommonMark::test_thematic_breaks_005",
"tests/test_spec.py::TestCommonMark::test_thematic_breaks_006",
"tests/test_spec.py::TestCommonMark::test_thematic_breaks_007",
"tests/test_spec.py::TestCommonMark::test_thematic_breaks_008",
"tests/test_spec.py::TestCommonMark::test_thematic_breaks_009",
"tests/test_spec.py::TestCommonMark::test_thematic_breaks_010",
"tests/test_spec.py::TestCommonMark::test_thematic_breaks_011",
"tests/test_spec.py::TestCommonMark::test_thematic_breaks_012",
"tests/test_spec.py::TestCommonMark::test_thematic_breaks_013",
"tests/test_spec.py::TestCommonMark::test_thematic_breaks_014",
"tests/test_spec.py::TestCommonMark::test_thematic_breaks_015",
"tests/test_spec.py::TestCommonMark::test_thematic_breaks_016",
"tests/test_spec.py::TestCommonMark::test_thematic_breaks_017",
"tests/test_spec.py::TestCommonMark::test_thematic_breaks_018",
"tests/test_spec.py::TestCommonMark::test_thematic_breaks_019",
"tests/test_spec.py::TestCommonMark::test_atx_headings_001",
"tests/test_spec.py::TestCommonMark::test_atx_headings_002",
"tests/test_spec.py::TestCommonMark::test_atx_headings_003",
"tests/test_spec.py::TestCommonMark::test_atx_headings_004",
"tests/test_spec.py::TestCommonMark::test_atx_headings_005",
"tests/test_spec.py::TestCommonMark::test_atx_headings_006",
"tests/test_spec.py::TestCommonMark::test_atx_headings_007",
"tests/test_spec.py::TestCommonMark::test_atx_headings_008",
"tests/test_spec.py::TestCommonMark::test_atx_headings_009",
"tests/test_spec.py::TestCommonMark::test_atx_headings_010",
"tests/test_spec.py::TestCommonMark::test_atx_headings_011",
"tests/test_spec.py::TestCommonMark::test_atx_headings_012",
"tests/test_spec.py::TestCommonMark::test_atx_headings_013",
"tests/test_spec.py::TestCommonMark::test_atx_headings_014",
"tests/test_spec.py::TestCommonMark::test_atx_headings_015",
"tests/test_spec.py::TestCommonMark::test_atx_headings_016",
"tests/test_spec.py::TestCommonMark::test_atx_headings_017",
"tests/test_spec.py::TestCommonMark::test_atx_headings_018",
"tests/test_spec.py::TestCommonMark::test_setext_headings_001",
"tests/test_spec.py::TestCommonMark::test_setext_headings_002",
"tests/test_spec.py::TestCommonMark::test_setext_headings_003",
"tests/test_spec.py::TestCommonMark::test_setext_headings_004",
"tests/test_spec.py::TestCommonMark::test_setext_headings_005",
"tests/test_spec.py::TestCommonMark::test_setext_headings_006",
"tests/test_spec.py::TestCommonMark::test_setext_headings_007",
"tests/test_spec.py::TestCommonMark::test_setext_headings_008",
"tests/test_spec.py::TestCommonMark::test_setext_headings_009",
"tests/test_spec.py::TestCommonMark::test_setext_headings_010",
"tests/test_spec.py::TestCommonMark::test_setext_headings_011",
"tests/test_spec.py::TestCommonMark::test_setext_headings_012",
"tests/test_spec.py::TestCommonMark::test_setext_headings_013",
"tests/test_spec.py::TestCommonMark::test_setext_headings_014",
"tests/test_spec.py::TestCommonMark::test_setext_headings_015",
"tests/test_spec.py::TestCommonMark::test_setext_headings_016",
"tests/test_spec.py::TestCommonMark::test_setext_headings_017",
"tests/test_spec.py::TestCommonMark::test_setext_headings_018",
"tests/test_spec.py::TestCommonMark::test_setext_headings_019",
"tests/test_spec.py::TestCommonMark::test_setext_headings_020",
"tests/test_spec.py::TestCommonMark::test_setext_headings_021",
"tests/test_spec.py::TestCommonMark::test_setext_headings_022",
"tests/test_spec.py::TestCommonMark::test_setext_headings_023",
"tests/test_spec.py::TestCommonMark::test_setext_headings_024",
"tests/test_spec.py::TestCommonMark::test_setext_headings_025",
"tests/test_spec.py::TestCommonMark::test_setext_headings_026",
"tests/test_spec.py::TestCommonMark::test_setext_headings_027",
"tests/test_spec.py::TestCommonMark::test_indented_code_blocks_001",
"tests/test_spec.py::TestCommonMark::test_indented_code_blocks_002",
"tests/test_spec.py::TestCommonMark::test_indented_code_blocks_003",
"tests/test_spec.py::TestCommonMark::test_indented_code_blocks_004",
"tests/test_spec.py::TestCommonMark::test_indented_code_blocks_005",
"tests/test_spec.py::TestCommonMark::test_indented_code_blocks_006",
"tests/test_spec.py::TestCommonMark::test_indented_code_blocks_007",
"tests/test_spec.py::TestCommonMark::test_indented_code_blocks_008",
"tests/test_spec.py::TestCommonMark::test_indented_code_blocks_009",
"tests/test_spec.py::TestCommonMark::test_indented_code_blocks_010",
"tests/test_spec.py::TestCommonMark::test_indented_code_blocks_011",
"tests/test_spec.py::TestCommonMark::test_indented_code_blocks_012",
"tests/test_spec.py::TestCommonMark::test_fenced_code_blocks_001",
"tests/test_spec.py::TestCommonMark::test_fenced_code_blocks_002",
"tests/test_spec.py::TestCommonMark::test_fenced_code_blocks_003",
"tests/test_spec.py::TestCommonMark::test_fenced_code_blocks_004",
"tests/test_spec.py::TestCommonMark::test_fenced_code_blocks_005",
"tests/test_spec.py::TestCommonMark::test_fenced_code_blocks_006",
"tests/test_spec.py::TestCommonMark::test_fenced_code_blocks_007",
"tests/test_spec.py::TestCommonMark::test_fenced_code_blocks_008",
"tests/test_spec.py::TestCommonMark::test_fenced_code_blocks_009",
"tests/test_spec.py::TestCommonMark::test_fenced_code_blocks_010",
"tests/test_spec.py::TestCommonMark::test_fenced_code_blocks_011",
"tests/test_spec.py::TestCommonMark::test_fenced_code_blocks_012",
"tests/test_spec.py::TestCommonMark::test_fenced_code_blocks_013",
"tests/test_spec.py::TestCommonMark::test_fenced_code_blocks_014",
"tests/test_spec.py::TestCommonMark::test_fenced_code_blocks_015",
"tests/test_spec.py::TestCommonMark::test_fenced_code_blocks_016",
"tests/test_spec.py::TestCommonMark::test_fenced_code_blocks_017",
"tests/test_spec.py::TestCommonMark::test_fenced_code_blocks_018",
"tests/test_spec.py::TestCommonMark::test_fenced_code_blocks_019",
"tests/test_spec.py::TestCommonMark::test_fenced_code_blocks_020",
"tests/test_spec.py::TestCommonMark::test_fenced_code_blocks_021",
"tests/test_spec.py::TestCommonMark::test_fenced_code_blocks_022",
"tests/test_spec.py::TestCommonMark::test_fenced_code_blocks_023",
"tests/test_spec.py::TestCommonMark::test_fenced_code_blocks_024",
"tests/test_spec.py::TestCommonMark::test_fenced_code_blocks_025",
"tests/test_spec.py::TestCommonMark::test_fenced_code_blocks_026",
"tests/test_spec.py::TestCommonMark::test_fenced_code_blocks_027",
"tests/test_spec.py::TestCommonMark::test_fenced_code_blocks_028",
"tests/test_spec.py::TestCommonMark::test_fenced_code_blocks_029",
"tests/test_spec.py::TestCommonMark::test_html_blocks_001",
"tests/test_spec.py::TestCommonMark::test_html_blocks_002",
"tests/test_spec.py::TestCommonMark::test_html_blocks_003",
"tests/test_spec.py::TestCommonMark::test_html_blocks_004",
"tests/test_spec.py::TestCommonMark::test_html_blocks_005",
"tests/test_spec.py::TestCommonMark::test_html_blocks_006",
"tests/test_spec.py::TestCommonMark::test_html_blocks_007",
"tests/test_spec.py::TestCommonMark::test_html_blocks_008",
"tests/test_spec.py::TestCommonMark::test_html_blocks_009",
"tests/test_spec.py::TestCommonMark::test_html_blocks_010",
"tests/test_spec.py::TestCommonMark::test_html_blocks_011",
"tests/test_spec.py::TestCommonMark::test_html_blocks_012",
"tests/test_spec.py::TestCommonMark::test_html_blocks_013",
"tests/test_spec.py::TestCommonMark::test_html_blocks_014",
"tests/test_spec.py::TestCommonMark::test_html_blocks_015",
"tests/test_spec.py::TestCommonMark::test_html_blocks_016",
"tests/test_spec.py::TestCommonMark::test_html_blocks_017",
"tests/test_spec.py::TestCommonMark::test_html_blocks_018",
"tests/test_spec.py::TestCommonMark::test_html_blocks_019",
"tests/test_spec.py::TestCommonMark::test_html_blocks_020",
"tests/test_spec.py::TestCommonMark::test_html_blocks_021",
"tests/test_spec.py::TestCommonMark::test_html_blocks_022",
"tests/test_spec.py::TestCommonMark::test_html_blocks_023",
"tests/test_spec.py::TestCommonMark::test_html_blocks_024",
"tests/test_spec.py::TestCommonMark::test_html_blocks_025",
"tests/test_spec.py::TestCommonMark::test_html_blocks_026",
"tests/test_spec.py::TestCommonMark::test_html_blocks_027",
"tests/test_spec.py::TestCommonMark::test_html_blocks_028",
"tests/test_spec.py::TestCommonMark::test_html_blocks_029",
"tests/test_spec.py::TestCommonMark::test_html_blocks_030",
"tests/test_spec.py::TestCommonMark::test_html_blocks_031",
"tests/test_spec.py::TestCommonMark::test_html_blocks_032",
"tests/test_spec.py::TestCommonMark::test_html_blocks_033",
"tests/test_spec.py::TestCommonMark::test_html_blocks_034",
"tests/test_spec.py::TestCommonMark::test_html_blocks_035",
"tests/test_spec.py::TestCommonMark::test_html_blocks_036",
"tests/test_spec.py::TestCommonMark::test_html_blocks_037",
"tests/test_spec.py::TestCommonMark::test_html_blocks_038",
"tests/test_spec.py::TestCommonMark::test_html_blocks_039",
"tests/test_spec.py::TestCommonMark::test_html_blocks_040",
"tests/test_spec.py::TestCommonMark::test_html_blocks_041",
"tests/test_spec.py::TestCommonMark::test_html_blocks_042",
"tests/test_spec.py::TestCommonMark::test_html_blocks_043",
"tests/test_spec.py::TestCommonMark::test_html_blocks_044",
"tests/test_spec.py::TestCommonMark::test_link_reference_definitions_001",
"tests/test_spec.py::TestCommonMark::test_link_reference_definitions_002",
"tests/test_spec.py::TestCommonMark::test_link_reference_definitions_003",
"tests/test_spec.py::TestCommonMark::test_link_reference_definitions_004",
"tests/test_spec.py::TestCommonMark::test_link_reference_definitions_005",
"tests/test_spec.py::TestCommonMark::test_link_reference_definitions_006",
"tests/test_spec.py::TestCommonMark::test_link_reference_definitions_007",
"tests/test_spec.py::TestCommonMark::test_link_reference_definitions_008",
"tests/test_spec.py::TestCommonMark::test_link_reference_definitions_009",
"tests/test_spec.py::TestCommonMark::test_link_reference_definitions_010",
"tests/test_spec.py::TestCommonMark::test_link_reference_definitions_011",
"tests/test_spec.py::TestCommonMark::test_link_reference_definitions_012",
"tests/test_spec.py::TestCommonMark::test_link_reference_definitions_013",
"tests/test_spec.py::TestCommonMark::test_link_reference_definitions_014",
"tests/test_spec.py::TestCommonMark::test_link_reference_definitions_015",
"tests/test_spec.py::TestCommonMark::test_link_reference_definitions_016",
"tests/test_spec.py::TestCommonMark::test_link_reference_definitions_017",
"tests/test_spec.py::TestCommonMark::test_link_reference_definitions_018",
"tests/test_spec.py::TestCommonMark::test_link_reference_definitions_019",
"tests/test_spec.py::TestCommonMark::test_link_reference_definitions_020",
"tests/test_spec.py::TestCommonMark::test_link_reference_definitions_021",
"tests/test_spec.py::TestCommonMark::test_link_reference_definitions_022",
"tests/test_spec.py::TestCommonMark::test_link_reference_definitions_023",
"tests/test_spec.py::TestCommonMark::test_link_reference_definitions_024",
"tests/test_spec.py::TestCommonMark::test_link_reference_definitions_025",
"tests/test_spec.py::TestCommonMark::test_link_reference_definitions_026",
"tests/test_spec.py::TestCommonMark::test_paragraphs_001",
"tests/test_spec.py::TestCommonMark::test_paragraphs_002",
"tests/test_spec.py::TestCommonMark::test_paragraphs_003",
"tests/test_spec.py::TestCommonMark::test_paragraphs_004",
"tests/test_spec.py::TestCommonMark::test_paragraphs_005",
"tests/test_spec.py::TestCommonMark::test_paragraphs_006",
"tests/test_spec.py::TestCommonMark::test_paragraphs_007",
"tests/test_spec.py::TestCommonMark::test_paragraphs_008",
"tests/test_spec.py::TestCommonMark::test_blank_lines_001",
"tests/test_spec.py::TestCommonMark::test_block_quotes_001",
"tests/test_spec.py::TestCommonMark::test_block_quotes_002",
"tests/test_spec.py::TestCommonMark::test_block_quotes_003",
"tests/test_spec.py::TestCommonMark::test_block_quotes_004",
"tests/test_spec.py::TestCommonMark::test_block_quotes_005",
"tests/test_spec.py::TestCommonMark::test_block_quotes_006",
"tests/test_spec.py::TestCommonMark::test_block_quotes_007",
"tests/test_spec.py::TestCommonMark::test_block_quotes_008",
"tests/test_spec.py::TestCommonMark::test_block_quotes_009",
"tests/test_spec.py::TestCommonMark::test_block_quotes_010",
"tests/test_spec.py::TestCommonMark::test_block_quotes_011",
"tests/test_spec.py::TestCommonMark::test_block_quotes_012",
"tests/test_spec.py::TestCommonMark::test_block_quotes_013",
"tests/test_spec.py::TestCommonMark::test_block_quotes_014",
"tests/test_spec.py::TestCommonMark::test_block_quotes_015",
"tests/test_spec.py::TestCommonMark::test_block_quotes_016",
"tests/test_spec.py::TestCommonMark::test_block_quotes_017",
"tests/test_spec.py::TestCommonMark::test_block_quotes_018",
"tests/test_spec.py::TestCommonMark::test_block_quotes_019",
"tests/test_spec.py::TestCommonMark::test_block_quotes_020",
"tests/test_spec.py::TestCommonMark::test_block_quotes_021",
"tests/test_spec.py::TestCommonMark::test_block_quotes_022",
"tests/test_spec.py::TestCommonMark::test_block_quotes_023",
"tests/test_spec.py::TestCommonMark::test_block_quotes_024",
"tests/test_spec.py::TestCommonMark::test_block_quotes_025",
"tests/test_spec.py::TestCommonMark::test_list_items_001",
"tests/test_spec.py::TestCommonMark::test_list_items_002",
"tests/test_spec.py::TestCommonMark::test_list_items_003",
"tests/test_spec.py::TestCommonMark::test_list_items_004",
"tests/test_spec.py::TestCommonMark::test_list_items_005",
"tests/test_spec.py::TestCommonMark::test_list_items_006",
"tests/test_spec.py::TestCommonMark::test_list_items_007",
"tests/test_spec.py::TestCommonMark::test_list_items_008",
"tests/test_spec.py::TestCommonMark::test_list_items_009",
"tests/test_spec.py::TestCommonMark::test_list_items_010",
"tests/test_spec.py::TestCommonMark::test_list_items_011",
"tests/test_spec.py::TestCommonMark::test_list_items_012",
"tests/test_spec.py::TestCommonMark::test_list_items_013",
"tests/test_spec.py::TestCommonMark::test_list_items_014",
"tests/test_spec.py::TestCommonMark::test_list_items_015",
"tests/test_spec.py::TestCommonMark::test_list_items_016",
"tests/test_spec.py::TestCommonMark::test_list_items_017",
"tests/test_spec.py::TestCommonMark::test_list_items_018",
"tests/test_spec.py::TestCommonMark::test_list_items_019",
"tests/test_spec.py::TestCommonMark::test_list_items_020",
"tests/test_spec.py::TestCommonMark::test_list_items_021",
"tests/test_spec.py::TestCommonMark::test_list_items_022",
"tests/test_spec.py::TestCommonMark::test_list_items_023",
"tests/test_spec.py::TestCommonMark::test_list_items_024",
"tests/test_spec.py::TestCommonMark::test_list_items_025",
"tests/test_spec.py::TestCommonMark::test_list_items_026",
"tests/test_spec.py::TestCommonMark::test_list_items_027",
"tests/test_spec.py::TestCommonMark::test_list_items_028",
"tests/test_spec.py::TestCommonMark::test_list_items_029",
"tests/test_spec.py::TestCommonMark::test_list_items_030",
"tests/test_spec.py::TestCommonMark::test_list_items_031",
"tests/test_spec.py::TestCommonMark::test_list_items_032",
"tests/test_spec.py::TestCommonMark::test_list_items_033",
"tests/test_spec.py::TestCommonMark::test_list_items_034",
"tests/test_spec.py::TestCommonMark::test_list_items_035",
"tests/test_spec.py::TestCommonMark::test_list_items_036",
"tests/test_spec.py::TestCommonMark::test_list_items_037",
"tests/test_spec.py::TestCommonMark::test_list_items_038",
"tests/test_spec.py::TestCommonMark::test_list_items_039",
"tests/test_spec.py::TestCommonMark::test_list_items_040",
"tests/test_spec.py::TestCommonMark::test_list_items_041",
"tests/test_spec.py::TestCommonMark::test_list_items_042",
"tests/test_spec.py::TestCommonMark::test_list_items_043",
"tests/test_spec.py::TestCommonMark::test_list_items_044",
"tests/test_spec.py::TestCommonMark::test_list_items_045",
"tests/test_spec.py::TestCommonMark::test_list_items_046",
"tests/test_spec.py::TestCommonMark::test_list_items_047",
"tests/test_spec.py::TestCommonMark::test_list_items_048",
"tests/test_spec.py::TestCommonMark::test_lists_001",
"tests/test_spec.py::TestCommonMark::test_lists_002",
"tests/test_spec.py::TestCommonMark::test_lists_003",
"tests/test_spec.py::TestCommonMark::test_lists_004",
"tests/test_spec.py::TestCommonMark::test_lists_005",
"tests/test_spec.py::TestCommonMark::test_lists_006",
"tests/test_spec.py::TestCommonMark::test_lists_007",
"tests/test_spec.py::TestCommonMark::test_lists_008",
"tests/test_spec.py::TestCommonMark::test_lists_009",
"tests/test_spec.py::TestCommonMark::test_lists_010",
"tests/test_spec.py::TestCommonMark::test_lists_011",
"tests/test_spec.py::TestCommonMark::test_lists_012",
"tests/test_spec.py::TestCommonMark::test_lists_013",
"tests/test_spec.py::TestCommonMark::test_lists_014",
"tests/test_spec.py::TestCommonMark::test_lists_015",
"tests/test_spec.py::TestCommonMark::test_lists_016",
"tests/test_spec.py::TestCommonMark::test_lists_017",
"tests/test_spec.py::TestCommonMark::test_lists_018",
"tests/test_spec.py::TestCommonMark::test_lists_019",
"tests/test_spec.py::TestCommonMark::test_lists_020",
"tests/test_spec.py::TestCommonMark::test_lists_021",
"tests/test_spec.py::TestCommonMark::test_lists_022",
"tests/test_spec.py::TestCommonMark::test_lists_023",
"tests/test_spec.py::TestCommonMark::test_lists_024",
"tests/test_spec.py::TestCommonMark::test_lists_025",
"tests/test_spec.py::TestCommonMark::test_lists_026",
"tests/test_spec.py::TestCommonMark::test_inlines_001",
"tests/test_spec.py::TestCommonMark::test_code_spans_001",
"tests/test_spec.py::TestCommonMark::test_code_spans_002",
"tests/test_spec.py::TestCommonMark::test_code_spans_003",
"tests/test_spec.py::TestCommonMark::test_code_spans_004",
"tests/test_spec.py::TestCommonMark::test_code_spans_005",
"tests/test_spec.py::TestCommonMark::test_code_spans_006",
"tests/test_spec.py::TestCommonMark::test_code_spans_007",
"tests/test_spec.py::TestCommonMark::test_code_spans_008",
"tests/test_spec.py::TestCommonMark::test_code_spans_009",
"tests/test_spec.py::TestCommonMark::test_code_spans_010",
"tests/test_spec.py::TestCommonMark::test_code_spans_011",
"tests/test_spec.py::TestCommonMark::test_code_spans_012",
"tests/test_spec.py::TestCommonMark::test_code_spans_013",
"tests/test_spec.py::TestCommonMark::test_code_spans_014",
"tests/test_spec.py::TestCommonMark::test_code_spans_015",
"tests/test_spec.py::TestCommonMark::test_code_spans_016",
"tests/test_spec.py::TestCommonMark::test_code_spans_017",
"tests/test_spec.py::TestCommonMark::test_code_spans_018",
"tests/test_spec.py::TestCommonMark::test_code_spans_019",
"tests/test_spec.py::TestCommonMark::test_code_spans_020",
"tests/test_spec.py::TestCommonMark::test_code_spans_021",
"tests/test_spec.py::TestCommonMark::test_code_spans_022",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_001",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_002",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_003",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_004",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_005",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_006",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_007",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_008",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_009",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_010",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_011",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_012",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_013",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_014",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_015",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_016",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_017",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_018",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_019",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_020",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_021",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_022",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_023",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_024",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_025",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_026",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_027",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_028",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_029",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_030",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_031",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_032",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_033",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_034",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_035",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_036",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_037",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_038",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_039",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_040",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_041",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_042",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_043",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_044",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_045",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_046",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_047",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_048",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_049",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_050",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_051",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_052",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_053",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_054",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_055",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_056",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_057",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_058",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_059",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_060",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_061",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_062",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_063",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_064",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_065",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_066",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_067",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_068",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_069",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_070",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_071",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_072",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_073",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_074",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_075",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_076",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_077",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_078",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_079",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_080",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_081",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_082",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_083",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_084",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_085",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_086",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_087",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_088",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_089",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_090",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_091",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_092",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_093",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_094",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_095",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_096",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_097",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_098",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_099",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_100",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_101",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_102",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_103",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_104",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_105",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_106",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_107",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_108",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_109",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_110",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_111",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_112",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_113",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_114",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_115",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_116",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_117",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_118",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_119",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_120",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_121",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_122",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_123",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_124",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_125",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_126",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_127",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_128",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_129",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_130",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_131",
"tests/test_spec.py::TestCommonMark::test_links_001",
"tests/test_spec.py::TestCommonMark::test_links_002",
"tests/test_spec.py::TestCommonMark::test_links_003",
"tests/test_spec.py::TestCommonMark::test_links_004",
"tests/test_spec.py::TestCommonMark::test_links_005",
"tests/test_spec.py::TestCommonMark::test_links_006",
"tests/test_spec.py::TestCommonMark::test_links_007",
"tests/test_spec.py::TestCommonMark::test_links_008",
"tests/test_spec.py::TestCommonMark::test_links_009",
"tests/test_spec.py::TestCommonMark::test_links_010",
"tests/test_spec.py::TestCommonMark::test_links_011",
"tests/test_spec.py::TestCommonMark::test_links_012",
"tests/test_spec.py::TestCommonMark::test_links_013",
"tests/test_spec.py::TestCommonMark::test_links_014",
"tests/test_spec.py::TestCommonMark::test_links_015",
"tests/test_spec.py::TestCommonMark::test_links_016",
"tests/test_spec.py::TestCommonMark::test_links_017",
"tests/test_spec.py::TestCommonMark::test_links_018",
"tests/test_spec.py::TestCommonMark::test_links_019",
"tests/test_spec.py::TestCommonMark::test_links_020",
"tests/test_spec.py::TestCommonMark::test_links_021",
"tests/test_spec.py::TestCommonMark::test_links_022",
"tests/test_spec.py::TestCommonMark::test_links_023",
"tests/test_spec.py::TestCommonMark::test_links_024",
"tests/test_spec.py::TestCommonMark::test_links_025",
"tests/test_spec.py::TestCommonMark::test_links_026",
"tests/test_spec.py::TestCommonMark::test_links_027",
"tests/test_spec.py::TestCommonMark::test_links_028",
"tests/test_spec.py::TestCommonMark::test_links_029",
"tests/test_spec.py::TestCommonMark::test_links_030",
"tests/test_spec.py::TestCommonMark::test_links_031",
"tests/test_spec.py::TestCommonMark::test_links_032",
"tests/test_spec.py::TestCommonMark::test_links_033",
"tests/test_spec.py::TestCommonMark::test_links_034",
"tests/test_spec.py::TestCommonMark::test_links_035",
"tests/test_spec.py::TestCommonMark::test_links_036",
"tests/test_spec.py::TestCommonMark::test_links_037",
"tests/test_spec.py::TestCommonMark::test_links_038",
"tests/test_spec.py::TestCommonMark::test_links_039",
"tests/test_spec.py::TestCommonMark::test_links_040",
"tests/test_spec.py::TestCommonMark::test_links_041",
"tests/test_spec.py::TestCommonMark::test_links_042",
"tests/test_spec.py::TestCommonMark::test_links_043",
"tests/test_spec.py::TestCommonMark::test_links_044",
"tests/test_spec.py::TestCommonMark::test_links_045",
"tests/test_spec.py::TestCommonMark::test_links_046",
"tests/test_spec.py::TestCommonMark::test_links_047",
"tests/test_spec.py::TestCommonMark::test_links_048",
"tests/test_spec.py::TestCommonMark::test_links_049",
"tests/test_spec.py::TestCommonMark::test_links_050",
"tests/test_spec.py::TestCommonMark::test_links_051",
"tests/test_spec.py::TestCommonMark::test_links_052",
"tests/test_spec.py::TestCommonMark::test_links_053",
"tests/test_spec.py::TestCommonMark::test_links_054",
"tests/test_spec.py::TestCommonMark::test_links_055",
"tests/test_spec.py::TestCommonMark::test_links_056",
"tests/test_spec.py::TestCommonMark::test_links_057",
"tests/test_spec.py::TestCommonMark::test_links_058",
"tests/test_spec.py::TestCommonMark::test_links_059",
"tests/test_spec.py::TestCommonMark::test_links_060",
"tests/test_spec.py::TestCommonMark::test_links_061",
"tests/test_spec.py::TestCommonMark::test_links_062",
"tests/test_spec.py::TestCommonMark::test_links_063",
"tests/test_spec.py::TestCommonMark::test_links_064",
"tests/test_spec.py::TestCommonMark::test_links_065",
"tests/test_spec.py::TestCommonMark::test_links_066",
"tests/test_spec.py::TestCommonMark::test_links_067",
"tests/test_spec.py::TestCommonMark::test_links_068",
"tests/test_spec.py::TestCommonMark::test_links_069",
"tests/test_spec.py::TestCommonMark::test_links_070",
"tests/test_spec.py::TestCommonMark::test_links_071",
"tests/test_spec.py::TestCommonMark::test_links_072",
"tests/test_spec.py::TestCommonMark::test_links_073",
"tests/test_spec.py::TestCommonMark::test_links_074",
"tests/test_spec.py::TestCommonMark::test_links_075",
"tests/test_spec.py::TestCommonMark::test_links_076",
"tests/test_spec.py::TestCommonMark::test_links_077",
"tests/test_spec.py::TestCommonMark::test_links_078",
"tests/test_spec.py::TestCommonMark::test_links_079",
"tests/test_spec.py::TestCommonMark::test_links_080",
"tests/test_spec.py::TestCommonMark::test_links_081",
"tests/test_spec.py::TestCommonMark::test_links_082",
"tests/test_spec.py::TestCommonMark::test_links_083",
"tests/test_spec.py::TestCommonMark::test_links_084",
"tests/test_spec.py::TestCommonMark::test_links_085",
"tests/test_spec.py::TestCommonMark::test_links_086",
"tests/test_spec.py::TestCommonMark::test_links_087",
"tests/test_spec.py::TestCommonMark::test_links_088",
"tests/test_spec.py::TestCommonMark::test_links_089",
"tests/test_spec.py::TestCommonMark::test_links_090",
"tests/test_spec.py::TestCommonMark::test_images_001",
"tests/test_spec.py::TestCommonMark::test_images_002",
"tests/test_spec.py::TestCommonMark::test_images_003",
"tests/test_spec.py::TestCommonMark::test_images_004",
"tests/test_spec.py::TestCommonMark::test_images_005",
"tests/test_spec.py::TestCommonMark::test_images_006",
"tests/test_spec.py::TestCommonMark::test_images_007",
"tests/test_spec.py::TestCommonMark::test_images_008",
"tests/test_spec.py::TestCommonMark::test_images_009",
"tests/test_spec.py::TestCommonMark::test_images_010",
"tests/test_spec.py::TestCommonMark::test_images_011",
"tests/test_spec.py::TestCommonMark::test_images_012",
"tests/test_spec.py::TestCommonMark::test_images_013",
"tests/test_spec.py::TestCommonMark::test_images_014",
"tests/test_spec.py::TestCommonMark::test_images_015",
"tests/test_spec.py::TestCommonMark::test_images_016",
"tests/test_spec.py::TestCommonMark::test_images_017",
"tests/test_spec.py::TestCommonMark::test_images_018",
"tests/test_spec.py::TestCommonMark::test_images_019",
"tests/test_spec.py::TestCommonMark::test_images_020",
"tests/test_spec.py::TestCommonMark::test_images_021",
"tests/test_spec.py::TestCommonMark::test_images_022",
"tests/test_spec.py::TestCommonMark::test_autolinks_001",
"tests/test_spec.py::TestCommonMark::test_autolinks_002",
"tests/test_spec.py::TestCommonMark::test_autolinks_003",
"tests/test_spec.py::TestCommonMark::test_autolinks_004",
"tests/test_spec.py::TestCommonMark::test_autolinks_005",
"tests/test_spec.py::TestCommonMark::test_autolinks_006",
"tests/test_spec.py::TestCommonMark::test_autolinks_007",
"tests/test_spec.py::TestCommonMark::test_autolinks_008",
"tests/test_spec.py::TestCommonMark::test_autolinks_009",
"tests/test_spec.py::TestCommonMark::test_autolinks_010",
"tests/test_spec.py::TestCommonMark::test_autolinks_011",
"tests/test_spec.py::TestCommonMark::test_autolinks_012",
"tests/test_spec.py::TestCommonMark::test_autolinks_013",
"tests/test_spec.py::TestCommonMark::test_autolinks_014",
"tests/test_spec.py::TestCommonMark::test_autolinks_015",
"tests/test_spec.py::TestCommonMark::test_autolinks_016",
"tests/test_spec.py::TestCommonMark::test_autolinks_017",
"tests/test_spec.py::TestCommonMark::test_autolinks_018",
"tests/test_spec.py::TestCommonMark::test_autolinks_019",
"tests/test_spec.py::TestCommonMark::test_raw_html_001",
"tests/test_spec.py::TestCommonMark::test_raw_html_002",
"tests/test_spec.py::TestCommonMark::test_raw_html_003",
"tests/test_spec.py::TestCommonMark::test_raw_html_004",
"tests/test_spec.py::TestCommonMark::test_raw_html_005",
"tests/test_spec.py::TestCommonMark::test_raw_html_006",
"tests/test_spec.py::TestCommonMark::test_raw_html_007",
"tests/test_spec.py::TestCommonMark::test_raw_html_008",
"tests/test_spec.py::TestCommonMark::test_raw_html_009",
"tests/test_spec.py::TestCommonMark::test_raw_html_010",
"tests/test_spec.py::TestCommonMark::test_raw_html_011",
"tests/test_spec.py::TestCommonMark::test_raw_html_012",
"tests/test_spec.py::TestCommonMark::test_raw_html_013",
"tests/test_spec.py::TestCommonMark::test_raw_html_014",
"tests/test_spec.py::TestCommonMark::test_raw_html_015",
"tests/test_spec.py::TestCommonMark::test_raw_html_016",
"tests/test_spec.py::TestCommonMark::test_raw_html_017",
"tests/test_spec.py::TestCommonMark::test_raw_html_018",
"tests/test_spec.py::TestCommonMark::test_raw_html_019",
"tests/test_spec.py::TestCommonMark::test_raw_html_020",
"tests/test_spec.py::TestCommonMark::test_raw_html_021",
"tests/test_spec.py::TestCommonMark::test_hard_line_breaks_001",
"tests/test_spec.py::TestCommonMark::test_hard_line_breaks_002",
"tests/test_spec.py::TestCommonMark::test_hard_line_breaks_003",
"tests/test_spec.py::TestCommonMark::test_hard_line_breaks_004",
"tests/test_spec.py::TestCommonMark::test_hard_line_breaks_005",
"tests/test_spec.py::TestCommonMark::test_hard_line_breaks_006",
"tests/test_spec.py::TestCommonMark::test_hard_line_breaks_007",
"tests/test_spec.py::TestCommonMark::test_hard_line_breaks_008",
"tests/test_spec.py::TestCommonMark::test_hard_line_breaks_009",
"tests/test_spec.py::TestCommonMark::test_hard_line_breaks_010",
"tests/test_spec.py::TestCommonMark::test_hard_line_breaks_011",
"tests/test_spec.py::TestCommonMark::test_hard_line_breaks_012",
"tests/test_spec.py::TestCommonMark::test_hard_line_breaks_013",
"tests/test_spec.py::TestCommonMark::test_hard_line_breaks_014",
"tests/test_spec.py::TestCommonMark::test_hard_line_breaks_015",
"tests/test_spec.py::TestCommonMark::test_soft_line_breaks_001",
"tests/test_spec.py::TestCommonMark::test_soft_line_breaks_002",
"tests/test_spec.py::TestCommonMark::test_textual_content_001",
"tests/test_spec.py::TestCommonMark::test_textual_content_002",
"tests/test_spec.py::TestCommonMark::test_textual_content_003",
"tests/test_spec.py::TestGFM::test_mixed_tab_space_in_list_item",
"tests/test_spec.py::TestGFM::test_parse_table_with_backslashes",
"tests/test_spec.py::TestGFM::test_tabs_001",
"tests/test_spec.py::TestGFM::test_tabs_002",
"tests/test_spec.py::TestGFM::test_tabs_003",
"tests/test_spec.py::TestGFM::test_tabs_004",
"tests/test_spec.py::TestGFM::test_tabs_005",
"tests/test_spec.py::TestGFM::test_tabs_006",
"tests/test_spec.py::TestGFM::test_tabs_007",
"tests/test_spec.py::TestGFM::test_tabs_008",
"tests/test_spec.py::TestGFM::test_tabs_009",
"tests/test_spec.py::TestGFM::test_tabs_010",
"tests/test_spec.py::TestGFM::test_tabs_011",
"tests/test_spec.py::TestGFM::test_precedence_001",
"tests/test_spec.py::TestGFM::test_thematic_breaks_001",
"tests/test_spec.py::TestGFM::test_thematic_breaks_002",
"tests/test_spec.py::TestGFM::test_thematic_breaks_003",
"tests/test_spec.py::TestGFM::test_thematic_breaks_004",
"tests/test_spec.py::TestGFM::test_thematic_breaks_005",
"tests/test_spec.py::TestGFM::test_thematic_breaks_006",
"tests/test_spec.py::TestGFM::test_thematic_breaks_007",
"tests/test_spec.py::TestGFM::test_thematic_breaks_008",
"tests/test_spec.py::TestGFM::test_thematic_breaks_009",
"tests/test_spec.py::TestGFM::test_thematic_breaks_010",
"tests/test_spec.py::TestGFM::test_thematic_breaks_011",
"tests/test_spec.py::TestGFM::test_thematic_breaks_012",
"tests/test_spec.py::TestGFM::test_thematic_breaks_013",
"tests/test_spec.py::TestGFM::test_thematic_breaks_014",
"tests/test_spec.py::TestGFM::test_thematic_breaks_015",
"tests/test_spec.py::TestGFM::test_thematic_breaks_016",
"tests/test_spec.py::TestGFM::test_thematic_breaks_017",
"tests/test_spec.py::TestGFM::test_thematic_breaks_018",
"tests/test_spec.py::TestGFM::test_thematic_breaks_019",
"tests/test_spec.py::TestGFM::test_atx_headings_001",
"tests/test_spec.py::TestGFM::test_atx_headings_002",
"tests/test_spec.py::TestGFM::test_atx_headings_003",
"tests/test_spec.py::TestGFM::test_atx_headings_004",
"tests/test_spec.py::TestGFM::test_atx_headings_005",
"tests/test_spec.py::TestGFM::test_atx_headings_006",
"tests/test_spec.py::TestGFM::test_atx_headings_007",
"tests/test_spec.py::TestGFM::test_atx_headings_008",
"tests/test_spec.py::TestGFM::test_atx_headings_009",
"tests/test_spec.py::TestGFM::test_atx_headings_010",
"tests/test_spec.py::TestGFM::test_atx_headings_011",
"tests/test_spec.py::TestGFM::test_atx_headings_012",
"tests/test_spec.py::TestGFM::test_atx_headings_013",
"tests/test_spec.py::TestGFM::test_atx_headings_014",
"tests/test_spec.py::TestGFM::test_atx_headings_015",
"tests/test_spec.py::TestGFM::test_atx_headings_016",
"tests/test_spec.py::TestGFM::test_atx_headings_017",
"tests/test_spec.py::TestGFM::test_atx_headings_018",
"tests/test_spec.py::TestGFM::test_setext_headings_001",
"tests/test_spec.py::TestGFM::test_setext_headings_002",
"tests/test_spec.py::TestGFM::test_setext_headings_003",
"tests/test_spec.py::TestGFM::test_setext_headings_004",
"tests/test_spec.py::TestGFM::test_setext_headings_005",
"tests/test_spec.py::TestGFM::test_setext_headings_006",
"tests/test_spec.py::TestGFM::test_setext_headings_007",
"tests/test_spec.py::TestGFM::test_setext_headings_008",
"tests/test_spec.py::TestGFM::test_setext_headings_009",
"tests/test_spec.py::TestGFM::test_setext_headings_010",
"tests/test_spec.py::TestGFM::test_setext_headings_011",
"tests/test_spec.py::TestGFM::test_setext_headings_012",
"tests/test_spec.py::TestGFM::test_setext_headings_013",
"tests/test_spec.py::TestGFM::test_setext_headings_014",
"tests/test_spec.py::TestGFM::test_setext_headings_015",
"tests/test_spec.py::TestGFM::test_setext_headings_016",
"tests/test_spec.py::TestGFM::test_setext_headings_017",
"tests/test_spec.py::TestGFM::test_setext_headings_018",
"tests/test_spec.py::TestGFM::test_setext_headings_019",
"tests/test_spec.py::TestGFM::test_setext_headings_020",
"tests/test_spec.py::TestGFM::test_setext_headings_021",
"tests/test_spec.py::TestGFM::test_setext_headings_022",
"tests/test_spec.py::TestGFM::test_setext_headings_023",
"tests/test_spec.py::TestGFM::test_setext_headings_024",
"tests/test_spec.py::TestGFM::test_setext_headings_025",
"tests/test_spec.py::TestGFM::test_setext_headings_026",
"tests/test_spec.py::TestGFM::test_setext_headings_027",
"tests/test_spec.py::TestGFM::test_indented_code_blocks_001",
"tests/test_spec.py::TestGFM::test_indented_code_blocks_002",
"tests/test_spec.py::TestGFM::test_indented_code_blocks_003",
"tests/test_spec.py::TestGFM::test_indented_code_blocks_004",
"tests/test_spec.py::TestGFM::test_indented_code_blocks_005",
"tests/test_spec.py::TestGFM::test_indented_code_blocks_006",
"tests/test_spec.py::TestGFM::test_indented_code_blocks_007",
"tests/test_spec.py::TestGFM::test_indented_code_blocks_008",
"tests/test_spec.py::TestGFM::test_indented_code_blocks_009",
"tests/test_spec.py::TestGFM::test_indented_code_blocks_010",
"tests/test_spec.py::TestGFM::test_indented_code_blocks_011",
"tests/test_spec.py::TestGFM::test_indented_code_blocks_012",
"tests/test_spec.py::TestGFM::test_fenced_code_blocks_001",
"tests/test_spec.py::TestGFM::test_fenced_code_blocks_002",
"tests/test_spec.py::TestGFM::test_fenced_code_blocks_003",
"tests/test_spec.py::TestGFM::test_fenced_code_blocks_004",
"tests/test_spec.py::TestGFM::test_fenced_code_blocks_005",
"tests/test_spec.py::TestGFM::test_fenced_code_blocks_006",
"tests/test_spec.py::TestGFM::test_fenced_code_blocks_007",
"tests/test_spec.py::TestGFM::test_fenced_code_blocks_008",
"tests/test_spec.py::TestGFM::test_fenced_code_blocks_009",
"tests/test_spec.py::TestGFM::test_fenced_code_blocks_010",
"tests/test_spec.py::TestGFM::test_fenced_code_blocks_011",
"tests/test_spec.py::TestGFM::test_fenced_code_blocks_012",
"tests/test_spec.py::TestGFM::test_fenced_code_blocks_013",
"tests/test_spec.py::TestGFM::test_fenced_code_blocks_014",
"tests/test_spec.py::TestGFM::test_fenced_code_blocks_015",
"tests/test_spec.py::TestGFM::test_fenced_code_blocks_016",
"tests/test_spec.py::TestGFM::test_fenced_code_blocks_017",
"tests/test_spec.py::TestGFM::test_fenced_code_blocks_018",
"tests/test_spec.py::TestGFM::test_fenced_code_blocks_019",
"tests/test_spec.py::TestGFM::test_fenced_code_blocks_020",
"tests/test_spec.py::TestGFM::test_fenced_code_blocks_021",
"tests/test_spec.py::TestGFM::test_fenced_code_blocks_022",
"tests/test_spec.py::TestGFM::test_fenced_code_blocks_023",
"tests/test_spec.py::TestGFM::test_fenced_code_blocks_024",
"tests/test_spec.py::TestGFM::test_fenced_code_blocks_025",
"tests/test_spec.py::TestGFM::test_fenced_code_blocks_026",
"tests/test_spec.py::TestGFM::test_fenced_code_blocks_027",
"tests/test_spec.py::TestGFM::test_fenced_code_blocks_028",
"tests/test_spec.py::TestGFM::test_fenced_code_blocks_029",
"tests/test_spec.py::TestGFM::test_html_blocks_001",
"tests/test_spec.py::TestGFM::test_html_blocks_002",
"tests/test_spec.py::TestGFM::test_html_blocks_003",
"tests/test_spec.py::TestGFM::test_html_blocks_004",
"tests/test_spec.py::TestGFM::test_html_blocks_005",
"tests/test_spec.py::TestGFM::test_html_blocks_006",
"tests/test_spec.py::TestGFM::test_html_blocks_007",
"tests/test_spec.py::TestGFM::test_html_blocks_008",
"tests/test_spec.py::TestGFM::test_html_blocks_009",
"tests/test_spec.py::TestGFM::test_html_blocks_010",
"tests/test_spec.py::TestGFM::test_html_blocks_011",
"tests/test_spec.py::TestGFM::test_html_blocks_012",
"tests/test_spec.py::TestGFM::test_html_blocks_013",
"tests/test_spec.py::TestGFM::test_html_blocks_014",
"tests/test_spec.py::TestGFM::test_html_blocks_015",
"tests/test_spec.py::TestGFM::test_html_blocks_016",
"tests/test_spec.py::TestGFM::test_html_blocks_017",
"tests/test_spec.py::TestGFM::test_html_blocks_018",
"tests/test_spec.py::TestGFM::test_html_blocks_019",
"tests/test_spec.py::TestGFM::test_html_blocks_020",
"tests/test_spec.py::TestGFM::test_html_blocks_021",
"tests/test_spec.py::TestGFM::test_html_blocks_022",
"tests/test_spec.py::TestGFM::test_html_blocks_023",
"tests/test_spec.py::TestGFM::test_html_blocks_024",
"tests/test_spec.py::TestGFM::test_html_blocks_025",
"tests/test_spec.py::TestGFM::test_html_blocks_026",
"tests/test_spec.py::TestGFM::test_html_blocks_027",
"tests/test_spec.py::TestGFM::test_html_blocks_028",
"tests/test_spec.py::TestGFM::test_html_blocks_029",
"tests/test_spec.py::TestGFM::test_html_blocks_030",
"tests/test_spec.py::TestGFM::test_html_blocks_031",
"tests/test_spec.py::TestGFM::test_html_blocks_032",
"tests/test_spec.py::TestGFM::test_html_blocks_033",
"tests/test_spec.py::TestGFM::test_html_blocks_034",
"tests/test_spec.py::TestGFM::test_html_blocks_035",
"tests/test_spec.py::TestGFM::test_html_blocks_036",
"tests/test_spec.py::TestGFM::test_html_blocks_037",
"tests/test_spec.py::TestGFM::test_html_blocks_038",
"tests/test_spec.py::TestGFM::test_html_blocks_039",
"tests/test_spec.py::TestGFM::test_html_blocks_040",
"tests/test_spec.py::TestGFM::test_html_blocks_041",
"tests/test_spec.py::TestGFM::test_html_blocks_042",
"tests/test_spec.py::TestGFM::test_html_blocks_043",
"tests/test_spec.py::TestGFM::test_link_reference_definitions_001",
"tests/test_spec.py::TestGFM::test_link_reference_definitions_002",
"tests/test_spec.py::TestGFM::test_link_reference_definitions_003",
"tests/test_spec.py::TestGFM::test_link_reference_definitions_004",
"tests/test_spec.py::TestGFM::test_link_reference_definitions_005",
"tests/test_spec.py::TestGFM::test_link_reference_definitions_006",
"tests/test_spec.py::TestGFM::test_link_reference_definitions_007",
"tests/test_spec.py::TestGFM::test_link_reference_definitions_008",
"tests/test_spec.py::TestGFM::test_link_reference_definitions_009",
"tests/test_spec.py::TestGFM::test_link_reference_definitions_010",
"tests/test_spec.py::TestGFM::test_link_reference_definitions_011",
"tests/test_spec.py::TestGFM::test_link_reference_definitions_012",
"tests/test_spec.py::TestGFM::test_link_reference_definitions_013",
"tests/test_spec.py::TestGFM::test_link_reference_definitions_014",
"tests/test_spec.py::TestGFM::test_link_reference_definitions_015",
"tests/test_spec.py::TestGFM::test_link_reference_definitions_016",
"tests/test_spec.py::TestGFM::test_link_reference_definitions_017",
"tests/test_spec.py::TestGFM::test_link_reference_definitions_018",
"tests/test_spec.py::TestGFM::test_link_reference_definitions_019",
"tests/test_spec.py::TestGFM::test_link_reference_definitions_020",
"tests/test_spec.py::TestGFM::test_link_reference_definitions_021",
"tests/test_spec.py::TestGFM::test_link_reference_definitions_022",
"tests/test_spec.py::TestGFM::test_link_reference_definitions_023",
"tests/test_spec.py::TestGFM::test_link_reference_definitions_024",
"tests/test_spec.py::TestGFM::test_link_reference_definitions_025",
"tests/test_spec.py::TestGFM::test_link_reference_definitions_026",
"tests/test_spec.py::TestGFM::test_paragraphs_001",
"tests/test_spec.py::TestGFM::test_paragraphs_002",
"tests/test_spec.py::TestGFM::test_paragraphs_003",
"tests/test_spec.py::TestGFM::test_paragraphs_004",
"tests/test_spec.py::TestGFM::test_paragraphs_005",
"tests/test_spec.py::TestGFM::test_paragraphs_006",
"tests/test_spec.py::TestGFM::test_paragraphs_007",
"tests/test_spec.py::TestGFM::test_paragraphs_008",
"tests/test_spec.py::TestGFM::test_blank_lines_001",
"tests/test_spec.py::TestGFM::test_block_quotes_001",
"tests/test_spec.py::TestGFM::test_block_quotes_002",
"tests/test_spec.py::TestGFM::test_block_quotes_003",
"tests/test_spec.py::TestGFM::test_block_quotes_004",
"tests/test_spec.py::TestGFM::test_block_quotes_005",
"tests/test_spec.py::TestGFM::test_block_quotes_006",
"tests/test_spec.py::TestGFM::test_block_quotes_007",
"tests/test_spec.py::TestGFM::test_block_quotes_008",
"tests/test_spec.py::TestGFM::test_block_quotes_009",
"tests/test_spec.py::TestGFM::test_block_quotes_010",
"tests/test_spec.py::TestGFM::test_block_quotes_011",
"tests/test_spec.py::TestGFM::test_block_quotes_012",
"tests/test_spec.py::TestGFM::test_block_quotes_013",
"tests/test_spec.py::TestGFM::test_block_quotes_014",
"tests/test_spec.py::TestGFM::test_block_quotes_015",
"tests/test_spec.py::TestGFM::test_block_quotes_016",
"tests/test_spec.py::TestGFM::test_block_quotes_017",
"tests/test_spec.py::TestGFM::test_block_quotes_018",
"tests/test_spec.py::TestGFM::test_block_quotes_019",
"tests/test_spec.py::TestGFM::test_block_quotes_020",
"tests/test_spec.py::TestGFM::test_block_quotes_021",
"tests/test_spec.py::TestGFM::test_block_quotes_022",
"tests/test_spec.py::TestGFM::test_block_quotes_023",
"tests/test_spec.py::TestGFM::test_block_quotes_024",
"tests/test_spec.py::TestGFM::test_block_quotes_025",
"tests/test_spec.py::TestGFM::test_list_items_001",
"tests/test_spec.py::TestGFM::test_list_items_002",
"tests/test_spec.py::TestGFM::test_list_items_003",
"tests/test_spec.py::TestGFM::test_list_items_004",
"tests/test_spec.py::TestGFM::test_list_items_005",
"tests/test_spec.py::TestGFM::test_list_items_006",
"tests/test_spec.py::TestGFM::test_list_items_007",
"tests/test_spec.py::TestGFM::test_list_items_008",
"tests/test_spec.py::TestGFM::test_list_items_009",
"tests/test_spec.py::TestGFM::test_list_items_010",
"tests/test_spec.py::TestGFM::test_list_items_011",
"tests/test_spec.py::TestGFM::test_list_items_012",
"tests/test_spec.py::TestGFM::test_list_items_013",
"tests/test_spec.py::TestGFM::test_list_items_014",
"tests/test_spec.py::TestGFM::test_list_items_015",
"tests/test_spec.py::TestGFM::test_list_items_016",
"tests/test_spec.py::TestGFM::test_list_items_017",
"tests/test_spec.py::TestGFM::test_list_items_018",
"tests/test_spec.py::TestGFM::test_list_items_019",
"tests/test_spec.py::TestGFM::test_list_items_020",
"tests/test_spec.py::TestGFM::test_list_items_021",
"tests/test_spec.py::TestGFM::test_list_items_022",
"tests/test_spec.py::TestGFM::test_list_items_023",
"tests/test_spec.py::TestGFM::test_list_items_024",
"tests/test_spec.py::TestGFM::test_list_items_025",
"tests/test_spec.py::TestGFM::test_list_items_026",
"tests/test_spec.py::TestGFM::test_list_items_027",
"tests/test_spec.py::TestGFM::test_list_items_028",
"tests/test_spec.py::TestGFM::test_list_items_029",
"tests/test_spec.py::TestGFM::test_list_items_030",
"tests/test_spec.py::TestGFM::test_list_items_031",
"tests/test_spec.py::TestGFM::test_list_items_032",
"tests/test_spec.py::TestGFM::test_list_items_033",
"tests/test_spec.py::TestGFM::test_list_items_034",
"tests/test_spec.py::TestGFM::test_list_items_035",
"tests/test_spec.py::TestGFM::test_list_items_036",
"tests/test_spec.py::TestGFM::test_list_items_037",
"tests/test_spec.py::TestGFM::test_list_items_038",
"tests/test_spec.py::TestGFM::test_list_items_039",
"tests/test_spec.py::TestGFM::test_list_items_040",
"tests/test_spec.py::TestGFM::test_list_items_041",
"tests/test_spec.py::TestGFM::test_list_items_042",
"tests/test_spec.py::TestGFM::test_list_items_043",
"tests/test_spec.py::TestGFM::test_list_items_044",
"tests/test_spec.py::TestGFM::test_list_items_045",
"tests/test_spec.py::TestGFM::test_list_items_046",
"tests/test_spec.py::TestGFM::test_list_items_047",
"tests/test_spec.py::TestGFM::test_list_items_048",
"tests/test_spec.py::TestGFM::test_lists_001",
"tests/test_spec.py::TestGFM::test_lists_002",
"tests/test_spec.py::TestGFM::test_lists_003",
"tests/test_spec.py::TestGFM::test_lists_004",
"tests/test_spec.py::TestGFM::test_lists_005",
"tests/test_spec.py::TestGFM::test_lists_006",
"tests/test_spec.py::TestGFM::test_lists_007",
"tests/test_spec.py::TestGFM::test_lists_008",
"tests/test_spec.py::TestGFM::test_lists_009",
"tests/test_spec.py::TestGFM::test_lists_010",
"tests/test_spec.py::TestGFM::test_lists_011",
"tests/test_spec.py::TestGFM::test_lists_012",
"tests/test_spec.py::TestGFM::test_lists_013",
"tests/test_spec.py::TestGFM::test_lists_014",
"tests/test_spec.py::TestGFM::test_lists_015",
"tests/test_spec.py::TestGFM::test_lists_016",
"tests/test_spec.py::TestGFM::test_lists_017",
"tests/test_spec.py::TestGFM::test_lists_018",
"tests/test_spec.py::TestGFM::test_lists_019",
"tests/test_spec.py::TestGFM::test_lists_020",
"tests/test_spec.py::TestGFM::test_lists_021",
"tests/test_spec.py::TestGFM::test_lists_022",
"tests/test_spec.py::TestGFM::test_lists_023",
"tests/test_spec.py::TestGFM::test_lists_024",
"tests/test_spec.py::TestGFM::test_lists_025",
"tests/test_spec.py::TestGFM::test_lists_026",
"tests/test_spec.py::TestGFM::test_inlines_001",
"tests/test_spec.py::TestGFM::test_backslash_escapes_001",
"tests/test_spec.py::TestGFM::test_backslash_escapes_002",
"tests/test_spec.py::TestGFM::test_backslash_escapes_003",
"tests/test_spec.py::TestGFM::test_backslash_escapes_004",
"tests/test_spec.py::TestGFM::test_backslash_escapes_005",
"tests/test_spec.py::TestGFM::test_backslash_escapes_006",
"tests/test_spec.py::TestGFM::test_backslash_escapes_007",
"tests/test_spec.py::TestGFM::test_backslash_escapes_008",
"tests/test_spec.py::TestGFM::test_backslash_escapes_009",
"tests/test_spec.py::TestGFM::test_backslash_escapes_010",
"tests/test_spec.py::TestGFM::test_backslash_escapes_011",
"tests/test_spec.py::TestGFM::test_backslash_escapes_012",
"tests/test_spec.py::TestGFM::test_backslash_escapes_013",
"tests/test_spec.py::TestGFM::test_entity_and_numeric_character_references_001",
"tests/test_spec.py::TestGFM::test_entity_and_numeric_character_references_002",
"tests/test_spec.py::TestGFM::test_entity_and_numeric_character_references_003",
"tests/test_spec.py::TestGFM::test_entity_and_numeric_character_references_004",
"tests/test_spec.py::TestGFM::test_entity_and_numeric_character_references_005",
"tests/test_spec.py::TestGFM::test_entity_and_numeric_character_references_006",
"tests/test_spec.py::TestGFM::test_entity_and_numeric_character_references_007",
"tests/test_spec.py::TestGFM::test_entity_and_numeric_character_references_008",
"tests/test_spec.py::TestGFM::test_entity_and_numeric_character_references_009",
"tests/test_spec.py::TestGFM::test_entity_and_numeric_character_references_010",
"tests/test_spec.py::TestGFM::test_entity_and_numeric_character_references_011",
"tests/test_spec.py::TestGFM::test_entity_and_numeric_character_references_012",
"tests/test_spec.py::TestGFM::test_entity_and_numeric_character_references_013",
"tests/test_spec.py::TestGFM::test_entity_and_numeric_character_references_014",
"tests/test_spec.py::TestGFM::test_entity_and_numeric_character_references_015",
"tests/test_spec.py::TestGFM::test_entity_and_numeric_character_references_016",
"tests/test_spec.py::TestGFM::test_entity_and_numeric_character_references_017",
"tests/test_spec.py::TestGFM::test_code_spans_001",
"tests/test_spec.py::TestGFM::test_code_spans_002",
"tests/test_spec.py::TestGFM::test_code_spans_003",
"tests/test_spec.py::TestGFM::test_code_spans_004",
"tests/test_spec.py::TestGFM::test_code_spans_005",
"tests/test_spec.py::TestGFM::test_code_spans_006",
"tests/test_spec.py::TestGFM::test_code_spans_007",
"tests/test_spec.py::TestGFM::test_code_spans_008",
"tests/test_spec.py::TestGFM::test_code_spans_009",
"tests/test_spec.py::TestGFM::test_code_spans_010",
"tests/test_spec.py::TestGFM::test_code_spans_011",
"tests/test_spec.py::TestGFM::test_code_spans_012",
"tests/test_spec.py::TestGFM::test_code_spans_013",
"tests/test_spec.py::TestGFM::test_code_spans_014",
"tests/test_spec.py::TestGFM::test_code_spans_015",
"tests/test_spec.py::TestGFM::test_code_spans_016",
"tests/test_spec.py::TestGFM::test_code_spans_017",
"tests/test_spec.py::TestGFM::test_code_spans_018",
"tests/test_spec.py::TestGFM::test_code_spans_019",
"tests/test_spec.py::TestGFM::test_code_spans_020",
"tests/test_spec.py::TestGFM::test_code_spans_021",
"tests/test_spec.py::TestGFM::test_code_spans_022",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_001",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_002",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_003",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_004",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_005",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_006",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_007",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_008",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_009",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_010",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_011",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_012",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_013",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_014",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_015",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_016",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_017",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_018",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_019",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_020",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_021",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_022",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_023",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_024",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_025",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_026",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_027",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_028",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_029",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_030",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_031",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_032",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_033",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_034",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_035",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_036",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_037",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_038",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_039",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_040",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_041",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_042",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_043",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_044",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_045",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_046",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_047",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_048",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_049",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_050",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_051",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_052",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_053",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_054",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_055",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_056",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_057",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_058",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_059",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_060",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_061",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_062",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_063",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_064",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_065",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_066",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_067",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_068",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_069",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_070",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_071",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_072",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_073",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_074",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_075",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_076",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_077",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_078",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_079",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_080",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_081",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_082",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_083",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_084",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_085",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_086",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_087",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_088",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_089",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_090",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_091",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_092",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_093",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_094",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_095",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_096",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_097",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_098",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_099",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_100",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_101",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_102",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_103",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_104",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_105",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_106",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_107",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_108",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_109",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_110",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_111",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_112",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_113",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_114",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_115",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_116",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_117",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_118",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_119",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_120",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_121",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_122",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_123",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_124",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_125",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_126",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_127",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_128",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_129",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_130",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_131",
"tests/test_spec.py::TestGFM::test_links_001",
"tests/test_spec.py::TestGFM::test_links_002",
"tests/test_spec.py::TestGFM::test_links_003",
"tests/test_spec.py::TestGFM::test_links_004",
"tests/test_spec.py::TestGFM::test_links_005",
"tests/test_spec.py::TestGFM::test_links_006",
"tests/test_spec.py::TestGFM::test_links_007",
"tests/test_spec.py::TestGFM::test_links_008",
"tests/test_spec.py::TestGFM::test_links_009",
"tests/test_spec.py::TestGFM::test_links_010",
"tests/test_spec.py::TestGFM::test_links_011",
"tests/test_spec.py::TestGFM::test_links_012",
"tests/test_spec.py::TestGFM::test_links_013",
"tests/test_spec.py::TestGFM::test_links_014",
"tests/test_spec.py::TestGFM::test_links_015",
"tests/test_spec.py::TestGFM::test_links_016",
"tests/test_spec.py::TestGFM::test_links_017",
"tests/test_spec.py::TestGFM::test_links_018",
"tests/test_spec.py::TestGFM::test_links_019",
"tests/test_spec.py::TestGFM::test_links_020",
"tests/test_spec.py::TestGFM::test_links_021",
"tests/test_spec.py::TestGFM::test_links_022",
"tests/test_spec.py::TestGFM::test_links_023",
"tests/test_spec.py::TestGFM::test_links_024",
"tests/test_spec.py::TestGFM::test_links_025",
"tests/test_spec.py::TestGFM::test_links_026",
"tests/test_spec.py::TestGFM::test_links_027",
"tests/test_spec.py::TestGFM::test_links_028",
"tests/test_spec.py::TestGFM::test_links_029",
"tests/test_spec.py::TestGFM::test_links_030",
"tests/test_spec.py::TestGFM::test_links_031",
"tests/test_spec.py::TestGFM::test_links_032",
"tests/test_spec.py::TestGFM::test_links_033",
"tests/test_spec.py::TestGFM::test_links_034",
"tests/test_spec.py::TestGFM::test_links_035",
"tests/test_spec.py::TestGFM::test_links_036",
"tests/test_spec.py::TestGFM::test_links_037",
"tests/test_spec.py::TestGFM::test_links_038",
"tests/test_spec.py::TestGFM::test_links_039",
"tests/test_spec.py::TestGFM::test_links_040",
"tests/test_spec.py::TestGFM::test_links_041",
"tests/test_spec.py::TestGFM::test_links_042",
"tests/test_spec.py::TestGFM::test_links_043",
"tests/test_spec.py::TestGFM::test_links_044",
"tests/test_spec.py::TestGFM::test_links_045",
"tests/test_spec.py::TestGFM::test_links_046",
"tests/test_spec.py::TestGFM::test_links_047",
"tests/test_spec.py::TestGFM::test_links_048",
"tests/test_spec.py::TestGFM::test_links_049",
"tests/test_spec.py::TestGFM::test_links_050",
"tests/test_spec.py::TestGFM::test_links_051",
"tests/test_spec.py::TestGFM::test_links_052",
"tests/test_spec.py::TestGFM::test_links_053",
"tests/test_spec.py::TestGFM::test_links_054",
"tests/test_spec.py::TestGFM::test_links_055",
"tests/test_spec.py::TestGFM::test_links_056",
"tests/test_spec.py::TestGFM::test_links_057",
"tests/test_spec.py::TestGFM::test_links_058",
"tests/test_spec.py::TestGFM::test_links_059",
"tests/test_spec.py::TestGFM::test_links_060",
"tests/test_spec.py::TestGFM::test_links_061",
"tests/test_spec.py::TestGFM::test_links_062",
"tests/test_spec.py::TestGFM::test_links_063",
"tests/test_spec.py::TestGFM::test_links_064",
"tests/test_spec.py::TestGFM::test_links_065",
"tests/test_spec.py::TestGFM::test_links_066",
"tests/test_spec.py::TestGFM::test_links_067",
"tests/test_spec.py::TestGFM::test_links_068",
"tests/test_spec.py::TestGFM::test_links_069",
"tests/test_spec.py::TestGFM::test_links_070",
"tests/test_spec.py::TestGFM::test_links_071",
"tests/test_spec.py::TestGFM::test_links_072",
"tests/test_spec.py::TestGFM::test_links_073",
"tests/test_spec.py::TestGFM::test_links_074",
"tests/test_spec.py::TestGFM::test_links_075",
"tests/test_spec.py::TestGFM::test_links_076",
"tests/test_spec.py::TestGFM::test_links_077",
"tests/test_spec.py::TestGFM::test_links_078",
"tests/test_spec.py::TestGFM::test_links_079",
"tests/test_spec.py::TestGFM::test_links_080",
"tests/test_spec.py::TestGFM::test_links_081",
"tests/test_spec.py::TestGFM::test_links_082",
"tests/test_spec.py::TestGFM::test_links_083",
"tests/test_spec.py::TestGFM::test_links_084",
"tests/test_spec.py::TestGFM::test_links_085",
"tests/test_spec.py::TestGFM::test_links_086",
"tests/test_spec.py::TestGFM::test_links_087",
"tests/test_spec.py::TestGFM::test_images_001",
"tests/test_spec.py::TestGFM::test_images_002",
"tests/test_spec.py::TestGFM::test_images_003",
"tests/test_spec.py::TestGFM::test_images_004",
"tests/test_spec.py::TestGFM::test_images_005",
"tests/test_spec.py::TestGFM::test_images_006",
"tests/test_spec.py::TestGFM::test_images_007",
"tests/test_spec.py::TestGFM::test_images_008",
"tests/test_spec.py::TestGFM::test_images_009",
"tests/test_spec.py::TestGFM::test_images_010",
"tests/test_spec.py::TestGFM::test_images_011",
"tests/test_spec.py::TestGFM::test_images_012",
"tests/test_spec.py::TestGFM::test_images_013",
"tests/test_spec.py::TestGFM::test_images_014",
"tests/test_spec.py::TestGFM::test_images_015",
"tests/test_spec.py::TestGFM::test_images_016",
"tests/test_spec.py::TestGFM::test_images_017",
"tests/test_spec.py::TestGFM::test_images_018",
"tests/test_spec.py::TestGFM::test_images_019",
"tests/test_spec.py::TestGFM::test_images_020",
"tests/test_spec.py::TestGFM::test_images_021",
"tests/test_spec.py::TestGFM::test_images_022",
"tests/test_spec.py::TestGFM::test_autolinks_001",
"tests/test_spec.py::TestGFM::test_autolinks_002",
"tests/test_spec.py::TestGFM::test_autolinks_003",
"tests/test_spec.py::TestGFM::test_autolinks_004",
"tests/test_spec.py::TestGFM::test_autolinks_005",
"tests/test_spec.py::TestGFM::test_autolinks_006",
"tests/test_spec.py::TestGFM::test_autolinks_007",
"tests/test_spec.py::TestGFM::test_autolinks_008",
"tests/test_spec.py::TestGFM::test_autolinks_009",
"tests/test_spec.py::TestGFM::test_autolinks_010",
"tests/test_spec.py::TestGFM::test_autolinks_011",
"tests/test_spec.py::TestGFM::test_autolinks_012",
"tests/test_spec.py::TestGFM::test_autolinks_013",
"tests/test_spec.py::TestGFM::test_autolinks_014",
"tests/test_spec.py::TestGFM::test_autolinks_016",
"tests/test_spec.py::TestGFM::test_autolinks_017",
"tests/test_spec.py::TestGFM::test_raw_html_001",
"tests/test_spec.py::TestGFM::test_raw_html_002",
"tests/test_spec.py::TestGFM::test_raw_html_003",
"tests/test_spec.py::TestGFM::test_raw_html_004",
"tests/test_spec.py::TestGFM::test_raw_html_005",
"tests/test_spec.py::TestGFM::test_raw_html_006",
"tests/test_spec.py::TestGFM::test_raw_html_007",
"tests/test_spec.py::TestGFM::test_raw_html_008",
"tests/test_spec.py::TestGFM::test_raw_html_009",
"tests/test_spec.py::TestGFM::test_raw_html_010",
"tests/test_spec.py::TestGFM::test_raw_html_011",
"tests/test_spec.py::TestGFM::test_raw_html_012",
"tests/test_spec.py::TestGFM::test_raw_html_013",
"tests/test_spec.py::TestGFM::test_raw_html_014",
"tests/test_spec.py::TestGFM::test_raw_html_015",
"tests/test_spec.py::TestGFM::test_raw_html_016",
"tests/test_spec.py::TestGFM::test_raw_html_017",
"tests/test_spec.py::TestGFM::test_raw_html_018",
"tests/test_spec.py::TestGFM::test_raw_html_019",
"tests/test_spec.py::TestGFM::test_raw_html_020",
"tests/test_spec.py::TestGFM::test_raw_html_021",
"tests/test_spec.py::TestGFM::test_hard_line_breaks_001",
"tests/test_spec.py::TestGFM::test_hard_line_breaks_002",
"tests/test_spec.py::TestGFM::test_hard_line_breaks_003",
"tests/test_spec.py::TestGFM::test_hard_line_breaks_004",
"tests/test_spec.py::TestGFM::test_hard_line_breaks_005",
"tests/test_spec.py::TestGFM::test_hard_line_breaks_006",
"tests/test_spec.py::TestGFM::test_hard_line_breaks_007",
"tests/test_spec.py::TestGFM::test_hard_line_breaks_008",
"tests/test_spec.py::TestGFM::test_hard_line_breaks_009",
"tests/test_spec.py::TestGFM::test_hard_line_breaks_010",
"tests/test_spec.py::TestGFM::test_hard_line_breaks_011",
"tests/test_spec.py::TestGFM::test_hard_line_breaks_012",
"tests/test_spec.py::TestGFM::test_hard_line_breaks_013",
"tests/test_spec.py::TestGFM::test_hard_line_breaks_014",
"tests/test_spec.py::TestGFM::test_hard_line_breaks_015",
"tests/test_spec.py::TestGFM::test_soft_line_breaks_001",
"tests/test_spec.py::TestGFM::test_soft_line_breaks_002",
"tests/test_spec.py::TestGFM::test_textual_content_001",
"tests/test_spec.py::TestGFM::test_textual_content_002",
"tests/test_spec.py::TestGFM::test_textual_content_003"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-09-16 09:41:09+00:00
|
mit
| 2,414 |
|
frostming__marko-50
|
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 3c1a6e0..2f7da2c 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -45,6 +45,7 @@ jobs:
- name: Install dependencies
run: |
pdm use -f ${{ matrix.python-version }}
+ pdm config set parallel_install false
pip install wheel
pdm install -d -s toc -s codehilite
- name: Run Tests
diff --git a/marko/_compat.py b/marko/_compat.py
index ba77dd7..2a12269 100644
--- a/marko/_compat.py
+++ b/marko/_compat.py
@@ -16,8 +16,17 @@ if PY2:
s = s.encode("utf-8")
return _quote(s, safe)
+ def lru_cache(maxsize=128, typed=False):
+ """Python 2.7 doesn't support LRU cache, return a fake decoractor."""
+
+ def decorator(f):
+ return f
+
+ return decorator
+
else:
string_types = str
import html
from urllib.parse import quote
+ from functools import lru_cache
diff --git a/marko/block.py b/marko/block.py
index a50e17c..c4f4fac 100644
--- a/marko/block.py
+++ b/marko/block.py
@@ -84,7 +84,7 @@ class Document(BlockElement):
virtual = True
def __init__(self, text): # type: (str) -> None
- self.link_ref_defs = {} # type: Dict[str, Tuple[str, str]]
+ self.link_ref_defs = {} # type: Dict[str, Tuple[str, str]]
source = Source(text)
inline._root_node = self # type: ignore
with source.under_state(self):
@@ -168,7 +168,7 @@ class CodeBlock(BlockElement):
if isinstance(source.state, Quote):
# requires five spaces to prefix
prefix = source.prefix[:-1] + " {4}"
- return cls.strip_prefix(line, prefix) # type: ignore
+ return cls.strip_prefix(line, prefix) # type: ignore
@classmethod
def parse(cls, source): # type: (Source) -> str
@@ -229,9 +229,9 @@ class FencedCode(BlockElement):
if not m:
return None
prefix, leading, info = m.groups()
- if leading[0] == '`' and '`' in info:
+ if leading[0] == "`" and "`" in info:
return None
- lang, extra = (info.split(None, 1) + [''] * 2)[:2]
+ lang, extra = (info.split(None, 1) + [""] * 2)[:2]
cls._parse_info = prefix, leading, lang, extra
return m
@@ -281,7 +281,7 @@ class HTMLBlock(BlockElement):
"""HTML blocks, parsed as it is"""
priority = 5
- _end_cond = None # Optional[Match]
+ _end_cond = None # Optional[Match]
def __init__(self, lines): # type: (str) -> None
self.children = lines
@@ -532,7 +532,15 @@ class ListItem(BlockElement):
return False
if not source.expect_re(cls.pattern):
return False
- indent, bullet, mid, tail = cls.parse_leading(source.next_line()) # type: ignore
+ next_line = source.next_line(False)
+ assert next_line is not None
+ for i in range(1, len(next_line) + 1):
+ m = re.match(source.prefix, next_line[:i].expandtabs(4))
+ if not m:
+ continue
+ next_line = next_line[:i].expandtabs(4)[m.end() :] + next_line[i:]
+ break
+ indent, bullet, mid, tail = cls.parse_leading(next_line) # type: ignore
parent = source.state
assert isinstance(parent, List)
if (
diff --git a/marko/cli.py b/marko/cli.py
index cb1d301..c4ddccb 100644
--- a/marko/cli.py
+++ b/marko/cli.py
@@ -41,15 +41,11 @@ def parse(args):
default="marko.HTMLRenderer",
help="Specify another renderer class",
)
- parser.add_argument(
- "-o",
- "--output",
- help="Ouput to a file"
- )
+ parser.add_argument("-o", "--output", help="Ouput to a file")
parser.add_argument(
"document",
nargs="?",
- help="The document to convert, will use stdin if not given."
+ help="The document to convert, will use stdin if not given.",
)
return parser.parse_args(args)
diff --git a/marko/helpers.py b/marko/helpers.py
index 9e6654d..c733baf 100644
--- a/marko/helpers.py
+++ b/marko/helpers.py
@@ -6,7 +6,7 @@ from contextlib import contextmanager
from importlib import import_module
import warnings
-from ._compat import string_types
+from ._compat import string_types, lru_cache
def camel_to_snake_case(name): # type: (str) -> str
@@ -102,6 +102,7 @@ class Source(object):
return regexp.match(self._buffer, pos)
@staticmethod
+ @lru_cache()
def match_prefix(prefix, line): # type: (str, str) -> int
"""Check if the line starts with given prefix and
return the position of the end of prefix.
|
frostming/marko
|
da5fd4ee730d3c842d264fb5f387282f6f8f59fb
|
diff --git a/tests/__init__.py b/tests/__init__.py
index ecdd6c2..1b0364f 100644
--- a/tests/__init__.py
+++ b/tests/__init__.py
@@ -7,10 +7,8 @@ from tests.normalize import normalize_html
TEST_ROOT = os.path.dirname(__file__)
EXAMPLE_PATTERN = re.compile(
- r'^`{32} example\n([\s\S]*?)'
- r'^\.\n([\s\S]*?)'
- r'^`{32}$|^#{1,6} *(.*)$',
- flags=re.M
+ r"^`{32} example\n([\s\S]*?)" r"^\.\n([\s\S]*?)" r"^`{32}$|^#{1,6} *(.*)$",
+ flags=re.M,
)
@@ -22,31 +20,30 @@ def parse_examples(text):
for md, html, title in data:
if title:
count = 0
- section = title.lower().replace(' ', '_')
+ section = title.lower().replace(" ", "_")
if md and html:
count += 1
- name = '%s_%03d' % (section, count)
- md = md.replace(u'→', '\t')
- html = html.replace(u'→', '\t')
+ name = "%s_%03d" % (section, count)
+ md = md.replace(u"→", "\t")
+ html = html.replace(u"→", "\t")
yield name, md, html
class SpecTestSuite:
-
@classmethod
def load_spec(cls, spec_name):
def attach_case(n, md, html):
def method(self):
self.assert_case(md, html)
- name = 'test_{}'.format(n)
+ name = "test_{}".format(n)
method.__name__ = name
- method.__doc__ = 'Run spec {} - {}'.format(spec_name, n)
+ method.__doc__ = "Run spec {} - {}".format(spec_name, n)
setattr(cls, name, method)
- spec_file = os.path.join(TEST_ROOT, 'spec/{}.txt'.format(spec_name))
- with codecs.open(spec_file, encoding='utf-8') as f:
+ spec_file = os.path.join(TEST_ROOT, "spec/{}.txt".format(spec_name))
+ with codecs.open(spec_file, encoding="utf-8") as f:
for name, md, html in parse_examples(f.read()):
if not cls.ignore_case(name):
attach_case(name, md, html)
@@ -58,3 +55,9 @@ class SpecTestSuite:
def assert_case(self, text, html):
result = self.markdown(text)
assert normalize_html(result) == normalize_html(html)
+
+ # Extra cases that are not included
+ def test_mixed_tab_space_in_list_item(self):
+ text = "* foo\n\t* foo.bar"
+ html = "<ul><li>foo<ul><li>foo.bar</li></ul></li></ul>"
+ self.assert_case(text, html)
diff --git a/tests/test_spec.py b/tests/test_spec.py
index 8d90625..cb3df7d 100644
--- a/tests/test_spec.py
+++ b/tests/test_spec.py
@@ -4,23 +4,17 @@ from marko.ext.gfm import gfm
class TestCommonMark(SpecTestSuite):
-
@classmethod
def setup_class(cls):
cls.markdown = Markdown()
-TestCommonMark.load_spec('commonmark')
+TestCommonMark.load_spec("commonmark")
-GFM_IGNORE = [
- 'autolinks_015',
- 'autolinks_018',
- 'autolinks_019'
-]
+GFM_IGNORE = ["autolinks_015", "autolinks_018", "autolinks_019"]
class TestGFM(SpecTestSuite):
-
@classmethod
def setup_class(cls):
cls.markdown = gfm
@@ -30,4 +24,4 @@ class TestGFM(SpecTestSuite):
return n in GFM_IGNORE
-TestGFM.load_spec('gfm')
+TestGFM.load_spec("gfm")
|
Parse error on mixed preceding whitespaces
Example doc:
```md
# Summary
* [主页](README.md)
* [安全技术]
* Windows取证
\t* 常用命令
\t * [基础网络命令](安全技术/常用命令/基础网络命令.md)
```
|
0.0
|
da5fd4ee730d3c842d264fb5f387282f6f8f59fb
|
[
"tests/test_spec.py::TestCommonMark::test_mixed_tab_space_in_list_item",
"tests/test_spec.py::TestGFM::test_mixed_tab_space_in_list_item"
] |
[
"tests/test_spec.py::TestCommonMark::test_tabs_001",
"tests/test_spec.py::TestCommonMark::test_tabs_002",
"tests/test_spec.py::TestCommonMark::test_tabs_003",
"tests/test_spec.py::TestCommonMark::test_tabs_004",
"tests/test_spec.py::TestCommonMark::test_tabs_005",
"tests/test_spec.py::TestCommonMark::test_tabs_006",
"tests/test_spec.py::TestCommonMark::test_tabs_007",
"tests/test_spec.py::TestCommonMark::test_tabs_008",
"tests/test_spec.py::TestCommonMark::test_tabs_009",
"tests/test_spec.py::TestCommonMark::test_tabs_010",
"tests/test_spec.py::TestCommonMark::test_tabs_011",
"tests/test_spec.py::TestCommonMark::test_precedence_001",
"tests/test_spec.py::TestCommonMark::test_thematic_breaks_001",
"tests/test_spec.py::TestCommonMark::test_thematic_breaks_002",
"tests/test_spec.py::TestCommonMark::test_thematic_breaks_003",
"tests/test_spec.py::TestCommonMark::test_thematic_breaks_004",
"tests/test_spec.py::TestCommonMark::test_thematic_breaks_005",
"tests/test_spec.py::TestCommonMark::test_thematic_breaks_006",
"tests/test_spec.py::TestCommonMark::test_thematic_breaks_007",
"tests/test_spec.py::TestCommonMark::test_thematic_breaks_008",
"tests/test_spec.py::TestCommonMark::test_thematic_breaks_009",
"tests/test_spec.py::TestCommonMark::test_thematic_breaks_010",
"tests/test_spec.py::TestCommonMark::test_thematic_breaks_011",
"tests/test_spec.py::TestCommonMark::test_thematic_breaks_012",
"tests/test_spec.py::TestCommonMark::test_thematic_breaks_013",
"tests/test_spec.py::TestCommonMark::test_thematic_breaks_014",
"tests/test_spec.py::TestCommonMark::test_thematic_breaks_015",
"tests/test_spec.py::TestCommonMark::test_thematic_breaks_016",
"tests/test_spec.py::TestCommonMark::test_thematic_breaks_017",
"tests/test_spec.py::TestCommonMark::test_thematic_breaks_018",
"tests/test_spec.py::TestCommonMark::test_thematic_breaks_019",
"tests/test_spec.py::TestCommonMark::test_atx_headings_001",
"tests/test_spec.py::TestCommonMark::test_atx_headings_002",
"tests/test_spec.py::TestCommonMark::test_atx_headings_003",
"tests/test_spec.py::TestCommonMark::test_atx_headings_004",
"tests/test_spec.py::TestCommonMark::test_atx_headings_005",
"tests/test_spec.py::TestCommonMark::test_atx_headings_006",
"tests/test_spec.py::TestCommonMark::test_atx_headings_007",
"tests/test_spec.py::TestCommonMark::test_atx_headings_008",
"tests/test_spec.py::TestCommonMark::test_atx_headings_009",
"tests/test_spec.py::TestCommonMark::test_atx_headings_010",
"tests/test_spec.py::TestCommonMark::test_atx_headings_011",
"tests/test_spec.py::TestCommonMark::test_atx_headings_012",
"tests/test_spec.py::TestCommonMark::test_atx_headings_013",
"tests/test_spec.py::TestCommonMark::test_atx_headings_014",
"tests/test_spec.py::TestCommonMark::test_atx_headings_015",
"tests/test_spec.py::TestCommonMark::test_atx_headings_016",
"tests/test_spec.py::TestCommonMark::test_atx_headings_017",
"tests/test_spec.py::TestCommonMark::test_atx_headings_018",
"tests/test_spec.py::TestCommonMark::test_setext_headings_001",
"tests/test_spec.py::TestCommonMark::test_setext_headings_002",
"tests/test_spec.py::TestCommonMark::test_setext_headings_003",
"tests/test_spec.py::TestCommonMark::test_setext_headings_004",
"tests/test_spec.py::TestCommonMark::test_setext_headings_005",
"tests/test_spec.py::TestCommonMark::test_setext_headings_006",
"tests/test_spec.py::TestCommonMark::test_setext_headings_007",
"tests/test_spec.py::TestCommonMark::test_setext_headings_008",
"tests/test_spec.py::TestCommonMark::test_setext_headings_009",
"tests/test_spec.py::TestCommonMark::test_setext_headings_010",
"tests/test_spec.py::TestCommonMark::test_setext_headings_011",
"tests/test_spec.py::TestCommonMark::test_setext_headings_012",
"tests/test_spec.py::TestCommonMark::test_setext_headings_013",
"tests/test_spec.py::TestCommonMark::test_setext_headings_014",
"tests/test_spec.py::TestCommonMark::test_setext_headings_015",
"tests/test_spec.py::TestCommonMark::test_setext_headings_016",
"tests/test_spec.py::TestCommonMark::test_setext_headings_017",
"tests/test_spec.py::TestCommonMark::test_setext_headings_018",
"tests/test_spec.py::TestCommonMark::test_setext_headings_019",
"tests/test_spec.py::TestCommonMark::test_setext_headings_020",
"tests/test_spec.py::TestCommonMark::test_setext_headings_021",
"tests/test_spec.py::TestCommonMark::test_setext_headings_022",
"tests/test_spec.py::TestCommonMark::test_setext_headings_023",
"tests/test_spec.py::TestCommonMark::test_setext_headings_024",
"tests/test_spec.py::TestCommonMark::test_setext_headings_025",
"tests/test_spec.py::TestCommonMark::test_setext_headings_026",
"tests/test_spec.py::TestCommonMark::test_setext_headings_027",
"tests/test_spec.py::TestCommonMark::test_indented_code_blocks_001",
"tests/test_spec.py::TestCommonMark::test_indented_code_blocks_002",
"tests/test_spec.py::TestCommonMark::test_indented_code_blocks_003",
"tests/test_spec.py::TestCommonMark::test_indented_code_blocks_004",
"tests/test_spec.py::TestCommonMark::test_indented_code_blocks_005",
"tests/test_spec.py::TestCommonMark::test_indented_code_blocks_006",
"tests/test_spec.py::TestCommonMark::test_indented_code_blocks_007",
"tests/test_spec.py::TestCommonMark::test_indented_code_blocks_008",
"tests/test_spec.py::TestCommonMark::test_indented_code_blocks_009",
"tests/test_spec.py::TestCommonMark::test_indented_code_blocks_010",
"tests/test_spec.py::TestCommonMark::test_indented_code_blocks_011",
"tests/test_spec.py::TestCommonMark::test_indented_code_blocks_012",
"tests/test_spec.py::TestCommonMark::test_fenced_code_blocks_001",
"tests/test_spec.py::TestCommonMark::test_fenced_code_blocks_002",
"tests/test_spec.py::TestCommonMark::test_fenced_code_blocks_003",
"tests/test_spec.py::TestCommonMark::test_fenced_code_blocks_004",
"tests/test_spec.py::TestCommonMark::test_fenced_code_blocks_005",
"tests/test_spec.py::TestCommonMark::test_fenced_code_blocks_006",
"tests/test_spec.py::TestCommonMark::test_fenced_code_blocks_007",
"tests/test_spec.py::TestCommonMark::test_fenced_code_blocks_008",
"tests/test_spec.py::TestCommonMark::test_fenced_code_blocks_009",
"tests/test_spec.py::TestCommonMark::test_fenced_code_blocks_010",
"tests/test_spec.py::TestCommonMark::test_fenced_code_blocks_011",
"tests/test_spec.py::TestCommonMark::test_fenced_code_blocks_012",
"tests/test_spec.py::TestCommonMark::test_fenced_code_blocks_013",
"tests/test_spec.py::TestCommonMark::test_fenced_code_blocks_014",
"tests/test_spec.py::TestCommonMark::test_fenced_code_blocks_015",
"tests/test_spec.py::TestCommonMark::test_fenced_code_blocks_016",
"tests/test_spec.py::TestCommonMark::test_fenced_code_blocks_017",
"tests/test_spec.py::TestCommonMark::test_fenced_code_blocks_018",
"tests/test_spec.py::TestCommonMark::test_fenced_code_blocks_019",
"tests/test_spec.py::TestCommonMark::test_fenced_code_blocks_020",
"tests/test_spec.py::TestCommonMark::test_fenced_code_blocks_021",
"tests/test_spec.py::TestCommonMark::test_fenced_code_blocks_022",
"tests/test_spec.py::TestCommonMark::test_fenced_code_blocks_023",
"tests/test_spec.py::TestCommonMark::test_fenced_code_blocks_024",
"tests/test_spec.py::TestCommonMark::test_fenced_code_blocks_025",
"tests/test_spec.py::TestCommonMark::test_fenced_code_blocks_026",
"tests/test_spec.py::TestCommonMark::test_fenced_code_blocks_027",
"tests/test_spec.py::TestCommonMark::test_fenced_code_blocks_028",
"tests/test_spec.py::TestCommonMark::test_fenced_code_blocks_029",
"tests/test_spec.py::TestCommonMark::test_html_blocks_001",
"tests/test_spec.py::TestCommonMark::test_html_blocks_002",
"tests/test_spec.py::TestCommonMark::test_html_blocks_003",
"tests/test_spec.py::TestCommonMark::test_html_blocks_004",
"tests/test_spec.py::TestCommonMark::test_html_blocks_005",
"tests/test_spec.py::TestCommonMark::test_html_blocks_006",
"tests/test_spec.py::TestCommonMark::test_html_blocks_007",
"tests/test_spec.py::TestCommonMark::test_html_blocks_008",
"tests/test_spec.py::TestCommonMark::test_html_blocks_009",
"tests/test_spec.py::TestCommonMark::test_html_blocks_010",
"tests/test_spec.py::TestCommonMark::test_html_blocks_011",
"tests/test_spec.py::TestCommonMark::test_html_blocks_012",
"tests/test_spec.py::TestCommonMark::test_html_blocks_013",
"tests/test_spec.py::TestCommonMark::test_html_blocks_014",
"tests/test_spec.py::TestCommonMark::test_html_blocks_015",
"tests/test_spec.py::TestCommonMark::test_html_blocks_016",
"tests/test_spec.py::TestCommonMark::test_html_blocks_017",
"tests/test_spec.py::TestCommonMark::test_html_blocks_018",
"tests/test_spec.py::TestCommonMark::test_html_blocks_019",
"tests/test_spec.py::TestCommonMark::test_html_blocks_020",
"tests/test_spec.py::TestCommonMark::test_html_blocks_021",
"tests/test_spec.py::TestCommonMark::test_html_blocks_022",
"tests/test_spec.py::TestCommonMark::test_html_blocks_023",
"tests/test_spec.py::TestCommonMark::test_html_blocks_024",
"tests/test_spec.py::TestCommonMark::test_html_blocks_025",
"tests/test_spec.py::TestCommonMark::test_html_blocks_026",
"tests/test_spec.py::TestCommonMark::test_html_blocks_027",
"tests/test_spec.py::TestCommonMark::test_html_blocks_028",
"tests/test_spec.py::TestCommonMark::test_html_blocks_029",
"tests/test_spec.py::TestCommonMark::test_html_blocks_030",
"tests/test_spec.py::TestCommonMark::test_html_blocks_031",
"tests/test_spec.py::TestCommonMark::test_html_blocks_032",
"tests/test_spec.py::TestCommonMark::test_html_blocks_033",
"tests/test_spec.py::TestCommonMark::test_html_blocks_034",
"tests/test_spec.py::TestCommonMark::test_html_blocks_035",
"tests/test_spec.py::TestCommonMark::test_html_blocks_036",
"tests/test_spec.py::TestCommonMark::test_html_blocks_037",
"tests/test_spec.py::TestCommonMark::test_html_blocks_038",
"tests/test_spec.py::TestCommonMark::test_html_blocks_039",
"tests/test_spec.py::TestCommonMark::test_html_blocks_040",
"tests/test_spec.py::TestCommonMark::test_html_blocks_041",
"tests/test_spec.py::TestCommonMark::test_html_blocks_042",
"tests/test_spec.py::TestCommonMark::test_html_blocks_043",
"tests/test_spec.py::TestCommonMark::test_link_reference_definitions_001",
"tests/test_spec.py::TestCommonMark::test_link_reference_definitions_002",
"tests/test_spec.py::TestCommonMark::test_link_reference_definitions_003",
"tests/test_spec.py::TestCommonMark::test_link_reference_definitions_004",
"tests/test_spec.py::TestCommonMark::test_link_reference_definitions_005",
"tests/test_spec.py::TestCommonMark::test_link_reference_definitions_006",
"tests/test_spec.py::TestCommonMark::test_link_reference_definitions_007",
"tests/test_spec.py::TestCommonMark::test_link_reference_definitions_008",
"tests/test_spec.py::TestCommonMark::test_link_reference_definitions_009",
"tests/test_spec.py::TestCommonMark::test_link_reference_definitions_010",
"tests/test_spec.py::TestCommonMark::test_link_reference_definitions_011",
"tests/test_spec.py::TestCommonMark::test_link_reference_definitions_012",
"tests/test_spec.py::TestCommonMark::test_link_reference_definitions_013",
"tests/test_spec.py::TestCommonMark::test_link_reference_definitions_014",
"tests/test_spec.py::TestCommonMark::test_link_reference_definitions_015",
"tests/test_spec.py::TestCommonMark::test_link_reference_definitions_016",
"tests/test_spec.py::TestCommonMark::test_link_reference_definitions_017",
"tests/test_spec.py::TestCommonMark::test_link_reference_definitions_018",
"tests/test_spec.py::TestCommonMark::test_link_reference_definitions_019",
"tests/test_spec.py::TestCommonMark::test_link_reference_definitions_020",
"tests/test_spec.py::TestCommonMark::test_link_reference_definitions_021",
"tests/test_spec.py::TestCommonMark::test_link_reference_definitions_022",
"tests/test_spec.py::TestCommonMark::test_link_reference_definitions_023",
"tests/test_spec.py::TestCommonMark::test_link_reference_definitions_024",
"tests/test_spec.py::TestCommonMark::test_link_reference_definitions_025",
"tests/test_spec.py::TestCommonMark::test_link_reference_definitions_026",
"tests/test_spec.py::TestCommonMark::test_paragraphs_001",
"tests/test_spec.py::TestCommonMark::test_paragraphs_002",
"tests/test_spec.py::TestCommonMark::test_paragraphs_003",
"tests/test_spec.py::TestCommonMark::test_paragraphs_004",
"tests/test_spec.py::TestCommonMark::test_paragraphs_005",
"tests/test_spec.py::TestCommonMark::test_paragraphs_006",
"tests/test_spec.py::TestCommonMark::test_paragraphs_007",
"tests/test_spec.py::TestCommonMark::test_paragraphs_008",
"tests/test_spec.py::TestCommonMark::test_blank_lines_001",
"tests/test_spec.py::TestCommonMark::test_block_quotes_001",
"tests/test_spec.py::TestCommonMark::test_block_quotes_002",
"tests/test_spec.py::TestCommonMark::test_block_quotes_003",
"tests/test_spec.py::TestCommonMark::test_block_quotes_004",
"tests/test_spec.py::TestCommonMark::test_block_quotes_005",
"tests/test_spec.py::TestCommonMark::test_block_quotes_006",
"tests/test_spec.py::TestCommonMark::test_block_quotes_007",
"tests/test_spec.py::TestCommonMark::test_block_quotes_008",
"tests/test_spec.py::TestCommonMark::test_block_quotes_009",
"tests/test_spec.py::TestCommonMark::test_block_quotes_010",
"tests/test_spec.py::TestCommonMark::test_block_quotes_011",
"tests/test_spec.py::TestCommonMark::test_block_quotes_012",
"tests/test_spec.py::TestCommonMark::test_block_quotes_013",
"tests/test_spec.py::TestCommonMark::test_block_quotes_014",
"tests/test_spec.py::TestCommonMark::test_block_quotes_015",
"tests/test_spec.py::TestCommonMark::test_block_quotes_016",
"tests/test_spec.py::TestCommonMark::test_block_quotes_017",
"tests/test_spec.py::TestCommonMark::test_block_quotes_018",
"tests/test_spec.py::TestCommonMark::test_block_quotes_019",
"tests/test_spec.py::TestCommonMark::test_block_quotes_020",
"tests/test_spec.py::TestCommonMark::test_block_quotes_021",
"tests/test_spec.py::TestCommonMark::test_block_quotes_022",
"tests/test_spec.py::TestCommonMark::test_block_quotes_023",
"tests/test_spec.py::TestCommonMark::test_block_quotes_024",
"tests/test_spec.py::TestCommonMark::test_block_quotes_025",
"tests/test_spec.py::TestCommonMark::test_list_items_001",
"tests/test_spec.py::TestCommonMark::test_list_items_002",
"tests/test_spec.py::TestCommonMark::test_list_items_003",
"tests/test_spec.py::TestCommonMark::test_list_items_004",
"tests/test_spec.py::TestCommonMark::test_list_items_005",
"tests/test_spec.py::TestCommonMark::test_list_items_006",
"tests/test_spec.py::TestCommonMark::test_list_items_007",
"tests/test_spec.py::TestCommonMark::test_list_items_008",
"tests/test_spec.py::TestCommonMark::test_list_items_009",
"tests/test_spec.py::TestCommonMark::test_list_items_010",
"tests/test_spec.py::TestCommonMark::test_list_items_011",
"tests/test_spec.py::TestCommonMark::test_list_items_012",
"tests/test_spec.py::TestCommonMark::test_list_items_013",
"tests/test_spec.py::TestCommonMark::test_list_items_014",
"tests/test_spec.py::TestCommonMark::test_list_items_015",
"tests/test_spec.py::TestCommonMark::test_list_items_016",
"tests/test_spec.py::TestCommonMark::test_list_items_017",
"tests/test_spec.py::TestCommonMark::test_list_items_018",
"tests/test_spec.py::TestCommonMark::test_list_items_019",
"tests/test_spec.py::TestCommonMark::test_list_items_020",
"tests/test_spec.py::TestCommonMark::test_list_items_021",
"tests/test_spec.py::TestCommonMark::test_list_items_022",
"tests/test_spec.py::TestCommonMark::test_list_items_023",
"tests/test_spec.py::TestCommonMark::test_list_items_024",
"tests/test_spec.py::TestCommonMark::test_list_items_025",
"tests/test_spec.py::TestCommonMark::test_list_items_026",
"tests/test_spec.py::TestCommonMark::test_list_items_027",
"tests/test_spec.py::TestCommonMark::test_list_items_028",
"tests/test_spec.py::TestCommonMark::test_list_items_029",
"tests/test_spec.py::TestCommonMark::test_list_items_030",
"tests/test_spec.py::TestCommonMark::test_list_items_031",
"tests/test_spec.py::TestCommonMark::test_list_items_032",
"tests/test_spec.py::TestCommonMark::test_list_items_033",
"tests/test_spec.py::TestCommonMark::test_list_items_034",
"tests/test_spec.py::TestCommonMark::test_list_items_035",
"tests/test_spec.py::TestCommonMark::test_list_items_036",
"tests/test_spec.py::TestCommonMark::test_list_items_037",
"tests/test_spec.py::TestCommonMark::test_list_items_038",
"tests/test_spec.py::TestCommonMark::test_list_items_039",
"tests/test_spec.py::TestCommonMark::test_list_items_040",
"tests/test_spec.py::TestCommonMark::test_list_items_041",
"tests/test_spec.py::TestCommonMark::test_list_items_042",
"tests/test_spec.py::TestCommonMark::test_list_items_043",
"tests/test_spec.py::TestCommonMark::test_list_items_044",
"tests/test_spec.py::TestCommonMark::test_list_items_045",
"tests/test_spec.py::TestCommonMark::test_list_items_046",
"tests/test_spec.py::TestCommonMark::test_list_items_047",
"tests/test_spec.py::TestCommonMark::test_list_items_048",
"tests/test_spec.py::TestCommonMark::test_lists_001",
"tests/test_spec.py::TestCommonMark::test_lists_002",
"tests/test_spec.py::TestCommonMark::test_lists_003",
"tests/test_spec.py::TestCommonMark::test_lists_004",
"tests/test_spec.py::TestCommonMark::test_lists_005",
"tests/test_spec.py::TestCommonMark::test_lists_006",
"tests/test_spec.py::TestCommonMark::test_lists_007",
"tests/test_spec.py::TestCommonMark::test_lists_008",
"tests/test_spec.py::TestCommonMark::test_lists_009",
"tests/test_spec.py::TestCommonMark::test_lists_010",
"tests/test_spec.py::TestCommonMark::test_lists_011",
"tests/test_spec.py::TestCommonMark::test_lists_012",
"tests/test_spec.py::TestCommonMark::test_lists_013",
"tests/test_spec.py::TestCommonMark::test_lists_014",
"tests/test_spec.py::TestCommonMark::test_lists_015",
"tests/test_spec.py::TestCommonMark::test_lists_016",
"tests/test_spec.py::TestCommonMark::test_lists_017",
"tests/test_spec.py::TestCommonMark::test_lists_018",
"tests/test_spec.py::TestCommonMark::test_lists_019",
"tests/test_spec.py::TestCommonMark::test_lists_020",
"tests/test_spec.py::TestCommonMark::test_lists_021",
"tests/test_spec.py::TestCommonMark::test_lists_022",
"tests/test_spec.py::TestCommonMark::test_lists_023",
"tests/test_spec.py::TestCommonMark::test_lists_024",
"tests/test_spec.py::TestCommonMark::test_lists_025",
"tests/test_spec.py::TestCommonMark::test_lists_026",
"tests/test_spec.py::TestCommonMark::test_inlines_001",
"tests/test_spec.py::TestCommonMark::test_backslash_escapes_001",
"tests/test_spec.py::TestCommonMark::test_backslash_escapes_002",
"tests/test_spec.py::TestCommonMark::test_backslash_escapes_003",
"tests/test_spec.py::TestCommonMark::test_backslash_escapes_004",
"tests/test_spec.py::TestCommonMark::test_backslash_escapes_005",
"tests/test_spec.py::TestCommonMark::test_backslash_escapes_006",
"tests/test_spec.py::TestCommonMark::test_backslash_escapes_007",
"tests/test_spec.py::TestCommonMark::test_backslash_escapes_008",
"tests/test_spec.py::TestCommonMark::test_backslash_escapes_009",
"tests/test_spec.py::TestCommonMark::test_backslash_escapes_010",
"tests/test_spec.py::TestCommonMark::test_backslash_escapes_011",
"tests/test_spec.py::TestCommonMark::test_backslash_escapes_012",
"tests/test_spec.py::TestCommonMark::test_backslash_escapes_013",
"tests/test_spec.py::TestCommonMark::test_entity_and_numeric_character_references_001",
"tests/test_spec.py::TestCommonMark::test_entity_and_numeric_character_references_002",
"tests/test_spec.py::TestCommonMark::test_entity_and_numeric_character_references_003",
"tests/test_spec.py::TestCommonMark::test_entity_and_numeric_character_references_004",
"tests/test_spec.py::TestCommonMark::test_entity_and_numeric_character_references_005",
"tests/test_spec.py::TestCommonMark::test_entity_and_numeric_character_references_006",
"tests/test_spec.py::TestCommonMark::test_entity_and_numeric_character_references_007",
"tests/test_spec.py::TestCommonMark::test_entity_and_numeric_character_references_008",
"tests/test_spec.py::TestCommonMark::test_entity_and_numeric_character_references_009",
"tests/test_spec.py::TestCommonMark::test_entity_and_numeric_character_references_010",
"tests/test_spec.py::TestCommonMark::test_entity_and_numeric_character_references_011",
"tests/test_spec.py::TestCommonMark::test_entity_and_numeric_character_references_012",
"tests/test_spec.py::TestCommonMark::test_entity_and_numeric_character_references_013",
"tests/test_spec.py::TestCommonMark::test_entity_and_numeric_character_references_014",
"tests/test_spec.py::TestCommonMark::test_entity_and_numeric_character_references_015",
"tests/test_spec.py::TestCommonMark::test_entity_and_numeric_character_references_016",
"tests/test_spec.py::TestCommonMark::test_entity_and_numeric_character_references_017",
"tests/test_spec.py::TestCommonMark::test_code_spans_001",
"tests/test_spec.py::TestCommonMark::test_code_spans_002",
"tests/test_spec.py::TestCommonMark::test_code_spans_003",
"tests/test_spec.py::TestCommonMark::test_code_spans_004",
"tests/test_spec.py::TestCommonMark::test_code_spans_005",
"tests/test_spec.py::TestCommonMark::test_code_spans_006",
"tests/test_spec.py::TestCommonMark::test_code_spans_007",
"tests/test_spec.py::TestCommonMark::test_code_spans_008",
"tests/test_spec.py::TestCommonMark::test_code_spans_009",
"tests/test_spec.py::TestCommonMark::test_code_spans_010",
"tests/test_spec.py::TestCommonMark::test_code_spans_011",
"tests/test_spec.py::TestCommonMark::test_code_spans_012",
"tests/test_spec.py::TestCommonMark::test_code_spans_013",
"tests/test_spec.py::TestCommonMark::test_code_spans_014",
"tests/test_spec.py::TestCommonMark::test_code_spans_015",
"tests/test_spec.py::TestCommonMark::test_code_spans_016",
"tests/test_spec.py::TestCommonMark::test_code_spans_017",
"tests/test_spec.py::TestCommonMark::test_code_spans_018",
"tests/test_spec.py::TestCommonMark::test_code_spans_019",
"tests/test_spec.py::TestCommonMark::test_code_spans_020",
"tests/test_spec.py::TestCommonMark::test_code_spans_021",
"tests/test_spec.py::TestCommonMark::test_code_spans_022",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_001",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_002",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_003",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_004",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_005",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_006",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_007",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_008",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_009",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_010",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_011",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_012",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_013",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_014",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_015",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_016",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_017",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_018",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_019",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_020",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_021",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_022",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_023",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_024",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_025",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_026",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_027",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_028",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_029",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_030",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_031",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_032",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_033",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_034",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_035",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_036",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_037",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_038",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_039",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_040",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_041",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_042",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_043",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_044",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_045",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_046",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_047",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_048",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_049",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_050",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_051",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_052",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_053",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_054",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_055",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_056",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_057",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_058",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_059",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_060",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_061",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_062",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_063",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_064",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_065",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_066",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_067",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_068",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_069",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_070",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_071",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_072",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_073",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_074",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_075",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_076",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_077",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_078",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_079",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_080",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_081",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_082",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_083",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_084",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_085",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_086",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_087",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_088",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_089",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_090",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_091",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_092",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_093",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_094",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_095",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_096",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_097",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_098",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_099",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_100",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_101",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_102",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_103",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_104",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_105",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_106",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_107",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_108",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_109",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_110",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_111",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_112",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_113",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_114",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_115",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_116",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_117",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_118",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_119",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_120",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_121",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_122",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_123",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_124",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_125",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_126",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_127",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_128",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_129",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_130",
"tests/test_spec.py::TestCommonMark::test_emphasis_and_strong_emphasis_131",
"tests/test_spec.py::TestCommonMark::test_links_001",
"tests/test_spec.py::TestCommonMark::test_links_002",
"tests/test_spec.py::TestCommonMark::test_links_003",
"tests/test_spec.py::TestCommonMark::test_links_004",
"tests/test_spec.py::TestCommonMark::test_links_005",
"tests/test_spec.py::TestCommonMark::test_links_006",
"tests/test_spec.py::TestCommonMark::test_links_007",
"tests/test_spec.py::TestCommonMark::test_links_008",
"tests/test_spec.py::TestCommonMark::test_links_009",
"tests/test_spec.py::TestCommonMark::test_links_010",
"tests/test_spec.py::TestCommonMark::test_links_011",
"tests/test_spec.py::TestCommonMark::test_links_012",
"tests/test_spec.py::TestCommonMark::test_links_013",
"tests/test_spec.py::TestCommonMark::test_links_014",
"tests/test_spec.py::TestCommonMark::test_links_015",
"tests/test_spec.py::TestCommonMark::test_links_016",
"tests/test_spec.py::TestCommonMark::test_links_017",
"tests/test_spec.py::TestCommonMark::test_links_018",
"tests/test_spec.py::TestCommonMark::test_links_019",
"tests/test_spec.py::TestCommonMark::test_links_020",
"tests/test_spec.py::TestCommonMark::test_links_021",
"tests/test_spec.py::TestCommonMark::test_links_022",
"tests/test_spec.py::TestCommonMark::test_links_023",
"tests/test_spec.py::TestCommonMark::test_links_024",
"tests/test_spec.py::TestCommonMark::test_links_025",
"tests/test_spec.py::TestCommonMark::test_links_026",
"tests/test_spec.py::TestCommonMark::test_links_027",
"tests/test_spec.py::TestCommonMark::test_links_028",
"tests/test_spec.py::TestCommonMark::test_links_029",
"tests/test_spec.py::TestCommonMark::test_links_030",
"tests/test_spec.py::TestCommonMark::test_links_031",
"tests/test_spec.py::TestCommonMark::test_links_032",
"tests/test_spec.py::TestCommonMark::test_links_033",
"tests/test_spec.py::TestCommonMark::test_links_034",
"tests/test_spec.py::TestCommonMark::test_links_035",
"tests/test_spec.py::TestCommonMark::test_links_036",
"tests/test_spec.py::TestCommonMark::test_links_037",
"tests/test_spec.py::TestCommonMark::test_links_038",
"tests/test_spec.py::TestCommonMark::test_links_039",
"tests/test_spec.py::TestCommonMark::test_links_040",
"tests/test_spec.py::TestCommonMark::test_links_041",
"tests/test_spec.py::TestCommonMark::test_links_042",
"tests/test_spec.py::TestCommonMark::test_links_043",
"tests/test_spec.py::TestCommonMark::test_links_044",
"tests/test_spec.py::TestCommonMark::test_links_045",
"tests/test_spec.py::TestCommonMark::test_links_046",
"tests/test_spec.py::TestCommonMark::test_links_047",
"tests/test_spec.py::TestCommonMark::test_links_048",
"tests/test_spec.py::TestCommonMark::test_links_049",
"tests/test_spec.py::TestCommonMark::test_links_050",
"tests/test_spec.py::TestCommonMark::test_links_051",
"tests/test_spec.py::TestCommonMark::test_links_052",
"tests/test_spec.py::TestCommonMark::test_links_053",
"tests/test_spec.py::TestCommonMark::test_links_054",
"tests/test_spec.py::TestCommonMark::test_links_055",
"tests/test_spec.py::TestCommonMark::test_links_056",
"tests/test_spec.py::TestCommonMark::test_links_057",
"tests/test_spec.py::TestCommonMark::test_links_058",
"tests/test_spec.py::TestCommonMark::test_links_059",
"tests/test_spec.py::TestCommonMark::test_links_060",
"tests/test_spec.py::TestCommonMark::test_links_061",
"tests/test_spec.py::TestCommonMark::test_links_062",
"tests/test_spec.py::TestCommonMark::test_links_063",
"tests/test_spec.py::TestCommonMark::test_links_064",
"tests/test_spec.py::TestCommonMark::test_links_065",
"tests/test_spec.py::TestCommonMark::test_links_066",
"tests/test_spec.py::TestCommonMark::test_links_067",
"tests/test_spec.py::TestCommonMark::test_links_068",
"tests/test_spec.py::TestCommonMark::test_links_069",
"tests/test_spec.py::TestCommonMark::test_links_070",
"tests/test_spec.py::TestCommonMark::test_links_071",
"tests/test_spec.py::TestCommonMark::test_links_072",
"tests/test_spec.py::TestCommonMark::test_links_073",
"tests/test_spec.py::TestCommonMark::test_links_074",
"tests/test_spec.py::TestCommonMark::test_links_075",
"tests/test_spec.py::TestCommonMark::test_links_076",
"tests/test_spec.py::TestCommonMark::test_links_077",
"tests/test_spec.py::TestCommonMark::test_links_078",
"tests/test_spec.py::TestCommonMark::test_links_079",
"tests/test_spec.py::TestCommonMark::test_links_080",
"tests/test_spec.py::TestCommonMark::test_links_081",
"tests/test_spec.py::TestCommonMark::test_links_082",
"tests/test_spec.py::TestCommonMark::test_links_083",
"tests/test_spec.py::TestCommonMark::test_links_084",
"tests/test_spec.py::TestCommonMark::test_links_085",
"tests/test_spec.py::TestCommonMark::test_links_086",
"tests/test_spec.py::TestCommonMark::test_links_087",
"tests/test_spec.py::TestCommonMark::test_images_001",
"tests/test_spec.py::TestCommonMark::test_images_002",
"tests/test_spec.py::TestCommonMark::test_images_003",
"tests/test_spec.py::TestCommonMark::test_images_004",
"tests/test_spec.py::TestCommonMark::test_images_005",
"tests/test_spec.py::TestCommonMark::test_images_006",
"tests/test_spec.py::TestCommonMark::test_images_007",
"tests/test_spec.py::TestCommonMark::test_images_008",
"tests/test_spec.py::TestCommonMark::test_images_009",
"tests/test_spec.py::TestCommonMark::test_images_010",
"tests/test_spec.py::TestCommonMark::test_images_011",
"tests/test_spec.py::TestCommonMark::test_images_012",
"tests/test_spec.py::TestCommonMark::test_images_013",
"tests/test_spec.py::TestCommonMark::test_images_014",
"tests/test_spec.py::TestCommonMark::test_images_015",
"tests/test_spec.py::TestCommonMark::test_images_016",
"tests/test_spec.py::TestCommonMark::test_images_017",
"tests/test_spec.py::TestCommonMark::test_images_018",
"tests/test_spec.py::TestCommonMark::test_images_019",
"tests/test_spec.py::TestCommonMark::test_images_020",
"tests/test_spec.py::TestCommonMark::test_images_021",
"tests/test_spec.py::TestCommonMark::test_images_022",
"tests/test_spec.py::TestCommonMark::test_autolinks_001",
"tests/test_spec.py::TestCommonMark::test_autolinks_002",
"tests/test_spec.py::TestCommonMark::test_autolinks_003",
"tests/test_spec.py::TestCommonMark::test_autolinks_004",
"tests/test_spec.py::TestCommonMark::test_autolinks_005",
"tests/test_spec.py::TestCommonMark::test_autolinks_006",
"tests/test_spec.py::TestCommonMark::test_autolinks_007",
"tests/test_spec.py::TestCommonMark::test_autolinks_008",
"tests/test_spec.py::TestCommonMark::test_autolinks_009",
"tests/test_spec.py::TestCommonMark::test_autolinks_010",
"tests/test_spec.py::TestCommonMark::test_autolinks_011",
"tests/test_spec.py::TestCommonMark::test_autolinks_012",
"tests/test_spec.py::TestCommonMark::test_autolinks_013",
"tests/test_spec.py::TestCommonMark::test_autolinks_014",
"tests/test_spec.py::TestCommonMark::test_autolinks_015",
"tests/test_spec.py::TestCommonMark::test_autolinks_016",
"tests/test_spec.py::TestCommonMark::test_autolinks_017",
"tests/test_spec.py::TestCommonMark::test_autolinks_018",
"tests/test_spec.py::TestCommonMark::test_autolinks_019",
"tests/test_spec.py::TestCommonMark::test_raw_html_001",
"tests/test_spec.py::TestCommonMark::test_raw_html_002",
"tests/test_spec.py::TestCommonMark::test_raw_html_003",
"tests/test_spec.py::TestCommonMark::test_raw_html_004",
"tests/test_spec.py::TestCommonMark::test_raw_html_005",
"tests/test_spec.py::TestCommonMark::test_raw_html_006",
"tests/test_spec.py::TestCommonMark::test_raw_html_007",
"tests/test_spec.py::TestCommonMark::test_raw_html_008",
"tests/test_spec.py::TestCommonMark::test_raw_html_009",
"tests/test_spec.py::TestCommonMark::test_raw_html_010",
"tests/test_spec.py::TestCommonMark::test_raw_html_011",
"tests/test_spec.py::TestCommonMark::test_raw_html_012",
"tests/test_spec.py::TestCommonMark::test_raw_html_013",
"tests/test_spec.py::TestCommonMark::test_raw_html_014",
"tests/test_spec.py::TestCommonMark::test_raw_html_015",
"tests/test_spec.py::TestCommonMark::test_raw_html_016",
"tests/test_spec.py::TestCommonMark::test_raw_html_017",
"tests/test_spec.py::TestCommonMark::test_raw_html_018",
"tests/test_spec.py::TestCommonMark::test_raw_html_019",
"tests/test_spec.py::TestCommonMark::test_raw_html_020",
"tests/test_spec.py::TestCommonMark::test_raw_html_021",
"tests/test_spec.py::TestCommonMark::test_hard_line_breaks_001",
"tests/test_spec.py::TestCommonMark::test_hard_line_breaks_002",
"tests/test_spec.py::TestCommonMark::test_hard_line_breaks_003",
"tests/test_spec.py::TestCommonMark::test_hard_line_breaks_004",
"tests/test_spec.py::TestCommonMark::test_hard_line_breaks_005",
"tests/test_spec.py::TestCommonMark::test_hard_line_breaks_006",
"tests/test_spec.py::TestCommonMark::test_hard_line_breaks_007",
"tests/test_spec.py::TestCommonMark::test_hard_line_breaks_008",
"tests/test_spec.py::TestCommonMark::test_hard_line_breaks_009",
"tests/test_spec.py::TestCommonMark::test_hard_line_breaks_010",
"tests/test_spec.py::TestCommonMark::test_hard_line_breaks_011",
"tests/test_spec.py::TestCommonMark::test_hard_line_breaks_012",
"tests/test_spec.py::TestCommonMark::test_hard_line_breaks_013",
"tests/test_spec.py::TestCommonMark::test_hard_line_breaks_014",
"tests/test_spec.py::TestCommonMark::test_hard_line_breaks_015",
"tests/test_spec.py::TestCommonMark::test_soft_line_breaks_001",
"tests/test_spec.py::TestCommonMark::test_soft_line_breaks_002",
"tests/test_spec.py::TestCommonMark::test_textual_content_001",
"tests/test_spec.py::TestCommonMark::test_textual_content_002",
"tests/test_spec.py::TestCommonMark::test_textual_content_003",
"tests/test_spec.py::TestGFM::test_tabs_001",
"tests/test_spec.py::TestGFM::test_tabs_002",
"tests/test_spec.py::TestGFM::test_tabs_003",
"tests/test_spec.py::TestGFM::test_tabs_004",
"tests/test_spec.py::TestGFM::test_tabs_005",
"tests/test_spec.py::TestGFM::test_tabs_006",
"tests/test_spec.py::TestGFM::test_tabs_007",
"tests/test_spec.py::TestGFM::test_tabs_008",
"tests/test_spec.py::TestGFM::test_tabs_009",
"tests/test_spec.py::TestGFM::test_tabs_010",
"tests/test_spec.py::TestGFM::test_tabs_011",
"tests/test_spec.py::TestGFM::test_precedence_001",
"tests/test_spec.py::TestGFM::test_thematic_breaks_001",
"tests/test_spec.py::TestGFM::test_thematic_breaks_002",
"tests/test_spec.py::TestGFM::test_thematic_breaks_003",
"tests/test_spec.py::TestGFM::test_thematic_breaks_004",
"tests/test_spec.py::TestGFM::test_thematic_breaks_005",
"tests/test_spec.py::TestGFM::test_thematic_breaks_006",
"tests/test_spec.py::TestGFM::test_thematic_breaks_007",
"tests/test_spec.py::TestGFM::test_thematic_breaks_008",
"tests/test_spec.py::TestGFM::test_thematic_breaks_009",
"tests/test_spec.py::TestGFM::test_thematic_breaks_010",
"tests/test_spec.py::TestGFM::test_thematic_breaks_011",
"tests/test_spec.py::TestGFM::test_thematic_breaks_012",
"tests/test_spec.py::TestGFM::test_thematic_breaks_013",
"tests/test_spec.py::TestGFM::test_thematic_breaks_014",
"tests/test_spec.py::TestGFM::test_thematic_breaks_015",
"tests/test_spec.py::TestGFM::test_thematic_breaks_016",
"tests/test_spec.py::TestGFM::test_thematic_breaks_017",
"tests/test_spec.py::TestGFM::test_thematic_breaks_018",
"tests/test_spec.py::TestGFM::test_thematic_breaks_019",
"tests/test_spec.py::TestGFM::test_atx_headings_001",
"tests/test_spec.py::TestGFM::test_atx_headings_002",
"tests/test_spec.py::TestGFM::test_atx_headings_003",
"tests/test_spec.py::TestGFM::test_atx_headings_004",
"tests/test_spec.py::TestGFM::test_atx_headings_005",
"tests/test_spec.py::TestGFM::test_atx_headings_006",
"tests/test_spec.py::TestGFM::test_atx_headings_007",
"tests/test_spec.py::TestGFM::test_atx_headings_008",
"tests/test_spec.py::TestGFM::test_atx_headings_009",
"tests/test_spec.py::TestGFM::test_atx_headings_010",
"tests/test_spec.py::TestGFM::test_atx_headings_011",
"tests/test_spec.py::TestGFM::test_atx_headings_012",
"tests/test_spec.py::TestGFM::test_atx_headings_013",
"tests/test_spec.py::TestGFM::test_atx_headings_014",
"tests/test_spec.py::TestGFM::test_atx_headings_015",
"tests/test_spec.py::TestGFM::test_atx_headings_016",
"tests/test_spec.py::TestGFM::test_atx_headings_017",
"tests/test_spec.py::TestGFM::test_atx_headings_018",
"tests/test_spec.py::TestGFM::test_setext_headings_001",
"tests/test_spec.py::TestGFM::test_setext_headings_002",
"tests/test_spec.py::TestGFM::test_setext_headings_003",
"tests/test_spec.py::TestGFM::test_setext_headings_004",
"tests/test_spec.py::TestGFM::test_setext_headings_005",
"tests/test_spec.py::TestGFM::test_setext_headings_006",
"tests/test_spec.py::TestGFM::test_setext_headings_007",
"tests/test_spec.py::TestGFM::test_setext_headings_008",
"tests/test_spec.py::TestGFM::test_setext_headings_009",
"tests/test_spec.py::TestGFM::test_setext_headings_010",
"tests/test_spec.py::TestGFM::test_setext_headings_011",
"tests/test_spec.py::TestGFM::test_setext_headings_012",
"tests/test_spec.py::TestGFM::test_setext_headings_013",
"tests/test_spec.py::TestGFM::test_setext_headings_014",
"tests/test_spec.py::TestGFM::test_setext_headings_015",
"tests/test_spec.py::TestGFM::test_setext_headings_016",
"tests/test_spec.py::TestGFM::test_setext_headings_017",
"tests/test_spec.py::TestGFM::test_setext_headings_018",
"tests/test_spec.py::TestGFM::test_setext_headings_019",
"tests/test_spec.py::TestGFM::test_setext_headings_020",
"tests/test_spec.py::TestGFM::test_setext_headings_021",
"tests/test_spec.py::TestGFM::test_setext_headings_022",
"tests/test_spec.py::TestGFM::test_setext_headings_023",
"tests/test_spec.py::TestGFM::test_setext_headings_024",
"tests/test_spec.py::TestGFM::test_setext_headings_025",
"tests/test_spec.py::TestGFM::test_setext_headings_026",
"tests/test_spec.py::TestGFM::test_setext_headings_027",
"tests/test_spec.py::TestGFM::test_indented_code_blocks_001",
"tests/test_spec.py::TestGFM::test_indented_code_blocks_002",
"tests/test_spec.py::TestGFM::test_indented_code_blocks_003",
"tests/test_spec.py::TestGFM::test_indented_code_blocks_004",
"tests/test_spec.py::TestGFM::test_indented_code_blocks_005",
"tests/test_spec.py::TestGFM::test_indented_code_blocks_006",
"tests/test_spec.py::TestGFM::test_indented_code_blocks_007",
"tests/test_spec.py::TestGFM::test_indented_code_blocks_008",
"tests/test_spec.py::TestGFM::test_indented_code_blocks_009",
"tests/test_spec.py::TestGFM::test_indented_code_blocks_010",
"tests/test_spec.py::TestGFM::test_indented_code_blocks_011",
"tests/test_spec.py::TestGFM::test_indented_code_blocks_012",
"tests/test_spec.py::TestGFM::test_fenced_code_blocks_001",
"tests/test_spec.py::TestGFM::test_fenced_code_blocks_002",
"tests/test_spec.py::TestGFM::test_fenced_code_blocks_003",
"tests/test_spec.py::TestGFM::test_fenced_code_blocks_004",
"tests/test_spec.py::TestGFM::test_fenced_code_blocks_005",
"tests/test_spec.py::TestGFM::test_fenced_code_blocks_006",
"tests/test_spec.py::TestGFM::test_fenced_code_blocks_007",
"tests/test_spec.py::TestGFM::test_fenced_code_blocks_008",
"tests/test_spec.py::TestGFM::test_fenced_code_blocks_009",
"tests/test_spec.py::TestGFM::test_fenced_code_blocks_010",
"tests/test_spec.py::TestGFM::test_fenced_code_blocks_011",
"tests/test_spec.py::TestGFM::test_fenced_code_blocks_012",
"tests/test_spec.py::TestGFM::test_fenced_code_blocks_013",
"tests/test_spec.py::TestGFM::test_fenced_code_blocks_014",
"tests/test_spec.py::TestGFM::test_fenced_code_blocks_015",
"tests/test_spec.py::TestGFM::test_fenced_code_blocks_016",
"tests/test_spec.py::TestGFM::test_fenced_code_blocks_017",
"tests/test_spec.py::TestGFM::test_fenced_code_blocks_018",
"tests/test_spec.py::TestGFM::test_fenced_code_blocks_019",
"tests/test_spec.py::TestGFM::test_fenced_code_blocks_020",
"tests/test_spec.py::TestGFM::test_fenced_code_blocks_021",
"tests/test_spec.py::TestGFM::test_fenced_code_blocks_022",
"tests/test_spec.py::TestGFM::test_fenced_code_blocks_023",
"tests/test_spec.py::TestGFM::test_fenced_code_blocks_024",
"tests/test_spec.py::TestGFM::test_fenced_code_blocks_025",
"tests/test_spec.py::TestGFM::test_fenced_code_blocks_026",
"tests/test_spec.py::TestGFM::test_fenced_code_blocks_027",
"tests/test_spec.py::TestGFM::test_fenced_code_blocks_028",
"tests/test_spec.py::TestGFM::test_fenced_code_blocks_029",
"tests/test_spec.py::TestGFM::test_html_blocks_001",
"tests/test_spec.py::TestGFM::test_html_blocks_002",
"tests/test_spec.py::TestGFM::test_html_blocks_003",
"tests/test_spec.py::TestGFM::test_html_blocks_004",
"tests/test_spec.py::TestGFM::test_html_blocks_005",
"tests/test_spec.py::TestGFM::test_html_blocks_006",
"tests/test_spec.py::TestGFM::test_html_blocks_007",
"tests/test_spec.py::TestGFM::test_html_blocks_008",
"tests/test_spec.py::TestGFM::test_html_blocks_009",
"tests/test_spec.py::TestGFM::test_html_blocks_010",
"tests/test_spec.py::TestGFM::test_html_blocks_011",
"tests/test_spec.py::TestGFM::test_html_blocks_012",
"tests/test_spec.py::TestGFM::test_html_blocks_013",
"tests/test_spec.py::TestGFM::test_html_blocks_014",
"tests/test_spec.py::TestGFM::test_html_blocks_015",
"tests/test_spec.py::TestGFM::test_html_blocks_016",
"tests/test_spec.py::TestGFM::test_html_blocks_017",
"tests/test_spec.py::TestGFM::test_html_blocks_018",
"tests/test_spec.py::TestGFM::test_html_blocks_019",
"tests/test_spec.py::TestGFM::test_html_blocks_020",
"tests/test_spec.py::TestGFM::test_html_blocks_021",
"tests/test_spec.py::TestGFM::test_html_blocks_022",
"tests/test_spec.py::TestGFM::test_html_blocks_023",
"tests/test_spec.py::TestGFM::test_html_blocks_024",
"tests/test_spec.py::TestGFM::test_html_blocks_025",
"tests/test_spec.py::TestGFM::test_html_blocks_026",
"tests/test_spec.py::TestGFM::test_html_blocks_027",
"tests/test_spec.py::TestGFM::test_html_blocks_028",
"tests/test_spec.py::TestGFM::test_html_blocks_029",
"tests/test_spec.py::TestGFM::test_html_blocks_030",
"tests/test_spec.py::TestGFM::test_html_blocks_031",
"tests/test_spec.py::TestGFM::test_html_blocks_032",
"tests/test_spec.py::TestGFM::test_html_blocks_033",
"tests/test_spec.py::TestGFM::test_html_blocks_034",
"tests/test_spec.py::TestGFM::test_html_blocks_035",
"tests/test_spec.py::TestGFM::test_html_blocks_036",
"tests/test_spec.py::TestGFM::test_html_blocks_037",
"tests/test_spec.py::TestGFM::test_html_blocks_038",
"tests/test_spec.py::TestGFM::test_html_blocks_039",
"tests/test_spec.py::TestGFM::test_html_blocks_040",
"tests/test_spec.py::TestGFM::test_html_blocks_041",
"tests/test_spec.py::TestGFM::test_html_blocks_042",
"tests/test_spec.py::TestGFM::test_html_blocks_043",
"tests/test_spec.py::TestGFM::test_link_reference_definitions_001",
"tests/test_spec.py::TestGFM::test_link_reference_definitions_002",
"tests/test_spec.py::TestGFM::test_link_reference_definitions_003",
"tests/test_spec.py::TestGFM::test_link_reference_definitions_004",
"tests/test_spec.py::TestGFM::test_link_reference_definitions_005",
"tests/test_spec.py::TestGFM::test_link_reference_definitions_006",
"tests/test_spec.py::TestGFM::test_link_reference_definitions_007",
"tests/test_spec.py::TestGFM::test_link_reference_definitions_008",
"tests/test_spec.py::TestGFM::test_link_reference_definitions_009",
"tests/test_spec.py::TestGFM::test_link_reference_definitions_010",
"tests/test_spec.py::TestGFM::test_link_reference_definitions_011",
"tests/test_spec.py::TestGFM::test_link_reference_definitions_012",
"tests/test_spec.py::TestGFM::test_link_reference_definitions_013",
"tests/test_spec.py::TestGFM::test_link_reference_definitions_014",
"tests/test_spec.py::TestGFM::test_link_reference_definitions_015",
"tests/test_spec.py::TestGFM::test_link_reference_definitions_016",
"tests/test_spec.py::TestGFM::test_link_reference_definitions_017",
"tests/test_spec.py::TestGFM::test_link_reference_definitions_018",
"tests/test_spec.py::TestGFM::test_link_reference_definitions_019",
"tests/test_spec.py::TestGFM::test_link_reference_definitions_020",
"tests/test_spec.py::TestGFM::test_link_reference_definitions_021",
"tests/test_spec.py::TestGFM::test_link_reference_definitions_022",
"tests/test_spec.py::TestGFM::test_link_reference_definitions_023",
"tests/test_spec.py::TestGFM::test_link_reference_definitions_024",
"tests/test_spec.py::TestGFM::test_link_reference_definitions_025",
"tests/test_spec.py::TestGFM::test_link_reference_definitions_026",
"tests/test_spec.py::TestGFM::test_paragraphs_001",
"tests/test_spec.py::TestGFM::test_paragraphs_002",
"tests/test_spec.py::TestGFM::test_paragraphs_003",
"tests/test_spec.py::TestGFM::test_paragraphs_004",
"tests/test_spec.py::TestGFM::test_paragraphs_005",
"tests/test_spec.py::TestGFM::test_paragraphs_006",
"tests/test_spec.py::TestGFM::test_paragraphs_007",
"tests/test_spec.py::TestGFM::test_paragraphs_008",
"tests/test_spec.py::TestGFM::test_blank_lines_001",
"tests/test_spec.py::TestGFM::test_block_quotes_001",
"tests/test_spec.py::TestGFM::test_block_quotes_002",
"tests/test_spec.py::TestGFM::test_block_quotes_003",
"tests/test_spec.py::TestGFM::test_block_quotes_004",
"tests/test_spec.py::TestGFM::test_block_quotes_005",
"tests/test_spec.py::TestGFM::test_block_quotes_006",
"tests/test_spec.py::TestGFM::test_block_quotes_007",
"tests/test_spec.py::TestGFM::test_block_quotes_008",
"tests/test_spec.py::TestGFM::test_block_quotes_009",
"tests/test_spec.py::TestGFM::test_block_quotes_010",
"tests/test_spec.py::TestGFM::test_block_quotes_011",
"tests/test_spec.py::TestGFM::test_block_quotes_012",
"tests/test_spec.py::TestGFM::test_block_quotes_013",
"tests/test_spec.py::TestGFM::test_block_quotes_014",
"tests/test_spec.py::TestGFM::test_block_quotes_015",
"tests/test_spec.py::TestGFM::test_block_quotes_016",
"tests/test_spec.py::TestGFM::test_block_quotes_017",
"tests/test_spec.py::TestGFM::test_block_quotes_018",
"tests/test_spec.py::TestGFM::test_block_quotes_019",
"tests/test_spec.py::TestGFM::test_block_quotes_020",
"tests/test_spec.py::TestGFM::test_block_quotes_021",
"tests/test_spec.py::TestGFM::test_block_quotes_022",
"tests/test_spec.py::TestGFM::test_block_quotes_023",
"tests/test_spec.py::TestGFM::test_block_quotes_024",
"tests/test_spec.py::TestGFM::test_block_quotes_025",
"tests/test_spec.py::TestGFM::test_list_items_001",
"tests/test_spec.py::TestGFM::test_list_items_002",
"tests/test_spec.py::TestGFM::test_list_items_003",
"tests/test_spec.py::TestGFM::test_list_items_004",
"tests/test_spec.py::TestGFM::test_list_items_005",
"tests/test_spec.py::TestGFM::test_list_items_006",
"tests/test_spec.py::TestGFM::test_list_items_007",
"tests/test_spec.py::TestGFM::test_list_items_008",
"tests/test_spec.py::TestGFM::test_list_items_009",
"tests/test_spec.py::TestGFM::test_list_items_010",
"tests/test_spec.py::TestGFM::test_list_items_011",
"tests/test_spec.py::TestGFM::test_list_items_012",
"tests/test_spec.py::TestGFM::test_list_items_013",
"tests/test_spec.py::TestGFM::test_list_items_014",
"tests/test_spec.py::TestGFM::test_list_items_015",
"tests/test_spec.py::TestGFM::test_list_items_016",
"tests/test_spec.py::TestGFM::test_list_items_017",
"tests/test_spec.py::TestGFM::test_list_items_018",
"tests/test_spec.py::TestGFM::test_list_items_019",
"tests/test_spec.py::TestGFM::test_list_items_020",
"tests/test_spec.py::TestGFM::test_list_items_021",
"tests/test_spec.py::TestGFM::test_list_items_022",
"tests/test_spec.py::TestGFM::test_list_items_023",
"tests/test_spec.py::TestGFM::test_list_items_024",
"tests/test_spec.py::TestGFM::test_list_items_025",
"tests/test_spec.py::TestGFM::test_list_items_026",
"tests/test_spec.py::TestGFM::test_list_items_027",
"tests/test_spec.py::TestGFM::test_list_items_028",
"tests/test_spec.py::TestGFM::test_list_items_029",
"tests/test_spec.py::TestGFM::test_list_items_030",
"tests/test_spec.py::TestGFM::test_list_items_031",
"tests/test_spec.py::TestGFM::test_list_items_032",
"tests/test_spec.py::TestGFM::test_list_items_033",
"tests/test_spec.py::TestGFM::test_list_items_034",
"tests/test_spec.py::TestGFM::test_list_items_035",
"tests/test_spec.py::TestGFM::test_list_items_036",
"tests/test_spec.py::TestGFM::test_list_items_037",
"tests/test_spec.py::TestGFM::test_list_items_038",
"tests/test_spec.py::TestGFM::test_list_items_039",
"tests/test_spec.py::TestGFM::test_list_items_040",
"tests/test_spec.py::TestGFM::test_list_items_041",
"tests/test_spec.py::TestGFM::test_list_items_042",
"tests/test_spec.py::TestGFM::test_list_items_043",
"tests/test_spec.py::TestGFM::test_list_items_044",
"tests/test_spec.py::TestGFM::test_list_items_045",
"tests/test_spec.py::TestGFM::test_list_items_046",
"tests/test_spec.py::TestGFM::test_list_items_047",
"tests/test_spec.py::TestGFM::test_list_items_048",
"tests/test_spec.py::TestGFM::test_lists_001",
"tests/test_spec.py::TestGFM::test_lists_002",
"tests/test_spec.py::TestGFM::test_lists_003",
"tests/test_spec.py::TestGFM::test_lists_004",
"tests/test_spec.py::TestGFM::test_lists_005",
"tests/test_spec.py::TestGFM::test_lists_006",
"tests/test_spec.py::TestGFM::test_lists_007",
"tests/test_spec.py::TestGFM::test_lists_008",
"tests/test_spec.py::TestGFM::test_lists_009",
"tests/test_spec.py::TestGFM::test_lists_010",
"tests/test_spec.py::TestGFM::test_lists_011",
"tests/test_spec.py::TestGFM::test_lists_012",
"tests/test_spec.py::TestGFM::test_lists_013",
"tests/test_spec.py::TestGFM::test_lists_014",
"tests/test_spec.py::TestGFM::test_lists_015",
"tests/test_spec.py::TestGFM::test_lists_016",
"tests/test_spec.py::TestGFM::test_lists_017",
"tests/test_spec.py::TestGFM::test_lists_018",
"tests/test_spec.py::TestGFM::test_lists_019",
"tests/test_spec.py::TestGFM::test_lists_020",
"tests/test_spec.py::TestGFM::test_lists_021",
"tests/test_spec.py::TestGFM::test_lists_022",
"tests/test_spec.py::TestGFM::test_lists_023",
"tests/test_spec.py::TestGFM::test_lists_024",
"tests/test_spec.py::TestGFM::test_lists_025",
"tests/test_spec.py::TestGFM::test_lists_026",
"tests/test_spec.py::TestGFM::test_inlines_001",
"tests/test_spec.py::TestGFM::test_backslash_escapes_001",
"tests/test_spec.py::TestGFM::test_backslash_escapes_002",
"tests/test_spec.py::TestGFM::test_backslash_escapes_003",
"tests/test_spec.py::TestGFM::test_backslash_escapes_004",
"tests/test_spec.py::TestGFM::test_backslash_escapes_005",
"tests/test_spec.py::TestGFM::test_backslash_escapes_006",
"tests/test_spec.py::TestGFM::test_backslash_escapes_007",
"tests/test_spec.py::TestGFM::test_backslash_escapes_008",
"tests/test_spec.py::TestGFM::test_backslash_escapes_009",
"tests/test_spec.py::TestGFM::test_backslash_escapes_010",
"tests/test_spec.py::TestGFM::test_backslash_escapes_011",
"tests/test_spec.py::TestGFM::test_backslash_escapes_012",
"tests/test_spec.py::TestGFM::test_backslash_escapes_013",
"tests/test_spec.py::TestGFM::test_entity_and_numeric_character_references_001",
"tests/test_spec.py::TestGFM::test_entity_and_numeric_character_references_002",
"tests/test_spec.py::TestGFM::test_entity_and_numeric_character_references_003",
"tests/test_spec.py::TestGFM::test_entity_and_numeric_character_references_004",
"tests/test_spec.py::TestGFM::test_entity_and_numeric_character_references_005",
"tests/test_spec.py::TestGFM::test_entity_and_numeric_character_references_006",
"tests/test_spec.py::TestGFM::test_entity_and_numeric_character_references_007",
"tests/test_spec.py::TestGFM::test_entity_and_numeric_character_references_008",
"tests/test_spec.py::TestGFM::test_entity_and_numeric_character_references_009",
"tests/test_spec.py::TestGFM::test_entity_and_numeric_character_references_010",
"tests/test_spec.py::TestGFM::test_entity_and_numeric_character_references_011",
"tests/test_spec.py::TestGFM::test_entity_and_numeric_character_references_012",
"tests/test_spec.py::TestGFM::test_entity_and_numeric_character_references_013",
"tests/test_spec.py::TestGFM::test_entity_and_numeric_character_references_014",
"tests/test_spec.py::TestGFM::test_entity_and_numeric_character_references_015",
"tests/test_spec.py::TestGFM::test_entity_and_numeric_character_references_016",
"tests/test_spec.py::TestGFM::test_entity_and_numeric_character_references_017",
"tests/test_spec.py::TestGFM::test_code_spans_001",
"tests/test_spec.py::TestGFM::test_code_spans_002",
"tests/test_spec.py::TestGFM::test_code_spans_003",
"tests/test_spec.py::TestGFM::test_code_spans_004",
"tests/test_spec.py::TestGFM::test_code_spans_005",
"tests/test_spec.py::TestGFM::test_code_spans_006",
"tests/test_spec.py::TestGFM::test_code_spans_007",
"tests/test_spec.py::TestGFM::test_code_spans_008",
"tests/test_spec.py::TestGFM::test_code_spans_009",
"tests/test_spec.py::TestGFM::test_code_spans_010",
"tests/test_spec.py::TestGFM::test_code_spans_011",
"tests/test_spec.py::TestGFM::test_code_spans_012",
"tests/test_spec.py::TestGFM::test_code_spans_013",
"tests/test_spec.py::TestGFM::test_code_spans_014",
"tests/test_spec.py::TestGFM::test_code_spans_015",
"tests/test_spec.py::TestGFM::test_code_spans_016",
"tests/test_spec.py::TestGFM::test_code_spans_017",
"tests/test_spec.py::TestGFM::test_code_spans_018",
"tests/test_spec.py::TestGFM::test_code_spans_019",
"tests/test_spec.py::TestGFM::test_code_spans_020",
"tests/test_spec.py::TestGFM::test_code_spans_021",
"tests/test_spec.py::TestGFM::test_code_spans_022",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_001",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_002",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_003",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_004",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_005",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_006",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_007",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_008",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_009",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_010",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_011",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_012",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_013",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_014",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_015",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_016",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_017",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_018",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_019",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_020",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_021",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_022",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_023",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_024",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_025",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_026",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_027",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_028",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_029",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_030",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_031",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_032",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_033",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_034",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_035",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_036",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_037",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_038",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_039",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_040",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_041",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_042",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_043",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_044",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_045",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_046",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_047",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_048",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_049",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_050",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_051",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_052",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_053",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_054",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_055",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_056",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_057",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_058",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_059",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_060",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_061",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_062",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_063",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_064",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_065",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_066",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_067",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_068",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_069",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_070",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_071",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_072",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_073",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_074",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_075",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_076",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_077",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_078",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_079",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_080",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_081",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_082",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_083",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_084",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_085",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_086",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_087",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_088",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_089",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_090",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_091",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_092",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_093",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_094",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_095",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_096",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_097",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_098",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_099",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_100",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_101",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_102",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_103",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_104",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_105",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_106",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_107",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_108",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_109",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_110",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_111",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_112",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_113",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_114",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_115",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_116",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_117",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_118",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_119",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_120",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_121",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_122",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_123",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_124",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_125",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_126",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_127",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_128",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_129",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_130",
"tests/test_spec.py::TestGFM::test_emphasis_and_strong_emphasis_131",
"tests/test_spec.py::TestGFM::test_links_001",
"tests/test_spec.py::TestGFM::test_links_002",
"tests/test_spec.py::TestGFM::test_links_003",
"tests/test_spec.py::TestGFM::test_links_004",
"tests/test_spec.py::TestGFM::test_links_005",
"tests/test_spec.py::TestGFM::test_links_006",
"tests/test_spec.py::TestGFM::test_links_007",
"tests/test_spec.py::TestGFM::test_links_008",
"tests/test_spec.py::TestGFM::test_links_009",
"tests/test_spec.py::TestGFM::test_links_010",
"tests/test_spec.py::TestGFM::test_links_011",
"tests/test_spec.py::TestGFM::test_links_012",
"tests/test_spec.py::TestGFM::test_links_013",
"tests/test_spec.py::TestGFM::test_links_014",
"tests/test_spec.py::TestGFM::test_links_015",
"tests/test_spec.py::TestGFM::test_links_016",
"tests/test_spec.py::TestGFM::test_links_017",
"tests/test_spec.py::TestGFM::test_links_018",
"tests/test_spec.py::TestGFM::test_links_019",
"tests/test_spec.py::TestGFM::test_links_020",
"tests/test_spec.py::TestGFM::test_links_021",
"tests/test_spec.py::TestGFM::test_links_022",
"tests/test_spec.py::TestGFM::test_links_023",
"tests/test_spec.py::TestGFM::test_links_024",
"tests/test_spec.py::TestGFM::test_links_025",
"tests/test_spec.py::TestGFM::test_links_026",
"tests/test_spec.py::TestGFM::test_links_027",
"tests/test_spec.py::TestGFM::test_links_028",
"tests/test_spec.py::TestGFM::test_links_029",
"tests/test_spec.py::TestGFM::test_links_030",
"tests/test_spec.py::TestGFM::test_links_031",
"tests/test_spec.py::TestGFM::test_links_032",
"tests/test_spec.py::TestGFM::test_links_033",
"tests/test_spec.py::TestGFM::test_links_034",
"tests/test_spec.py::TestGFM::test_links_035",
"tests/test_spec.py::TestGFM::test_links_036",
"tests/test_spec.py::TestGFM::test_links_037",
"tests/test_spec.py::TestGFM::test_links_038",
"tests/test_spec.py::TestGFM::test_links_039",
"tests/test_spec.py::TestGFM::test_links_040",
"tests/test_spec.py::TestGFM::test_links_041",
"tests/test_spec.py::TestGFM::test_links_042",
"tests/test_spec.py::TestGFM::test_links_043",
"tests/test_spec.py::TestGFM::test_links_044",
"tests/test_spec.py::TestGFM::test_links_045",
"tests/test_spec.py::TestGFM::test_links_046",
"tests/test_spec.py::TestGFM::test_links_047",
"tests/test_spec.py::TestGFM::test_links_048",
"tests/test_spec.py::TestGFM::test_links_049",
"tests/test_spec.py::TestGFM::test_links_050",
"tests/test_spec.py::TestGFM::test_links_051",
"tests/test_spec.py::TestGFM::test_links_052",
"tests/test_spec.py::TestGFM::test_links_053",
"tests/test_spec.py::TestGFM::test_links_054",
"tests/test_spec.py::TestGFM::test_links_055",
"tests/test_spec.py::TestGFM::test_links_056",
"tests/test_spec.py::TestGFM::test_links_057",
"tests/test_spec.py::TestGFM::test_links_058",
"tests/test_spec.py::TestGFM::test_links_059",
"tests/test_spec.py::TestGFM::test_links_060",
"tests/test_spec.py::TestGFM::test_links_061",
"tests/test_spec.py::TestGFM::test_links_062",
"tests/test_spec.py::TestGFM::test_links_063",
"tests/test_spec.py::TestGFM::test_links_064",
"tests/test_spec.py::TestGFM::test_links_065",
"tests/test_spec.py::TestGFM::test_links_066",
"tests/test_spec.py::TestGFM::test_links_067",
"tests/test_spec.py::TestGFM::test_links_068",
"tests/test_spec.py::TestGFM::test_links_069",
"tests/test_spec.py::TestGFM::test_links_070",
"tests/test_spec.py::TestGFM::test_links_071",
"tests/test_spec.py::TestGFM::test_links_072",
"tests/test_spec.py::TestGFM::test_links_073",
"tests/test_spec.py::TestGFM::test_links_074",
"tests/test_spec.py::TestGFM::test_links_075",
"tests/test_spec.py::TestGFM::test_links_076",
"tests/test_spec.py::TestGFM::test_links_077",
"tests/test_spec.py::TestGFM::test_links_078",
"tests/test_spec.py::TestGFM::test_links_079",
"tests/test_spec.py::TestGFM::test_links_080",
"tests/test_spec.py::TestGFM::test_links_081",
"tests/test_spec.py::TestGFM::test_links_082",
"tests/test_spec.py::TestGFM::test_links_083",
"tests/test_spec.py::TestGFM::test_links_084",
"tests/test_spec.py::TestGFM::test_links_085",
"tests/test_spec.py::TestGFM::test_links_086",
"tests/test_spec.py::TestGFM::test_links_087",
"tests/test_spec.py::TestGFM::test_images_001",
"tests/test_spec.py::TestGFM::test_images_002",
"tests/test_spec.py::TestGFM::test_images_003",
"tests/test_spec.py::TestGFM::test_images_004",
"tests/test_spec.py::TestGFM::test_images_005",
"tests/test_spec.py::TestGFM::test_images_006",
"tests/test_spec.py::TestGFM::test_images_007",
"tests/test_spec.py::TestGFM::test_images_008",
"tests/test_spec.py::TestGFM::test_images_009",
"tests/test_spec.py::TestGFM::test_images_010",
"tests/test_spec.py::TestGFM::test_images_011",
"tests/test_spec.py::TestGFM::test_images_012",
"tests/test_spec.py::TestGFM::test_images_013",
"tests/test_spec.py::TestGFM::test_images_014",
"tests/test_spec.py::TestGFM::test_images_015",
"tests/test_spec.py::TestGFM::test_images_016",
"tests/test_spec.py::TestGFM::test_images_017",
"tests/test_spec.py::TestGFM::test_images_018",
"tests/test_spec.py::TestGFM::test_images_019",
"tests/test_spec.py::TestGFM::test_images_020",
"tests/test_spec.py::TestGFM::test_images_021",
"tests/test_spec.py::TestGFM::test_images_022",
"tests/test_spec.py::TestGFM::test_autolinks_001",
"tests/test_spec.py::TestGFM::test_autolinks_002",
"tests/test_spec.py::TestGFM::test_autolinks_003",
"tests/test_spec.py::TestGFM::test_autolinks_004",
"tests/test_spec.py::TestGFM::test_autolinks_005",
"tests/test_spec.py::TestGFM::test_autolinks_006",
"tests/test_spec.py::TestGFM::test_autolinks_007",
"tests/test_spec.py::TestGFM::test_autolinks_008",
"tests/test_spec.py::TestGFM::test_autolinks_009",
"tests/test_spec.py::TestGFM::test_autolinks_010",
"tests/test_spec.py::TestGFM::test_autolinks_011",
"tests/test_spec.py::TestGFM::test_autolinks_012",
"tests/test_spec.py::TestGFM::test_autolinks_013",
"tests/test_spec.py::TestGFM::test_autolinks_014",
"tests/test_spec.py::TestGFM::test_autolinks_016",
"tests/test_spec.py::TestGFM::test_autolinks_017",
"tests/test_spec.py::TestGFM::test_raw_html_001",
"tests/test_spec.py::TestGFM::test_raw_html_002",
"tests/test_spec.py::TestGFM::test_raw_html_003",
"tests/test_spec.py::TestGFM::test_raw_html_004",
"tests/test_spec.py::TestGFM::test_raw_html_005",
"tests/test_spec.py::TestGFM::test_raw_html_006",
"tests/test_spec.py::TestGFM::test_raw_html_007",
"tests/test_spec.py::TestGFM::test_raw_html_008",
"tests/test_spec.py::TestGFM::test_raw_html_009",
"tests/test_spec.py::TestGFM::test_raw_html_010",
"tests/test_spec.py::TestGFM::test_raw_html_011",
"tests/test_spec.py::TestGFM::test_raw_html_012",
"tests/test_spec.py::TestGFM::test_raw_html_013",
"tests/test_spec.py::TestGFM::test_raw_html_014",
"tests/test_spec.py::TestGFM::test_raw_html_015",
"tests/test_spec.py::TestGFM::test_raw_html_016",
"tests/test_spec.py::TestGFM::test_raw_html_017",
"tests/test_spec.py::TestGFM::test_raw_html_018",
"tests/test_spec.py::TestGFM::test_raw_html_019",
"tests/test_spec.py::TestGFM::test_raw_html_020",
"tests/test_spec.py::TestGFM::test_raw_html_021",
"tests/test_spec.py::TestGFM::test_hard_line_breaks_001",
"tests/test_spec.py::TestGFM::test_hard_line_breaks_002",
"tests/test_spec.py::TestGFM::test_hard_line_breaks_003",
"tests/test_spec.py::TestGFM::test_hard_line_breaks_004",
"tests/test_spec.py::TestGFM::test_hard_line_breaks_005",
"tests/test_spec.py::TestGFM::test_hard_line_breaks_006",
"tests/test_spec.py::TestGFM::test_hard_line_breaks_007",
"tests/test_spec.py::TestGFM::test_hard_line_breaks_008",
"tests/test_spec.py::TestGFM::test_hard_line_breaks_009",
"tests/test_spec.py::TestGFM::test_hard_line_breaks_010",
"tests/test_spec.py::TestGFM::test_hard_line_breaks_011",
"tests/test_spec.py::TestGFM::test_hard_line_breaks_012",
"tests/test_spec.py::TestGFM::test_hard_line_breaks_013",
"tests/test_spec.py::TestGFM::test_hard_line_breaks_014",
"tests/test_spec.py::TestGFM::test_hard_line_breaks_015",
"tests/test_spec.py::TestGFM::test_soft_line_breaks_001",
"tests/test_spec.py::TestGFM::test_soft_line_breaks_002",
"tests/test_spec.py::TestGFM::test_textual_content_001",
"tests/test_spec.py::TestGFM::test_textual_content_002",
"tests/test_spec.py::TestGFM::test_textual_content_003"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-04-04 09:23:33+00:00
|
mit
| 2,415 |
|
fsspec__filesystem_spec-1094
|
diff --git a/docs/environment.yml b/docs/environment.yml
index b5f5a9d..814bd85 100644
--- a/docs/environment.yml
+++ b/docs/environment.yml
@@ -5,3 +5,4 @@ dependencies:
- python=3.9
- docutils<0.17
- numpydoc
+ - yarl
diff --git a/fsspec/generic.py b/fsspec/generic.py
index 360f59a..2796048 100644
--- a/fsspec/generic.py
+++ b/fsspec/generic.py
@@ -170,7 +170,7 @@ class GenericFileSystem(AsyncFileSystem):
if hasattr(fs, "open_async")
else fs.open(url, "rb", **kw)
)
- callback.set_size(maybe_await(f1.size))
+ callback.set_size(await maybe_await(f1.size))
f2 = (
await fs2.open_async(url2, "wb")
if hasattr(fs2, "open_async")
diff --git a/fsspec/implementations/arrow.py b/fsspec/implementations/arrow.py
index 0edf8c5..803d44b 100644
--- a/fsspec/implementations/arrow.py
+++ b/fsspec/implementations/arrow.py
@@ -59,6 +59,7 @@ class ArrowFSWrapper(AbstractFileSystem):
return path
def ls(self, path, detail=False, **kwargs):
+ path = self._strip_protocol(path)
from pyarrow.fs import FileSelector
entries = [
@@ -184,6 +185,11 @@ class ArrowFSWrapper(AbstractFileSystem):
path = self._strip_protocol(path)
self.fs.delete_dir(path)
+ @wrap_exceptions
+ def modified(self, path):
+ path = self._strip_protocol(path)
+ return self.fs.get_file_info(path).mtime
+
@mirror_from(
"stream", ["read", "seek", "tell", "write", "readable", "writable", "close", "size"]
diff --git a/fsspec/implementations/cached.py b/fsspec/implementations/cached.py
index a0799a0..0619d1a 100644
--- a/fsspec/implementations/cached.py
+++ b/fsspec/implementations/cached.py
@@ -232,6 +232,44 @@ class CachingFileSystem(AbstractFileSystem):
rmtree(self.storage[-1])
self.load_cache()
+ def clear_expired_cache(self, expiry_time=None):
+ """Remove all expired files and metadata from the cache
+
+ In the case of multiple cache locations, this clears only the last one,
+ which is assumed to be the read/write one.
+
+ Parameters
+ ----------
+ expiry_time: int
+ The time in seconds after which a local copy is considered useless.
+ If not defined the default is equivalent to the attribute from the
+ file caching instantiation.
+ """
+
+ if not expiry_time:
+ expiry_time = self.expiry
+
+ self._check_cache()
+
+ for path, detail in self.cached_files[-1].copy().items():
+ if time.time() - detail["time"] > expiry_time:
+ if self.same_names:
+ basename = os.path.basename(detail["original"])
+ fn = os.path.join(self.storage[-1], basename)
+ else:
+ fn = os.path.join(self.storage[-1], detail["fn"])
+ if os.path.exists(fn):
+ os.remove(fn)
+ self.cached_files[-1].pop(path)
+
+ if self.cached_files[-1]:
+ cache_path = os.path.join(self.storage[-1], "cache")
+ with open(cache_path, "wb") as fc:
+ pickle.dump(self.cached_files[-1], fc)
+ else:
+ rmtree(self.storage[-1])
+ self.load_cache()
+
def pop_from_cache(self, path):
"""Remove cached version of given file
@@ -389,6 +427,7 @@ class CachingFileSystem(AbstractFileSystem):
"_check_cache",
"_mkcache",
"clear_cache",
+ "clear_expired_cache",
"pop_from_cache",
"_mkcache",
"local_file",
diff --git a/fsspec/implementations/memory.py b/fsspec/implementations/memory.py
index 09df148..cf0b2c5 100644
--- a/fsspec/implementations/memory.py
+++ b/fsspec/implementations/memory.py
@@ -40,7 +40,7 @@ class MemoryFileSystem(AbstractFileSystem):
"name": path,
"size": self.store[path].size,
"type": "file",
- "created": self.store[path].created,
+ "created": self.store[path].created.timestamp(),
}
]
paths = set()
@@ -55,7 +55,7 @@ class MemoryFileSystem(AbstractFileSystem):
"name": p2,
"size": self.store[p2].size,
"type": "file",
- "created": self.store[p2].created,
+ "created": self.store[p2].created.timestamp(),
}
)
elif len(p2) > len(starter):
@@ -221,6 +221,20 @@ class MemoryFileSystem(AbstractFileSystem):
except KeyError as e:
raise FileNotFoundError(path) from e
+ def modified(self, path):
+ path = self._strip_protocol(path)
+ try:
+ return self.store[path].modified
+ except KeyError:
+ raise FileNotFoundError(path)
+
+ def created(self, path):
+ path = self._strip_protocol(path)
+ try:
+ return self.store[path].created
+ except KeyError:
+ raise FileNotFoundError(path)
+
def rm(self, path, recursive=False, maxdepth=None):
if isinstance(path, str):
path = self._strip_protocol(path)
@@ -252,7 +266,8 @@ class MemoryFile(BytesIO):
logger.debug("open file %s", path)
self.fs = fs
self.path = path
- self.created = datetime.utcnow().timestamp()
+ self.created = datetime.utcnow()
+ self.modified = datetime.utcnow()
if data:
super().__init__(data)
self.seek(0)
@@ -272,3 +287,4 @@ class MemoryFile(BytesIO):
def commit(self):
self.fs.store[self.path] = self
+ self.modified = datetime.utcnow()
|
fsspec/filesystem_spec
|
5d052473ffa0ff9064d41e3db37391d07d74e45f
|
diff --git a/fsspec/implementations/tests/conftest.py b/fsspec/implementations/tests/conftest.py
index 70d79ef..7dce3ee 100644
--- a/fsspec/implementations/tests/conftest.py
+++ b/fsspec/implementations/tests/conftest.py
@@ -2,21 +2,33 @@ import tempfile
import pytest
+from fsspec.implementations.arrow import ArrowFSWrapper
from fsspec.implementations.local import LocalFileSystem
-
+from fsspec.implementations.memory import MemoryFileSystem
# A dummy filesystem that has a list of protocols
+
+
class MultiProtocolFileSystem(LocalFileSystem):
protocol = ["file", "other"]
-FILESYSTEMS = {"local": LocalFileSystem, "multi": MultiProtocolFileSystem}
+FILESYSTEMS = {
+ "local": LocalFileSystem,
+ "multi": MultiProtocolFileSystem,
+ "memory": MemoryFileSystem,
+}
READ_ONLY_FILESYSTEMS = []
@pytest.fixture(scope="function")
def fs(request):
+ pyarrow_fs = pytest.importorskip("pyarrow.fs")
+ FileSystem = pyarrow_fs.FileSystem
+ if request.param == "arrow":
+ fs = ArrowFSWrapper(FileSystem.from_uri("file:///")[0])
+ return fs
cls = FILESYSTEMS[request.param]
return cls()
diff --git a/fsspec/implementations/tests/test_arrow.py b/fsspec/implementations/tests/test_arrow.py
index 1386df8..99d8a49 100644
--- a/fsspec/implementations/tests/test_arrow.py
+++ b/fsspec/implementations/tests/test_arrow.py
@@ -14,11 +14,11 @@ def fs():
return ArrowFSWrapper(fs)
[email protected](scope="function")
-def remote_dir(fs):
[email protected](scope="function", params=[False, True])
+def remote_dir(fs, request):
directory = secrets.token_hex(16)
fs.makedirs(directory)
- yield directory
+ yield ("hdfs://" if request.param else "") + directory
fs.rm(directory, recursive=True)
@@ -30,18 +30,19 @@ def strip_keys(original_entry):
def test_info(fs, remote_dir):
fs.touch(remote_dir + "/a.txt")
+ remote_dir_strip_protocol = fs._strip_protocol(remote_dir)
details = fs.info(remote_dir + "/a.txt")
assert details["type"] == "file"
- assert details["name"] == remote_dir + "/a.txt"
+ assert details["name"] == remote_dir_strip_protocol + "/a.txt"
assert details["size"] == 0
fs.mkdir(remote_dir + "/dir")
details = fs.info(remote_dir + "/dir")
assert details["type"] == "directory"
- assert details["name"] == remote_dir + "/dir"
+ assert details["name"] == remote_dir_strip_protocol + "/dir"
details = fs.info(remote_dir + "/dir/")
- assert details["name"] == remote_dir + "/dir/"
+ assert details["name"] == remote_dir_strip_protocol + "/dir/"
def test_move(fs, remote_dir):
@@ -114,12 +115,14 @@ def test_rm(fs, remote_dir):
def test_ls(fs, remote_dir):
+ remote_dir_strip_protocol = fs._strip_protocol(remote_dir)
fs.mkdir(remote_dir + "dir/")
files = set()
for no in range(8):
file = remote_dir + f"dir/test_{no}"
+ # we also want to make sure `fs.touch` works with protocol
fs.touch(file)
- files.add(file)
+ files.add(remote_dir_strip_protocol + f"dir/test_{no}")
assert set(fs.ls(remote_dir + "dir/")) == files
diff --git a/fsspec/implementations/tests/test_cached.py b/fsspec/implementations/tests/test_cached.py
index 4ddc051..51c451e 100644
--- a/fsspec/implementations/tests/test_cached.py
+++ b/fsspec/implementations/tests/test_cached.py
@@ -153,6 +153,109 @@ def test_clear():
assert len(os.listdir(cache1)) < 2
+def test_clear_expired(tmp_path):
+ def __ager(cache_fn, fn):
+ """
+ Modify the cache file to virtually add time lag to selected files.
+
+ Parameters
+ ---------
+ cache_fn: str
+ cache path
+ fn: str
+ file name to be modified
+ """
+ import pathlib
+ import time
+
+ if os.path.exists(cache_fn):
+ with open(cache_fn, "rb") as f:
+ cached_files = pickle.load(f)
+ fn_posix = pathlib.Path(fn).as_posix()
+ cached_files[fn_posix]["time"] = cached_files[fn_posix]["time"] - 691200
+ assert os.access(cache_fn, os.W_OK), "Cache is not writable"
+ with open(cache_fn, "wb") as f:
+ pickle.dump(cached_files, f)
+ time.sleep(1)
+
+ origin = tmp_path.joinpath("origin")
+ cache1 = tmp_path.joinpath("cache1")
+ cache2 = tmp_path.joinpath("cache2")
+ cache3 = tmp_path.joinpath("cache3")
+
+ origin.mkdir()
+ cache1.mkdir()
+ cache2.mkdir()
+ cache3.mkdir()
+
+ data = b"test data"
+ f1 = origin.joinpath("afile")
+ f2 = origin.joinpath("bfile")
+ f3 = origin.joinpath("cfile")
+ f4 = origin.joinpath("dfile")
+
+ with open(f1, "wb") as f:
+ f.write(data)
+ with open(f2, "wb") as f:
+ f.write(data)
+ with open(f3, "wb") as f:
+ f.write(data)
+ with open(f4, "wb") as f:
+ f.write(data)
+
+ # populates first cache
+ fs = fsspec.filesystem(
+ "filecache", target_protocol="file", cache_storage=str(cache1), cache_check=1
+ )
+ assert fs.cat(str(f1)) == data
+
+ # populates "last" cache if file not found in first one
+ fs = fsspec.filesystem(
+ "filecache",
+ target_protocol="file",
+ cache_storage=[str(cache1), str(cache2)],
+ cache_check=1,
+ )
+ assert fs.cat(str(f2)) == data
+ assert fs.cat(str(f3)) == data
+ assert len(os.listdir(cache2)) == 3
+
+ # force the expiration
+ cache_fn = os.path.join(fs.storage[-1], "cache")
+ __ager(cache_fn, f2)
+
+ # remove from cache2 the expired files
+ fs.clear_expired_cache()
+ assert len(os.listdir(cache2)) == 2
+
+ # check complete cleanup
+ __ager(cache_fn, f3)
+
+ fs.clear_expired_cache()
+ assert not fs._check_file(f2)
+ assert not fs._check_file(f3)
+ assert len(os.listdir(cache2)) < 2
+
+ # check cache1 to be untouched after cleaning
+ assert len(os.listdir(cache1)) == 2
+
+ # check cleaning with 'same_name' option enabled
+ fs = fsspec.filesystem(
+ "filecache",
+ target_protocol="file",
+ cache_storage=[str(cache1), str(cache2), str(cache3)],
+ same_names=True,
+ cache_check=1,
+ )
+ assert fs.cat(str(f4)) == data
+
+ cache_fn = os.path.join(fs.storage[-1], "cache")
+ __ager(cache_fn, f4)
+
+ fs.clear_expired_cache()
+ assert not fs._check_file(str(f4))
+
+
def test_pop():
import tempfile
diff --git a/fsspec/implementations/tests/test_common.py b/fsspec/implementations/tests/test_common.py
index 4417213..fe88dc3 100644
--- a/fsspec/implementations/tests/test_common.py
+++ b/fsspec/implementations/tests/test_common.py
@@ -18,14 +18,15 @@ def test_created(fs: AbstractFileSystem, temp_file):
fs.rm(temp_file)
[email protected]("fs", ["local"], indirect=["fs"])
[email protected]("fs", ["local", "memory", "arrow"], indirect=["fs"])
def test_modified(fs: AbstractFileSystem, temp_file):
try:
fs.touch(temp_file)
- created = fs.created(path=temp_file)
+ # created = fs.created(path=temp_file)
+ created = datetime.datetime.utcnow() # pyarrow only have modified
time.sleep(0.05)
fs.touch(temp_file)
- modified = fs.modified(path=temp_file)
+ modified = fs.modified(path=temp_file).replace(tzinfo=None)
assert isinstance(modified, datetime.datetime)
assert modified > created
finally:
|
Generic Filesystem does not await call to async function
**Describe the problem**
In generic.py on line 173, the function _cp_file of GenericFileSystem makes the following call:
`callback.set_size(maybe_await(f1.size))`
maybe_await is a wrapper that decides whether or not it's parameter is a Coroutine, and therefore if the parameter should be called with await or not. The maybe_await function itself is an asynchronous function, and thus the call to it on line 173 should be awaited, which it is currently not.
**Propose a solution**
Simply add the await statement in front of the call to maybe_await:
`callback.set_size(await maybe_await(f1.size))`
|
0.0
|
5d052473ffa0ff9064d41e3db37391d07d74e45f
|
[
"fsspec/implementations/tests/test_cached.py::test_clear_expired"
] |
[
"fsspec/implementations/tests/test_cached.py::test_idempotent",
"fsspec/implementations/tests/test_cached.py::test_write",
"fsspec/implementations/tests/test_cached.py::test_clear",
"fsspec/implementations/tests/test_cached.py::test_pop",
"fsspec/implementations/tests/test_cached.py::test_write_pickle_context",
"fsspec/implementations/tests/test_cached.py::test_local_filecache_creates_dir_if_needed[filecache]",
"fsspec/implementations/tests/test_cached.py::test_local_filecache_creates_dir_if_needed[simplecache]",
"fsspec/implementations/tests/test_cached.py::test_local_filecache_creates_dir_if_needed[blockcache]",
"fsspec/implementations/tests/test_cached.py::test_get_mapper[filecache-True]",
"fsspec/implementations/tests/test_cached.py::test_get_mapper[filecache-False]",
"fsspec/implementations/tests/test_cached.py::test_get_mapper[simplecache-True]",
"fsspec/implementations/tests/test_cached.py::test_get_mapper[simplecache-False]",
"fsspec/implementations/tests/test_cached.py::test_get_mapper[blockcache-True]",
"fsspec/implementations/tests/test_cached.py::test_get_mapper[blockcache-False]",
"fsspec/implementations/tests/test_cached.py::test_local_filecache_basic",
"fsspec/implementations/tests/test_cached.py::test_local_filecache_does_not_change_when_original_data_changed",
"fsspec/implementations/tests/test_cached.py::test_local_filecache_gets_from_original_if_cache_deleted",
"fsspec/implementations/tests/test_cached.py::test_local_filecache_with_new_cache_location_makes_a_new_copy",
"fsspec/implementations/tests/test_cached.py::test_filecache_multicache",
"fsspec/implementations/tests/test_cached.py::test_filecache_multicache_with_same_file_different_data_reads_from_first[filecache]",
"fsspec/implementations/tests/test_cached.py::test_filecache_multicache_with_same_file_different_data_reads_from_first[simplecache]",
"fsspec/implementations/tests/test_cached.py::test_filecache_with_checks",
"fsspec/implementations/tests/test_cached.py::test_add_file_to_cache_after_save",
"fsspec/implementations/tests/test_cached.py::test_with_compression[gzip-filecache]",
"fsspec/implementations/tests/test_cached.py::test_with_compression[gzip-simplecache]",
"fsspec/implementations/tests/test_cached.py::test_with_compression[bz2-filecache]",
"fsspec/implementations/tests/test_cached.py::test_with_compression[bz2-simplecache]",
"fsspec/implementations/tests/test_cached.py::test_again[simplecache]",
"fsspec/implementations/tests/test_cached.py::test_again[filecache]",
"fsspec/implementations/tests/test_cached.py::test_multi_cache[simplecache]",
"fsspec/implementations/tests/test_cached.py::test_multi_cache[filecache]",
"fsspec/implementations/tests/test_cached.py::test_multi_cache_chain[simplecache]",
"fsspec/implementations/tests/test_cached.py::test_multi_cache_chain[filecache]",
"fsspec/implementations/tests/test_cached.py::test_strip[blockcache]",
"fsspec/implementations/tests/test_cached.py::test_strip[simplecache]",
"fsspec/implementations/tests/test_cached.py::test_strip[filecache]",
"fsspec/implementations/tests/test_cached.py::test_cached_write[simplecache]",
"fsspec/implementations/tests/test_cached.py::test_cached_write[filecache]",
"fsspec/implementations/tests/test_cached.py::test_expiry",
"fsspec/implementations/tests/test_cached.py::test_equality",
"fsspec/implementations/tests/test_cached.py::test_str"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-11-03 15:34:10+00:00
|
bsd-3-clause
| 2,416 |
|
fsspec__filesystem_spec-1202
|
diff --git a/fsspec/implementations/cached.py b/fsspec/implementations/cached.py
index 4a13834..31fb3ff 100644
--- a/fsspec/implementations/cached.py
+++ b/fsspec/implementations/cached.py
@@ -614,20 +614,28 @@ class WholeFileCacheFileSystem(CachingFileSystem):
getpaths = []
storepaths = []
fns = []
- for p in paths:
- detail = self._check_file(p)
- if not detail:
- fn = self._make_local_details(p)
- getpaths.append(p)
- storepaths.append(fn)
- else:
- detail, fn = detail if isinstance(detail, tuple) else (None, detail)
- fns.append(fn)
+ out = {}
+ for p in paths.copy():
+ try:
+ detail = self._check_file(p)
+ if not detail:
+ fn = self._make_local_details(p)
+ getpaths.append(p)
+ storepaths.append(fn)
+ else:
+ detail, fn = detail if isinstance(detail, tuple) else (None, detail)
+ fns.append(fn)
+ except Exception as e:
+ if on_error == "raise":
+ raise
+ if on_error == "return":
+ out[p] = e
+ paths.remove(p)
+
if getpaths:
self.fs.get(getpaths, storepaths)
self.save_cache()
- out = {}
callback.set_size(len(paths))
for p, fn in zip(paths, fns):
with open(fn, "rb") as f:
|
fsspec/filesystem_spec
|
7c192d8211ab515fae4f96103f3af908616fe67c
|
diff --git a/fsspec/implementations/tests/test_cached.py b/fsspec/implementations/tests/test_cached.py
index 2b6d538..53ec289 100644
--- a/fsspec/implementations/tests/test_cached.py
+++ b/fsspec/implementations/tests/test_cached.py
@@ -924,3 +924,28 @@ def test_str():
lfs = LocalFileSystem()
cfs = CachingFileSystem(fs=lfs)
assert "CachingFileSystem" in str(cfs)
+
+
+def test_getitems_errors(tmpdir):
+ tmpdir = str(tmpdir)
+ os.makedirs(os.path.join(tmpdir, "afolder"))
+ open(os.path.join(tmpdir, "afile"), "w").write("test")
+ open(os.path.join(tmpdir, "afolder", "anotherfile"), "w").write("test2")
+ m = fsspec.get_mapper("file://" + tmpdir)
+ assert m.getitems(["afile", "bfile"], on_error="omit") == {"afile": b"test"}
+
+ # my code
+ m2 = fsspec.get_mapper("simplecache::file://" + tmpdir)
+ assert m2.getitems(["afile"], on_error="omit") == {"afile": b"test"} # works
+ assert m2.getitems(["afile", "bfile"], on_error="omit") == {
+ "afile": b"test"
+ } # throws KeyError
+
+ with pytest.raises(KeyError):
+ m.getitems(["afile", "bfile"])
+ out = m.getitems(["afile", "bfile"], on_error="return")
+ assert isinstance(out["bfile"], KeyError)
+ m = fsspec.get_mapper("file://" + tmpdir, missing_exceptions=())
+ assert m.getitems(["afile", "bfile"], on_error="omit") == {"afile": b"test"}
+ with pytest.raises(FileNotFoundError):
+ m.getitems(["afile", "bfile"])
|
bug: FSMap on_error option does not work with simplecache
Recently, I noticed that when I create a FSMap to a `simplecache` FS, the `on_error="omit"` does not work as intended. Here is an example, which is a modified version of `test_getitems_errors` in `/fsspec/tests/test_mapping.py` that I ran with FSSpec version 2023.1.0:
```py
def test_getitems_errors(tmpdir):
tmpdir = str(tmpdir)
os.makedirs(os.path.join(tmpdir, "afolder"))
open(os.path.join(tmpdir, "afile"), "w").write("test")
open(os.path.join(tmpdir, "afolder", "anotherfile"), "w").write("test2")
m = fsspec.get_mapper("file://" + tmpdir)
assert m.getitems(["afile", "bfile"], on_error="omit") == {"afile": b"test"}
# my code
m2 = fsspec.get_mapper("simplecache::file://" + tmpdir)
assert m2.getitems(["afile"], on_error="omit") == {"afile": b"test"} # works
assert m2.getitems(["afile", "bfile"], on_error="omit") == {"afile": b"test"} # throws KeyError
with pytest.raises(KeyError):
m.getitems(["afile", "bfile"])
out = m.getitems(["afile", "bfile"], on_error="return")
assert isinstance(out["bfile"], KeyError)
m = fsspec.get_mapper("file://" + tmpdir, missing_exceptions=())
assert m.getitems(["afile", "bfile"], on_error="omit") == {"afile": b"test"}
with pytest.raises(FileNotFoundError):
m.getitems(["afile", "bfile"])
```
In the example, a `KeyError` is still thrown even when `on_error="omit"` is specified. I was able to reproduce this bug both on the local filesystem (as shown in the example) as well as on GCS.
|
0.0
|
7c192d8211ab515fae4f96103f3af908616fe67c
|
[
"fsspec/implementations/tests/test_cached.py::test_getitems_errors"
] |
[
"fsspec/implementations/tests/test_cached.py::test_idempotent",
"fsspec/implementations/tests/test_cached.py::test_write",
"fsspec/implementations/tests/test_cached.py::test_clear",
"fsspec/implementations/tests/test_cached.py::test_clear_expired",
"fsspec/implementations/tests/test_cached.py::test_pop",
"fsspec/implementations/tests/test_cached.py::test_write_pickle_context",
"fsspec/implementations/tests/test_cached.py::test_local_filecache_creates_dir_if_needed[filecache]",
"fsspec/implementations/tests/test_cached.py::test_local_filecache_creates_dir_if_needed[simplecache]",
"fsspec/implementations/tests/test_cached.py::test_local_filecache_creates_dir_if_needed[blockcache]",
"fsspec/implementations/tests/test_cached.py::test_get_mapper[filecache-True]",
"fsspec/implementations/tests/test_cached.py::test_get_mapper[filecache-False]",
"fsspec/implementations/tests/test_cached.py::test_get_mapper[simplecache-True]",
"fsspec/implementations/tests/test_cached.py::test_get_mapper[simplecache-False]",
"fsspec/implementations/tests/test_cached.py::test_get_mapper[blockcache-True]",
"fsspec/implementations/tests/test_cached.py::test_get_mapper[blockcache-False]",
"fsspec/implementations/tests/test_cached.py::test_local_filecache_basic",
"fsspec/implementations/tests/test_cached.py::test_local_filecache_does_not_change_when_original_data_changed",
"fsspec/implementations/tests/test_cached.py::test_local_filecache_gets_from_original_if_cache_deleted",
"fsspec/implementations/tests/test_cached.py::test_local_filecache_with_new_cache_location_makes_a_new_copy",
"fsspec/implementations/tests/test_cached.py::test_filecache_multicache",
"fsspec/implementations/tests/test_cached.py::test_filecache_multicache_with_same_file_different_data_reads_from_first[filecache]",
"fsspec/implementations/tests/test_cached.py::test_filecache_multicache_with_same_file_different_data_reads_from_first[simplecache]",
"fsspec/implementations/tests/test_cached.py::test_filecache_with_checks",
"fsspec/implementations/tests/test_cached.py::test_add_file_to_cache_after_save",
"fsspec/implementations/tests/test_cached.py::test_with_compression[gzip-filecache]",
"fsspec/implementations/tests/test_cached.py::test_with_compression[gzip-simplecache]",
"fsspec/implementations/tests/test_cached.py::test_with_compression[bz2-filecache]",
"fsspec/implementations/tests/test_cached.py::test_with_compression[bz2-simplecache]",
"fsspec/implementations/tests/test_cached.py::test_again[simplecache]",
"fsspec/implementations/tests/test_cached.py::test_again[filecache]",
"fsspec/implementations/tests/test_cached.py::test_multi_cache[simplecache]",
"fsspec/implementations/tests/test_cached.py::test_multi_cache[filecache]",
"fsspec/implementations/tests/test_cached.py::test_multi_cache_chain[simplecache]",
"fsspec/implementations/tests/test_cached.py::test_multi_cache_chain[filecache]",
"fsspec/implementations/tests/test_cached.py::test_strip[blockcache]",
"fsspec/implementations/tests/test_cached.py::test_strip[simplecache]",
"fsspec/implementations/tests/test_cached.py::test_strip[filecache]",
"fsspec/implementations/tests/test_cached.py::test_cached_write[simplecache]",
"fsspec/implementations/tests/test_cached.py::test_cached_write[filecache]",
"fsspec/implementations/tests/test_cached.py::test_expiry",
"fsspec/implementations/tests/test_cached.py::test_equality",
"fsspec/implementations/tests/test_cached.py::test_str"
] |
{
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
}
|
2023-03-04 01:37:15+00:00
|
bsd-3-clause
| 2,417 |
|
fsspec__filesystem_spec-1452
|
diff --git a/fsspec/core.py b/fsspec/core.py
index a1e15b2..8bc8e8e 100644
--- a/fsspec/core.py
+++ b/fsspec/core.py
@@ -521,7 +521,7 @@ def split_protocol(urlpath):
if len(protocol) > 1:
# excludes Windows paths
return protocol, path
- if ":" in urlpath and urlpath.find(":") > 1:
+ if urlpath.startswith("data:"):
return urlpath.split(":", 1)
return None, urlpath
diff --git a/fsspec/generic.py b/fsspec/generic.py
index 290bb43..20534cf 100644
--- a/fsspec/generic.py
+++ b/fsspec/generic.py
@@ -250,9 +250,12 @@ class GenericFileSystem(AsyncFileSystem):
return fs.pipe_file(path, value, **kwargs)
async def _rm(self, url, **kwargs):
- fs = _resolve_fs(url, self.method)
+ urls = url
+ if isinstance(urls, str):
+ urls = [urls]
+ fs = _resolve_fs(urls[0], self.method)
if fs.async_impl:
- await fs._rm(url, **kwargs)
+ await fs._rm(urls, **kwargs)
else:
fs.rm(url, **kwargs)
|
fsspec/filesystem_spec
|
30e479b2f25020a70293d0ff4dc555388bc7bc33
|
diff --git a/fsspec/implementations/tests/test_local.py b/fsspec/implementations/tests/test_local.py
index 82eba0f..2980eb7 100644
--- a/fsspec/implementations/tests/test_local.py
+++ b/fsspec/implementations/tests/test_local.py
@@ -33,7 +33,6 @@ files = {
),
}
-
csv_files = {
".test.fakedata.1.csv": (b"a,b\n" b"1,2\n"),
".test.fakedata.2.csv": (b"a,b\n" b"3,4\n"),
@@ -56,6 +55,8 @@ def filetexts(d, open=open, mode="t"):
try:
os.chdir(dirname)
for filename, text in d.items():
+ if dirname := os.path.dirname(filename):
+ os.makedirs(dirname, exist_ok=True)
f = open(filename, f"w{mode}")
try:
f.write(text)
@@ -991,3 +992,21 @@ def test_cp_two_files(tmpdir):
make_path_posix(os.path.join(target, "file0")),
make_path_posix(os.path.join(target, "file1")),
]
+
+
[email protected](WIN, reason="Windows does not support colons in filenames")
+def test_issue_1447():
+ files_with_colons = {
+ ".local:file:with:colons.txt": b"content1",
+ ".colons-after-extension.txt:after": b"content2",
+ ".colons-after-extension/file:colon.txt:before/after": b"content3",
+ }
+ with filetexts(files_with_colons, mode="b"):
+ for file, contents in files_with_colons.items():
+ with fsspec.filesystem("file").open(file, "rb") as f:
+ assert f.read() == contents
+
+ fs, urlpath = fsspec.core.url_to_fs(file)
+ assert isinstance(fs, fsspec.implementations.local.LocalFileSystem)
+ with fs.open(urlpath, "rb") as f:
+ assert f.read() == contents
|
Local files with colons in name no longer readable after `2023.12.0` version
Newer `fsspec` versions [2023.12.1](https://github.com/fsspec/filesystem_spec/releases/tag/2023.12.1) and [2023.12.0](https://github.com/fsspec/filesystem_spec/releases/tag/2023.12.0) break the ability to read local files with `:` in the file name.
This is the behaviour in version `2023.10.0`
```python
import fsspec
fsspec.core.url_to_fs("file-with:colons.txt")
(<fsspec.implementations.local.LocalFileSystem object at 0x101b13610>, '/Users/lobis/git/uproot/file-with:colons.txt')
```
On a newer version:
```python
import fsspec
fsspec.core.url_to_fs("file-with:colons.txt")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/lobis/anaconda3/envs/uproot/lib/python3.11/site-packages/fsspec/core.py", line 383, in url_to_fs
chain = _un_chain(url, kwargs)
^^^^^^^^^^^^^^^^^^^^^^
File "/Users/lobis/anaconda3/envs/uproot/lib/python3.11/site-packages/fsspec/core.py", line 332, in _un_chain
cls = get_filesystem_class(protocol)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/lobis/anaconda3/envs/uproot/lib/python3.11/site-packages/fsspec/registry.py", line 233, in get_filesystem_class
raise ValueError(f"Protocol not known: {protocol}")
ValueError: Protocol not known: file-with
```
It appears that previously the protocol delimiter was `://` but now has been updated to `:`.
This is currently breaking the uproot `fsspec` source for local files since we rely on being able to parse file names with `:` https://github.com/scikit-hep/uproot5/issues/1054.
I believe files with a `:` in the filename are still valid filenames (unlike files with `://`) so I assume this change was not intentional. Please let me know otherwise so I will modify how we use `fsspec` to read local files.
Thanks!
|
0.0
|
30e479b2f25020a70293d0ff4dc555388bc7bc33
|
[
"fsspec/implementations/tests/test_local.py::test_issue_1447"
] |
[
"fsspec/implementations/tests/test_local.py::test_urlpath_inference_strips_protocol",
"fsspec/implementations/tests/test_local.py::test_urlpath_expand_read",
"fsspec/implementations/tests/test_local.py::test_cats",
"fsspec/implementations/tests/test_local.py::test_urlpath_expand_write",
"fsspec/implementations/tests/test_local.py::test_open_files",
"fsspec/implementations/tests/test_local.py::test_open_files_text_mode[utf-8]",
"fsspec/implementations/tests/test_local.py::test_open_files_text_mode[ascii]",
"fsspec/implementations/tests/test_local.py::test_compressions[None-rt]",
"fsspec/implementations/tests/test_local.py::test_compressions[None-rb]",
"fsspec/implementations/tests/test_local.py::test_compressions[zip-rt]",
"fsspec/implementations/tests/test_local.py::test_compressions[zip-rb]",
"fsspec/implementations/tests/test_local.py::test_compressions[bz2-rt]",
"fsspec/implementations/tests/test_local.py::test_compressions[bz2-rb]",
"fsspec/implementations/tests/test_local.py::test_compressions[gzip-rt]",
"fsspec/implementations/tests/test_local.py::test_compressions[gzip-rb]",
"fsspec/implementations/tests/test_local.py::test_compressions[lzma-rt]",
"fsspec/implementations/tests/test_local.py::test_compressions[lzma-rb]",
"fsspec/implementations/tests/test_local.py::test_compressions[xz-rt]",
"fsspec/implementations/tests/test_local.py::test_compressions[xz-rb]",
"fsspec/implementations/tests/test_local.py::test_bad_compression",
"fsspec/implementations/tests/test_local.py::test_not_found",
"fsspec/implementations/tests/test_local.py::test_isfile",
"fsspec/implementations/tests/test_local.py::test_isdir",
"fsspec/implementations/tests/test_local.py::test_open_files_write[compression_opener0]",
"fsspec/implementations/tests/test_local.py::test_open_files_write[compression_opener1]",
"fsspec/implementations/tests/test_local.py::test_abs_paths",
"fsspec/implementations/tests/test_local.py::test_glob_weird_characters[+-/]",
"fsspec/implementations/tests/test_local.py::test_glob_weird_characters[+-\\\\]",
"fsspec/implementations/tests/test_local.py::test_glob_weird_characters[++-/]",
"fsspec/implementations/tests/test_local.py::test_glob_weird_characters[++-\\\\]",
"fsspec/implementations/tests/test_local.py::test_glob_weird_characters[(-/]",
"fsspec/implementations/tests/test_local.py::test_glob_weird_characters[(-\\\\]",
"fsspec/implementations/tests/test_local.py::test_glob_weird_characters[)-/]",
"fsspec/implementations/tests/test_local.py::test_glob_weird_characters[)-\\\\]",
"fsspec/implementations/tests/test_local.py::test_glob_weird_characters[|-/]",
"fsspec/implementations/tests/test_local.py::test_glob_weird_characters[|-\\\\]",
"fsspec/implementations/tests/test_local.py::test_glob_weird_characters[\\\\-/]",
"fsspec/implementations/tests/test_local.py::test_glob_weird_characters[\\\\-\\\\]",
"fsspec/implementations/tests/test_local.py::test_globfind_dirs",
"fsspec/implementations/tests/test_local.py::test_touch",
"fsspec/implementations/tests/test_local.py::test_touch_truncate",
"fsspec/implementations/tests/test_local.py::test_directories",
"fsspec/implementations/tests/test_local.py::test_file_ops[]",
"fsspec/implementations/tests/test_local.py::test_file_ops[file://]",
"fsspec/implementations/tests/test_local.py::test_recursive_get_put",
"fsspec/implementations/tests/test_local.py::test_commit_discard",
"fsspec/implementations/tests/test_local.py::test_make_path_posix",
"fsspec/implementations/tests/test_local.py::test_linked_files",
"fsspec/implementations/tests/test_local.py::test_linked_files_exists",
"fsspec/implementations/tests/test_local.py::test_linked_directories",
"fsspec/implementations/tests/test_local.py::test_isfilestore",
"fsspec/implementations/tests/test_local.py::test_pickle",
"fsspec/implementations/tests/test_local.py::test_strip_protocol_expanduser",
"fsspec/implementations/tests/test_local.py::test_strip_protocol_no_authority",
"fsspec/implementations/tests/test_local.py::test_mkdir_twice_faile",
"fsspec/implementations/tests/test_local.py::test_iterable",
"fsspec/implementations/tests/test_local.py::test_mv_empty",
"fsspec/implementations/tests/test_local.py::test_mv_recursive",
"fsspec/implementations/tests/test_local.py::test_copy_errors",
"fsspec/implementations/tests/test_local.py::test_transaction",
"fsspec/implementations/tests/test_local.py::test_delete_cwd",
"fsspec/implementations/tests/test_local.py::test_delete_non_recursive_dir_fails",
"fsspec/implementations/tests/test_local.py::test_infer_compression[open-.bz2]",
"fsspec/implementations/tests/test_local.py::test_infer_compression[open-.gz]",
"fsspec/implementations/tests/test_local.py::test_infer_compression[open-]",
"fsspec/implementations/tests/test_local.py::test_info_path_like",
"fsspec/implementations/tests/test_local.py::test_seekable",
"fsspec/implementations/tests/test_local.py::test_link",
"fsspec/implementations/tests/test_local.py::test_symlink",
"fsspec/implementations/tests/test_local.py::test_put_file_to_dir",
"fsspec/implementations/tests/test_local.py::test_du",
"fsspec/implementations/tests/test_local.py::test_cp_get_put_directory_recursive[cp]",
"fsspec/implementations/tests/test_local.py::test_cp_get_put_directory_recursive[get]",
"fsspec/implementations/tests/test_local.py::test_cp_get_put_directory_recursive[put]",
"fsspec/implementations/tests/test_local.py::test_cp_get_put_empty_directory[cp]",
"fsspec/implementations/tests/test_local.py::test_cp_get_put_empty_directory[get]",
"fsspec/implementations/tests/test_local.py::test_cp_get_put_empty_directory[put]",
"fsspec/implementations/tests/test_local.py::test_cp_two_files"
] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2023-12-07 15:55:03+00:00
|
bsd-3-clause
| 2,418 |
|
fsspec__filesystem_spec-1465
|
diff --git a/fsspec/implementations/dirfs.py b/fsspec/implementations/dirfs.py
index a3eac87..b1b3f6d 100644
--- a/fsspec/implementations/dirfs.py
+++ b/fsspec/implementations/dirfs.py
@@ -124,6 +124,12 @@ class DirFileSystem(AsyncFileSystem):
def pipe(self, path, *args, **kwargs):
return self.fs.pipe(self._join(path), *args, **kwargs)
+ async def _pipe_file(self, path, *args, **kwargs):
+ return await self.fs._pipe_file(self._join(path), *args, **kwargs)
+
+ def pipe_file(self, path, *args, **kwargs):
+ return self.fs.pipe_file(self._join(path), *args, **kwargs)
+
async def _cat_file(self, path, *args, **kwargs):
return await self.fs._cat_file(self._join(path), *args, **kwargs)
|
fsspec/filesystem_spec
|
dd8cb9bf620be4d9153e854dd1431c23a2be6db0
|
diff --git a/fsspec/implementations/tests/test_dirfs.py b/fsspec/implementations/tests/test_dirfs.py
index 98e7fc6..b2a7bbe 100644
--- a/fsspec/implementations/tests/test_dirfs.py
+++ b/fsspec/implementations/tests/test_dirfs.py
@@ -162,6 +162,17 @@ def test_pipe(dirfs):
dirfs.fs.pipe.assert_called_once_with(f"{PATH}/file", *ARGS, **KWARGS)
[email protected]
+async def test_async_pipe_file(adirfs):
+ await adirfs._pipe_file("file", *ARGS, **KWARGS)
+ adirfs.fs._pipe_file.assert_called_once_with(f"{PATH}/file", *ARGS, **KWARGS)
+
+
+def test_pipe_file(dirfs):
+ dirfs.pipe_file("file", *ARGS, **KWARGS)
+ dirfs.fs.pipe_file.assert_called_once_with(f"{PATH}/file", *ARGS, **KWARGS)
+
+
@pytest.mark.asyncio
async def test_async_cat_file(adirfs):
assert (
|
`DirFileSystem.write_bytes` raises `NotImplementedError`
I've got a `DirFileSystem` wrapping a `LocalFileSystem` and am seeing a `NotImplementedError` when trying to use `write_bytes`.
```python-traceback
fs.write_bytes(filepath, blob)
Traceback (most recent call last):
File "C:\python\envs\dev-py310\lib\site-packages\IPython\core\interactiveshell.py", line 3548, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-3-cd365f2247d4>", line 1, in <module>
fs.write_bytes(filepath, blob)
File "C:\python\envs\dev-py310\lib\site-packages\fsspec\spec.py", line 1502, in write_bytes
self.pipe_file(path, value, **kwargs)
File "C:\python\envs\dev-py310\lib\site-packages\fsspec\asyn.py", line 118, in wrapper
return sync(self.loop, func, *args, **kwargs)
File "C:\python\envs\dev-py310\lib\site-packages\fsspec\asyn.py", line 103, in sync
raise return_result
File "C:\python\envs\dev-py310\lib\site-packages\fsspec\asyn.py", line 56, in _runner
result[0] = await coro
File "C:\python\envs\dev-py310\lib\site-packages\fsspec\asyn.py", line 393, in _pipe_file
raise NotImplementedError
NotImplementedError
```
Repro:
```python
In [3]: from fsspec.implementations.local import LocalFileSystem
...: from fsspec.implementations.dirfs import DirFileSystem
In [5]: fs = DirFileSystem(path='C:/temp', fs=LocalFileSystem())
In [6]: fs.write_bytes('/deleteme.bin', b"123")
---------------------------------------------------------------------------
NotImplementedError Traceback (most recent call last)
Cell In[6], line 1
----> 1 fs.write_bytes('/deleteme.bin', b"123")
File C:\python\envs\dev-py310\lib\site-packages\fsspec\spec.py:1502, in AbstractFileSystem.write_bytes(self, path, value, **kwargs)
1500 def write_bytes(self, path, value, **kwargs):
1501 """Alias of `AbstractFileSystem.pipe_file`."""
-> 1502 self.pipe_file(path, value, **kwargs)
File C:\python\envs\dev-py310\lib\site-packages\fsspec\asyn.py:118, in sync_wrapper.<locals>.wrapper(*args, **kwargs)
115 @functools.wraps(func)
116 def wrapper(*args, **kwargs):
117 self = obj or args[0]
--> 118 return sync(self.loop, func, *args, **kwargs)
File C:\python\envs\dev-py310\lib\site-packages\fsspec\asyn.py:103, in sync(loop, func, timeout, *args, **kwargs)
101 raise FSTimeoutError from return_result
102 elif isinstance(return_result, BaseException):
--> 103 raise return_result
104 else:
105 return return_result
File C:\python\envs\dev-py310\lib\site-packages\fsspec\asyn.py:56, in _runner(event, coro, result, timeout)
54 coro = asyncio.wait_for(coro, timeout=timeout)
55 try:
---> 56 result[0] = await coro
57 except Exception as ex:
58 result[0] = ex
File C:\python\envs\dev-py310\lib\site-packages\fsspec\asyn.py:393, in AsyncFileSystem._pipe_file(self, path, value, **kwargs)
392 async def _pipe_file(self, path, value, **kwargs):
--> 393 raise NotImplementedError
NotImplementedError:
```
_Originally posted by @dhirschfeld in https://github.com/fsspec/filesystem_spec/issues/1414#issuecomment-1825166644_
|
0.0
|
dd8cb9bf620be4d9153e854dd1431c23a2be6db0
|
[
"fsspec/implementations/tests/test_dirfs.py::test_async_pipe_file",
"fsspec/implementations/tests/test_dirfs.py::test_pipe_file[sync]",
"fsspec/implementations/tests/test_dirfs.py::test_pipe_file[async]"
] |
[
"fsspec/implementations/tests/test_dirfs.py::test_dirfs[sync]",
"fsspec/implementations/tests/test_dirfs.py::test_dirfs[async]",
"fsspec/implementations/tests/test_dirfs.py::test_path[sync---]",
"fsspec/implementations/tests/test_dirfs.py::test_path[sync--foo-foo]",
"fsspec/implementations/tests/test_dirfs.py::test_path[sync-root--root]",
"fsspec/implementations/tests/test_dirfs.py::test_path[sync-root-foo-root/foo]",
"fsspec/implementations/tests/test_dirfs.py::test_path[async---]",
"fsspec/implementations/tests/test_dirfs.py::test_path[async--foo-foo]",
"fsspec/implementations/tests/test_dirfs.py::test_path[async-root--root]",
"fsspec/implementations/tests/test_dirfs.py::test_path[async-root-foo-root/foo]",
"fsspec/implementations/tests/test_dirfs.py::test_sep[sync]",
"fsspec/implementations/tests/test_dirfs.py::test_sep[async]",
"fsspec/implementations/tests/test_dirfs.py::test_set_session",
"fsspec/implementations/tests/test_dirfs.py::test_async_rm_file",
"fsspec/implementations/tests/test_dirfs.py::test_rm_file[sync]",
"fsspec/implementations/tests/test_dirfs.py::test_rm_file[async]",
"fsspec/implementations/tests/test_dirfs.py::test_async_rm",
"fsspec/implementations/tests/test_dirfs.py::test_rm[sync]",
"fsspec/implementations/tests/test_dirfs.py::test_rm[async]",
"fsspec/implementations/tests/test_dirfs.py::test_async_cp_file",
"fsspec/implementations/tests/test_dirfs.py::test_cp_file[sync]",
"fsspec/implementations/tests/test_dirfs.py::test_cp_file[async]",
"fsspec/implementations/tests/test_dirfs.py::test_async_copy",
"fsspec/implementations/tests/test_dirfs.py::test_copy[sync]",
"fsspec/implementations/tests/test_dirfs.py::test_copy[async]",
"fsspec/implementations/tests/test_dirfs.py::test_async_pipe",
"fsspec/implementations/tests/test_dirfs.py::test_pipe[sync]",
"fsspec/implementations/tests/test_dirfs.py::test_pipe[async]",
"fsspec/implementations/tests/test_dirfs.py::test_async_cat_file",
"fsspec/implementations/tests/test_dirfs.py::test_cat_file[sync]",
"fsspec/implementations/tests/test_dirfs.py::test_cat_file[async]",
"fsspec/implementations/tests/test_dirfs.py::test_async_cat",
"fsspec/implementations/tests/test_dirfs.py::test_cat[sync]",
"fsspec/implementations/tests/test_dirfs.py::test_cat[async]",
"fsspec/implementations/tests/test_dirfs.py::test_async_cat_list",
"fsspec/implementations/tests/test_dirfs.py::test_cat_list[sync]",
"fsspec/implementations/tests/test_dirfs.py::test_cat_list[async]",
"fsspec/implementations/tests/test_dirfs.py::test_async_put_file",
"fsspec/implementations/tests/test_dirfs.py::test_put_file[sync]",
"fsspec/implementations/tests/test_dirfs.py::test_put_file[async]",
"fsspec/implementations/tests/test_dirfs.py::test_async_put",
"fsspec/implementations/tests/test_dirfs.py::test_put[sync]",
"fsspec/implementations/tests/test_dirfs.py::test_put[async]",
"fsspec/implementations/tests/test_dirfs.py::test_async_get_file",
"fsspec/implementations/tests/test_dirfs.py::test_get_file[sync]",
"fsspec/implementations/tests/test_dirfs.py::test_get_file[async]",
"fsspec/implementations/tests/test_dirfs.py::test_async_get",
"fsspec/implementations/tests/test_dirfs.py::test_get[sync]",
"fsspec/implementations/tests/test_dirfs.py::test_get[async]",
"fsspec/implementations/tests/test_dirfs.py::test_async_isfile",
"fsspec/implementations/tests/test_dirfs.py::test_isfile[sync]",
"fsspec/implementations/tests/test_dirfs.py::test_isfile[async]",
"fsspec/implementations/tests/test_dirfs.py::test_async_isdir",
"fsspec/implementations/tests/test_dirfs.py::test_isdir[sync]",
"fsspec/implementations/tests/test_dirfs.py::test_isdir[async]",
"fsspec/implementations/tests/test_dirfs.py::test_async_size",
"fsspec/implementations/tests/test_dirfs.py::test_size[sync]",
"fsspec/implementations/tests/test_dirfs.py::test_size[async]",
"fsspec/implementations/tests/test_dirfs.py::test_async_exists",
"fsspec/implementations/tests/test_dirfs.py::test_exists[sync]",
"fsspec/implementations/tests/test_dirfs.py::test_exists[async]",
"fsspec/implementations/tests/test_dirfs.py::test_async_info",
"fsspec/implementations/tests/test_dirfs.py::test_info[sync]",
"fsspec/implementations/tests/test_dirfs.py::test_info[async]",
"fsspec/implementations/tests/test_dirfs.py::test_async_ls",
"fsspec/implementations/tests/test_dirfs.py::test_ls[sync]",
"fsspec/implementations/tests/test_dirfs.py::test_ls[async]",
"fsspec/implementations/tests/test_dirfs.py::test_async_ls_detail",
"fsspec/implementations/tests/test_dirfs.py::test_ls_detail[sync]",
"fsspec/implementations/tests/test_dirfs.py::test_ls_detail[async]",
"fsspec/implementations/tests/test_dirfs.py::test_async_walk",
"fsspec/implementations/tests/test_dirfs.py::test_walk[sync]",
"fsspec/implementations/tests/test_dirfs.py::test_walk[async]",
"fsspec/implementations/tests/test_dirfs.py::test_async_glob",
"fsspec/implementations/tests/test_dirfs.py::test_glob[sync]",
"fsspec/implementations/tests/test_dirfs.py::test_glob[async]",
"fsspec/implementations/tests/test_dirfs.py::test_glob_with_protocol[sync]",
"fsspec/implementations/tests/test_dirfs.py::test_glob_with_protocol[async]",
"fsspec/implementations/tests/test_dirfs.py::test_async_glob_detail",
"fsspec/implementations/tests/test_dirfs.py::test_glob_detail[sync]",
"fsspec/implementations/tests/test_dirfs.py::test_glob_detail[async]",
"fsspec/implementations/tests/test_dirfs.py::test_async_du",
"fsspec/implementations/tests/test_dirfs.py::test_du[sync]",
"fsspec/implementations/tests/test_dirfs.py::test_du[async]",
"fsspec/implementations/tests/test_dirfs.py::test_async_du_granular",
"fsspec/implementations/tests/test_dirfs.py::test_du_granular[sync]",
"fsspec/implementations/tests/test_dirfs.py::test_du_granular[async]",
"fsspec/implementations/tests/test_dirfs.py::test_async_find",
"fsspec/implementations/tests/test_dirfs.py::test_find[sync]",
"fsspec/implementations/tests/test_dirfs.py::test_find[async]",
"fsspec/implementations/tests/test_dirfs.py::test_async_find_detail",
"fsspec/implementations/tests/test_dirfs.py::test_find_detail[sync]",
"fsspec/implementations/tests/test_dirfs.py::test_find_detail[async]",
"fsspec/implementations/tests/test_dirfs.py::test_async_expand_path",
"fsspec/implementations/tests/test_dirfs.py::test_expand_path[sync]",
"fsspec/implementations/tests/test_dirfs.py::test_expand_path[async]",
"fsspec/implementations/tests/test_dirfs.py::test_async_expand_path_list",
"fsspec/implementations/tests/test_dirfs.py::test_expand_path_list[sync]",
"fsspec/implementations/tests/test_dirfs.py::test_expand_path_list[async]",
"fsspec/implementations/tests/test_dirfs.py::test_async_mkdir",
"fsspec/implementations/tests/test_dirfs.py::test_mkdir[sync]",
"fsspec/implementations/tests/test_dirfs.py::test_mkdir[async]",
"fsspec/implementations/tests/test_dirfs.py::test_async_makedirs",
"fsspec/implementations/tests/test_dirfs.py::test_makedirs[sync]",
"fsspec/implementations/tests/test_dirfs.py::test_makedirs[async]",
"fsspec/implementations/tests/test_dirfs.py::test_rmdir[sync]",
"fsspec/implementations/tests/test_dirfs.py::test_rmdir[async]",
"fsspec/implementations/tests/test_dirfs.py::test_mv_file[sync]",
"fsspec/implementations/tests/test_dirfs.py::test_mv_file[async]",
"fsspec/implementations/tests/test_dirfs.py::test_touch[sync]",
"fsspec/implementations/tests/test_dirfs.py::test_touch[async]",
"fsspec/implementations/tests/test_dirfs.py::test_created[sync]",
"fsspec/implementations/tests/test_dirfs.py::test_created[async]",
"fsspec/implementations/tests/test_dirfs.py::test_modified[sync]",
"fsspec/implementations/tests/test_dirfs.py::test_modified[async]",
"fsspec/implementations/tests/test_dirfs.py::test_sign[sync]",
"fsspec/implementations/tests/test_dirfs.py::test_sign[async]",
"fsspec/implementations/tests/test_dirfs.py::test_open[sync]",
"fsspec/implementations/tests/test_dirfs.py::test_open[async]",
"fsspec/implementations/tests/test_dirfs.py::test_from_url"
] |
{
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
}
|
2023-12-13 12:04:03+00:00
|
bsd-3-clause
| 2,419 |
|
fsspec__filesystem_spec-1479
|
diff --git a/fsspec/implementations/local.py b/fsspec/implementations/local.py
index e7861e2..17f96c1 100644
--- a/fsspec/implementations/local.py
+++ b/fsspec/implementations/local.py
@@ -3,7 +3,6 @@ import io
import logging
import os
import os.path as osp
-import posixpath
import re
import shutil
import stat
@@ -59,11 +58,16 @@ class LocalFileSystem(AbstractFileSystem):
def ls(self, path, detail=False, **kwargs):
path = self._strip_protocol(path)
- if detail:
+ info = self.info(path)
+ if info["type"] == "directory":
with os.scandir(path) as it:
- return [self.info(f) for f in it]
+ infos = [self.info(f) for f in it]
else:
- return [posixpath.join(path, f) for f in os.listdir(path)]
+ infos = [info]
+
+ if not detail:
+ return [i["name"] for i in infos]
+ return infos
def info(self, path, **kwargs):
if isinstance(path, os.DirEntry):
|
fsspec/filesystem_spec
|
069e107fa056166fd4e7db75e909ebac85f372fd
|
diff --git a/fsspec/implementations/tests/test_local.py b/fsspec/implementations/tests/test_local.py
index 2980eb7..ffa5cbb 100644
--- a/fsspec/implementations/tests/test_local.py
+++ b/fsspec/implementations/tests/test_local.py
@@ -367,6 +367,16 @@ def test_directories(tmpdir):
assert fs.ls(fs.root_marker)
+def test_ls_on_file(tmpdir):
+ tmpdir = make_path_posix(str(tmpdir))
+ fs = LocalFileSystem()
+ resource = tmpdir + "/a.json"
+ fs.touch(resource)
+ assert fs.exists(resource)
+ assert fs.ls(tmpdir) == fs.ls(resource)
+ assert fs.ls(resource, detail=True)[0] == fs.info(resource)
+
+
@pytest.mark.parametrize("file_protocol", ["", "file://"])
def test_file_ops(tmpdir, file_protocol):
tmpdir = make_path_posix(str(tmpdir))
|
`LocalFileSystem.ls()` does not work on filenames
Repro:
```
fs = LocalFileSystem()
fs.touch("a.json")
fs.ls("a.json")
```
I expected this to return a single-entry list with the stat object for `a.json`, but instead it raises a `NotADirectoryError` because `os.scandir()` does not allow file-like inputs:
https://github.com/fsspec/filesystem_spec/blob/069e107fa056166fd4e7db75e909ebac85f372fd/fsspec/implementations/local.py#L63-L64
In contrast, a subsequent `ls -la a.json` behaves as expected, showing the single file stat result.
|
0.0
|
069e107fa056166fd4e7db75e909ebac85f372fd
|
[
"fsspec/implementations/tests/test_local.py::test_ls_on_file"
] |
[
"fsspec/implementations/tests/test_local.py::test_urlpath_inference_strips_protocol",
"fsspec/implementations/tests/test_local.py::test_urlpath_expand_read",
"fsspec/implementations/tests/test_local.py::test_cats",
"fsspec/implementations/tests/test_local.py::test_urlpath_expand_write",
"fsspec/implementations/tests/test_local.py::test_open_files",
"fsspec/implementations/tests/test_local.py::test_open_files_text_mode[utf-8]",
"fsspec/implementations/tests/test_local.py::test_open_files_text_mode[ascii]",
"fsspec/implementations/tests/test_local.py::test_compressions[None-rt]",
"fsspec/implementations/tests/test_local.py::test_compressions[None-rb]",
"fsspec/implementations/tests/test_local.py::test_compressions[zip-rt]",
"fsspec/implementations/tests/test_local.py::test_compressions[zip-rb]",
"fsspec/implementations/tests/test_local.py::test_compressions[bz2-rt]",
"fsspec/implementations/tests/test_local.py::test_compressions[bz2-rb]",
"fsspec/implementations/tests/test_local.py::test_compressions[gzip-rt]",
"fsspec/implementations/tests/test_local.py::test_compressions[gzip-rb]",
"fsspec/implementations/tests/test_local.py::test_compressions[lzma-rt]",
"fsspec/implementations/tests/test_local.py::test_compressions[lzma-rb]",
"fsspec/implementations/tests/test_local.py::test_compressions[xz-rt]",
"fsspec/implementations/tests/test_local.py::test_compressions[xz-rb]",
"fsspec/implementations/tests/test_local.py::test_bad_compression",
"fsspec/implementations/tests/test_local.py::test_not_found",
"fsspec/implementations/tests/test_local.py::test_isfile",
"fsspec/implementations/tests/test_local.py::test_isdir",
"fsspec/implementations/tests/test_local.py::test_open_files_write[compression_opener0]",
"fsspec/implementations/tests/test_local.py::test_open_files_write[compression_opener1]",
"fsspec/implementations/tests/test_local.py::test_abs_paths",
"fsspec/implementations/tests/test_local.py::test_glob_weird_characters[+-/]",
"fsspec/implementations/tests/test_local.py::test_glob_weird_characters[+-\\\\]",
"fsspec/implementations/tests/test_local.py::test_glob_weird_characters[++-/]",
"fsspec/implementations/tests/test_local.py::test_glob_weird_characters[++-\\\\]",
"fsspec/implementations/tests/test_local.py::test_glob_weird_characters[(-/]",
"fsspec/implementations/tests/test_local.py::test_glob_weird_characters[(-\\\\]",
"fsspec/implementations/tests/test_local.py::test_glob_weird_characters[)-/]",
"fsspec/implementations/tests/test_local.py::test_glob_weird_characters[)-\\\\]",
"fsspec/implementations/tests/test_local.py::test_glob_weird_characters[|-/]",
"fsspec/implementations/tests/test_local.py::test_glob_weird_characters[|-\\\\]",
"fsspec/implementations/tests/test_local.py::test_glob_weird_characters[\\\\-/]",
"fsspec/implementations/tests/test_local.py::test_glob_weird_characters[\\\\-\\\\]",
"fsspec/implementations/tests/test_local.py::test_globfind_dirs",
"fsspec/implementations/tests/test_local.py::test_touch",
"fsspec/implementations/tests/test_local.py::test_touch_truncate",
"fsspec/implementations/tests/test_local.py::test_directories",
"fsspec/implementations/tests/test_local.py::test_file_ops[]",
"fsspec/implementations/tests/test_local.py::test_file_ops[file://]",
"fsspec/implementations/tests/test_local.py::test_recursive_get_put",
"fsspec/implementations/tests/test_local.py::test_commit_discard",
"fsspec/implementations/tests/test_local.py::test_make_path_posix",
"fsspec/implementations/tests/test_local.py::test_linked_files",
"fsspec/implementations/tests/test_local.py::test_linked_files_exists",
"fsspec/implementations/tests/test_local.py::test_linked_directories",
"fsspec/implementations/tests/test_local.py::test_isfilestore",
"fsspec/implementations/tests/test_local.py::test_pickle",
"fsspec/implementations/tests/test_local.py::test_strip_protocol_expanduser",
"fsspec/implementations/tests/test_local.py::test_strip_protocol_no_authority",
"fsspec/implementations/tests/test_local.py::test_mkdir_twice_faile",
"fsspec/implementations/tests/test_local.py::test_iterable",
"fsspec/implementations/tests/test_local.py::test_mv_empty",
"fsspec/implementations/tests/test_local.py::test_mv_recursive",
"fsspec/implementations/tests/test_local.py::test_copy_errors",
"fsspec/implementations/tests/test_local.py::test_transaction",
"fsspec/implementations/tests/test_local.py::test_delete_cwd",
"fsspec/implementations/tests/test_local.py::test_delete_non_recursive_dir_fails",
"fsspec/implementations/tests/test_local.py::test_infer_compression[open-.bz2]",
"fsspec/implementations/tests/test_local.py::test_infer_compression[open-.gz]",
"fsspec/implementations/tests/test_local.py::test_infer_compression[open-]",
"fsspec/implementations/tests/test_local.py::test_info_path_like",
"fsspec/implementations/tests/test_local.py::test_seekable",
"fsspec/implementations/tests/test_local.py::test_link",
"fsspec/implementations/tests/test_local.py::test_symlink",
"fsspec/implementations/tests/test_local.py::test_put_file_to_dir",
"fsspec/implementations/tests/test_local.py::test_du",
"fsspec/implementations/tests/test_local.py::test_cp_get_put_directory_recursive[cp]",
"fsspec/implementations/tests/test_local.py::test_cp_get_put_directory_recursive[get]",
"fsspec/implementations/tests/test_local.py::test_cp_get_put_directory_recursive[put]",
"fsspec/implementations/tests/test_local.py::test_cp_get_put_empty_directory[cp]",
"fsspec/implementations/tests/test_local.py::test_cp_get_put_empty_directory[get]",
"fsspec/implementations/tests/test_local.py::test_cp_get_put_empty_directory[put]",
"fsspec/implementations/tests/test_local.py::test_cp_two_files",
"fsspec/implementations/tests/test_local.py::test_issue_1447"
] |
{
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
}
|
2023-12-22 20:17:55+00:00
|
bsd-3-clause
| 2,420 |
|
fsspec__filesystem_spec-1516
|
diff --git a/fsspec/implementations/http.py b/fsspec/implementations/http.py
index 2ffb7ed..4580764 100644
--- a/fsspec/implementations/http.py
+++ b/fsspec/implementations/http.py
@@ -451,7 +451,7 @@ class HTTPFileSystem(AsyncFileSystem):
ends_with_slash = path.endswith("/") # _strip_protocol strips trailing slash
path = self._strip_protocol(path)
- append_slash_to_dirname = ends_with_slash or path.endswith("/**")
+ append_slash_to_dirname = ends_with_slash or path.endswith(("/**", "/*"))
idx_star = path.find("*") if path.find("*") >= 0 else len(path)
idx_brace = path.find("[") if path.find("[") >= 0 else len(path)
@@ -494,15 +494,15 @@ class HTTPFileSystem(AsyncFileSystem):
pattern = re.compile(pattern)
out = {
- p: info
+ (
+ p.rstrip("/")
+ if not append_slash_to_dirname
+ and info["type"] == "directory"
+ and p.endswith("/")
+ else p
+ ): info
for p, info in sorted(allpaths.items())
- if pattern.match(
- (
- p + "/"
- if append_slash_to_dirname and info["type"] == "directory"
- else p
- )
- )
+ if pattern.match(p.rstrip("/"))
}
if detail:
|
fsspec/filesystem_spec
|
518984d494e48f007d8aa48de882ed7014da2574
|
diff --git a/fsspec/implementations/tests/test_http.py b/fsspec/implementations/tests/test_http.py
index af11644..fdae51f 100644
--- a/fsspec/implementations/tests/test_http.py
+++ b/fsspec/implementations/tests/test_http.py
@@ -129,6 +129,15 @@ def test_list_cache_with_skip_instance_cache(server):
assert out == [server + "/index/realfile"]
+def test_glob_return_subfolders(server):
+ h = fsspec.filesystem("http")
+ out = h.glob(server + "/simple/*")
+ assert set(out) == {
+ server + "/simple/dir/",
+ server + "/simple/file",
+ }
+
+
def test_isdir(server):
h = fsspec.filesystem("http")
assert h.isdir(server + "/index/")
diff --git a/fsspec/tests/conftest.py b/fsspec/tests/conftest.py
index d305e21..fb1efb0 100644
--- a/fsspec/tests/conftest.py
+++ b/fsspec/tests/conftest.py
@@ -19,6 +19,13 @@ listing = open(
win = os.name == "nt"
+def _make_listing(*paths):
+ return "\n".join(
+ f'<a href="http://127.0.0.1:{port}{f}">Link_{i}</a>'
+ for i, f in enumerate(paths)
+ ).encode()
+
+
@pytest.fixture
def reset_files():
yield
@@ -34,6 +41,10 @@ class HTTPTestHandler(BaseHTTPRequestHandler):
"/index/otherfile": data,
"/index": index,
"/data/20020401": listing,
+ "/simple/": _make_listing("/simple/file", "/simple/dir/"),
+ "/simple/file": data,
+ "/simple/dir/": _make_listing("/simple/dir/file"),
+ "/simple/dir/file": data,
}
dynamic_files = {}
@@ -53,7 +64,9 @@ class HTTPTestHandler(BaseHTTPRequestHandler):
self.wfile.write(data)
def do_GET(self):
- file_path = self.path.rstrip("/")
+ file_path = self.path
+ if file_path.endswith("/") and file_path.rstrip("/") in self.files:
+ file_path = file_path.rstrip("/")
file_data = self.files.get(file_path)
if "give_path" in self.headers:
return self._respond(200, data=json.dumps({"path": self.path}).encode())
|
HTTPFileSystem.glob misses folders on fsspec>2023.10.0
Hello everyone,
Since #1382 was merged HTTPFileSystem's glob is missing folders for patterns ending in `"/*"`.
To reproduce:
```shell
mkdir share
mkdir share/folder1
touch share/file1.txt
python -m http.server -d share 8080
```
execute in another shell:
```console
# OLD BEHAVIOR
$ python -m venv venvA
$ source venvA/bin/activate
$ python -m pip install "fsspec[http]==2023.10.0"
$ python -c "import fsspec; print(fsspec.__version__); print(fsspec.filesystem('http').glob('http://127.0.0.1:8080/*'))"
2023.10.0
['http://127.0.0.1:8080/file1.txt', 'http://127.0.0.1:8080/folder1/']
```
```console
# CURRENT BEHAVIOR
$ python -m venv venvB
$ source venvB/bin/activate
$ python -m pip install "fsspec[http]>2023.10.0"
$ python -c "import fsspec; print(fsspec.__version__); print(fsspec.filesystem('http').glob('http://127.0.0.1:8080/*'))"
2023.12.2
['http://127.0.0.1:8080/file1.txt']
```
I'll open a PR with a fix right away.
Cheers,
Andreas
|
0.0
|
518984d494e48f007d8aa48de882ed7014da2574
|
[
"fsspec/implementations/tests/test_http.py::test_glob_return_subfolders"
] |
[
"fsspec/implementations/tests/test_http.py::test_list",
"fsspec/implementations/tests/test_http.py::test_list_invalid_args",
"fsspec/implementations/tests/test_http.py::test_list_cache",
"fsspec/implementations/tests/test_http.py::test_list_cache_with_expiry_time_cached",
"fsspec/implementations/tests/test_http.py::test_list_cache_with_expiry_time_purged",
"fsspec/implementations/tests/test_http.py::test_list_cache_reuse",
"fsspec/implementations/tests/test_http.py::test_ls_raises_filenotfound",
"fsspec/implementations/tests/test_http.py::test_list_cache_with_max_paths",
"fsspec/implementations/tests/test_http.py::test_list_cache_with_skip_instance_cache",
"fsspec/implementations/tests/test_http.py::test_isdir",
"fsspec/implementations/tests/test_http.py::test_policy_arg",
"fsspec/implementations/tests/test_http.py::test_exists",
"fsspec/implementations/tests/test_http.py::test_read",
"fsspec/implementations/tests/test_http.py::test_file_pickle",
"fsspec/implementations/tests/test_http.py::test_methods",
"fsspec/implementations/tests/test_http.py::test_random_access[headers0]",
"fsspec/implementations/tests/test_http.py::test_random_access[headers1]",
"fsspec/implementations/tests/test_http.py::test_random_access[headers2]",
"fsspec/implementations/tests/test_http.py::test_random_access[headers3]",
"fsspec/implementations/tests/test_http.py::test_random_access[headers4]",
"fsspec/implementations/tests/test_http.py::test_random_access[headers5]",
"fsspec/implementations/tests/test_http.py::test_random_access[headers6]",
"fsspec/implementations/tests/test_http.py::test_random_access[headers7]",
"fsspec/implementations/tests/test_http.py::test_random_access[headers8]",
"fsspec/implementations/tests/test_http.py::test_no_range_support[headers0]",
"fsspec/implementations/tests/test_http.py::test_no_range_support[headers1]",
"fsspec/implementations/tests/test_http.py::test_no_range_support[headers2]",
"fsspec/implementations/tests/test_http.py::test_stream_seek",
"fsspec/implementations/tests/test_http.py::test_mapper_url",
"fsspec/implementations/tests/test_http.py::test_content_length_zero",
"fsspec/implementations/tests/test_http.py::test_content_encoding_gzip",
"fsspec/implementations/tests/test_http.py::test_download",
"fsspec/implementations/tests/test_http.py::test_multi_download",
"fsspec/implementations/tests/test_http.py::test_ls",
"fsspec/implementations/tests/test_http.py::test_mcat",
"fsspec/implementations/tests/test_http.py::test_cat_file_range",
"fsspec/implementations/tests/test_http.py::test_cat_file_range_numpy",
"fsspec/implementations/tests/test_http.py::test_mcat_cache",
"fsspec/implementations/tests/test_http.py::test_mcat_expand",
"fsspec/implementations/tests/test_http.py::test_info",
"fsspec/implementations/tests/test_http.py::test_put_file[POST]",
"fsspec/implementations/tests/test_http.py::test_put_file[PUT]",
"fsspec/implementations/tests/test_http.py::test_docstring",
"fsspec/implementations/tests/test_http.py::test_async_other_thread",
"fsspec/implementations/tests/test_http.py::test_async_this_thread",
"fsspec/implementations/tests/test_http.py::test_processes[spawn]",
"fsspec/implementations/tests/test_http.py::test_processes[forkserver]",
"fsspec/implementations/tests/test_http.py::test_close[get_aiohttp]",
"fsspec/implementations/tests/test_http.py::test_close[get_proxy]",
"fsspec/implementations/tests/test_http.py::test_async_file",
"fsspec/implementations/tests/test_http.py::test_encoded",
"fsspec/implementations/tests/test_http.py::test_with_cache",
"fsspec/implementations/tests/test_http.py::test_async_expand_path",
"fsspec/implementations/tests/test_http.py::test_async_walk"
] |
{
"failed_lite_validators": [
"has_hyperlinks"
],
"has_test_patch": true,
"is_lite": false
}
|
2024-01-26 10:29:21+00:00
|
bsd-3-clause
| 2,421 |
|
fsspec__filesystem_spec-1536
|
diff --git a/fsspec/core.py b/fsspec/core.py
index 8bc8e8e..c6263a6 100644
--- a/fsspec/core.py
+++ b/fsspec/core.py
@@ -643,7 +643,10 @@ def get_fs_token_paths(
else:
paths = fs._strip_protocol(paths)
if isinstance(paths, (list, tuple, set)):
- paths = expand_paths_if_needed(paths, mode, num, fs, name_function)
+ if expand:
+ paths = expand_paths_if_needed(paths, mode, num, fs, name_function)
+ elif not isinstance(paths, list):
+ paths = list(paths)
else:
if "w" in mode and expand:
paths = _expand_paths(paths, name_function, num)
|
fsspec/filesystem_spec
|
8a542c8c555614ab91fe07ce27a2d3dd3fd6700f
|
diff --git a/fsspec/tests/test_core.py b/fsspec/tests/test_core.py
index a14f688..943ab92 100644
--- a/fsspec/tests/test_core.py
+++ b/fsspec/tests/test_core.py
@@ -239,6 +239,101 @@ def test_pickle_after_open_open():
of2.close()
+# Define a list of special glob characters.
+# Note that we need to escape some characters and also consider file system limitations.
+# '*' and '?' are excluded because they are not valid for many file systems.
+# Similarly, we're careful with '{', '}', and '@' as their special meaning is
+# context-specific and might not be considered special for filenames.
+# Add tests for more file systems and for more glob magic later
+glob_magic_characters = ["[", "]", "!"]
+if os.name != "nt":
+ glob_magic_characters.extend(("*", "?")) # not valid on Windows
+
+
[email protected]("char", glob_magic_characters)
+def test_open_file_read_with_special_characters(tmp_path, char):
+ # Create a filename incorporating the special character
+ file_name = f"test{char}.txt"
+ file_path = tmp_path / file_name
+ expected_content = "Hello, world!"
+
+ with open(file_path, "w") as f:
+ f.write(expected_content)
+
+ with fsspec.open(file_path, "r") as f:
+ actual_content = f.read()
+
+ assert actual_content == expected_content
+
+
[email protected]("char", glob_magic_characters)
+def test_open_files_read_with_special_characters(tmp_path, char):
+ # Create a filename incorporating the special character
+ file_name = f"test{char}.txt"
+ file_path = tmp_path / file_name
+ expected_content = "Hello, world!"
+
+ with open(file_path, "w") as f:
+ f.write(expected_content)
+
+ with fsspec.open_files(file_path, "r")[0] as f:
+ actual_content = f.read()
+
+ assert actual_content == expected_content
+
+
[email protected]("char", glob_magic_characters)
+def test_open_file_write_with_special_characters(tmp_path, char):
+ # Create a filename incorporating the special character
+ file_name = f"test{char}.txt"
+ file_path = tmp_path / file_name
+ expected_content = "Hello, world!"
+
+ with fsspec.open(file_path, "w") as f:
+ f.write(expected_content)
+
+ with open(file_path, "r") as f:
+ actual_content = f.read()
+
+ assert actual_content == expected_content
+
+
[email protected]("char", glob_magic_characters)
+def test_open_files_read_with_special_characters(tmp_path, char):
+ # Create a filename incorporating the special character
+ file_name = f"test{char}.txt"
+ file_path = tmp_path / file_name
+ expected_content = "Hello, world!"
+
+ with open(file_path, "w") as f:
+ f.write(expected_content)
+
+ with fsspec.open_files(
+ urlpath=[os.fspath(file_path)], mode="r", auto_mkdir=False, expand=False
+ )[0] as f:
+ actual_content = f.read()
+
+ assert actual_content == expected_content
+
+
[email protected]("char", glob_magic_characters)
+def test_open_files_write_with_special_characters(tmp_path, char):
+ # Create a filename incorporating the special character
+ file_name = f"test{char}.txt"
+ file_path = tmp_path / file_name
+ expected_content = "Hello, world!"
+
+ with fsspec.open_files(
+ urlpath=[os.fspath(file_path)], mode="w", auto_mkdir=False, expand=False
+ )[0] as f:
+ f.write(expected_content)
+
+ with open(file_path, "r") as f:
+ actual_content = f.read()
+
+ assert actual_content == expected_content
+
+
def test_mismatch():
pytest.importorskip("s3fs")
with pytest.raises(ValueError):
|
`fsspec.open()` doesn't work with square brackets in a filename
For example, `fsspec.open("filename[test].csv")`.
Is this by design or a bug? (python builtin `open` function works in this case, at least for python 3.11)
|
0.0
|
8a542c8c555614ab91fe07ce27a2d3dd3fd6700f
|
[
"fsspec/tests/test_core.py::test_open_files_write_with_special_characters[*]",
"fsspec/tests/test_core.py::test_open_file_write_with_special_characters[*]"
] |
[
"fsspec/tests/test_core.py::test_expand_paths_if_needed_in_read_mode[create_files2-apath*-out2]",
"fsspec/tests/test_core.py::test_open_file_write_with_special_characters[]]",
"fsspec/tests/test_core.py::test_open_files_read_with_special_characters[?]",
"fsspec/tests/test_core.py::test_open_file_write_with_special_characters[!]",
"fsspec/tests/test_core.py::test_open_files_write_with_special_characters[!]",
"fsspec/tests/test_core.py::test_expand_error",
"fsspec/tests/test_core.py::test_open_file_write_with_special_characters[[]",
"fsspec/tests/test_core.py::test_multi_context",
"fsspec/tests/test_core.py::test_open_files_write_with_special_characters[]]",
"fsspec/tests/test_core.py::test_open_file_read_with_special_characters[*]",
"fsspec/tests/test_core.py::test_expand_fs_token_paths[x]",
"fsspec/tests/test_core.py::test_open_local_w_magic",
"fsspec/tests/test_core.py::test_pathobject",
"fsspec/tests/test_core.py::test_expand_fs_token_paths[x+]",
"fsspec/tests/test_core.py::test_open_file_read_with_special_characters[]]",
"fsspec/tests/test_core.py::test_open_files_read_with_special_characters[]]",
"fsspec/tests/test_core.py::test_expand_paths_if_needed_in_read_mode[create_files0-apath-out0]",
"fsspec/tests/test_core.py::test_expand_paths[path0-None-1-out0]",
"fsspec/tests/test_core.py::test_expand_fs_token_paths[w]",
"fsspec/tests/test_core.py::test_open_files_read_with_special_characters[*]",
"fsspec/tests/test_core.py::test_pickle_after_open_open",
"fsspec/tests/test_core.py::test_open_local_w_cache",
"fsspec/tests/test_core.py::test_expand_paths_if_needed_in_read_mode[create_files1-apath*-out1]",
"fsspec/tests/test_core.py::test_expand_paths_if_needed_in_read_mode[create_files4-apath?-out4]",
"fsspec/tests/test_core.py::test_automkdir_readonly",
"fsspec/tests/test_core.py::test_expand_paths[a*-<lambda>-2-out3]",
"fsspec/tests/test_core.py::test_open_local_w_path",
"fsspec/tests/test_core.py::test_open_files_read_with_special_characters[[]",
"fsspec/tests/test_core.py::test_open_files_write_with_special_characters[?]",
"fsspec/tests/test_core.py::test_open_local_w_list_of_path",
"fsspec/tests/test_core.py::test_open_file_read_with_special_characters[?]",
"fsspec/tests/test_core.py::test_not_local",
"fsspec/tests/test_core.py::test_expand_paths[apath.*.csv-None-2-out2]",
"fsspec/tests/test_core.py::test_list",
"fsspec/tests/test_core.py::test_expand_paths_if_needed_in_read_mode[create_files3-apath[1]-out3]",
"fsspec/tests/test_core.py::test_open_file_read_with_special_characters[!]",
"fsspec/tests/test_core.py::test_openfile_pickle_newline",
"fsspec/tests/test_core.py::test_open_file_write_with_special_characters[?]",
"fsspec/tests/test_core.py::test_openfile_api",
"fsspec/tests/test_core.py::test_expand_paths[apath.*.csv-None-1-out1]",
"fsspec/tests/test_core.py::test_xz_lzma_compressions",
"fsspec/tests/test_core.py::test_open_files_write_with_special_characters[[]",
"fsspec/tests/test_core.py::test_openfile_open",
"fsspec/tests/test_core.py::test_open_files_read_with_special_characters[!]",
"fsspec/tests/test_core.py::test_open_local_w_list_of_str",
"fsspec/tests/test_core.py::test_open_file_read_with_special_characters[[]",
"fsspec/tests/test_core.py::test_automkdir_local",
"fsspec/tests/test_core.py::test_expand_fs_token_paths[w+]",
"fsspec/tests/test_core.py::test_automkdir"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2024-03-06 17:10:25+00:00
|
bsd-3-clause
| 2,422 |
|
fsspec__filesystem_spec-831
|
diff --git a/ci/environment-win.yml b/ci/environment-win.yml
index 7e847e7..af9671e 100644
--- a/ci/environment-win.yml
+++ b/ci/environment-win.yml
@@ -8,7 +8,7 @@ dependencies:
- requests
- zstandard
- python-snappy
- - lz4
+ - lz4<3.1.3
- pyftpdlib
- cloudpickle
- pytest
diff --git a/fsspec/dircache.py b/fsspec/dircache.py
index 97a73bc..014e482 100644
--- a/fsspec/dircache.py
+++ b/fsspec/dircache.py
@@ -38,7 +38,7 @@ class DirCache(MutableMapping):
use_listings_cache: bool
If False, this cache never returns items, but always reports KeyError,
and setting items has no effect
- listings_expiry_time: int (optional)
+ listings_expiry_time: int or float (optional)
Time in seconds that a listing is considered valid. If None,
listings do not expire.
max_paths: int (optional)
diff --git a/fsspec/implementations/local.py b/fsspec/implementations/local.py
index 16eda94..51f86d3 100644
--- a/fsspec/implementations/local.py
+++ b/fsspec/implementations/local.py
@@ -184,7 +184,7 @@ class LocalFileSystem(AbstractFileSystem):
path = stringify_path(path)
if path.startswith("file://"):
path = path[7:]
- return make_path_posix(path).rstrip("/")
+ return make_path_posix(path).rstrip("/") or cls.root_marker
def _isfilestore(self):
# Inheriting from DaskFileSystem makes this False (S3, etc. were)
|
fsspec/filesystem_spec
|
cf08ec23ffccc321b51bce2ffdc0186c25f17cc0
|
diff --git a/fsspec/implementations/tests/test_local.py b/fsspec/implementations/tests/test_local.py
index 2779018..f3bbad8 100644
--- a/fsspec/implementations/tests/test_local.py
+++ b/fsspec/implementations/tests/test_local.py
@@ -370,6 +370,7 @@ def test_directories(tmpdir):
assert fs.ls(tmpdir, True)[0]["type"] == "directory"
fs.rmdir(tmpdir + "/dir")
assert not fs.ls(tmpdir)
+ assert fs.ls(fs.root_marker)
def test_file_ops(tmpdir):
|
FileNotFoundError [LocalFileSystem] on unix-like root / directory
Hello,
in case of `LocalFileSystem().ls('/')`, a `FileNotFoundError` is being raised.
```python
FileNotFoundError: [Errno 2] No such file or directory: ''
```
This looks quite normal as path is stripped right
https://github.com/fsspec/filesystem_spec/blob/b68be6c57f54a71c6ffc89e669c410da353ebc1f/fsspec/implementations/local.py#L54
Is this an expected behavior?
|
0.0
|
cf08ec23ffccc321b51bce2ffdc0186c25f17cc0
|
[
"fsspec/implementations/tests/test_local.py::test_directories"
] |
[
"fsspec/implementations/tests/test_local.py::test_urlpath_inference_strips_protocol",
"fsspec/implementations/tests/test_local.py::test_urlpath_inference_errors",
"fsspec/implementations/tests/test_local.py::test_urlpath_expand_read",
"fsspec/implementations/tests/test_local.py::test_cats",
"fsspec/implementations/tests/test_local.py::test_urlpath_expand_write",
"fsspec/implementations/tests/test_local.py::test_open_files",
"fsspec/implementations/tests/test_local.py::test_open_files_text_mode[utf-8]",
"fsspec/implementations/tests/test_local.py::test_open_files_text_mode[ascii]",
"fsspec/implementations/tests/test_local.py::test_compressions[None-rt]",
"fsspec/implementations/tests/test_local.py::test_compressions[None-rb]",
"fsspec/implementations/tests/test_local.py::test_compressions[zip-rt]",
"fsspec/implementations/tests/test_local.py::test_compressions[zip-rb]",
"fsspec/implementations/tests/test_local.py::test_compressions[bz2-rt]",
"fsspec/implementations/tests/test_local.py::test_compressions[bz2-rb]",
"fsspec/implementations/tests/test_local.py::test_compressions[gzip-rt]",
"fsspec/implementations/tests/test_local.py::test_compressions[gzip-rb]",
"fsspec/implementations/tests/test_local.py::test_compressions[lzma-rt]",
"fsspec/implementations/tests/test_local.py::test_compressions[lzma-rb]",
"fsspec/implementations/tests/test_local.py::test_compressions[xz-rt]",
"fsspec/implementations/tests/test_local.py::test_compressions[xz-rb]",
"fsspec/implementations/tests/test_local.py::test_bad_compression",
"fsspec/implementations/tests/test_local.py::test_not_found",
"fsspec/implementations/tests/test_local.py::test_isfile",
"fsspec/implementations/tests/test_local.py::test_isdir",
"fsspec/implementations/tests/test_local.py::test_open_files_write[compression_opener0]",
"fsspec/implementations/tests/test_local.py::test_open_files_write[compression_opener1]",
"fsspec/implementations/tests/test_local.py::test_abs_paths",
"fsspec/implementations/tests/test_local.py::test_glob_weird_characters[+-/]",
"fsspec/implementations/tests/test_local.py::test_glob_weird_characters[+-\\\\]",
"fsspec/implementations/tests/test_local.py::test_glob_weird_characters[++-/]",
"fsspec/implementations/tests/test_local.py::test_glob_weird_characters[++-\\\\]",
"fsspec/implementations/tests/test_local.py::test_glob_weird_characters[(-/]",
"fsspec/implementations/tests/test_local.py::test_glob_weird_characters[(-\\\\]",
"fsspec/implementations/tests/test_local.py::test_glob_weird_characters[)-/]",
"fsspec/implementations/tests/test_local.py::test_glob_weird_characters[)-\\\\]",
"fsspec/implementations/tests/test_local.py::test_glob_weird_characters[|-/]",
"fsspec/implementations/tests/test_local.py::test_glob_weird_characters[|-\\\\]",
"fsspec/implementations/tests/test_local.py::test_glob_weird_characters[\\\\-/]",
"fsspec/implementations/tests/test_local.py::test_glob_weird_characters[\\\\-\\\\]",
"fsspec/implementations/tests/test_local.py::test_globfind_dirs",
"fsspec/implementations/tests/test_local.py::test_touch",
"fsspec/implementations/tests/test_local.py::test_file_ops",
"fsspec/implementations/tests/test_local.py::test_recursive_get_put",
"fsspec/implementations/tests/test_local.py::test_commit_discard",
"fsspec/implementations/tests/test_local.py::test_make_path_posix",
"fsspec/implementations/tests/test_local.py::test_linked_files",
"fsspec/implementations/tests/test_local.py::test_linked_files_exists",
"fsspec/implementations/tests/test_local.py::test_linked_directories",
"fsspec/implementations/tests/test_local.py::test_isfilestore",
"fsspec/implementations/tests/test_local.py::test_pickle",
"fsspec/implementations/tests/test_local.py::test_strip_protocol_expanduser",
"fsspec/implementations/tests/test_local.py::test_mkdir_twice_faile",
"fsspec/implementations/tests/test_local.py::test_iterable",
"fsspec/implementations/tests/test_local.py::test_mv_empty",
"fsspec/implementations/tests/test_local.py::test_mv_recursive",
"fsspec/implementations/tests/test_local.py::test_copy_errors",
"fsspec/implementations/tests/test_local.py::test_transaction",
"fsspec/implementations/tests/test_local.py::test_delete_cwd",
"fsspec/implementations/tests/test_local.py::test_infer_compression[open-.bz2]",
"fsspec/implementations/tests/test_local.py::test_infer_compression[open-.gz]",
"fsspec/implementations/tests/test_local.py::test_infer_compression[open-]",
"fsspec/implementations/tests/test_local.py::test_info_path_like",
"fsspec/implementations/tests/test_local.py::test_seekable"
] |
{
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-11-21 10:54:58+00:00
|
bsd-3-clause
| 2,423 |
|
fsspec__filesystem_spec-926
|
diff --git a/fsspec/implementations/memory.py b/fsspec/implementations/memory.py
index 334f9db..9356a56 100644
--- a/fsspec/implementations/memory.py
+++ b/fsspec/implementations/memory.py
@@ -116,6 +116,9 @@ class MemoryFileSystem(AbstractFileSystem):
def rmdir(self, path):
path = self._strip_protocol(path)
+ if path == "":
+ # silently avoid deleting FS root
+ return
if path in self.pseudo_dirs:
if not self.ls(path):
self.pseudo_dirs.remove(path)
@@ -124,7 +127,7 @@ class MemoryFileSystem(AbstractFileSystem):
else:
raise FileNotFoundError(path)
- def exists(self, path):
+ def exists(self, path, **kwargs):
path = self._strip_protocol(path)
return path in self.store or path in self.pseudo_dirs
|
fsspec/filesystem_spec
|
e5346c87367addc6e020933cc8631a0262ae500a
|
diff --git a/fsspec/conftest.py b/fsspec/conftest.py
index 393e4c4..47b49c9 100644
--- a/fsspec/conftest.py
+++ b/fsspec/conftest.py
@@ -17,7 +17,7 @@ def m():
"""
m = fsspec.filesystem("memory")
m.store.clear()
- m.pseudo_dirs.clear()
+ m.pseudo_dirs = [""]
try:
yield m
finally:
diff --git a/fsspec/implementations/tests/test_memory.py b/fsspec/implementations/tests/test_memory.py
index 184c9ee..c647fac 100644
--- a/fsspec/implementations/tests/test_memory.py
+++ b/fsspec/implementations/tests/test_memory.py
@@ -150,3 +150,9 @@ def test_seekable(m):
f.seek(1)
assert f.read(1) == "a"
assert f.tell() == 2
+
+
+def test_remove_all(m):
+ m.touch("afile")
+ m.rm("/", recursive=True)
+ assert not m.ls("/")
|
fs.ls("/") raises error after fs.rm("/", recursive=True) for memory filesystem
To replicate this error, run this:
```python
import fsspec
fs = fsspec.filesystem("memory")
fs.rm("/", recursive=True)
fs.ls("/")
```
Which results in the following traceback:
```
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/.../site-packages/fsspec/implementations/memory.py", line 91, in ls
raise FileNotFoundError(path)
FileNotFoundError
```
I would expect it to return an empty list as it does before the `ls.rm()` call.
|
0.0
|
e5346c87367addc6e020933cc8631a0262ae500a
|
[
"fsspec/implementations/tests/test_memory.py::test_remove_all"
] |
[
"fsspec/implementations/tests/test_memory.py::test_1",
"fsspec/implementations/tests/test_memory.py::test_strip",
"fsspec/implementations/tests/test_memory.py::test_put_single",
"fsspec/implementations/tests/test_memory.py::test_ls",
"fsspec/implementations/tests/test_memory.py::test_directories",
"fsspec/implementations/tests/test_memory.py::test_mv_recursive",
"fsspec/implementations/tests/test_memory.py::test_rm_no_psuedo_dir",
"fsspec/implementations/tests/test_memory.py::test_rewind",
"fsspec/implementations/tests/test_memory.py::test_empty_raises",
"fsspec/implementations/tests/test_memory.py::test_dir_errors",
"fsspec/implementations/tests/test_memory.py::test_no_rewind_append_mode",
"fsspec/implementations/tests/test_memory.py::test_moves",
"fsspec/implementations/tests/test_memory.py::test_rm_reursive_empty_subdir",
"fsspec/implementations/tests/test_memory.py::test_seekable"
] |
{
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
}
|
2022-03-22 19:56:12+00:00
|
bsd-3-clause
| 2,424 |
|
fsspec__filesystem_spec-930
|
diff --git a/fsspec/mapping.py b/fsspec/mapping.py
index d6346f4..8bad2de 100644
--- a/fsspec/mapping.py
+++ b/fsspec/mapping.py
@@ -187,7 +187,7 @@ def maybe_convert(value):
def get_mapper(
- url,
+ url="",
check=False,
create=False,
missing_exceptions=None,
diff --git a/fsspec/spec.py b/fsspec/spec.py
index fa8feb3..7f9a241 100644
--- a/fsspec/spec.py
+++ b/fsspec/spec.py
@@ -1153,7 +1153,7 @@ class AbstractFileSystem(metaclass=_Cached):
# all instances already also derive from pyarrow
return self
- def get_mapper(self, root, check=False, create=False):
+ def get_mapper(self, root="", check=False, create=False):
"""Create key/value store based on this file-system
Makes a MutableMapping interface to the FS at the given root path.
|
fsspec/filesystem_spec
|
dcd8b22a72c83481d40ab3edbe390ee3fa14ec69
|
diff --git a/fsspec/implementations/tests/test_archive.py b/fsspec/implementations/tests/test_archive.py
index 816f826..abc6d35 100644
--- a/fsspec/implementations/tests/test_archive.py
+++ b/fsspec/implementations/tests/test_archive.py
@@ -249,7 +249,7 @@ class TestAnyArchive:
def test_mapping(self, scenario: ArchiveTestScenario):
with scenario.provider(archive_data) as archive:
fs = fsspec.filesystem(scenario.protocol, fo=archive)
- m = fs.get_mapper("")
+ m = fs.get_mapper()
assert list(m) == ["a", "b", "deeply/nested/path"]
assert m["b"] == archive_data["b"]
diff --git a/fsspec/implementations/tests/test_memory.py b/fsspec/implementations/tests/test_memory.py
index c647fac..7cf29e4 100644
--- a/fsspec/implementations/tests/test_memory.py
+++ b/fsspec/implementations/tests/test_memory.py
@@ -9,7 +9,7 @@ def test_1(m):
files = m.find("")
assert files == ["/afiles/and/another", "/somefile"]
- files = sorted(m.get_mapper("/"))
+ files = sorted(m.get_mapper())
assert files == ["afiles/and/another", "somefile"]
diff --git a/fsspec/tests/test_mapping.py b/fsspec/tests/test_mapping.py
index 71de1e0..ed5a3b0 100644
--- a/fsspec/tests/test_mapping.py
+++ b/fsspec/tests/test_mapping.py
@@ -5,6 +5,7 @@ import sys
import pytest
import fsspec
+from fsspec.implementations.local import LocalFileSystem
from fsspec.implementations.memory import MemoryFileSystem
@@ -143,3 +144,8 @@ def test_setitem_numpy():
dtype="<m8[ns]",
) # timedelta64 scalar
assert m["c"] == b',M"\x9e\xc6\x99A\x065\x1c\xf0Rn4\xcb+'
+
+
+def test_empty_url():
+ m = fsspec.get_mapper()
+ assert isinstance(m.fs, LocalFileSystem)
|
Make `url` in `get_mapper` optional
Currently when using a reference filesystem, users need to always provide an empty string `""` or `/` as the root url. Is there any reason not to set `""` or `/` as the default, so users can just do `fs.get_mapper()`?
|
0.0
|
dcd8b22a72c83481d40ab3edbe390ee3fa14ec69
|
[
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_mapping[zip]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_mapping[tar]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_mapping[tar-gz]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_mapping[tar-bz2]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_mapping[tar-xz]",
"fsspec/implementations/tests/test_memory.py::test_1",
"fsspec/tests/test_mapping.py::test_empty_url"
] |
[
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_repr[zip]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_empty[zip]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_glob[zip]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_pickle[zip]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_all_dirnames[zip]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_ls[zip]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_find[zip]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_walk[zip]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_info[zip]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_isdir_isfile[zip-128]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_isdir_isfile[zip-512]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_isdir_isfile[zip-4096]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_repr[tar]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_empty[tar]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_glob[tar]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_pickle[tar]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_all_dirnames[tar]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_ls[tar]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_find[tar]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_walk[tar]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_info[tar]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_isdir_isfile[tar-128]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_isdir_isfile[tar-512]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_isdir_isfile[tar-4096]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_repr[tar-gz]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_empty[tar-gz]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_glob[tar-gz]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_pickle[tar-gz]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_all_dirnames[tar-gz]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_ls[tar-gz]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_find[tar-gz]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_walk[tar-gz]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_info[tar-gz]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_isdir_isfile[tar-gz-128]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_isdir_isfile[tar-gz-512]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_isdir_isfile[tar-gz-4096]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_repr[tar-bz2]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_empty[tar-bz2]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_glob[tar-bz2]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_pickle[tar-bz2]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_all_dirnames[tar-bz2]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_ls[tar-bz2]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_find[tar-bz2]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_walk[tar-bz2]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_info[tar-bz2]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_isdir_isfile[tar-bz2-128]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_isdir_isfile[tar-bz2-512]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_isdir_isfile[tar-bz2-4096]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_repr[tar-xz]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_empty[tar-xz]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_glob[tar-xz]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_pickle[tar-xz]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_all_dirnames[tar-xz]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_ls[tar-xz]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_find[tar-xz]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_walk[tar-xz]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_info[tar-xz]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_isdir_isfile[tar-xz-128]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_isdir_isfile[tar-xz-512]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_isdir_isfile[tar-xz-4096]",
"fsspec/implementations/tests/test_memory.py::test_strip",
"fsspec/implementations/tests/test_memory.py::test_put_single",
"fsspec/implementations/tests/test_memory.py::test_ls",
"fsspec/implementations/tests/test_memory.py::test_directories",
"fsspec/implementations/tests/test_memory.py::test_mv_recursive",
"fsspec/implementations/tests/test_memory.py::test_rm_no_psuedo_dir",
"fsspec/implementations/tests/test_memory.py::test_rewind",
"fsspec/implementations/tests/test_memory.py::test_empty_raises",
"fsspec/implementations/tests/test_memory.py::test_dir_errors",
"fsspec/implementations/tests/test_memory.py::test_no_rewind_append_mode",
"fsspec/implementations/tests/test_memory.py::test_moves",
"fsspec/implementations/tests/test_memory.py::test_rm_reursive_empty_subdir",
"fsspec/implementations/tests/test_memory.py::test_seekable",
"fsspec/implementations/tests/test_memory.py::test_remove_all",
"fsspec/tests/test_mapping.py::test_mapping_prefix",
"fsspec/tests/test_mapping.py::test_getitems_errors",
"fsspec/tests/test_mapping.py::test_ops",
"fsspec/tests/test_mapping.py::test_pickle",
"fsspec/tests/test_mapping.py::test_keys_view",
"fsspec/tests/test_mapping.py::test_multi",
"fsspec/tests/test_mapping.py::test_setitem_types"
] |
{
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-03-25 13:45:14+00:00
|
bsd-3-clause
| 2,425 |
|
fsspec__filesystem_spec-931
|
diff --git a/README.md b/README.md
index 411240c..bffc475 100644
--- a/README.md
+++ b/README.md
@@ -40,7 +40,7 @@ environments. First, install conda with tox and tox-conda in a base environment
used to configure a development environment and run tests.
First, setup a development conda environment via ``tox -e {env}`` where ``env`` is one of ``{py36,py37,py38,py39}``.
-This will install fspec dependencies, test & dev tools, and install fsspec in develop
+This will install fsspec dependencies, test & dev tools, and install fsspec in develop
mode. You may activate the dev environment under ``.tox/{env}`` via ``conda activate .tox/{env}``.
### Testing
diff --git a/docs/source/api.rst b/docs/source/api.rst
index 81639a7..5d379c4 100644
--- a/docs/source/api.rst
+++ b/docs/source/api.rst
@@ -51,6 +51,7 @@ Base Classes
fsspec.callbacks.Callback
fsspec.callbacks.NoOpCallback
fsspec.callbacks.DotPrinterCallback
+ fsspec.callbacks.TqdmCallback
.. autoclass:: fsspec.spec.AbstractFileSystem
:members:
@@ -96,6 +97,9 @@ Base Classes
.. autoclass:: fsspec.callbacks.DotPrinterCallback
:members:
+.. autoclass:: fsspec.callbacks.TqdmCallback
+ :members:
+
.. _implementations:
Built-in Implementations
diff --git a/docs/source/features.rst b/docs/source/features.rst
index 2f309d5..700d84f 100644
--- a/docs/source/features.rst
+++ b/docs/source/features.rst
@@ -399,3 +399,5 @@ feature is new and experimental and supported by varying amounts in the
backends.
See the docstrings in the callbacks module for further details.
+``fsspec.callbacks.TqdmCallback`` can be used to display a progress bar using
+tqdm.
diff --git a/fsspec/callbacks.py b/fsspec/callbacks.py
index f8312ad..30590b2 100644
--- a/fsspec/callbacks.py
+++ b/fsspec/callbacks.py
@@ -177,4 +177,44 @@ class DotPrinterCallback(Callback):
print(self.chr, end="")
+class TqdmCallback(Callback):
+ """
+ A callback to display a progress bar using tqdm
+
+ Examples
+ --------
+ >>> import fsspec
+ >>> from fsspec.callbacks import TqdmCallback
+ >>> fs = fsspec.filesystem("memory")
+ >>> path2distant_data = "/your-path"
+ >>> fs.upload(
+ ".",
+ path2distant_data,
+ recursive=True,
+ callback=TqdmCallback(),
+ )
+ """
+
+ def __init__(self, *args, **kwargs):
+ try:
+ import tqdm
+
+ self._tqdm = tqdm
+ except ImportError as exce:
+ raise ImportError(
+ "Using TqdmCallback requires tqdm to be installed"
+ ) from exce
+ super().__init__(*args, **kwargs)
+
+ def set_size(self, size):
+ self.tqdm = self._tqdm.tqdm(desc="test", total=size)
+
+ def relative_update(self, inc=1):
+ self.tqdm.update(inc)
+
+ def __del__(self):
+ self.tqdm.close()
+ self.tqdm = None
+
+
_DEFAULT_CALLBACK = NoOpCallback()
diff --git a/fsspec/mapping.py b/fsspec/mapping.py
index d6346f4..8bad2de 100644
--- a/fsspec/mapping.py
+++ b/fsspec/mapping.py
@@ -187,7 +187,7 @@ def maybe_convert(value):
def get_mapper(
- url,
+ url="",
check=False,
create=False,
missing_exceptions=None,
diff --git a/fsspec/spec.py b/fsspec/spec.py
index fa8feb3..7f9a241 100644
--- a/fsspec/spec.py
+++ b/fsspec/spec.py
@@ -1153,7 +1153,7 @@ class AbstractFileSystem(metaclass=_Cached):
# all instances already also derive from pyarrow
return self
- def get_mapper(self, root, check=False, create=False):
+ def get_mapper(self, root="", check=False, create=False):
"""Create key/value store based on this file-system
Makes a MutableMapping interface to the FS at the given root path.
diff --git a/setup.py b/setup.py
index 70f99f4..04251e0 100644
--- a/setup.py
+++ b/setup.py
@@ -54,6 +54,7 @@ setup(
"fuse": ["fusepy"],
"libarchive": ["libarchive-c"],
"gui": ["panel"],
+ "tqdm": ["tqdm"],
},
zip_safe=False,
)
|
fsspec/filesystem_spec
|
dcd8b22a72c83481d40ab3edbe390ee3fa14ec69
|
diff --git a/fsspec/implementations/tests/test_archive.py b/fsspec/implementations/tests/test_archive.py
index 816f826..abc6d35 100644
--- a/fsspec/implementations/tests/test_archive.py
+++ b/fsspec/implementations/tests/test_archive.py
@@ -249,7 +249,7 @@ class TestAnyArchive:
def test_mapping(self, scenario: ArchiveTestScenario):
with scenario.provider(archive_data) as archive:
fs = fsspec.filesystem(scenario.protocol, fo=archive)
- m = fs.get_mapper("")
+ m = fs.get_mapper()
assert list(m) == ["a", "b", "deeply/nested/path"]
assert m["b"] == archive_data["b"]
diff --git a/fsspec/implementations/tests/test_memory.py b/fsspec/implementations/tests/test_memory.py
index c647fac..7cf29e4 100644
--- a/fsspec/implementations/tests/test_memory.py
+++ b/fsspec/implementations/tests/test_memory.py
@@ -9,7 +9,7 @@ def test_1(m):
files = m.find("")
assert files == ["/afiles/and/another", "/somefile"]
- files = sorted(m.get_mapper("/"))
+ files = sorted(m.get_mapper())
assert files == ["afiles/and/another", "somefile"]
diff --git a/fsspec/tests/test_mapping.py b/fsspec/tests/test_mapping.py
index 71de1e0..ed5a3b0 100644
--- a/fsspec/tests/test_mapping.py
+++ b/fsspec/tests/test_mapping.py
@@ -5,6 +5,7 @@ import sys
import pytest
import fsspec
+from fsspec.implementations.local import LocalFileSystem
from fsspec.implementations.memory import MemoryFileSystem
@@ -143,3 +144,8 @@ def test_setitem_numpy():
dtype="<m8[ns]",
) # timedelta64 scalar
assert m["c"] == b',M"\x9e\xc6\x99A\x065\x1c\xf0Rn4\xcb+'
+
+
+def test_empty_url():
+ m = fsspec.get_mapper()
+ assert isinstance(m.fs, LocalFileSystem)
|
Docs could use an example for callbacks.
Hi !
Thank you for fsspec ! :heart: 🙏
I think the docs could use an example for callbacks. I've come up with this little hook with `tqdm`, not sure if it's the right way to do it:
```python
import tqdm
import fsspec
class FsspecTqdmCallback(tqdm.tqdm):
"""Provides `update_to(n)` which uses `tqdm.update(delta_n)`."""
def update_to(self, total_size, value, **kwargs):
"""
total_size : int
Total size (in tqdm units)
value : int, optional
Number of blocks transferred so far.
"""
self.total = total_size
return self.update(value - self.n)
storage_opts = {
"key": KEY,
"secret": SECRET_KEY,
}
fs = fsspec.filesystem("s3", **storage_opts)
path2distant_data = "s3://your-path"
with FsspecTqdmCallback(
desc="test",
) as pbar:
fs.upload(
"local_path/",
path2distant_data,
recursive=True,
callback=fsspec.callbacks.Callback(hooks={"tqdm": pbar.update_to}),
)
```
|
0.0
|
dcd8b22a72c83481d40ab3edbe390ee3fa14ec69
|
[
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_mapping[zip]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_mapping[tar]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_mapping[tar-gz]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_mapping[tar-bz2]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_mapping[tar-xz]",
"fsspec/implementations/tests/test_memory.py::test_1",
"fsspec/tests/test_mapping.py::test_empty_url"
] |
[
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_repr[zip]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_empty[zip]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_glob[zip]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_pickle[zip]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_all_dirnames[zip]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_ls[zip]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_find[zip]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_walk[zip]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_info[zip]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_isdir_isfile[zip-128]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_isdir_isfile[zip-512]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_isdir_isfile[zip-4096]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_repr[tar]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_empty[tar]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_glob[tar]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_pickle[tar]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_all_dirnames[tar]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_ls[tar]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_find[tar]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_walk[tar]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_info[tar]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_isdir_isfile[tar-128]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_isdir_isfile[tar-512]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_isdir_isfile[tar-4096]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_repr[tar-gz]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_empty[tar-gz]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_glob[tar-gz]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_pickle[tar-gz]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_all_dirnames[tar-gz]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_ls[tar-gz]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_find[tar-gz]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_walk[tar-gz]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_info[tar-gz]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_isdir_isfile[tar-gz-128]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_isdir_isfile[tar-gz-512]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_isdir_isfile[tar-gz-4096]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_repr[tar-bz2]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_empty[tar-bz2]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_glob[tar-bz2]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_pickle[tar-bz2]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_all_dirnames[tar-bz2]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_ls[tar-bz2]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_find[tar-bz2]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_walk[tar-bz2]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_info[tar-bz2]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_isdir_isfile[tar-bz2-128]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_isdir_isfile[tar-bz2-512]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_isdir_isfile[tar-bz2-4096]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_repr[tar-xz]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_empty[tar-xz]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_glob[tar-xz]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_pickle[tar-xz]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_all_dirnames[tar-xz]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_ls[tar-xz]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_find[tar-xz]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_walk[tar-xz]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_info[tar-xz]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_isdir_isfile[tar-xz-128]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_isdir_isfile[tar-xz-512]",
"fsspec/implementations/tests/test_archive.py::TestAnyArchive::test_isdir_isfile[tar-xz-4096]",
"fsspec/implementations/tests/test_memory.py::test_strip",
"fsspec/implementations/tests/test_memory.py::test_put_single",
"fsspec/implementations/tests/test_memory.py::test_ls",
"fsspec/implementations/tests/test_memory.py::test_directories",
"fsspec/implementations/tests/test_memory.py::test_mv_recursive",
"fsspec/implementations/tests/test_memory.py::test_rm_no_psuedo_dir",
"fsspec/implementations/tests/test_memory.py::test_rewind",
"fsspec/implementations/tests/test_memory.py::test_empty_raises",
"fsspec/implementations/tests/test_memory.py::test_dir_errors",
"fsspec/implementations/tests/test_memory.py::test_no_rewind_append_mode",
"fsspec/implementations/tests/test_memory.py::test_moves",
"fsspec/implementations/tests/test_memory.py::test_rm_reursive_empty_subdir",
"fsspec/implementations/tests/test_memory.py::test_seekable",
"fsspec/implementations/tests/test_memory.py::test_remove_all",
"fsspec/tests/test_mapping.py::test_mapping_prefix",
"fsspec/tests/test_mapping.py::test_getitems_errors",
"fsspec/tests/test_mapping.py::test_ops",
"fsspec/tests/test_mapping.py::test_pickle",
"fsspec/tests/test_mapping.py::test_keys_view",
"fsspec/tests/test_mapping.py::test_multi",
"fsspec/tests/test_mapping.py::test_setitem_types"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-03-25 13:56:04+00:00
|
bsd-3-clause
| 2,426 |
|
fsspec__filesystem_spec-966
|
diff --git a/fsspec/implementations/http.py b/fsspec/implementations/http.py
index 0802932..126b410 100644
--- a/fsspec/implementations/http.py
+++ b/fsspec/implementations/http.py
@@ -209,7 +209,6 @@ class HTTPFileSystem(AsyncFileSystem):
kw.update(kwargs)
logger.debug(url)
- # TODO: extract into testable utility function?
if start is not None or end is not None:
if start == end:
return b""
diff --git a/fsspec/implementations/libarchive.py b/fsspec/implementations/libarchive.py
index 8e99bea..28845c3 100644
--- a/fsspec/implementations/libarchive.py
+++ b/fsspec/implementations/libarchive.py
@@ -91,6 +91,7 @@ class LibArchiveFileSystem(AbstractArchiveFileSystem):
root_marker = ""
protocol = "libarchive"
+ cachable = False
def __init__(
self,
diff --git a/fsspec/implementations/reference.py b/fsspec/implementations/reference.py
index 9de586c..85b1e1d 100644
--- a/fsspec/implementations/reference.py
+++ b/fsspec/implementations/reference.py
@@ -197,15 +197,7 @@ class ReferenceFileSystem(AsyncFileSystem):
def _cat_common(self, path):
path = self._strip_protocol(path)
logger.debug(f"cat: {path}")
- # TODO: can extract and cache templating here
- if self.dataframe:
- part = self.df.loc[path]
- if part["data"]:
- part = part["data"]
- else:
- part = part[["url", "offset", "size"]]
- else:
- part = self.references[path]
+ part = self.references[path]
if isinstance(part, str):
part = part.encode()
if isinstance(part, bytes):
diff --git a/fsspec/implementations/tar.py b/fsspec/implementations/tar.py
index dfea48c..6ac7f0e 100644
--- a/fsspec/implementations/tar.py
+++ b/fsspec/implementations/tar.py
@@ -23,6 +23,7 @@ class TarFileSystem(AbstractArchiveFileSystem):
root_marker = ""
protocol = "tar"
+ cachable = False
def __init__(
self,
diff --git a/fsspec/implementations/zip.py b/fsspec/implementations/zip.py
index 5452bf7..2ede0dc 100644
--- a/fsspec/implementations/zip.py
+++ b/fsspec/implementations/zip.py
@@ -17,6 +17,7 @@ class ZipFileSystem(AbstractArchiveFileSystem):
root_marker = ""
protocol = "zip"
+ cachable = False
def __init__(
self,
|
fsspec/filesystem_spec
|
22b2c5960cc2685acf4e691551150516856bd65f
|
diff --git a/fsspec/implementations/tests/test_zip.py b/fsspec/implementations/tests/test_zip.py
index 2d9c26b..0aab4a2 100644
--- a/fsspec/implementations/tests/test_zip.py
+++ b/fsspec/implementations/tests/test_zip.py
@@ -32,3 +32,10 @@ def test_fsspec_get_mapper():
assert isinstance(mapping, fsspec.mapping.FSMap)
items = dict(mapping.getitems(keys))
assert items == {"a": b"", "b": b"hello", "deeply/nested/path": b"stuff"}
+
+
+def test_not_cached():
+ with tempzip(archive_data) as z:
+ fs = fsspec.filesystem("zip", fo=z)
+ fs2 = fsspec.filesystem("zip", fo=z)
+ assert fs is not fs2
|
Archive filesystems do not close file after deletion.
We noticed this undesired behaviour in one of out processes using fsspec:
```python
import fsspec
import psutil
import gc
fs = fsspec.filesystem("tar", fo="./foo.tar")
# here other things happen, eg
# filelist = fs.find("/")
del fs
gc.collect() # returns 0, so fs is not collectable...
print(psutil.Process().open_files())
```
prints out
`[popenfile(path='/path/to/foo.tar', fd=4, position=4096, mode='r', flags=557056)]`
This has been observed on at least zip and tar filesystems, and lead to filling up our harddrives very quicky on our servers...
|
0.0
|
22b2c5960cc2685acf4e691551150516856bd65f
|
[
"fsspec/implementations/tests/test_zip.py::test_not_cached"
] |
[
"fsspec/implementations/tests/test_zip.py::test_info",
"fsspec/implementations/tests/test_zip.py::test_fsspec_get_mapper"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-05-16 17:55:37+00:00
|
bsd-3-clause
| 2,427 |
|
fsspec__filesystem_spec-996
|
diff --git a/.github/workflows/main.yaml b/.github/workflows/main.yaml
index 3044529..af54daa 100644
--- a/.github/workflows/main.yaml
+++ b/.github/workflows/main.yaml
@@ -13,7 +13,7 @@ jobs:
strategy:
fail-fast: false
matrix:
- TOXENV: [py37, py38, py39, s3fs, gcsfs]
+ TOXENV: [py38, py39, py310, s3fs, gcsfs]
env:
TOXENV: ${{ matrix.TOXENV }}
@@ -42,7 +42,7 @@ jobs:
strategy:
fail-fast: false
matrix:
- TOXENV: [py38]
+ TOXENV: [py39]
env:
TOXENV: ${{ matrix.TOXENV }}
diff --git a/fsspec/archive.py b/fsspec/archive.py
index f83d040..07d169e 100644
--- a/fsspec/archive.py
+++ b/fsspec/archive.py
@@ -34,6 +34,8 @@ class AbstractArchiveFileSystem(AbstractFileSystem):
def info(self, path, **kwargs):
self._get_dirs()
path = self._strip_protocol(path)
+ if path in {"", "/"} and self.dir_cache:
+ return {"name": "/", "type": "directory", "size": 0}
if path in self.dir_cache:
return self.dir_cache[path]
elif path + "/" in self.dir_cache:
diff --git a/tox.ini b/tox.ini
index e33159c..09abb6c 100644
--- a/tox.ini
+++ b/tox.ini
@@ -1,6 +1,6 @@
# content of: tox.ini , put in same dir as setup.py
[tox]
-envlist = {py37,py38,py39}
+envlist = {py38,py39,py310}
[core]
conda_channels=
@@ -41,7 +41,6 @@ conda_deps=
deps=
hadoop-test-cluster==0.1.0
smbprotocol
- py37: importlib_metadata
[testenv]
description=Run test suite against target versions.
|
fsspec/filesystem_spec
|
b5b7429403447b058147f4c2528259131da064b8
|
diff --git a/fsspec/implementations/tests/test_zip.py b/fsspec/implementations/tests/test_zip.py
index 0aab4a2..6be4013 100644
--- a/fsspec/implementations/tests/test_zip.py
+++ b/fsspec/implementations/tests/test_zip.py
@@ -39,3 +39,10 @@ def test_not_cached():
fs = fsspec.filesystem("zip", fo=z)
fs2 = fsspec.filesystem("zip", fo=z)
assert fs is not fs2
+
+
+def test_root_info():
+ with tempzip(archive_data) as z:
+ fs = fsspec.filesystem("zip", fo=z)
+ assert fs.info("/") == {"name": "/", "type": "directory", "size": 0}
+ assert fs.info("") == {"name": "/", "type": "directory", "size": 0}
|
info('/') doesn't seem to match ls('/') -- zip+http archive
Hi, I notice that the info method doesn't seem to be behaving as I would have expected expected (["returns a single dictionary, with exactly the same information as ``ls`` would with ``detail=True``."](https://github.com/fsspec/filesystem_spec/blob/b5b7429403447b058147f4c2528259131da064b8/fsspec/spec.py#L586)) with either 'zip' or 'libarchive' as shown below. Ultimately, I'm trying to leverage pyarrow's dataset via pyarrow's FSSpecHandler, the latter of which [calls fsspec.info('/')](https://github.com/apache/arrow/blob/7b5912deea1c0fc8e2ac801b99d2448f387fa98e/python/pyarrow/fs.py#L314) and returns FileNotFoundError in this case.
Is the below expected, or is a change needed so that info() on the root path returns the root file list, assuming that's reasonable?
Thank you!
```python
#!/usr/bin/env python3
import fsspec
sample_file = (
"https://firstratedata.com/_data/_deploy/stocks-complete_bundle_sample.zip"
)
fsspec_fs = fsspec.filesystem("zip", fo=fsspec.open(sample_file))
fsspec_fs.ls("/")
# [
# "AAPL_1hour_sample.txt",
# "AAPL_1min_sample.txt",
# "AAPL_30min_sample.txt",
# "AAPL_5min_sample.txt",
# ...
# ]
fsspec_fs.info("/")
# Traceback (most recent call last):
# File "/fsspec_test.py", line 31, in <module>
# fsspec_fs.info("/")
# File "/.pyenv/versions/3.8.2/lib/python3.8/site-packages/fsspec/archive.py", line 44, in info
# raise FileNotFoundError(path)
# FileNotFoundError
```
|
0.0
|
b5b7429403447b058147f4c2528259131da064b8
|
[
"fsspec/implementations/tests/test_zip.py::test_root_info"
] |
[
"fsspec/implementations/tests/test_zip.py::test_info",
"fsspec/implementations/tests/test_zip.py::test_fsspec_get_mapper",
"fsspec/implementations/tests/test_zip.py::test_not_cached"
] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-07-25 17:55:32+00:00
|
bsd-3-clause
| 2,428 |
|
ftao__python-ifcfg-22
|
diff --git a/src/ifcfg/cli.py b/src/ifcfg/cli.py
index a489f28..fe48138 100644
--- a/src/ifcfg/cli.py
+++ b/src/ifcfg/cli.py
@@ -1,9 +1,12 @@
-import ifcfg
+from __future__ import print_function
+
import json
+import ifcfg
+
def main():
- print json.dumps(ifcfg.interfaces(), indent=2)
+ print(json.dumps(ifcfg.interfaces(), indent=2))
if __name__ == "__main__":
|
ftao/python-ifcfg
|
4825b285f92b570f2fc9e975dda1798fdcc1199c
|
diff --git a/tests/cli_tests.py b/tests/cli_tests.py
new file mode 100644
index 0000000..3146025
--- /dev/null
+++ b/tests/cli_tests.py
@@ -0,0 +1,5 @@
+from ifcfg import cli
+
+
+def test_cli():
+ cli.main()
|
Python 2 syntax in `cli.py`
A `print` statement has entered the codebase!
|
0.0
|
4825b285f92b570f2fc9e975dda1798fdcc1199c
|
[
"tests/cli_tests.py::test_cli"
] |
[] |
{
"failed_lite_validators": [
"has_short_problem_statement"
],
"has_test_patch": true,
"is_lite": false
}
|
2018-02-02 13:22:00+00:00
|
bsd-3-clause
| 2,429 |
|
fuhrysteve__marshmallow-jsonschema-151
|
diff --git a/marshmallow_jsonschema/base.py b/marshmallow_jsonschema/base.py
index 55c0360..a8fb726 100644
--- a/marshmallow_jsonschema/base.py
+++ b/marshmallow_jsonschema/base.py
@@ -187,7 +187,7 @@ class JSONSchema(Schema):
if field.dump_only:
json_schema["readOnly"] = True
- if field.default is not missing:
+ if field.default is not missing and not callable(field.default):
json_schema["default"] = field.default
if ALLOW_ENUMS and isinstance(field, EnumField):
@@ -324,6 +324,9 @@ class JSONSchema(Schema):
continue
schema[md_key] = md_val
+ if field.default is not missing and not callable(field.default):
+ schema["default"] = nested_instance.dump(field.default)
+
if field.many:
schema = {
"type": "array" if field.required else ["array", "null"],
|
fuhrysteve/marshmallow-jsonschema
|
05fe2f57466ad7a3144ce46c88793ea5fad4b2e1
|
diff --git a/tests/test_dump.py b/tests/test_dump.py
index e862491..ca3f316 100644
--- a/tests/test_dump.py
+++ b/tests/test_dump.py
@@ -1,3 +1,4 @@
+import uuid
from enum import Enum
import pytest
@@ -30,6 +31,18 @@ def test_default():
assert props["id"]["default"] == "no-id"
+def test_default_callable_not_serialized():
+ class TestSchema(Schema):
+ uid = fields.UUID(default=uuid.uuid4)
+
+ schema = TestSchema()
+
+ dumped = validate_and_dump(schema)
+
+ props = dumped["definitions"]["TestSchema"]["properties"]
+ assert "default" not in props["uid"]
+
+
def test_uuid():
schema = UserSchema()
@@ -307,6 +320,26 @@ def test_respect_dotted_exclude_for_nested_schema():
assert "recursive" not in inner_props
+def test_respect_default_for_nested_schema():
+ class TestNestedSchema(Schema):
+ myfield = fields.String()
+ yourfield = fields.Integer(required=True)
+
+ nested_default = {"myfield": "myval", "yourfield": 1}
+
+ class TestSchema(Schema):
+ nested = fields.Nested(
+ TestNestedSchema,
+ default=nested_default,
+ )
+ yourfield_nested = fields.Integer(required=True)
+
+ schema = TestSchema()
+ dumped = validate_and_dump(schema)
+ default = dumped["definitions"]["TestSchema"]["properties"]["nested"]["default"]
+ assert default == nested_default
+
+
def test_nested_instance():
"""Should also work with nested schema instances"""
|
Default field values may be callable
When building the json schema from a marshmallow schema, with a default value being a callable, the resulting schema is not clean to pass to `json.dumps()` for instance.
https://github.com/fuhrysteve/marshmallow-jsonschema/blob/8e70c7e3262eb5ce8a34462e9ebbc08b90201afb/marshmallow_jsonschema/base.py#L191
Example
```python
import json
import uuid
from marshmallow import Schema, fields
from marshmallow_jsonschema import JSONSchema
class Test(Schema):
id = fields.UUID(default=uuid.uuid1)
json.dumps(JSONSchema().dump(Test()))
# >> TypeError: Object of type function is not JSON serializable
# JSONSchema().dump(Test()) >>
{'$schema': 'http://json-schema.org/draft-07/schema#',
'definitions': {'Test': {'properties': {'id': {'title': 'id',
'type': 'string',
'default': <function uuid.uuid1(node=None, clock_seq=None)>}},
'type': 'object',
'additionalProperties': False}},
'$ref': '#/definitions/Test'}
```
Both `missing` and `default` may be callable values for marshmallow fields: https://marshmallow.readthedocs.io/en/stable/marshmallow.fields.html#marshmallow.fields.Field
|
0.0
|
05fe2f57466ad7a3144ce46c88793ea5fad4b2e1
|
[
"tests/test_dump.py::test_default_callable_not_serialized",
"tests/test_dump.py::test_respect_default_for_nested_schema"
] |
[
"tests/test_dump.py::test_respect_only_for_nested_schema",
"tests/test_dump.py::test_field_subclass",
"tests/test_dump.py::test_datetime_based",
"tests/test_dump.py::test_enum_based",
"tests/test_dump.py::test_list_nested",
"tests/test_dump.py::test_sorting_properties",
"tests/test_dump.py::test_metadata_direct_from_field",
"tests/test_dump.py::test_uuid",
"tests/test_dump.py::test_dict",
"tests/test_dump.py::test_allow_none",
"tests/test_dump.py::test_readonly",
"tests/test_dump.py::test_required_excluded_when_empty",
"tests/test_dump.py::test_unknown_typed_field",
"tests/test_dump.py::test_enum_based_load_dump_value",
"tests/test_dump.py::test_list",
"tests/test_dump.py::test_required_uses_data_key",
"tests/test_dump.py::test_descriptions",
"tests/test_dump.py::test_dumps_iterable_enums",
"tests/test_dump.py::test_dict_with_nested_value_field",
"tests/test_dump.py::test_unknown_typed_field_throws_valueerror",
"tests/test_dump.py::test_default",
"tests/test_dump.py::test_respect_dotted_exclude_for_nested_schema",
"tests/test_dump.py::test_dict_with_value_field",
"tests/test_dump.py::test_nested_string_to_cls",
"tests/test_dump.py::test_title",
"tests/test_dump.py::test_deep_nested",
"tests/test_dump.py::test_dump_schema",
"tests/test_dump.py::test_function",
"tests/test_dump.py::test_union_based",
"tests/test_dump.py::test_respect_exclude_for_nested_schema",
"tests/test_dump.py::test_nested_instance",
"tests/test_dump.py::test_nested_recursive",
"tests/test_dump.py::test_metadata",
"tests/test_dump.py::test_nested_descriptions"
] |
{
"failed_lite_validators": [
"has_hyperlinks"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-06-02 09:23:00+00:00
|
mit
| 2,430 |
|
fullflu__pydtr-9
|
diff --git a/README.md b/README.md
index 0210681..76d80b4 100644
--- a/README.md
+++ b/README.md
@@ -15,7 +15,7 @@ Pydtr enables you to implement DTR methods easily by using sklearn-based interfa
| Method | Single binary treatment | Multiple treatments | Multinomial treatment | Continuous Treatment |
| ---- | ---- | ---- | ---- | ---- |
-| IqLearnReg <br> (with sklearn) | :white_check_mark: | :white_check_mark: | :white_check_mark: <br>(with ordinal encoded treatment) |
+| IqLearnReg <br> (with sklearn) | :white_check_mark: | :white_check_mark: | :white_check_mark: <br>(with pipeline) |
| IqLearnReg <br> (with statsmodels) | :white_check_mark: | :white_check_mark: | :white_check_mark: |
| GEstimation | WIP | | WIP | WIP |
@@ -25,21 +25,37 @@ When a treatment variable is multinomial and you use a sklearn model as a regres
G-estimation, a famous method of DTR, is now unavailable.
-## Requirement
+## Requirements
-- python (>= 3.6)
-- pip
+- python>=3.6
+- pandas>=1.1.2
+- scikit-learn>=0.23.2
+- numpy>=1.19.2
+- statsmodels>=0.12.0
-## Install
+## Installation
-`pip install pydtr`
+### From pypi
+
+```
+pip install pydtr
+```
+
+### From source
+
+```
+git clone https://github.com/fullflu/pydtr.git
+cd pydtr
+python setup.py install
+```
## Usage
### Iterative Q Learning (IqLearnReg)
You need to import libraries and prepare data.
-```
+
+```python
# import
import numpy as np
import pandas as pd
@@ -59,7 +75,8 @@ df["Y2"] = np.zeros(n)
```
You can use sklearn-based models.
-```
+
+```python
# set model info
model_info = [
{
@@ -89,7 +106,8 @@ opt_action_all_stages = dtr_model.predict_all_stages(df)
```
You can also use statsmodels-based models.
-```
+
+```python
# set model info
model_info = [
{
@@ -160,4 +178,4 @@ If all checkes have passed in pull-requests, I will merge and release them.
## References
-- Chakraborty, Bibhas. *Statistical methods for dynamic treatment regimes.* Springer, 2013.
+- Chakraborty, B, Moodie, EE. *Statistical Methods for Dynamic Treatment Regimes.* Springer, New York, 2013.
diff --git a/src/pydtr/iqlearn/base.py b/src/pydtr/iqlearn/base.py
index 52ca6e7..d08901d 100644
--- a/src/pydtr/iqlearn/base.py
+++ b/src/pydtr/iqlearn/base.py
@@ -6,7 +6,6 @@ from abc import ABCMeta, abstractmethod
import pandas as pd
import numpy as np
from sklearn.utils import resample
-from sklearn.utils.estimator_checks import check_estimator
class IqLearnBase(object):
@@ -103,10 +102,6 @@ class IqLearnBase(object):
size_bs = df.shape[0]
return resample(df, n_samples=size_bs)
- @staticmethod
- def _check_model_type(model):
- assert type(model) == str or check_estimator(model)
-
def fit(self, df: pd.DataFrame):
"""
Fit dtr models
@@ -136,16 +131,15 @@ class IqLearnBase(object):
# fit models using bootstrap
for i in range(self.n_bs):
df_i = self._sample_bs(df)
- print("{}th bootstrap".format(i))
for t in reversed(range(self.n_stages)):
# extract feature and outcome
- X = df[self.model_info[t]["feature"]]
- y = df[self.model_info[t]["outcome"]]
+ X = df_i[self.model_info[t]["feature"]]
+ y = df_i[self.model_info[t]["outcome"]]
if t == self.n_stages - 1:
p_outcome = y.values
else:
- X2 = df[self.model_info[t + 1]["feature"]]
- y2 = df[self.model_info[t + 1]["outcome"]]
+ X2 = df_i[self.model_info[t + 1]["feature"]]
+ y2 = df_i[self.model_info[t + 1]["outcome"]]
p_outcome = self._get_p_outcome(self.model_all[t + 1], X2, y2, t)
# fit model of stage t
self._fit_model(X, p_outcome, t, i)
@@ -172,9 +166,9 @@ class IqLearnBase(object):
def get_params(self) -> pd.DataFrame:
# get estimated parameters
params = pd.DataFrame()
- for t, m in enumerate(self.models[:-1]):
+ for t in reversed(range(self.n_stages)):
if type(self.model_info[t]["model"]) == str:
- tmp_df = pd.melt(pd.DataFrame([i.params for i in m]))
+ tmp_df = pd.melt(pd.DataFrame([i.params for i in self.models[t]]))
tmp_df["stage"] = t
params = pd.concat([params, tmp_df])
return params
diff --git a/src/pydtr/version.py b/src/pydtr/version.py
index f102a9c..3b93d0b 100644
--- a/src/pydtr/version.py
+++ b/src/pydtr/version.py
@@ -1,1 +1,1 @@
-__version__ = "0.0.1"
+__version__ = "0.0.2"
|
fullflu/pydtr
|
13d59092b7e3d289945611b27951e3011a9d3beb
|
diff --git a/tests/test_iqlearn_sklearn_predict.py b/tests/test_iqlearn_sklearn_predict.py
index faec86e..e8b822c 100644
--- a/tests/test_iqlearn_sklearn_predict.py
+++ b/tests/test_iqlearn_sklearn_predict.py
@@ -114,11 +114,11 @@ def test_iqlearn_regwrapper_rule():
assert len(dtr_model.models[0]) == 2
-def test_iqlearn_regwrapper_rf():
+def test_iqlearn_rf():
# setup params
n = 10
thres = int(n / 2)
- # sample rule base models
+ # rf models
model1 = RandomForestRegressor()
model2 = RandomForestRegressor()
# sample dataframe
@@ -143,7 +143,7 @@ def test_iqlearn_regwrapper_rf():
"outcome": "Y2"
}
]
- # fit model (dummy)
+ # fit model
dtr_model = IqLearnReg(
n_stages=2,
model_info=model_info
@@ -163,7 +163,7 @@ def test_iqlearn_regwrapper_rf():
a2 = action_all.query("stage == 1")[["A2", "val"]].reset_index(drop=True)
assert_frame_equal(action_1, a1)
assert_frame_equal(action_2, a2)
- # fit bootstrap model (dummy)
+ # fit bootstrap model
dtr_model = IqLearnReg(
n_stages=2,
model_info=model_info,
@@ -177,7 +177,7 @@ def test_iqlearn_regwrapper_rf_multiple_actions():
# setup params
n = 10
thres = int(n / 2)
- # sample rule base models
+ # rf models
model1 = RandomForestRegressor()
model2 = RandomForestRegressor()
# sample dataframe
@@ -202,7 +202,7 @@ def test_iqlearn_regwrapper_rf_multiple_actions():
"outcome": "Y2"
}
]
- # fit model (dummy)
+ # fit model
dtr_model = IqLearnReg(
n_stages=2,
model_info=model_info
@@ -222,7 +222,7 @@ def test_iqlearn_regwrapper_rf_multiple_actions():
a2 = action_all.query("stage == 1")[["A1", "A2", "val"]].reset_index(drop=True)
assert_frame_equal(action_1, a1)
assert_frame_equal(action_2, a2)
- # fit bootstrap model (dummy)
+ # fit bootstrap model
dtr_model = IqLearnReg(
n_stages=2,
model_info=model_info,
@@ -236,7 +236,7 @@ def test_iqlearn_regwrapper_rf_ordinalencoder():
# setup params
n = 30
thres = int(n / 2)
- # sample rule base models
+ # rf models
model1 = RandomForestRegressor()
model2 = RandomForestRegressor()
# sample dataframe
@@ -261,7 +261,7 @@ def test_iqlearn_regwrapper_rf_ordinalencoder():
"outcome": "Y2"
}
]
- # fit model (dummy)
+ # fit model
dtr_model = IqLearnReg(
n_stages=2,
model_info=model_info
@@ -281,7 +281,7 @@ def test_iqlearn_regwrapper_rf_ordinalencoder():
a2 = action_all.query("stage == 1")[["A2", "val"]].reset_index(drop=True)
assert_frame_equal(action_1, a1)
assert_frame_equal(action_2, a2)
- # fit bootstrap model (dummy)
+ # fit bootstrap model
dtr_model = IqLearnReg(
n_stages=2,
model_info=model_info,
diff --git a/tests/test_iqlearn_sm_predict.py b/tests/test_iqlearn_sm_predict.py
index 448ab14..64dfc73 100644
--- a/tests/test_iqlearn_sm_predict.py
+++ b/tests/test_iqlearn_sm_predict.py
@@ -10,7 +10,7 @@ def test_iqlearn_sm():
# setup params
n = 10
thres = int(n / 2)
- # sample rule base models
+ # statsmodels
model1 = "p_outcome ~ L1 * A1"
model2 = "p_outcome ~ L1 + A1 + Y1 * A2"
# sample dataframe
@@ -35,7 +35,7 @@ def test_iqlearn_sm():
"outcome": "Y2"
}
]
- # fit model (dummy)
+ # fit model
dtr_model = IqLearnReg(
n_stages=2,
model_info=model_info
@@ -55,7 +55,7 @@ def test_iqlearn_sm():
a2 = action_all.query("stage == 1")[["A2", "val"]].reset_index(drop=True)
assert_frame_equal(action_1, a1)
assert_frame_equal(action_2, a2)
- # fit bootstrap model (dummy)
+ # fit bootstrap model
dtr_model = IqLearnReg(
n_stages=2,
model_info=model_info,
@@ -69,7 +69,7 @@ def test_iqlearn_sm_multiple_actions():
# setup params
n = 10
thres = int(n / 2)
- # sample rule base models
+ # statsmodels
model1 = "p_outcome ~ L1 * A1"
model2 = "p_outcome ~ L1 + A1 + Y1 * A2"
# sample dataframe
@@ -94,7 +94,7 @@ def test_iqlearn_sm_multiple_actions():
"outcome": "Y2"
}
]
- # fit model (dummy)
+ # fit model
dtr_model = IqLearnReg(
n_stages=2,
model_info=model_info
@@ -114,7 +114,7 @@ def test_iqlearn_sm_multiple_actions():
a2 = action_all.query("stage == 1")[["A1", "A2", "val"]].reset_index(drop=True)
assert_frame_equal(action_1, a1)
assert_frame_equal(action_2, a2)
- # fit bootstrap model (dummy)
+ # fit bootstrap model
dtr_model = IqLearnReg(
n_stages=2,
model_info=model_info,
@@ -128,7 +128,7 @@ def test_iqlearn_sm_multinomial_action():
# setup params
n = 30
thres = int(n / 2)
- # sample rule base models
+ # statsmodels
model1 = "p_outcome ~ L1 * C(A1)"
model2 = "p_outcome ~ L1 + A1 + Y1 * C(A2)"
# sample dataframe
@@ -153,7 +153,7 @@ def test_iqlearn_sm_multinomial_action():
"outcome": "Y2"
}
]
- # fit model (dummy)
+ # fit model
dtr_model = IqLearnReg(
n_stages=2,
model_info=model_info
@@ -173,7 +173,7 @@ def test_iqlearn_sm_multinomial_action():
a2 = action_all.query("stage == 1")[["A2", "val"]].reset_index(drop=True)
assert_frame_equal(action_1, a1)
assert_frame_equal(action_2, a2)
- # fit bootstrap model (dummy)
+ # fit bootstrap model
dtr_model = IqLearnReg(
n_stages=2,
model_info=model_info,
@@ -181,3 +181,48 @@ def test_iqlearn_sm_multinomial_action():
)
dtr_model.fit(df)
assert len(dtr_model.models[0]) == 2
+
+
+def test_iqlearn_sm_get_params():
+ # setup params
+ n = 300
+ thres = int(n / 2)
+ # statsmodels
+ model1 = "p_outcome ~ L1 * A1"
+ model2 = "p_outcome ~ L1 + A1 + Y1 * A2"
+ # sample dataframe
+ df = pd.DataFrame()
+ df["L1"] = np.random.normal(0, size=n)
+ df["A1"] = [0, 1] * int(n / 2)
+ df["A2"] = [0] * int(n / 2) + [1] * int(n / 2)
+ df["Y1"] = df["L1"] * df["A1"] + np.random.normal(0, scale=5, size=n)
+ df["Y2"] = df["A1"] + df["Y1"] * df["A2"] + np.random.normal(0, scale=5, size=n)
+ # set model info
+ model_info = [
+ {
+ "model": model1,
+ "action_dict": {"A1": [0, 1]},
+ "feature": ["L1", "A1"],
+ "outcome": "Y1"
+ },
+ {
+ "model": model2,
+ "action_dict": {"A1": [0, 1], "A2": [0, 1]},
+ "feature": ["L1", "A1", "Y1", "A2"],
+ "outcome": "Y2"
+ }
+ ]
+ # fit bootstrap model
+ dtr_model = IqLearnReg(
+ n_stages=2,
+ model_info=model_info,
+ n_bs=10
+ )
+ dtr_model.fit(df)
+ # get params
+ params = dtr_model.get_params()
+ l1_unique_shape = params.query("stage == 0 & variable == 'L1'")["value"].unique().shape[0]
+ a1_unique_shape = params.query("stage == 0 & variable == 'A1'")["value"].unique().shape[0]
+ a2_unique_shape = params.query("stage == 1 & variable == 'A2'")["value"].unique().shape[0]
+ assert l1_unique_shape != 1 or a1_unique_shape != 1 or a2_unique_shape != 1
+ assert len(dtr_model.models[0]) == 10
|
fix get_params
# WHY
There is a bug in the `get_params` method (`self.models` cannot be sliced) :
```
for t, m in enumerate(self.models[:-1]): <-
```
# TODO
- [ ] fix the function
- [ ] add tests of the function
|
0.0
|
13d59092b7e3d289945611b27951e3011a9d3beb
|
[
"tests/test_iqlearn_sm_predict.py::test_iqlearn_sm_get_params"
] |
[
"tests/test_iqlearn_sklearn_predict.py::test_iqlearn_regwrapper_rule",
"tests/test_iqlearn_sklearn_predict.py::test_iqlearn_rf",
"tests/test_iqlearn_sklearn_predict.py::test_iqlearn_regwrapper_rf_multiple_actions",
"tests/test_iqlearn_sklearn_predict.py::test_iqlearn_regwrapper_rf_ordinalencoder",
"tests/test_iqlearn_sm_predict.py::test_iqlearn_sm",
"tests/test_iqlearn_sm_predict.py::test_iqlearn_sm_multiple_actions",
"tests/test_iqlearn_sm_predict.py::test_iqlearn_sm_multinomial_action"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-10-24 10:42:12+00:00
|
bsd-3-clause
| 2,431 |
|
gahjelle__pyplugs-29
|
diff --git a/pyplugs/_plugins.py b/pyplugs/_plugins.py
index ca0d4d1..38f4434 100644
--- a/pyplugs/_plugins.py
+++ b/pyplugs/_plugins.py
@@ -141,7 +141,7 @@ def exists(package: str, plugin: str) -> bool:
try:
_import(package, plugin)
- except _exceptions.UnknownPluginError:
+ except (_exceptions.UnknownPluginError, _exceptions.UnknownPackageError):
return False
else:
return package in _PLUGINS and plugin in _PLUGINS[package]
@@ -175,6 +175,10 @@ def _import(package: str, plugin: str) -> None:
raise _exceptions.UnknownPluginError(
f"Plugin {plugin!r} not found in {package!r}"
) from None
+ elif repr(package) in err.msg: # type: ignore
+ raise _exceptions.UnknownPackageError(
+ f"Package {package!r} does not exist"
+ ) from None
raise
|
gahjelle/pyplugs
|
bd98efd851c820c6bc89e2b8b73f49956ddceb36
|
diff --git a/tests/test_plugins.py b/tests/test_plugins.py
index 35e6f7d..82aea8b 100644
--- a/tests/test_plugins.py
+++ b/tests/test_plugins.py
@@ -81,6 +81,12 @@ def test_exists(plugin_package):
assert pyplugs.exists(plugin_package, "non_existent") is False
+def test_exists_on_non_existing_package():
+ """Test that exists() correctly returns False for non-existing packages"""
+ assert pyplugs.exists("non_existent_package", "plugin_parts") is False
+ assert pyplugs.exists("non_existent_package", "non_existent") is False
+
+
def test_call_existing_plugin(plugin_package):
"""Test that calling a test-plugin works, and returns a string"""
plugin_name = pyplugs.names(plugin_package)[0]
|
`.exists()` crashes for non-existing packages
When using `pyplugs.exists()` with a package that doesn't exist, `pyplugs` crashes instead of returning `False`
|
0.0
|
bd98efd851c820c6bc89e2b8b73f49956ddceb36
|
[
"tests/test_plugins.py::test_exists_on_non_existing_package"
] |
[
"tests/test_plugins.py::test_package_not_empty",
"tests/test_plugins.py::test_package_empty",
"tests/test_plugins.py::test_list_funcs",
"tests/test_plugins.py::test_package_non_existing",
"tests/test_plugins.py::test_plugin_exists",
"tests/test_plugins.py::test_plugin_not_exists[no_plugins]",
"tests/test_plugins.py::test_plugin_not_exists[non_existent]",
"tests/test_plugins.py::test_exists",
"tests/test_plugins.py::test_call_existing_plugin",
"tests/test_plugins.py::test_call_non_existing_plugin",
"tests/test_plugins.py::test_ordered_plugin",
"tests/test_plugins.py::test_default_part",
"tests/test_plugins.py::test_call_non_existing_func",
"tests/test_plugins.py::test_short_doc",
"tests/test_plugins.py::test_long_doc",
"tests/test_plugins.py::test_names_factory",
"tests/test_plugins.py::test_funcs_factory",
"tests/test_plugins.py::test_info_factory",
"tests/test_plugins.py::test_exists_factory",
"tests/test_plugins.py::test_get_factory",
"tests/test_plugins.py::test_call_factory"
] |
{
"failed_lite_validators": [
"has_short_problem_statement"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-04-18 09:58:01+00:00
|
mit
| 2,432 |
|
gammapy__gammapy-5149
|
diff --git a/gammapy/estimators/points/sensitivity.py b/gammapy/estimators/points/sensitivity.py
index f072a7dc6..3c2730f59 100644
--- a/gammapy/estimators/points/sensitivity.py
+++ b/gammapy/estimators/points/sensitivity.py
@@ -1,5 +1,4 @@
# Licensed under a 3-clause BSD style license - see LICENSE.rst
-import logging
import numpy as np
from astropy.table import Column, Table
from gammapy.maps import Map
@@ -140,18 +139,9 @@ class SensitivityEstimator(Estimator):
criterion = self._get_criterion(
excess.data.squeeze(), dataset.background.data.squeeze()
)
- logging.warning(
- "Table column name energy will be deprecated by e_ref since v1.2"
- )
return Table(
[
- Column(
- data=energy,
- name="energy",
- format="5g",
- description="Reconstructed Energy",
- ),
Column(
data=energy,
name="e_ref",
diff --git a/gammapy/makers/safe.py b/gammapy/makers/safe.py
index 09c381c9f..73d9b60b8 100644
--- a/gammapy/makers/safe.py
+++ b/gammapy/makers/safe.py
@@ -62,7 +62,7 @@ class SafeMaskMaker(Maker):
def __init__(
self,
- methods=("aeff-default",),
+ methods=["aeff-default"],
aeff_percent=10,
bias_percent=10,
position=None,
|
gammapy/gammapy
|
fdd05df7453c294a8a898e7f790a0da17372f9d2
|
diff --git a/gammapy/estimators/points/tests/test_sensitivity.py b/gammapy/estimators/points/tests/test_sensitivity.py
index 3d90b2166..926b2bf18 100644
--- a/gammapy/estimators/points/tests/test_sensitivity.py
+++ b/gammapy/estimators/points/tests/test_sensitivity.py
@@ -41,15 +41,8 @@ def test_cta_sensitivity_estimator(spectrum_dataset, caplog):
sens = SensitivityEstimator(gamma_min=25, bkg_syst_fraction=0.075)
table = sens.run(dataset_on_off)
- warning_message = (
- "Table column name energy will be " "deprecated by e_ref since v1.2"
- )
- assert "WARNING" in [_.levelname for _ in caplog.records]
- assert warning_message in [_.message for _ in caplog.records]
-
assert len(table) == 4
assert table.colnames == [
- "energy",
"e_ref",
"e_min",
"e_max",
@@ -98,10 +91,6 @@ def test_integral_estimation(spectrum_dataset, caplog):
flux_points = FluxPoints.from_table(
table, sed_type="e2dnde", reference_model=sens.spectrum
)
- assert "WARNING" in [_.levelname for _ in caplog.records]
- assert "Table column name energy will be deprecated by e_ref since v1.2" in [
- _.message for _ in caplog.records
- ]
assert_allclose(table["excess"].data.squeeze(), 270540, rtol=1e-3)
assert_allclose(flux_points.flux.data.squeeze(), 7.52e-9, rtol=1e-3)
|
Strange warning when running the `SensitivityEstimator`
**Gammapy version**
Current main:
```
Gammapy support for parallelisation with ray is still a prototype and is not fully functional.
System:
python_executable : /home/maxnoe/.local/conda/envs/gammapy-dev/bin/python3.9
python_version : 3.9.16
machine : x86_64
system : Linux
Gammapy package:
version : 1.2.dev201+g514451881.d20230627
path : /home/maxnoe/Projects/gammapy/gammapy
Other packages:
numpy : 1.25.0
scipy : 1.11.0
astropy : 5.3
regions : 0.7
click : 8.1.3
yaml : 6.0
IPython : 8.14.0
jupyterlab : 3.5.3
matplotlib : 3.7.1
pandas : 2.0.2
healpy : 1.16.2
iminuit : 2.22.0
sherpa : 4.15.1
naima : 0.10.0
emcee : 3.1.4
corner : 2.2.2
ray : 2.5.1
Gammapy environment variables:
GAMMAPY_DATA : /home/maxnoe/Projects/gammapy/gammapy-datasets/dev
```
**Bug description**
There is a warning I don't understand and that seems to be outside of my control and also is at least worded a bit strangely when running the `SensitivityEstimator`.
I guess this should also be a `GammapyDeprecationWarning` and not using the logging system.
> Table column name energy will be deprecated by e_ref since v1.2
What is the intention here? Will the `energy` column be removed? Would a better message then be:
> The column "energy" is deprecated as of Gammapy 1.x and will be removed in Gammapy 1.y. Use the `e_ref` column instead
?
|
0.0
|
fdd05df7453c294a8a898e7f790a0da17372f9d2
|
[
"gammapy/estimators/points/tests/test_sensitivity.py::test_cta_sensitivity_estimator"
] |
[
"gammapy/estimators/points/tests/test_sensitivity.py::test_integral_estimation"
] |
{
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2024-03-05 11:30:20+00:00
|
bsd-3-clause
| 2,433 |
|
garcia__simfile-29
|
diff --git a/simfile/__init__.py b/simfile/__init__.py
index 37dc0ea..431cd21 100644
--- a/simfile/__init__.py
+++ b/simfile/__init__.py
@@ -22,7 +22,7 @@ from .sm import SMSimfile
from .types import Simfile
-__version__ = "2.1.0"
+__version__ = "2.1.1"
__all__ = [
"load",
"loads",
diff --git a/simfile/ssc.py b/simfile/ssc.py
index 7b3d5e0..400e4e6 100644
--- a/simfile/ssc.py
+++ b/simfile/ssc.py
@@ -99,20 +99,28 @@ class SSCChart(BaseChart):
raise ValueError("expected NOTEDATA property first")
for param in iterator:
- self[param.key] = param.value
+ if param.key in BaseSimfile.MULTI_VALUE_PROPERTIES:
+ self[param.key] = ":".join(param.components[1:])
+ else:
+ self[param.key] = param.value
if param.value is self.notes:
break
def serialize(self, file):
file.write(f"{MSDParameter(('NOTEDATA', ''))}\n")
notes_key = "NOTES"
+
for (key, value) in self.items():
- # notes must always be the last property in a chart
+ # Either NOTES or NOTES2 must be the last chart property
if value is self.notes:
notes_key = key
continue
- param = MSDParameter((key, value))
+ if key in BaseSimfile.MULTI_VALUE_PROPERTIES:
+ param = MSDParameter((key, *value.split(":")))
+ else:
+ param = MSDParameter((key, value))
file.write(f"{param}\n")
+
notes_param = MSDParameter((notes_key, self[notes_key]))
file.write(f"{notes_param}\n\n")
@@ -208,7 +216,7 @@ class SSCSimfile(BaseSimfile):
partial_chart: Optional[SSCChart] = None
for param in parser:
key = param.key.upper()
- if key not in BaseSimfile.MULTI_VALUE_PROPERTIES:
+ if key in BaseSimfile.MULTI_VALUE_PROPERTIES:
value: Optional[str] = ":".join(param.components[1:])
else:
value = param.value
|
garcia/simfile
|
46074d9b9ce14089f9c0c05ed20772748fcb810f
|
diff --git a/simfile/tests/test_sm.py b/simfile/tests/test_sm.py
index 8461af0..87929e9 100644
--- a/simfile/tests/test_sm.py
+++ b/simfile/tests/test_sm.py
@@ -159,6 +159,20 @@ class TestSMSimfile(unittest.TestCase):
self.assertEqual(with_bgchanges.bgchanges, with_animations.bgchanges)
self.assertNotIn("BGCHANGES", with_animations)
self.assertIn("ANIMATIONS", with_animations)
+
+ def test_init_handles_multi_value_properties(self):
+ with_multi_value_properties = SMSimfile(string='''
+ #TITLE:Colons should be preserved below: but not here;
+ #DISPLAYBPM:60:240;
+ #ATTACKS:TIME=1.000:LEN=0.500:MODS=*5 -2.5 reverse;
+ ''')
+ self.assertEqual('Colons should be preserved below', with_multi_value_properties.title)
+ self.assertEqual('60:240', with_multi_value_properties.displaybpm)
+ self.assertEqual(
+ 'TIME=1.000:LEN=0.500:MODS=*5 -2.5 reverse',
+ with_multi_value_properties.attacks,
+ )
+
def test_repr(self):
unit = SMSimfile(string=testing_simfile())
@@ -198,3 +212,19 @@ class TestSMSimfile(unittest.TestCase):
unit.charts = SMCharts()
self.assertEqual(0, len(unit.charts))
+
+ def test_serialize_handles_multi_value_properties(self):
+ expected = SMSimfile(string='''
+ #TITLE:Colons should be preserved below;
+ #DISPLAYBPM:60:240;
+ #ATTACKS:TIME=1.000:LEN=0.500:MODS=*5 -2.5 reverse;
+ ''')
+
+ # None of the colons should be escaped
+ serialized = str(expected)
+ self.assertNotIn('\\', serialized)
+
+ deserialized = SMSimfile(string=serialized)
+ self.assertEqual(expected.title, deserialized.title)
+ self.assertEqual(expected.displaybpm, deserialized.displaybpm)
+ self.assertEqual(expected.attacks, deserialized.attacks)
\ No newline at end of file
diff --git a/simfile/tests/test_ssc.py b/simfile/tests/test_ssc.py
index bde7305..8402a54 100644
--- a/simfile/tests/test_ssc.py
+++ b/simfile/tests/test_ssc.py
@@ -59,6 +59,29 @@ class TestSSCChart(unittest.TestCase):
self.assertEqual("0.793,1.205,0.500,0.298,0.961", unit.radarvalues)
self.assertEqual("\n\n0000\n0000\n0000\n0000\n", unit.notes)
+ def test_init_handles_multi_value_properties(self):
+ with_multi_value_properties = SSCChart.from_str(
+ """
+ #NOTEDATA:;
+ #CHARTNAME:Colons should be preserved below: but not here;
+ #DISPLAYBPM:60:240;
+ #ATTACKS:TIME=1.000:LEN=0.500:MODS=*5 -2.5 reverse;
+ #NOTES:
+ 0000
+ 0000
+ 0000
+ 0000
+ ;"""
+ )
+ self.assertEqual(
+ "Colons should be preserved below", with_multi_value_properties.chartname
+ )
+ self.assertEqual("60:240", with_multi_value_properties.displaybpm)
+ self.assertEqual(
+ "TIME=1.000:LEN=0.500:MODS=*5 -2.5 reverse",
+ with_multi_value_properties.attacks,
+ )
+
def test_serialize(self):
unit = SSCChart.from_str(testing_chart())
expected = (
@@ -81,6 +104,31 @@ class TestSSCChart(unittest.TestCase):
"\n"
)
+ def test_serialize_handles_multi_value_properties(self):
+ expected = SSCChart.from_str(
+ """
+ #NOTEDATA:;
+ #CHARTNAME:Colons in values below should be preserved;
+ #DISPLAYBPM:60:240;
+ #ATTACKS:TIME=1.000:LEN=0.500:MODS=*5 -2.5 reverse;
+ #NOTES:
+ 0000
+ 0000
+ 0000
+ 0000
+ ;"""
+ )
+ serialized = SSCChart.from_str(str(expected))
+
+ # None of the colons should be escaped
+ serialized = str(expected)
+ self.assertNotIn("\\", serialized)
+
+ deserialized = SSCChart.from_str(str(serialized))
+ self.assertEqual(expected.chartname, deserialized.chartname)
+ self.assertEqual(expected.displaybpm, deserialized.displaybpm)
+ self.assertEqual(expected.attacks, deserialized.attacks)
+
def test_serialize_with_escapes(self):
unit = SSCChart.from_str(testing_chart())
unit.chartname = "A:B;C//D\\E"
@@ -194,6 +242,43 @@ class TestSSCSimfile(unittest.TestCase):
self.assertNotIn("BGCHANGES", with_animations)
self.assertIn("ANIMATIONS", with_animations)
+ def test_init_handles_multi_value_properties(self):
+ with_multi_value_properties = SSCSimfile(
+ string="""
+ #VERSION:0.83;
+ #TITLE:Colons should be preserved below: but not here;
+ #DISPLAYBPM:60:240;
+ #ATTACKS:TIME=1.000:LEN=0.500:MODS=*5 -2.5 reverse;
+ """
+ )
+ self.assertEqual(
+ "Colons should be preserved below", with_multi_value_properties.title
+ )
+ self.assertEqual("60:240", with_multi_value_properties.displaybpm)
+ self.assertEqual(
+ "TIME=1.000:LEN=0.500:MODS=*5 -2.5 reverse",
+ with_multi_value_properties.attacks,
+ )
+
+ def test_serialize_handles_multi_value_properties(self):
+ expected = SSCSimfile(
+ string="""
+ #VERSION:0.83;
+ #TITLE:Colons should be preserved below;
+ #DISPLAYBPM:60:240;
+ #ATTACKS:TIME=1.000:LEN=0.500:MODS=*5 -2.5 reverse;
+ """
+ )
+
+ # None of the colons should be escaped
+ serialized = str(expected)
+ self.assertNotIn("\\", serialized)
+
+ deserialized = SSCSimfile(string=serialized)
+ self.assertEqual(expected.title, deserialized.title)
+ self.assertEqual(expected.displaybpm, deserialized.displaybpm)
+ self.assertEqual(expected.attacks, deserialized.attacks)
+
def test_repr(self):
unit = SSCSimfile(string=testing_simfile())
|
Multi-value properties aren't handled correctly in SSC
Two bugs in **simfile** 2.0.0–2.1.0's SSC implementation break multi-value properties, causing them to be truncated or mangled past the first value:
1. When opening an SSC file, the `DISPLAYBPM` and `ATTACKS` properties of both simfiles and charts stop parsing at the first `:`. For `DISPLAYBPM`, this means a BPM range of `min:max` will be incorrectly parsed as a static BPM of `min`. `ATTACKS` are completely broken as they use colon as a separator.
2. The aforementioned properties are incorrectly serialized with colons escaped from `SSCChart`. This has the same effects described above, but this only affects values with colons that were written to the chart object manually (e.g. `chart.displaybpm = "120:240"`) since the first bug shadows this bug during deserialization.
|
0.0
|
46074d9b9ce14089f9c0c05ed20772748fcb810f
|
[
"simfile/tests/test_ssc.py::TestSSCChart::test_init_handles_multi_value_properties",
"simfile/tests/test_ssc.py::TestSSCSimfile::test_init_handles_multi_value_properties"
] |
[
"simfile/tests/test_sm.py::testing_chart",
"simfile/tests/test_sm.py::testing_charts",
"simfile/tests/test_sm.py::testing_simfile",
"simfile/tests/test_sm.py::TestSMChart::test_eq",
"simfile/tests/test_sm.py::TestSMChart::test_getitem",
"simfile/tests/test_sm.py::TestSMChart::test_init_and_properties",
"simfile/tests/test_sm.py::TestSMChart::test_preserves_extra_data",
"simfile/tests/test_sm.py::TestSMChart::test_repr",
"simfile/tests/test_sm.py::TestSMChart::test_serialize",
"simfile/tests/test_sm.py::TestSMChart::test_serialize_with_escapes",
"simfile/tests/test_sm.py::TestSMCharts::test_init_and_list_methods",
"simfile/tests/test_sm.py::TestSMCharts::test_repr",
"simfile/tests/test_sm.py::TestSMCharts::test_serialize",
"simfile/tests/test_sm.py::TestSMSimfile::test_charts",
"simfile/tests/test_sm.py::TestSMSimfile::test_eq",
"simfile/tests/test_sm.py::TestSMSimfile::test_init_and_properties",
"simfile/tests/test_sm.py::TestSMSimfile::test_init_handles_animations_property",
"simfile/tests/test_sm.py::TestSMSimfile::test_init_handles_freezes_property",
"simfile/tests/test_sm.py::TestSMSimfile::test_init_handles_multi_value_properties",
"simfile/tests/test_sm.py::TestSMSimfile::test_repr",
"simfile/tests/test_sm.py::TestSMSimfile::test_serialize_handles_multi_value_properties",
"simfile/tests/test_ssc.py::testing_chart",
"simfile/tests/test_ssc.py::testing_charts",
"simfile/tests/test_ssc.py::testing_simfile",
"simfile/tests/test_ssc.py::TestSSCChart::test_eq",
"simfile/tests/test_ssc.py::TestSSCChart::test_handles_notes2",
"simfile/tests/test_ssc.py::TestSSCChart::test_init_and_properties",
"simfile/tests/test_ssc.py::TestSSCChart::test_repr",
"simfile/tests/test_ssc.py::TestSSCChart::test_serialize",
"simfile/tests/test_ssc.py::TestSSCChart::test_serialize_handles_added_properties",
"simfile/tests/test_ssc.py::TestSSCChart::test_serialize_handles_multi_value_properties",
"simfile/tests/test_ssc.py::TestSSCChart::test_serialize_with_escapes",
"simfile/tests/test_ssc.py::TestSSCCharts::test_init_and_list_methods",
"simfile/tests/test_ssc.py::TestSSCCharts::test_repr",
"simfile/tests/test_ssc.py::TestSSCCharts::test_serialize",
"simfile/tests/test_ssc.py::TestSSCSimfile::test_charts",
"simfile/tests/test_ssc.py::TestSSCSimfile::test_eq",
"simfile/tests/test_ssc.py::TestSSCSimfile::test_init_and_properties",
"simfile/tests/test_ssc.py::TestSSCSimfile::test_init_handles_animations_property",
"simfile/tests/test_ssc.py::TestSSCSimfile::test_repr",
"simfile/tests/test_ssc.py::TestSSCSimfile::test_serialize_handles_multi_value_properties"
] |
{
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-11-26 02:31:22+00:00
|
mit
| 2,434 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.