Dataset Viewer
Auto-converted to Parquet
repo
stringlengths
11
40
pull_number
int64
2
3.89k
instance_id
stringlengths
15
44
issue_numbers
stringlengths
5
16
base_commit
stringlengths
40
40
patch
stringlengths
185
211k
test_patch
stringlengths
348
511k
problem_statement
stringlengths
20
17.7k
hints_text
stringlengths
0
77.5k
created_at
stringdate
2013-06-18 08:42:56
2025-04-03 08:00:52
version
stringclasses
1 value
FAIL_TO_PASS
sequencelengths
1
2.63k
PASS_TO_PASS
sequencelengths
0
29.9k
DisnakeDev/disnake
655
DisnakeDev__disnake-655
['259']
593bc49b936f90aa45a06c30622c88de16ab042b
diff --git a/changelog/655.breaking.rst b/changelog/655.breaking.rst new file mode 100644 index 0000000000..bd7ddfe476 --- /dev/null +++ b/changelog/655.breaking.rst @@ -0,0 +1,1 @@ +|tasks| Change :class:`.ext.tasks.Loop` to use keyword-only parameters. diff --git a/changelog/655.feature.rst b/changelog/655.feature.rst new file mode 100644 index 0000000000..18654d6715 --- /dev/null +++ b/changelog/655.feature.rst @@ -0,0 +1,1 @@ +|tasks| Add support for subclassing :class:`.ext.tasks.Loop` and using subclasses in :func:`.ext.tasks.loop` decorator. diff --git a/disnake/ext/tasks/__init__.py b/disnake/ext/tasks/__init__.py index 014ade6f02..bcf833aee2 100644 --- a/disnake/ext/tasks/__init__.py +++ b/disnake/ext/tasks/__init__.py @@ -8,7 +8,22 @@ import sys import traceback from collections.abc import Sequence -from typing import Any, Callable, Coroutine, Generic, List, Optional, Type, TypeVar, Union +from typing import ( + TYPE_CHECKING, + Any, + Callable, + Coroutine, + Generic, + List, + Optional, + Protocol, + Type, + TypeVar, + Union, + cast, + get_origin, + overload, +) import aiohttp @@ -16,6 +31,14 @@ from disnake.backoff import ExponentialBackoff from disnake.utils import MISSING, utcnow +if TYPE_CHECKING: + from typing_extensions import Concatenate, ParamSpec, Self + + P = ParamSpec("P") + +else: + P = TypeVar("P") + __all__ = ("loop",) T = TypeVar("T") @@ -30,16 +53,16 @@ class SleepHandle: def __init__(self, dt: datetime.datetime, *, loop: asyncio.AbstractEventLoop) -> None: self.loop = loop - self.future = future = loop.create_future() + self.future: asyncio.Future[bool] = loop.create_future() relative_delta = disnake.utils.compute_timedelta(dt) - self.handle = loop.call_later(relative_delta, future.set_result, True) + self.handle = loop.call_later(relative_delta, self.future.set_result, True) def recalculate(self, dt: datetime.datetime) -> None: self.handle.cancel() relative_delta = disnake.utils.compute_timedelta(dt) self.handle = self.loop.call_later(relative_delta, self.future.set_result, True) - def wait(self) -> asyncio.Future[Any]: + def wait(self) -> asyncio.Future[bool]: return self.future def done(self) -> bool: @@ -59,14 +82,19 @@ class Loop(Generic[LF]): def __init__( self, coro: LF, - seconds: float, - hours: float, - minutes: float, - time: Union[datetime.time, Sequence[datetime.time]], - count: Optional[int], - reconnect: bool, - loop: asyncio.AbstractEventLoop, + *, + seconds: float = 0, + minutes: float = 0, + hours: float = 0, + time: Union[datetime.time, Sequence[datetime.time]] = MISSING, + count: Optional[int] = None, + reconnect: bool = True, + loop: asyncio.AbstractEventLoop = MISSING, ) -> None: + """ + .. note: + If you overwrite ``__init__`` arguments, make sure to redefine .clone too. + """ self.coro: LF = coro self.reconnect: bool = reconnect self.loop: asyncio.AbstractEventLoop = loop @@ -74,7 +102,7 @@ def __init__( self._current_loop = 0 self._handle: SleepHandle = MISSING self._task: asyncio.Task[None] = MISSING - self._injected = None + self._injected: Any = None self._valid_exception = ( OSError, disnake.GatewayNotFound, @@ -169,11 +197,16 @@ async def _loop(self, *args: Any, **kwargs: Any) -> None: self._stop_next_iteration = False self._has_failed = False - def __get__(self, obj: T, objtype: Type[T]) -> Loop[LF]: + def __get__(self, obj: T, objtype: Type[T]) -> Self: if obj is None: return self + clone = self.clone() + clone._injected = obj + setattr(obj, self.coro.__name__, clone) + return clone - copy: Loop[LF] = Loop( + def clone(self) -> Self: + instance = type(self)( self.coro, seconds=self._seconds, hours=self._hours, @@ -183,12 +216,11 @@ def __get__(self, obj: T, objtype: Type[T]) -> Loop[LF]: reconnect=self.reconnect, loop=self.loop, ) - copy._injected = obj - copy._before_loop = self._before_loop - copy._after_loop = self._after_loop - copy._error = self._error - setattr(obj, self.coro.__name__, copy) - return copy + instance._before_loop = self._before_loop + instance._after_loop = self._after_loop + instance._error = self._error + instance._injected = self._injected + return instance @property def seconds(self) -> Optional[float]: @@ -672,21 +704,55 @@ def change_interval( self._handle.recalculate(self._next_iteration) +T_co = TypeVar("T_co", covariant=True) +L_co = TypeVar("L_co", bound=Loop, covariant=True) + + +class Object(Protocol[T_co, P]): + def __new__(cls) -> T_co: + ... + + def __init__(*args: P.args, **kwargs: P.kwargs) -> None: + ... + + +@overload def loop( *, - seconds: float = MISSING, - minutes: float = MISSING, - hours: float = MISSING, - time: Union[datetime.time, Sequence[datetime.time]] = MISSING, + seconds: float = ..., + minutes: float = ..., + hours: float = ..., + time: Union[datetime.time, Sequence[datetime.time]] = ..., count: Optional[int] = None, reconnect: bool = True, - loop: asyncio.AbstractEventLoop = MISSING, + loop: asyncio.AbstractEventLoop = ..., ) -> Callable[[LF], Loop[LF]]: + ... + + +@overload +def loop( + cls: Type[Object[L_co, Concatenate[LF, P]]], *_: P.args, **kwargs: P.kwargs +) -> Callable[[LF], L_co]: + ... + + +def loop( + cls: Type[Object[L_co, Concatenate[LF, P]]] = Loop[LF], + **kwargs: Any, +) -> Callable[[LF], L_co]: """A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a :class:`Loop`. Parameters ---------- + cls: Type[:class:`Loop`] + The loop subclass to create an instance of. If provided, the following parameters + described below do not apply. Instead, this decorator will accept the same keywords + as the passed cls does. + + .. versionadded:: 2.6 + seconds: :class:`float` The number of seconds between every iteration. minutes: :class:`float` @@ -722,20 +788,21 @@ def loop( ValueError An invalid value was given. TypeError - The function was not a coroutine, an invalid value for the ``time`` parameter was passed, + The function was not a coroutine, the ``cls`` parameter was not a subclass of ``Loop``, + an invalid value for the ``time`` parameter was passed, or ``time`` parameter was passed in conjunction with relative time parameters. """ - def decorator(func: LF) -> Loop[LF]: - return Loop[LF]( - func, - seconds=seconds, - minutes=minutes, - hours=hours, - count=count, - time=time, - reconnect=reconnect, - loop=loop, - ) + if (origin := get_origin(cls)) is not None: + cls = origin + + if not isinstance(cls, type) or not issubclass(cls, Loop): + raise TypeError(f"cls argument must be a subclass of Loop, got {cls!r}") + + def decorator(func: LF) -> L_co: + if not asyncio.iscoroutinefunction(func): + raise TypeError("decorated function must be a coroutine") + + return cast("Type[L_co]", cls)(func, **kwargs) return decorator
diff --git a/tests/ext/tasks/test_loops.py b/tests/ext/tasks/test_loops.py new file mode 100644 index 0000000000..9ffe589121 --- /dev/null +++ b/tests/ext/tasks/test_loops.py @@ -0,0 +1,80 @@ +# SPDX-License-Identifier: MIT + +import datetime +from typing import Any, Tuple + +import pytest + +from disnake.ext import commands +from disnake.ext.tasks import LF, Loop, loop + + +class TestLoops: + def test_decorator(self): + class Cog(commands.Cog): + @loop(seconds=30, minutes=0, hours=0) + async def task(self) -> None: + ... + + for c in (Cog, Cog()): + assert c.task.seconds == 30 + + with pytest.raises(TypeError, match="must be a coroutine"): + + @loop() # type: ignore + def task() -> None: + ... + + def test_mixing_time(self): + async def callback(): + pass + + with pytest.raises(TypeError): + Loop(callback, seconds=30, time=datetime.time()) + + with pytest.raises(TypeError): + + @loop(seconds=30, time=datetime.time()) + async def task() -> None: + ... + + def test_inheritance(self): + class HyperLoop(Loop[LF]): + def __init__(self, coro: LF, time_tup: Tuple[float, float, float]) -> None: + s, m, h = time_tup + super().__init__(coro, seconds=s, minutes=m, hours=h) + + def clone(self): + instance = type(self)(self.coro, (self._seconds, self._minutes, self._hours)) + instance._time = self._time + instance.count = self.count + instance.reconnect = self.reconnect + instance.loop = self.loop + instance._before_loop = self._before_loop + instance._after_loop = self._after_loop + instance._error = self._error + instance._injected = self._injected + return instance + + class WhileTrueLoop: + def __init__(self, coro: Any) -> None: + ... + + async def callback(): + pass + + HyperLoop(callback, (1, 2, 3)) + + class Cog(commands.Cog): + @loop(cls=HyperLoop[Any], time_tup=(1, 2, 3)) + async def task(self) -> None: + ... + + for c in (Cog, Cog()): + assert (c.task.seconds, c.task.minutes, c.task.hours) == (1, 2, 3) + + with pytest.raises(TypeError, match="subclass of Loop"): + + @loop(cls=WhileTrueLoop) # type: ignore + async def task() -> None: + ...
ext.tasks.Loop descriptor inheritance support ## Summary <!-- What is this pull request for? Does it fix any issues? --> Descriptor of `disnake.ext.tasks.Loop` returns new `Loop` instance instead of current class instance. Thats inheritance issue. ## Checklist <!-- Put an x inside [ ] to check it, like so: [x] --> - [x] If code changes were made, then they have been tested - [ ] I have updated the documentation to reflect the changes - [x] I have formatted the code properly by running `pre-commit run --all-files` - [x] This PR fixes an issue - [ ] This PR adds something new (e.g. new method or parameters) - [ ] This PR is a breaking change (e.g. methods or parameters removed/renamed) - [ ] This PR is **not** a code change (e.g. documentation, README, ...)
2022-07-25T16:54:51.000
-1.0
[ "tests/ext/tasks/test_loops.py::TestLoops::test_decorator", "tests/ext/tasks/test_loops.py::TestLoops::test_inheritance" ]
[ "tests/ext/tasks/test_loops.py::TestLoops::test_mixing_time" ]
DisnakeDev/disnake
603
DisnakeDev__disnake-603
['573']
988e8c2b88428c5c205fecba16c96638e68dcfa0
diff --git a/disnake/mentions.py b/disnake/mentions.py index 07c811f320..6f3f02218a 100644 --- a/disnake/mentions.py +++ b/disnake/mentions.py @@ -27,10 +27,13 @@ from typing import TYPE_CHECKING, Any, List, Type, TypeVar, Union +from .enums import MessageType + __all__ = ("AllowedMentions",) if TYPE_CHECKING: from .abc import Snowflake + from .message import Message from .types.message import AllowedMentions as AllowedMentionsPayload @@ -111,6 +114,30 @@ def none(cls: Type[A]) -> A: """ return cls(everyone=False, users=False, roles=False, replied_user=False) + @classmethod + def from_message(cls: Type[A], message: Message) -> A: + """A factory method that returns a :class:`AllowedMentions` dervived from the current :class:`.Message` state. + + Note that this is not what AllowedMentions the message was sent with, but what the message actually mentioned. + For example, a message that successfully mentioned everyone will have :attr:`~AllowedMentions.everyone` set to ``True``. + + .. versionadded:: 2.6 + """ + # circular import + from .message import Message + + return cls( + everyone=message.mention_everyone, + users=message.mentions.copy(), # type: ignore # mentions is a list of Snowflakes + roles=message.role_mentions.copy(), # type: ignore # mentions is a list of Snowflakes + replied_user=bool( + message.type is MessageType.reply + and message.reference + and isinstance(message.reference.resolved, Message) + and message.reference.resolved.author in message.mentions + ), + ) + def to_dict(self) -> AllowedMentionsPayload: parse = [] data = {}
diff --git a/tests/test_mentions.py b/tests/test_mentions.py new file mode 100644 index 0000000000..492c445d12 --- /dev/null +++ b/tests/test_mentions.py @@ -0,0 +1,117 @@ +from typing import Dict, Union +from unittest import mock + +import pytest + +from disnake import AllowedMentions, Message, MessageType, Object + + +def test_classmethod_none() -> None: + none = AllowedMentions.none() + assert none.everyone is False + assert none.roles is False + assert none.users is False + assert none.replied_user is False + + +def test_classmethod_all() -> None: + all_mentions = AllowedMentions.all() + assert all_mentions.everyone is True + assert all_mentions.roles is True + assert all_mentions.users is True + assert all_mentions.replied_user is True + + [email protected]( + ("am", "expected"), + [ + (AllowedMentions(), {"parse": ["everyone", "users", "roles"], "replied_user": True}), + (AllowedMentions.all(), {"parse": ["everyone", "users", "roles"], "replied_user": True}), + (AllowedMentions(everyone=False), {"parse": ["users", "roles"], "replied_user": True}), + ( + AllowedMentions(users=[Object(x) for x in [123, 456, 789]]), + {"parse": ["everyone", "roles"], "replied_user": True, "users": [123, 456, 789]}, + ), + ( + AllowedMentions( + users=[Object(x) for x in [123, 456, 789]], + roles=[Object(x) for x in [123, 456, 789]], + ), + { + "parse": ["everyone"], + "replied_user": True, + "users": [123, 456, 789], + "roles": [123, 456, 789], + }, + ), + (AllowedMentions.none(), {"parse": []}), + ], +) +def test_to_dict(am: AllowedMentions, expected: Dict[str, Union[bool, list]]) -> None: + assert expected == am.to_dict() + + [email protected]( + ("og", "to_merge", "expected"), + [ + (AllowedMentions.none(), AllowedMentions.none(), AllowedMentions.none()), + (AllowedMentions.none(), AllowedMentions(), AllowedMentions.none()), + (AllowedMentions.all(), AllowedMentions(), AllowedMentions.all()), + (AllowedMentions(), AllowedMentions(), AllowedMentions()), + (AllowedMentions.all(), AllowedMentions.none(), AllowedMentions.none()), + ( + AllowedMentions(everyone=False), + AllowedMentions(users=True), + AllowedMentions(everyone=False, users=True), + ), + ( + AllowedMentions(users=[Object(x) for x in [123, 456, 789]]), + AllowedMentions(users=False), + AllowedMentions(users=False), + ), + ], +) +def test_merge(og: AllowedMentions, to_merge: AllowedMentions, expected: AllowedMentions) -> None: + merged = og.merge(to_merge) + + assert expected.everyone is merged.everyone + assert expected.users is merged.users + assert expected.roles is merged.roles + assert expected.replied_user is merged.replied_user + + +def test_from_message() -> None: + # as we don't have a message mock yet we are faking a message here with the necessary components + msg = mock.NonCallableMock() + msg.mention_everyone = True + users = [Object(x) for x in [123, 456, 789]] + msg.mentions = users + roles = [Object(x) for x in [123, 456, 789]] + msg.role_mentions = roles + msg.reference = None + + am = AllowedMentions.from_message(msg) + + assert am.everyone is True + # check that while the list matches, it isn't the same list + assert am.users == users + assert am.users is not users + + assert am.roles == roles + assert am.roles is not roles + + assert am.replied_user is False + + +def test_from_message_replied_user() -> None: + message = mock.Mock(Message) + author = Object(123) + message.mentions = [author] + assert AllowedMentions.from_message(message).replied_user is False + + message.type = MessageType.reply + assert AllowedMentions.from_message(message).replied_user is False + + resolved = mock.Mock(Message, author=author) + message.reference = mock.Mock(resolved=resolved) + assert AllowedMentions.from_message(message).replied_user is True
MessageInteraction.edit_original_message does not preserve allowed_mentions state if kwarg not passed ### Summary MessageInteraction.edit_original_message does not preserve allowed_mentions state if kwarg not passed ### Reproduction Steps 1. Set Client.allowed_mentions to AllowedMentions.none() 2. Send a message that mentions a user containing a button, explicitly defining allowed_mentions 3. Click the button, and have the button handler update the content of the message using `inter.edit_original_message(content=...)` 4. Observe that the allowed_mentions is not preserved ### Minimal Reproducible Code _No response_ ### Expected Results The edited message remains highlighted, mentioning the user ### Actual Results The edited message no longer appears highlighted Attaching a debugger reveals that https://github.com/DisnakeDev/disnake/blob/master/disnake/interactions/base.py#L449 became an AllowedMentions.none() instead of the actual previous allowed mentions ### Intents discord.Intents( guilds=True, members=True, messages=True, reactions=True, bans=False, emojis=False, integrations=False, webhooks=False, invites=False, voice_states=False, presences=False, typing=False, ) ### System Information ```markdown - Python v3.10.2-final - disnake v2.4.0-final - disnake pkg_resources: v2.4.0 - aiohttp v3.8.1 - system info: Darwin 18.7.0 Darwin Kernel Version 18.7.0: Tue Jun 22 19:37:08 PDT 2021; root:xnu-4903.278.70~1/RELEASE_X86_64 Note: this is not the most recent Disnake version but I have confirmed that the applicable code has not been updated since. ``` ### Checklist - [X] I have searched the open issues for duplicates. - [X] I have shown the entire traceback, if possible. - [X] I have removed my token from display, if visible. ### Additional Context - This might only occur if Client.allowed_mentions is set, overwriting the allowed_mentions with Client.allowed_mentions
This appears to be working as intended, as Discord unfortunately doesn't return the `allowed_mentions` value in the payload - there's no way of knowing the previous `allowed_mentions` value solely based on the interaction, and sending it again on edit. Editing messages works similarly for the same reason, which is why the only feasible default action is to fall back to the client's `allowed_mentions`.
2022-07-05T17:24:19.000
-1.0
[ "tests/test_mentions.py::test_from_message", "tests/test_mentions.py::test_from_message_replied_user" ]
[ "tests/test_mentions.py::test_merge[og5-to_merge5-expected5]", "tests/test_mentions.py::test_merge[og6-to_merge6-expected6]", "tests/test_mentions.py::test_to_dict[am2-expected2]", "tests/test_mentions.py::test_merge[og3-to_merge3-expected3]", "tests/test_mentions.py::test_merge[og1-to_merge1-expected1]", "tests/test_mentions.py::test_merge[og0-to_merge0-expected0]", "tests/test_mentions.py::test_to_dict[am1-expected1]", "tests/test_mentions.py::test_to_dict[am4-expected4]", "tests/test_mentions.py::test_to_dict[am0-expected0]", "tests/test_mentions.py::test_to_dict[am5-expected5]", "tests/test_mentions.py::test_classmethod_all", "tests/test_mentions.py::test_to_dict[am3-expected3]", "tests/test_mentions.py::test_classmethod_none", "tests/test_mentions.py::test_merge[og4-to_merge4-expected4]", "tests/test_mentions.py::test_merge[og2-to_merge2-expected2]" ]
DisnakeDev/disnake
584
DisnakeDev__disnake-584
['577']
1c9ddd8cc369bfaa8c6259b736ca8af772a9011d
diff --git a/disnake/ext/commands/params.py b/disnake/ext/commands/params.py index 46284b85dd..775b7d2863 100644 --- a/disnake/ext/commands/params.py +++ b/disnake/ext/commands/params.py @@ -36,6 +36,8 @@ Callable, ClassVar, Dict, + Final, + FrozenSet, List, Literal, Optional, @@ -43,7 +45,6 @@ Type, TypeVar, Union, - cast, get_args, get_origin, get_type_hints, @@ -114,8 +115,6 @@ def issubclass_(obj: Any, tp: Union[TypeT, Tuple[TypeT, ...]]) -> TypeGuard[Type def remove_optionals(annotation: Any) -> Any: """remove unwanted optionals from an annotation""" if get_origin(annotation) in (Union, UnionType): - annotation = cast(Any, annotation) - args = tuple(i for i in annotation.__args__ if i not in (None, type(None))) if len(args) == 1: annotation = args[0] @@ -280,6 +279,10 @@ class LargeInt(int): """Type for large integers in slash commands.""" +# option types that require additional handling in verify_type +_VERIFY_TYPES: Final[FrozenSet[OptionType]] = frozenset((OptionType.user, OptionType.mentionable)) + + class ParamInfo: """A class that basically connects function params with slash command options. The instances of this class are not created manually, but via the functional interface instead. @@ -443,14 +446,21 @@ async def get_default(self, inter: ApplicationCommandInteraction) -> Any: return default async def verify_type(self, inter: ApplicationCommandInteraction, argument: Any) -> Any: - """Check if a type of an argument is correct and possibly fix it""" - if issubclass_(self.type, disnake.Member): - if isinstance(argument, disnake.Member): - return argument + """Check if the type of an argument is correct and possibly raise if it's not.""" + if self.discord_type not in _VERIFY_TYPES: + return argument + # The API may return a `User` for options annotated with `Member`, + # including `Member` (user option), `Union[User, Member]` (user option) and + # `Union[Member, Role]` (mentionable option). + # If we received a `User` but didn't expect one, raise. + if ( + isinstance(argument, disnake.User) + and issubclass_(self.type, disnake.Member) + and not issubclass_(self.type, disnake.User) + ): raise errors.MemberNotFound(str(argument.id)) - # unexpected types may just be ignored return argument async def convert_argument(self, inter: ApplicationCommandInteraction, argument: Any) -> Any:
diff --git a/tests/ext/commands/test_params.py b/tests/ext/commands/test_params.py new file mode 100644 index 0000000000..b63ab9b851 --- /dev/null +++ b/tests/ext/commands/test_params.py @@ -0,0 +1,61 @@ +from typing import Union +from unittest import mock + +import pytest + +import disnake +from disnake import Member, Role, User +from disnake.ext import commands + +OptionType = disnake.OptionType + + +class TestParamInfo: + @pytest.mark.parametrize( + ("annotation", "expected_type", "arg_types"), + [ + # should accept user or member + (disnake.abc.User, OptionType.user, [User, Member]), + (User, OptionType.user, [User, Member]), + (Union[User, Member], OptionType.user, [User, Member]), + # only accepts member, not user + (Member, OptionType.user, [Member]), + # only accepts role + (Role, OptionType.role, [Role]), + # should accept member or role + (Union[Member, Role], OptionType.mentionable, [Member, Role]), + # should accept everything + (disnake.abc.Snowflake, OptionType.mentionable, [User, Member, Role]), + ], + ) + @pytest.mark.asyncio + async def test_verify_type(self, annotation, expected_type, arg_types) -> None: + # tests that the Discord option type is determined correctly, + # and that valid argument types are accepted + info = commands.ParamInfo() + info.parse_annotation(annotation) + + # type should be valid + assert info.discord_type is expected_type + + for arg_type in arg_types: + arg_mock = mock.Mock(arg_type) + assert await info.verify_type(mock.Mock(), arg_mock) is arg_mock + + @pytest.mark.parametrize( + ("annotation", "arg_types"), + [ + (Member, [User]), + (Union[Member, Role], [User]), + ], + ) + @pytest.mark.asyncio + async def test_verify_type__invalid_member(self, annotation, arg_types) -> None: + # tests that invalid argument types result in `verify_type` raising an exception + info = commands.ParamInfo() + info.parse_annotation(annotation) + + for arg_type in arg_types: + arg_mock = mock.Mock(arg_type) + with pytest.raises(commands.errors.MemberNotFound): + await info.verify_type(mock.Mock(), arg_mock)
Traceback when "Union[Member, User]" is used as type hint in slash command parameters ### Summary When "Union[Member, User]" is used as a type hint in a slash command parameter, a traceback from disnake is shown when the slash command is invoked targeting a user who should resolve to a User object, not a Member object.. ### Reproduction Steps Reference the below Minimal Reproducible Code and invoke the relevant slash command against a user who is not currently in the server. This issue does *not* occur when the target of the slash command is in the server (and resolves to a Member object). ### Minimal Reproducible Code ```python @discord_bot.slash_command() async def whois( inter: ApplicationCommandInteraction, user: Union[Member, User] = commands.Param( description="The member to display information about" ), ) -> None: pass ``` ### Expected Results The slash command should be invoked successfully without a traceback when targeting a user who is not in the server. This used to work in v2.4.0 of disnake - not positive if it is broken in v2.5.0 as well. ### Actual Results The following traceback is observed when this slash command is invoked: ``` Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/disnake/ext/commands/interaction_bot_base.py", line 1264, in process_application_commands await app_command.invoke(interaction) File "/usr/local/lib/python3.8/site-packages/disnake/ext/commands/slash_core.py", line 680, in invoke await call_param_func(self.callback, inter, self.cog, **kwargs) File "/usr/local/lib/python3.8/site-packages/disnake/ext/commands/params.py", line 811, in call_param_func kwargs[param.param_name] = await param.convert_argument( File "/usr/local/lib/python3.8/site-packages/disnake/ext/commands/params.py", line 464, in convert_argument return await self.verify_type(inter, argument) disnake.ext.commands.errors.MemberNotFound: Member "redacted_valid_snowflake_here" not found. ``` ### Intents default, members, message_content ### System Information ```markdown $ python -m disnake -v - Python v3.8.10-final - disnake v2.5.1-final - disnake pkg_resources: v2.5.1 - aiohttp v3.7.4.post0 - system info: Linux 5.4.0-120-generic #136-Ubuntu SMP Fri Jun 10 13:40:48 UTC 2022 ``` ``` ### Checklist - [X] I have searched the open issues for duplicates. - [X] I have shown the entire traceback, if possible. - [X] I have removed my token from display, if visible. ### Additional Context Talked with Mari about this over Discord, she said she'd open up an issue for this. I opened this up to save her some time 😅
2022-06-26T18:52:54.000
-1.0
[ "tests/ext/commands/test_params.py::TestParamInfo::test_verify_type[annotation2-expected_type2-arg_types2]", "tests/ext/commands/test_params.py::TestParamInfo::test_verify_type[annotation5-expected_type5-arg_types5]" ]
[ "tests/ext/commands/test_params.py::TestParamInfo::test_verify_type[User-expected_type0-arg_types0]", "tests/ext/commands/test_params.py::TestParamInfo::test_verify_type[Role-expected_type4-arg_types4]", "tests/ext/commands/test_params.py::TestParamInfo::test_verify_type[User-expected_type1-arg_types1]", "tests/ext/commands/test_params.py::TestParamInfo::test_verify_type__invalid_member[annotation1-arg_types1]", "tests/ext/commands/test_params.py::TestParamInfo::test_verify_type__invalid_member[Member-arg_types0]", "tests/ext/commands/test_params.py::TestParamInfo::test_verify_type[Member-expected_type3-arg_types3]", "tests/ext/commands/test_params.py::TestParamInfo::test_verify_type[Snowflake-expected_type6-arg_types6]" ]
DisnakeDev/disnake
435
DisnakeDev__disnake-435
['229']
db5cfd4e8fc91b012a009682150dd5091dc29d3d
diff --git a/disnake/abc.py b/disnake/abc.py index 21f3f54550..0b8981db11 100644 --- a/disnake/abc.py +++ b/disnake/abc.py @@ -1477,7 +1477,7 @@ async def send( for embed in embeds: if embed._files: files = files or [] - files += embed._files + files.extend(embed._files.values()) embeds_payload = [embed.to_dict() for embed in embeds] stickers_payload = None diff --git a/disnake/embeds.py b/disnake/embeds.py index 4611c98a30..5cbe034441 100644 --- a/disnake/embeds.py +++ b/disnake/embeds.py @@ -29,15 +29,17 @@ from typing import ( TYPE_CHECKING, Any, + ClassVar, Dict, - Final, List, + Literal, Mapping, Optional, Protocol, - Type, - TypeVar, + Sized, Union, + cast, + overload, ) from . import utils @@ -48,23 +50,10 @@ __all__ = ("Embed",) -class _EmptyEmbed: - def __bool__(self) -> bool: - return False - - def __repr__(self) -> str: - return "Embed.Empty" - - def __len__(self) -> int: - return 0 - - -EmptyEmbed: Final = _EmptyEmbed() - - class EmbedProxy: - def __init__(self, layer: Dict[str, Any]): - self.__dict__.update(layer) + def __init__(self, layer: Optional[Mapping[str, Any]]): + if layer is not None: + self.__dict__.update(layer) def __len__(self) -> int: return len(self.__dict__) @@ -73,47 +62,58 @@ def __repr__(self) -> str: inner = ", ".join((f"{k}={v!r}" for k, v in self.__dict__.items() if not k.startswith("_"))) return f"EmbedProxy({inner})" - def __getattr__(self, attr: str) -> _EmptyEmbed: - return EmptyEmbed - + def __getattr__(self, attr: str) -> None: + return None -E = TypeVar("E", bound="Embed") if TYPE_CHECKING: - from disnake.types.embed import Embed as EmbedData, EmbedType + from typing_extensions import Self + + from disnake.types.embed import ( + Embed as EmbedData, + EmbedAuthor as EmbedAuthorPayload, + EmbedField as EmbedFieldPayload, + EmbedFooter as EmbedFooterPayload, + EmbedImage as EmbedImagePayload, + EmbedProvider as EmbedProviderPayload, + EmbedThumbnail as EmbedThumbnailPayload, + EmbedType, + EmbedVideo as EmbedVideoPayload, + ) - T = TypeVar("T") - MaybeEmpty = Union[T, _EmptyEmbed] + class _EmbedFooterProxy(Sized, Protocol): + text: Optional[str] + icon_url: Optional[str] + proxy_icon_url: Optional[str] - class _EmbedFooterProxy(Protocol): - text: MaybeEmpty[str] - icon_url: MaybeEmpty[str] + class _EmbedFieldProxy(Sized, Protocol): + name: Optional[str] + value: Optional[str] + inline: Optional[bool] - class _EmbedFieldProxy(Protocol): - name: MaybeEmpty[str] - value: MaybeEmpty[str] - inline: bool + class _EmbedMediaProxy(Sized, Protocol): + url: Optional[str] + proxy_url: Optional[str] + height: Optional[int] + width: Optional[int] - class _EmbedMediaProxy(Protocol): - url: MaybeEmpty[str] - proxy_url: MaybeEmpty[str] - height: MaybeEmpty[int] - width: MaybeEmpty[int] + class _EmbedVideoProxy(Sized, Protocol): + url: Optional[str] + proxy_url: Optional[str] + height: Optional[int] + width: Optional[int] - class _EmbedVideoProxy(Protocol): - url: MaybeEmpty[str] - height: MaybeEmpty[int] - width: MaybeEmpty[int] + class _EmbedProviderProxy(Sized, Protocol): + name: Optional[str] + url: Optional[str] - class _EmbedProviderProxy(Protocol): - name: MaybeEmpty[str] - url: MaybeEmpty[str] + class _EmbedAuthorProxy(Sized, Protocol): + name: Optional[str] + url: Optional[str] + icon_url: Optional[str] + proxy_icon_url: Optional[str] - class _EmbedAuthorProxy(Protocol): - name: MaybeEmpty[str] - url: MaybeEmpty[str] - icon_url: MaybeEmpty[str] - proxy_icon_url: MaybeEmpty[str] + _FileKey = Literal["image", "thumbnail"] class Embed: @@ -134,39 +134,31 @@ class Embed: Certain properties return an ``EmbedProxy``, a type that acts similar to a regular :class:`dict` except using dotted access, - e.g. ``embed.author.icon_url``. If the attribute - is invalid or empty, then a special sentinel value is returned, - :attr:`Embed.Empty`. + e.g. ``embed.author.icon_url``. For ease of use, all parameters that expect a :class:`str` are implicitly - casted to :class:`str` for you. + cast to :class:`str` for you. Attributes ---------- - title: :class:`str` + title: Optional[:class:`str`] The title of the embed. - This can be set during initialisation. - type: :class:`str` + type: Optional[:class:`str`] The type of embed. Usually "rich". - This can be set during initialisation. - Possible strings for embed types can be found on discord's - `api docs <https://discord.com/developers/docs/resources/channel#embed-object-embed-types>`_ - description: :class:`str` + Possible strings for embed types can be found on Discord's + `api docs <https://discord.com/developers/docs/resources/channel#embed-object-embed-types>`__. + description: Optional[:class:`str`] The description of the embed. - This can be set during initialisation. - url: :class:`str` + url: Optional[:class:`str`] The URL of the embed. - This can be set during initialisation. - timestamp: :class:`datetime.datetime` + timestamp: Optional[:class:`datetime.datetime`] The timestamp of the embed content. This is an aware datetime. If a naive datetime is passed, it is converted to an aware datetime with the local timezone. - colour: Union[:class:`Colour`, :class:`int`] + colour: Optional[:class:`Colour`] The colour code of the embed. Aliased to ``color`` as well. - This can be set during initialisation. - Empty - A special sentinel value used by ``EmbedProxy`` and this class - to denote that the value or attribute is empty. + In addition to :class:`Colour`, :class:`int` can also be assigned to it, + in which case the value will be converted to a :class:`Colour` object. """ __slots__ = ( @@ -186,51 +178,52 @@ class Embed: "_files", ) - Empty: Final = EmptyEmbed - _default_colour: MaybeEmpty[Colour] = Empty + _default_colour: ClassVar[Optional[Colour]] = None + _colour: Optional[Colour] def __init__( self, *, - colour: Union[int, Colour, _EmptyEmbed] = EmptyEmbed, - color: Union[int, Colour, _EmptyEmbed] = EmptyEmbed, - title: MaybeEmpty[Any] = EmptyEmbed, - type: EmbedType = "rich", - url: MaybeEmpty[Any] = EmptyEmbed, - description: MaybeEmpty[Any] = EmptyEmbed, - timestamp: datetime.datetime = None, + title: Optional[Any] = None, + type: Optional[EmbedType] = "rich", + description: Optional[Any] = None, + url: Optional[Any] = None, + timestamp: Optional[datetime.datetime] = None, + colour: Optional[Union[int, Colour]] = MISSING, + color: Optional[Union[int, Colour]] = MISSING, ): - if colour or color: - self.colour = colour if colour is not EmptyEmbed else color - self.title = title - self.type = type - self.url = url - self.description = description - - if self.title is not EmptyEmbed: - self.title = str(self.title) - - if self.description is not EmptyEmbed: - self.description = str(self.description) - - if self.url is not EmptyEmbed: - self.url = str(self.url) - - if timestamp: - self.timestamp = timestamp - - self._files: List[File] = [] + self.title: Optional[str] = str(title) if title is not None else None + self.type: Optional[EmbedType] = type + self.description: Optional[str] = str(description) if description is not None else None + self.url: Optional[str] = str(url) if url is not None else None + + self.timestamp = timestamp + + # possible values: + # - MISSING: embed color will be _default_color + # - None: embed color will not be set + # - Color: embed color will be set to specified color + if colour is not MISSING: + color = colour + self.colour = color + + self._thumbnail: Optional[EmbedThumbnailPayload] = None + self._video: Optional[EmbedVideoPayload] = None + self._provider: Optional[EmbedProviderPayload] = None + self._author: Optional[EmbedAuthorPayload] = None + self._image: Optional[EmbedImagePayload] = None + self._footer: Optional[EmbedFooterPayload] = None + self._fields: Optional[List[EmbedFieldPayload]] = None + + self._files: Dict[_FileKey, File] = {} @classmethod - def from_dict(cls: Type[E], data: Mapping[str, Any]) -> E: + def from_dict(cls, data: EmbedData) -> Self: """Converts a :class:`dict` to a :class:`Embed` provided it is in the format that Discord expects it to be in. - You can find out about this format in the `official Discord documentation`__. - - .. _DiscordDocs: https://discord.com/developers/docs/resources/channel#embed-object - - __ DiscordDocs_ + You can find out about this format in the + `official Discord documentation <https://discord.com/developers/docs/resources/channel#embed-object>`__. Parameters ---------- @@ -238,73 +231,54 @@ def from_dict(cls: Type[E], data: Mapping[str, Any]) -> E: The dictionary to convert into an embed. """ # we are bypassing __init__ here since it doesn't apply here - self: E = cls.__new__(cls) + self = cls.__new__(cls) # fill in the basic fields - self.title = data.get("title", EmptyEmbed) - self.type = data.get("type", EmptyEmbed) - self.description = data.get("description", EmptyEmbed) - self.url = data.get("url", EmptyEmbed) - - if self.title is not EmptyEmbed: - self.title = str(self.title) - - if self.description is not EmptyEmbed: - self.description = str(self.description) - - if self.url is not EmptyEmbed: - self.url = str(self.url) + self.title = str(title) if (title := data.get("title")) is not None else None + self.type = data.get("type") + self.description = ( + str(description) if (description := data.get("description")) is not None else None + ) + self.url = str(url) if (url := data.get("url")) is not None else None - self._files = [] + self._files = {} # try to fill in the more rich fields - try: - self._colour = Colour(value=data["color"]) - except KeyError: - self._colour = EmptyEmbed - - try: - self._timestamp = utils.parse_time(data["timestamp"]) - except KeyError: - pass + self.colour = data.get("color") + self.timestamp = utils.parse_time(data.get("timestamp")) - for attr in ("thumbnail", "video", "provider", "author", "fields", "image", "footer"): - try: - value = data[attr] - except KeyError: - continue - else: - setattr(self, "_" + attr, value) + self._thumbnail = data.get("thumbnail") + self._video = data.get("video") + self._provider = data.get("provider") + self._author = data.get("author") + self._image = data.get("image") + self._footer = data.get("footer") + self._fields = data.get("fields") return self - def copy(self: E) -> E: + def copy(self) -> Self: """Returns a shallow copy of the embed.""" embed = type(self).from_dict(self.to_dict()) - embed.colour = getattr(self, "_colour", EmptyEmbed) - embed._files = self._files # TODO: Maybe copy these too? + # assign manually to keep behavior of default colors + embed._colour = self._colour + # shallow copy of files + embed._files = self._files.copy() return embed def __len__(self) -> int: - total = len(self.title) + len(self.description) - for field in getattr(self, "_fields", []): - total += len(field["name"]) + len(field["value"]) + total = len(self.title or "") + len(self.description or "") + if self._fields: + for field in self._fields: + total += len(field["name"]) + len(field["value"]) - try: - footer_text = self._footer["text"] - except (AttributeError, KeyError): - pass - else: + if self._footer and (footer_text := self._footer.get("text")): total += len(footer_text) - try: - author = self._author - except AttributeError: - pass - else: - total += len(author["name"]) + if self._author and (author_name := self._author.get("name")): + total += len(author_name) return total @@ -314,69 +288,73 @@ def __bool__(self) -> bool: self.title, self.url, self.description, - hasattr(self, "_colour") and self.colour, - self.fields, - self.timestamp, - self.author, - self.thumbnail, - self.footer, - self.image, - self.provider, - self.video, + # not checking for falsy value as `0` is a valid color + self._colour not in (MISSING, None), + self._fields, + self._timestamp, + self._author, + self._thumbnail, + self._footer, + self._image, + self._provider, + self._video, ) ) @property - def colour(self) -> MaybeEmpty[Colour]: - return getattr(self, "_colour", type(self)._default_colour) + def colour(self) -> Optional[Colour]: + col = self._colour + return col if col is not MISSING else type(self)._default_colour @colour.setter - def colour(self, value: Union[int, Colour, _EmptyEmbed]): # type: ignore - if isinstance(value, (Colour, _EmptyEmbed)): - self._colour = value - elif isinstance(value, int): + def colour(self, value: Optional[Union[int, Colour]]): + if isinstance(value, int): self._colour = Colour(value=value) + elif value is MISSING or value is None or isinstance(value, Colour): + self._colour = value else: raise TypeError( - f"Expected disnake.Colour, int, or Embed.Empty but received {type(value).__name__} instead." + f"Expected disnake.Colour, int, or None but received {type(value).__name__} instead." ) @colour.deleter def colour(self): - del self._colour + self._colour = MISSING color = colour @property - def timestamp(self) -> MaybeEmpty[datetime.datetime]: - return getattr(self, "_timestamp", EmptyEmbed) + def timestamp(self) -> Optional[datetime.datetime]: + return self._timestamp @timestamp.setter - def timestamp(self, value: MaybeEmpty[datetime.datetime]): + def timestamp(self, value: Optional[datetime.datetime]): if isinstance(value, datetime.datetime): if value.tzinfo is None: value = value.astimezone() self._timestamp = value - elif isinstance(value, _EmptyEmbed): + elif value is None: self._timestamp = value else: raise TypeError( - f"Expected datetime.datetime or Embed.Empty received {type(value).__name__} instead" + f"Expected datetime.datetime or None received {type(value).__name__} instead" ) @property def footer(self) -> _EmbedFooterProxy: """Returns an ``EmbedProxy`` denoting the footer contents. - See :meth:`set_footer` for possible values you can access. + Possible attributes you can access are: + + - ``text`` + - ``icon_url`` + - ``proxy_icon_url`` - If the attribute has no value then :attr:`Empty` is returned. + If an attribute is not set, it will be ``None``. """ - return EmbedProxy(getattr(self, "_footer", {})) # type: ignore + return cast("_EmbedFooterProxy", EmbedProxy(self._footer)) - def set_footer( - self: E, *, text: MaybeEmpty[Any] = EmptyEmbed, icon_url: MaybeEmpty[Any] = EmptyEmbed - ) -> E: + def set_footer(self, *, text: Any, icon_url: Optional[Any] = None) -> Self: """Sets the footer for the embed content. This function returns the class instance to allow for fluent-style @@ -386,19 +364,23 @@ def set_footer( ---------- text: :class:`str` The footer text. - icon_url: :class:`str` + + .. versionchanged:: 2.6 + No longer optional, must be set to a valid string. + + icon_url: Optional[:class:`str`] The URL of the footer icon. Only HTTP(S) is supported. """ - self._footer = {} - if text is not EmptyEmbed: - self._footer["text"] = str(text) + self._footer = { + "text": str(text), + } - if icon_url is not EmptyEmbed: + if icon_url is not None: self._footer["icon_url"] = str(icon_url) return self - def remove_footer(self: E) -> E: + def remove_footer(self) -> Self: """Clears embed's footer information. This function returns the class instance to allow for fluent-style @@ -406,11 +388,7 @@ def remove_footer(self: E) -> E: .. versionadded:: 2.0 """ - try: - del self._footer - except AttributeError: - pass - + self._footer = None return self @property @@ -424,45 +402,40 @@ def image(self) -> _EmbedMediaProxy: - ``width`` - ``height`` - If the attribute has no value then :attr:`Empty` is returned. + If an attribute is not set, it will be ``None``. """ - return EmbedProxy(getattr(self, "_image", {})) # type: ignore + return cast("_EmbedMediaProxy", EmbedProxy(self._image)) - def set_image(self: E, url: MaybeEmpty[Any] = MISSING, *, file: File = MISSING) -> E: + @overload + def set_image(self, url: Optional[Any]) -> Self: + ... + + @overload + def set_image(self, *, file: File) -> Self: + ... + + def set_image(self, url: Optional[Any] = MISSING, *, file: File = MISSING) -> Self: """Sets the image for the embed content. This function returns the class instance to allow for fluent-style chaining. + Exactly one of ``url`` or ``file`` must be passed. + .. versionchanged:: 1.4 - Passing :attr:`Empty` removes the image. + Passing ``None`` removes the image. Parameters ---------- - url: :class:`str` + url: Optional[:class:`str`] The source URL for the image. Only HTTP(S) is supported. file: :class:`File` The file to use as the image. .. versionadded:: 2.2 """ - if file: - if url: - raise TypeError("Cannot use both a url and a file at the same time") - if file.filename is None: - raise TypeError("File doesn't have a filename") - self._image = {"url": f"attachment://{file.filename}"} - self._files.append(file) - elif url is EmptyEmbed: - try: - del self._image - except AttributeError: - pass - elif url is MISSING: - raise TypeError("Neither a url nor a file have been provided") - else: - self._image = {"url": str(url)} - + result = self._handle_resource(url, file, key="image") + self._image = {"url": result} if result is not None else None return self @property @@ -476,45 +449,40 @@ def thumbnail(self) -> _EmbedMediaProxy: - ``width`` - ``height`` - If the attribute has no value then :attr:`Empty` is returned. + If an attribute is not set, it will be ``None``. """ - return EmbedProxy(getattr(self, "_thumbnail", {})) # type: ignore + return cast("_EmbedMediaProxy", EmbedProxy(self._thumbnail)) + + @overload + def set_thumbnail(self, url: Optional[Any]) -> Self: + ... - def set_thumbnail(self: E, url: MaybeEmpty[Any] = MISSING, *, file: File = MISSING) -> E: + @overload + def set_thumbnail(self, *, file: File) -> Self: + ... + + def set_thumbnail(self, url: Optional[Any] = MISSING, *, file: File = MISSING) -> Self: """Sets the thumbnail for the embed content. This function returns the class instance to allow for fluent-style chaining. + Exactly one of ``url`` or ``file`` must be passed. + .. versionchanged:: 1.4 - Passing :attr:`Empty` removes the thumbnail. + Passing ``None`` removes the thumbnail. Parameters ---------- - url: :class:`str` + url: Optional[:class:`str`] The source URL for the thumbnail. Only HTTP(S) is supported. file: :class:`File` The file to use as the image. .. versionadded:: 2.2 """ - if file: - if url: - raise TypeError("Cannot use both a url and a file at the same time") - if file.filename is None: - raise TypeError("File doesn't have a filename") - self._thumbnail = {"url": f"attachment://{file.filename}"} - self._files.append(file) - elif url is EmptyEmbed: - try: - del self._thumbnail - except AttributeError: - pass - elif url is MISSING: - raise TypeError("Neither a url nor a file have been provided") - else: - self._thumbnail = {"url": str(url)} - + result = self._handle_resource(url, file, key="thumbnail") + self._thumbnail = {"url": result} if result is not None else None return self @property @@ -524,12 +492,13 @@ def video(self) -> _EmbedVideoProxy: Possible attributes include: - ``url`` for the video URL. + - ``proxy_url`` for the proxied video URL. - ``height`` for the video height. - ``width`` for the video width. - If the attribute has no value then :attr:`Empty` is returned. + If an attribute is not set, it will be ``None``. """ - return EmbedProxy(getattr(self, "_video", {})) # type: ignore + return cast("_EmbedVideoProxy", EmbedProxy(self._video)) @property def provider(self) -> _EmbedProviderProxy: @@ -537,9 +506,9 @@ def provider(self) -> _EmbedProviderProxy: The only attributes that might be accessed are ``name`` and ``url``. - If the attribute has no value then :attr:`Empty` is returned. + If an attribute is not set, it will be ``None``. """ - return EmbedProxy(getattr(self, "_provider", {})) # type: ignore + return cast("_EmbedProviderProxy", EmbedProxy(self._provider)) @property def author(self) -> _EmbedAuthorProxy: @@ -547,17 +516,17 @@ def author(self) -> _EmbedAuthorProxy: See :meth:`set_author` for possible values you can access. - If the attribute has no value then :attr:`Empty` is returned. + If an attribute is not set, it will be ``None``. """ - return EmbedProxy(getattr(self, "_author", {})) # type: ignore + return cast("_EmbedAuthorProxy", EmbedProxy(self._author)) def set_author( - self: E, + self, *, name: Any, - url: MaybeEmpty[Any] = EmptyEmbed, - icon_url: MaybeEmpty[Any] = EmptyEmbed, - ) -> E: + url: Optional[Any] = None, + icon_url: Optional[Any] = None, + ) -> Self: """Sets the author for the embed content. This function returns the class instance to allow for fluent-style @@ -567,24 +536,24 @@ def set_author( ---------- name: :class:`str` The name of the author. - url: :class:`str` + url: Optional[:class:`str`] The URL for the author. - icon_url: :class:`str` + icon_url: Optional[:class:`str`] The URL of the author icon. Only HTTP(S) is supported. """ self._author = { "name": str(name), } - if url is not EmptyEmbed: + if url is not None: self._author["url"] = str(url) - if icon_url is not EmptyEmbed: + if icon_url is not None: self._author["icon_url"] = str(icon_url) return self - def remove_author(self: E) -> E: + def remove_author(self) -> Self: """Clears embed's author information. This function returns the class instance to allow for fluent-style @@ -592,24 +561,20 @@ def remove_author(self: E) -> E: .. versionadded:: 1.4 """ - try: - del self._author - except AttributeError: - pass - + self._author = None return self @property def fields(self) -> List[_EmbedFieldProxy]: - """List[Union[``EmbedProxy``, :attr:`Empty`]]: Returns a :class:`list` of ``EmbedProxy`` denoting the field contents. + """List[``EmbedProxy``]: Returns a :class:`list` of ``EmbedProxy`` denoting the field contents. See :meth:`add_field` for possible values you can access. - If the attribute has no value then :attr:`Empty` is returned. + If an attribute is not set, it will be ``None``. """ - return [EmbedProxy(d) for d in getattr(self, "_fields", [])] # type: ignore + return cast("List[_EmbedFieldProxy]", [EmbedProxy(d) for d in (self._fields or [])]) - def add_field(self: E, name: Any, value: Any, *, inline: bool = True) -> E: + def add_field(self, name: Any, value: Any, *, inline: bool = True) -> Self: """Adds a field to the embed object. This function returns the class instance to allow for fluent-style @@ -623,21 +588,22 @@ def add_field(self: E, name: Any, value: Any, *, inline: bool = True) -> E: The value of the field. inline: :class:`bool` Whether the field should be displayed inline. + Defaults to ``True``. """ - field = { + field: EmbedFieldPayload = { "inline": inline, "name": str(name), "value": str(value), } - try: + if self._fields is not None: self._fields.append(field) - except AttributeError: + else: self._fields = [field] return self - def insert_field_at(self: E, index: int, name: Any, value: Any, *, inline: bool = True) -> E: + def insert_field_at(self, index: int, name: Any, value: Any, *, inline: bool = True) -> Self: """Inserts a field before a specified index to the embed. This function returns the class instance to allow for fluent-style @@ -655,26 +621,24 @@ def insert_field_at(self: E, index: int, name: Any, value: Any, *, inline: bool The value of the field. inline: :class:`bool` Whether the field should be displayed inline. + Defaults to ``True``. """ - field = { + field: EmbedFieldPayload = { "inline": inline, "name": str(name), "value": str(value), } - try: + if self._fields is not None: self._fields.insert(index, field) - except AttributeError: + else: self._fields = [field] return self def clear_fields(self) -> None: """Removes all fields from this embed.""" - try: - self._fields.clear() - except AttributeError: - self._fields = [] + self._fields = None def remove_field(self, index: int) -> None: """Removes a field at a specified index. @@ -692,12 +656,13 @@ def remove_field(self, index: int) -> None: index: :class:`int` The index of the field to remove. """ - try: - del self._fields[index] - except (AttributeError, IndexError): - pass + if self._fields is not None: + try: + del self._fields[index] + except IndexError: + pass - def set_field_at(self: E, index: int, name: Any, value: Any, *, inline: bool = True) -> E: + def set_field_at(self, index: int, name: Any, value: Any, *, inline: bool = True) -> Self: """Modifies a field to the embed object. The index must point to a valid pre-existing field. @@ -715,15 +680,18 @@ def set_field_at(self: E, index: int, name: Any, value: Any, *, inline: bool = T The value of the field. inline: :class:`bool` Whether the field should be displayed inline. + Defaults to ``True``. Raises ------ IndexError An invalid index was provided. """ + if not self._fields: + raise IndexError("field index out of range") try: field = self._fields[index] - except (TypeError, IndexError, AttributeError): + except IndexError: raise IndexError("field index out of range") field["name"] = str(name) @@ -735,26 +703,28 @@ def to_dict(self) -> EmbedData: """Converts this embed object into a dict.""" # add in the raw data into the dict - # fmt: off - result = { - key[1:]: getattr(self, key) - for key in self.__slots__ - if key[0] == '_' and hasattr(self, key) and key not in ("_colour", "_files") - } - # fmt: on + result: EmbedData = {} + if self._footer is not None: + result["footer"] = self._footer + if self._image is not None: + result["image"] = self._image + if self._thumbnail is not None: + result["thumbnail"] = self._thumbnail + if self._video is not None: + result["video"] = self._video + if self._provider is not None: + result["provider"] = self._provider + if self._author is not None: + result["author"] = self._author + if self._fields is not None: + result["fields"] = self._fields # deal with basic convenience wrappers - - if isinstance(self.colour, Colour): + if self.colour: result["color"] = self.colour.value - try: - timestamp = result.pop("timestamp") - except KeyError: - pass - else: - if timestamp: - result["timestamp"] = timestamp.astimezone(tz=datetime.timezone.utc).isoformat() + if self._timestamp: + result["timestamp"] = self._timestamp.astimezone(tz=datetime.timezone.utc).isoformat() # add in the non raw attribute ones if self.type: @@ -769,7 +739,7 @@ def to_dict(self) -> EmbedData: if self.title: result["title"] = self.title - return result # type: ignore + return result @classmethod def set_default_colour(cls, value: Optional[Union[int, Colour]]): @@ -780,26 +750,23 @@ def set_default_colour(cls, value: Optional[Union[int, Colour]]): Returns ------- - :class:`Colour` + Optional[:class:`Colour`] The colour that was set. - """ - if value == None: - cls._default_colour = cls.Empty - elif isinstance(value, (Colour, _EmptyEmbed)): + if value is None or isinstance(value, Colour): cls._default_colour = value elif isinstance(value, int): cls._default_colour = Colour(value=value) else: raise TypeError( - f"Expected disnake.Colour, or int, but received {type(value).__name__} instead." + f"Expected disnake.Colour, int, or None but received {type(value).__name__} instead." ) return cls._default_colour set_default_color = set_default_colour @classmethod - def get_default_colour(cls) -> MaybeEmpty[Colour]: + def get_default_colour(cls) -> Optional[Colour]: """ Get the default colour of all new embeds. @@ -807,10 +774,23 @@ def get_default_colour(cls) -> MaybeEmpty[Colour]: Returns ------- - :class:`Colour` + Optional[:class:`Colour`] The default colour. """ return cls._default_colour get_default_color = get_default_colour + + def _handle_resource(self, url: Optional[Any], file: File, *, key: _FileKey) -> Optional[str]: + if not (url is MISSING) ^ (file is MISSING): + raise TypeError("Exactly one of url or file must be provided") + + if file: + if file.filename is None: + raise TypeError("File must have a filename") + self._files[key] = file + return f"attachment://{file.filename}" + else: + self._files.pop(key, None) + return str(url) if url is not None else None diff --git a/disnake/interactions/base.py b/disnake/interactions/base.py index 295cf4ca33..f75c1e068c 100644 --- a/disnake/interactions/base.py +++ b/disnake/interactions/base.py @@ -870,7 +870,7 @@ async def send_message( for embed in embeds: if embed._files: files = files or [] - files += embed._files + files.extend(embed._files.values()) if files is not MISSING and len(files) > 10: raise ValueError("files cannot exceed maximum of 10 elements") @@ -1049,7 +1049,7 @@ async def edit_message( for embed in embeds: if embed._files: files = files or [] - files += embed._files + files.extend(embed._files.values()) if files is not MISSING and len(files) > 10: raise ValueError("files cannot exceed maximum of 10 elements") diff --git a/disnake/message.py b/disnake/message.py index cb8274fe14..ba75db7988 100644 --- a/disnake/message.py +++ b/disnake/message.py @@ -175,7 +175,7 @@ async def _edit_handler( for embed in embeds: if embed._files: files = files or [] - files += embed._files + files.extend(embed._files.values()) if suppress_embeds is not MISSING: flags = MessageFlags._from_value(default_flags) diff --git a/disnake/ui/button.py b/disnake/ui/button.py index 2b6be1e4fe..7dad8db0a4 100644 --- a/disnake/ui/button.py +++ b/disnake/ui/button.py @@ -222,7 +222,7 @@ def emoji(self) -> Optional[PartialEmoji]: return self._underlying.emoji @emoji.setter - def emoji(self, value: Optional[Union[str, Emoji, PartialEmoji]]): # type: ignore + def emoji(self, value: Optional[Union[str, Emoji, PartialEmoji]]): if value is not None: if isinstance(value, str): self._underlying.emoji = PartialEmoji.from_str(value) diff --git a/disnake/webhook/async_.py b/disnake/webhook/async_.py index 70588079c5..8c151abcd6 100644 --- a/disnake/webhook/async_.py +++ b/disnake/webhook/async_.py @@ -527,7 +527,7 @@ def handle_message_parameters_dict( for embed in embeds: if embed._files: files = files or [] - files += embed._files + files.extend(embed._files.values()) if content is not MISSING: payload["content"] = str(content) if content is not None else None diff --git a/pyproject.toml b/pyproject.toml index 0621f5da31..6426b913d7 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -49,7 +49,6 @@ ignore = [ strictParameterNoneValue = false reportInvalidStringEscapeSequence = false -reportPropertyTypeMismatch = true reportDuplicateImport = true reportUntypedFunctionDecorator = true reportUntypedClassDecorator = true
diff --git a/tests/test_embeds.py b/tests/test_embeds.py new file mode 100644 index 0000000000..fcaf2da396 --- /dev/null +++ b/tests/test_embeds.py @@ -0,0 +1,312 @@ +import io +from datetime import datetime, timedelta + +import pytest + +from disnake import Color, Embed, File +from disnake.utils import MISSING, utcnow + +_BASE = {"type": "rich"} + + [email protected] +def embed() -> Embed: + time = utcnow() + timedelta(days=42) + return Embed( + type="link", + title="wow", + description="what a cool embed", + url="http://endless.horse", + timestamp=time, + color=0xF8A8B8, + ) + + [email protected] +def file() -> File: + return File(io.BytesIO(b"abcd"), filename="data.txt") + + +def test_init_empty() -> None: + embed = Embed() + assert embed.title is None + assert embed.description is None + assert embed.url is None + assert embed.timestamp is None + + assert embed.to_dict() == _BASE + assert not bool(embed) + + assert embed.fields == [] + + +def test_init_all(embed: Embed) -> None: + assert embed.timestamp + assert embed.to_dict() == { + "type": "link", + "title": "wow", + "description": "what a cool embed", + "url": "http://endless.horse", + "timestamp": embed.timestamp.isoformat(), + "color": 0xF8A8B8, + } + assert bool(embed) + + +def test_type_default() -> None: + # type for new embeds should be set to default value + assert Embed().type == "rich" + + # type shouldn't be set in from_dict if dict didn't contain a type + assert Embed.from_dict({}).type is None + + +def test_timestamp_naive(embed: Embed) -> None: + embed.timestamp = datetime.now() + assert embed.timestamp.tzinfo is not None + + +def test_len(embed: Embed) -> None: + assert len(embed) == 20 + + embed.set_footer(text="hmm", icon_url="https://localhost") + assert len(embed) == 23 + + embed.set_author(name="someone", url="https://127.0.0.1", icon_url="https://127.0.0.2") + assert len(embed) == 30 + + embed.add_field("field name", "field value") + embed.add_field("another field", "woooo") + assert len(embed) == 69 + + +def test_color_zero() -> None: + e = Embed() + assert not e + + # color=0 should be applied to bool and dict + e.color = 0 + assert e + assert e.to_dict() == {"color": 0, **_BASE} + + +def test_default_color() -> None: + try: + # color applies if set before init + Embed.set_default_color(123456) + embed = Embed() + assert embed.color == Color(123456) + + # default color should not affect __bool__ + assert not bool(embed) + + # custom value overrides default + embed.color = 987654 + assert embed.color == Color(987654) + assert embed.to_dict() == {"color": 987654, **_BASE} + assert bool(embed) + + # removing custom value resets to default + del embed.color + assert embed.color == Color(123456) + + # clearing default changes color to `None` + Embed.set_default_color(None) + assert embed.color is None + finally: + Embed.set_default_color(None) + + +def test_default_color_copy(embed: Embed) -> None: + # copy should retain color + assert embed.copy().color == Color(0xF8A8B8) + + del embed.color + assert embed.copy().color is None + + try: + # copying with default value should not set attribute + Embed.set_default_color(123456) + c = embed.copy() + assert c._colour is MISSING + + assert c.color == Color(123456) + finally: + Embed.set_default_color(None) + + +def test_attr_proxy() -> None: + embed = Embed() + author = embed.author + assert len(author) == 0 + + embed.set_author(name="someone") + author = embed.author + assert len(author) == 1 + assert author.name == "someone" + assert embed.to_dict() == {"author": {"name": "someone"}, **_BASE} + assert author.icon_url is None + + embed.set_author(name="abc", icon_url="https://xyz") + assert len(embed.author) == 2 + + embed.remove_author() + assert len(embed.author) == 0 + assert embed.to_dict() == _BASE + + +def test_image_init() -> None: + # should be empty initially + embed = Embed() + assert embed._files == {} + assert embed.to_dict() == _BASE + + +def test_image_none() -> None: + # removing image shouldn't change dict + embed = Embed() + embed.set_image(None) + assert embed._files == {} + assert embed.to_dict() == _BASE + + +def test_image_url() -> None: + embed = Embed() + embed.set_image("https://disnake.dev") + assert embed._files == {} + assert embed.to_dict() == {"image": {"url": "https://disnake.dev"}, **_BASE} + + +def test_image_file(file: File) -> None: + embed = Embed() + embed.set_image(file=file) + assert embed._files == {"image": file} + assert embed.to_dict() == {"image": {"url": "attachment://data.txt"}, **_BASE} + + +def test_image_remove(file: File) -> None: + embed = Embed() + embed.set_image(file=file) + embed.set_image(None) + assert embed._files == {} + assert embed.to_dict() == _BASE + + +def test_file_params(file: File) -> None: + embed = Embed() + with pytest.raises(TypeError): + embed.set_image("https://disnake.dev/assets/disnake-logo.png", file=file) # type: ignore + + assert embed._files == {} + assert embed.to_dict() == _BASE + + +def test_file_filename(file: File) -> None: + embed = Embed() + file.filename = None + with pytest.raises(TypeError): + embed.set_image(file=file) + + +def test_file_overwrite_url(file: File) -> None: + embed = Embed() + # setting url should remove file + embed.set_image(file=file) + embed.set_image("https://abc") + assert embed._files == {} + assert embed.to_dict() == {"image": {"url": "https://abc"}, **_BASE} + + +def test_file_overwrite_file(file: File) -> None: + embed = Embed() + # setting file twice should keep second one + file2 = File(io.BytesIO(), filename="empty.dat") + embed.set_image(file=file) + embed.set_image(file=file2) + assert embed._files == {"image": file2} + assert embed.to_dict() == {"image": {"url": "attachment://empty.dat"}, **_BASE} + + +def test_file_multiple(file: File) -> None: + embed = Embed() + # setting multiple files should work correctly + embed.set_image(file=file) + embed.set_thumbnail(file=file) + assert embed._files == {"image": file, "thumbnail": file} + assert embed.to_dict() == { + "image": {"url": "attachment://data.txt"}, + "thumbnail": {"url": "attachment://data.txt"}, + **_BASE, + } + + +def test_fields() -> None: + embed = Embed() + + embed.insert_field_at(42, "a", "b") + assert embed.to_dict() == {"fields": [{"name": "a", "value": "b", "inline": True}], **_BASE} + + embed.insert_field_at(0, "c", "d") + assert embed.to_dict() == { + "fields": [ + {"name": "c", "value": "d", "inline": True}, + {"name": "a", "value": "b", "inline": True}, + ], + **_BASE, + } + + embed.set_field_at(-1, "e", "f", inline=False) + assert embed.to_dict() == { + "fields": [ + {"name": "c", "value": "d", "inline": True}, + {"name": "e", "value": "f", "inline": False}, + ], + **_BASE, + } + + embed.remove_field(0) + assert embed.to_dict() == {"fields": [{"name": "e", "value": "f", "inline": False}], **_BASE} + + embed.clear_fields() + assert embed.to_dict() == _BASE + + +def test_fields_exceptions() -> None: + embed = Embed() + + # shouldn't raise + embed.remove_field(42) + + # also shouldn't raise + embed.add_field("a", "b") + embed.remove_field(5) + + with pytest.raises(IndexError): + embed.set_field_at(42, "x", "y") + + embed.clear_fields() + with pytest.raises(IndexError): + embed.set_field_at(0, "x", "y") + + +def test_copy(embed: Embed, file: File) -> None: + embed.set_footer(text="hi there", icon_url="https://localhost") + embed.set_author(name="someone", url="https://127.0.0.1", icon_url="https://127.0.0.2") + embed.add_field("field name", "field value") + embed.add_field("another field", "woooo") + embed.set_thumbnail("https://thumbnail.url") + embed.set_image(file=file) + + # copying should keep exact dict representation + copy = embed.copy() + assert embed.to_dict() == copy.to_dict() + + # shallow copy, but `_files` should be copied + assert embed._files == copy._files + assert embed._files is not copy._files + + +def test_copy_empty() -> None: + e = Embed.from_dict({}) + copy = e.copy() + assert e.to_dict() == copy.to_dict() == {}
Embed.set_author creates an invalid embed payload if you set icon_url=None ### Summary Embed.set_author creates an invalid embed payload if you set icon_url=None ### Reproduction Steps Where `author` is a member with no avatar set, meaning `author.avatar` is `None`, the code ```py embed.set_author( name=author.name, icon_url=author.avatar ) await send(embed=embed) ``` Will cause a 400 as embed payload being sent has an author with icon_url equal to the string `'None'`, as `Embed.set_author` simply do `str(icon_url)` if `icon_url` is not `EmptyEmbed`. The issue here is that `User.avatar` can be null, and if passing in `None` as `icon_url` into `Embed.set_author`, the actual url will be set to the string `'None'`. One can solve this in userland by doing: ```py embed.set_author( name=author.name, icon_url=author.avatar or disnake.Embed.Empty ) await send(embed=embed) ``` -- but surely that's not a recommended solution? ### Minimal Reproducible Code _No response_ ### Expected Results not applicable ### Actual Results not applicable ### Intents not applicable ### System Information disnake 2.3.0 ### Checklist - [X] I have searched the open issues for duplicates. - [X] I have shown the entire traceback, if possible. - [X] I have removed my token from display, if visible. ### Additional Context _No response_
This is due to some questionable legacy features left over from discord.py. In my opinion we should either get rid of empty where it isn't applicable or turn all None into empty by default. After looking more at this, I now realise what I want to use is `display_avatar`, as that will automatically handle the case where `avatar` is None, and use the value of `default_avatar`. I suppose this isn't really a bug, though the combination of `User.avatar` being optional and `Embed.set_author` freaking out if setting `icon_url` to None is unfortunate. I'll let repo owners close the issue if they feel this isn't a real bug, or the discussion of whether Embed.Empty is reasonable belongs in another issue. While this issue was indeed caused by the improper usage of `User.avatar` it still doesn't change the fact that embeds are very annoying to use due to how empty is handled. We'll be keeping this open until the user experience is improved.
2022-03-27T19:07:18.000
-1.0
[ "tests/test_embeds.py::test_file_overwrite_url", "tests/test_embeds.py::test_file_params", "tests/test_embeds.py::test_file_multiple", "tests/test_embeds.py::test_file_overwrite_file", "tests/test_embeds.py::test_image_url", "tests/test_embeds.py::test_fields", "tests/test_embeds.py::test_init_empty", "tests/test_embeds.py::test_default_color_copy", "tests/test_embeds.py::test_image_remove", "tests/test_embeds.py::test_default_color", "tests/test_embeds.py::test_copy", "tests/test_embeds.py::test_image_file", "tests/test_embeds.py::test_image_init", "tests/test_embeds.py::test_image_none", "tests/test_embeds.py::test_attr_proxy", "tests/test_embeds.py::test_type_default" ]
[ "tests/test_embeds.py::test_timestamp_naive", "tests/test_embeds.py::test_init_all", "tests/test_embeds.py::test_color_zero", "tests/test_embeds.py::test_copy_empty", "tests/test_embeds.py::test_file_filename", "tests/test_embeds.py::test_len", "tests/test_embeds.py::test_fields_exceptions" ]
drivendataorg/deon
91
drivendataorg__deon-91
['88']
1af17b9ef48382f18656e3e42c132de9f3b7764c
diff --git a/README.md b/README.md index 79f2ab0..749b693 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,7 @@ --- **δέον** • (déon) [n.] (_Ancient Greek_) <small><a href="https://en.wiktionary.org/wiki/%CE%B4%CE%AD%CE%BF%CE%BD#Ancient_Greek" target="_blank" style="text-decoration: none; color: #6d6d6d">wikitionary</a></small> - > Duty; that which is binding, needful, right, proper. + > Duty; that which is binding, needful, right, proper. -------- @@ -25,7 +25,7 @@ The conversation about ethics in data science, machine learning, and AI is incre We have a particular perspective with this package that we will use to make decisions about contributions, issues, PRs, and other maintenance and support activities. -First and foremost, our goal is not to be arbitrators of what ethical concerns merit inclusion. We have a [process for changing the default checklist](#changing-the-checklist), but we believe that many domain-specific concerns are not included and teams will benefit from developing [custom checklists](#custom-checklists). Not every checklist item will be relevant. We encourage teams to remove items, sections, or mark items as `N/A` as the concerns of their projects dictate. +First and foremost, our goal is not to be arbitrators of what ethical concerns merit inclusion. We have a [process for changing the default checklist](#changing-the-checklist), but we believe that many domain-specific concerns are not included and teams will benefit from developing [custom checklists](#custom-checklists). Not every checklist item will be relevant. We encourage teams to remove items, sections, or mark items as `N/A` as the concerns of their projects dictate. Second, we built our initial list from a set of proposed items on [multiple checklists that we referenced](#checklist-citations). This checklist was heavily inspired by an article written by Mike Loukides, Hilary Mason, and DJ Patil and published by O'Reilly: ["Of Oaths and Checklists"](https://www.oreilly.com/ideas/of-oaths-and-checklists). We owe a great debt to the thinking that proceeded this, and we look forward to thoughtful engagement with the ongoing discussion about checklists for data science ethics. @@ -50,7 +50,6 @@ Ninth, we want all the checklist items to be as simple as possible (but no simpl ## Prerequisites - Python >3.6: Your project need not be Python 3, but you need Python 3 to execute this tool. - - _(Linux Specific)_: using the `--clipboard` option requires the [`xclip`](https://github.com/astrand/xclip) package, which is easily installable on most distributions (e.g., `sudo apt-get install xclip`). ## Installation @@ -113,6 +112,11 @@ Here are the currently supported file types. We will accept pull requests with n ``` Usage: deon [OPTIONS] + Easily create an ethics checklist for your data science project. + + The checklist will be printed to standard output by default. Use the + --output option to write to a file instead. + Options: -l, --checklist PATH Override default checklist file with a path to a custom checklist.yml file. @@ -122,7 +126,6 @@ Options: -o, --output PATH Output file path. Extension can be one of [.txt, .html, .ipynb, .md, .rmd, .rst] The checklist is appended if the file exists. - -c, --clipboard Whether or not to copy the output to the clipboard. -w, --overwrite Overwrite output file if it exists. Default is False , which will append to existing file. @@ -180,7 +183,7 @@ Custom checklists must follow the same schema as `checklist.yml`. There must be ``` title: TITLE -sections: +sections: - title: SECTION TITLE section_id: SECTION NUMBER lines: @@ -193,7 +196,7 @@ sections: Please see [the framing](#background-and-perspective) for an understanding of our perspective. Given this perspective, we will consider changes to the default checklist that fit with that perspective and follow this process. -Our goal is to have checklist items that are actionable as part of a review of data science work or as part of a plan. Please avoid suggesting items that are too vague (e.g., "do no harm") or too specific (e.g., "remove social security numbers from data"). +Our goal is to have checklist items that are actionable as part of a review of data science work or as part of a plan. Please avoid suggesting items that are too vague (e.g., "do no harm") or too specific (e.g., "remove social security numbers from data"). **Note: This process is an experiment and is subject to change based on how well it works. Our goal is to avoid flame wars in the issue threads while still making a tool that will make adding an ethics checklist to a project easy.** diff --git a/deon/cli.py b/deon/cli.py index e8da480..8fd02dd 100644 --- a/deon/cli.py +++ b/deon/cli.py @@ -15,28 +15,28 @@ @click.option('--output', '-o', default=None, type=click.Path(), help='Output file path. Extension can be one of [{}] '.format(', '.join(EXTENSIONS.keys())) + 'The checklist is appended if the file exists.') [email protected]('--clipboard', '-c', is_flag=True, default=False, - help='Whether or not to copy the output to the clipboard.') @click.option('--overwrite', '-w', is_flag=True, default=False, help='Overwrite output file if it exists. \ Default is False , which will append \ to existing file.') -def main(checklist, output_format, output, clipboard, overwrite): +def main(checklist, output_format, output, overwrite): + """Easily create an ethics checklist for your data science project. + + The checklist will be printed to standard output by default. Use the --output option to write to a file instead. + """ try: - result = create(checklist, output_format, output, clipboard, overwrite) + result = create(checklist, output_format, output, overwrite) except ExtensionException: with click.get_current_context() as ctx: - msg = 'Output requires a file name with a supported extension.\n\n' - raise click.ClickException(msg + ctx.get_help()) + msg = 'Output requires a file name with a supported extension.\n\n' + raise click.ClickException(msg + ctx.get_help()) except FormatException: with click.get_current_context() as ctx: - msg = f"File format {output_format} is not supported.\n\n" - raise click.ClickException(msg + ctx.get_help()) + msg = f"File format {output_format} is not supported.\n\n" + raise click.ClickException(msg + ctx.get_help()) else: # write output or print to stdout if result: click.echo(result) - elif clipboard: - click.echo("Checklist successfully copied to clipboard.") else: click.echo(f"Checklist successfully written to file {output}.") diff --git a/deon/deon.py b/deon/deon.py index 74ad881..3ece392 100644 --- a/deon/deon.py +++ b/deon/deon.py @@ -1,8 +1,6 @@ import os from pathlib import Path -import xerox - from .formats import EXTENSIONS, FORMATS from .parser import Checklist @@ -19,7 +17,7 @@ class FormatException(Exception): pass -def create(checklist, output_format, output, clipboard, overwrite): +def create(checklist, output_format, output, overwrite): # load checklist cl_path = Path(checklist) if checklist else DEFAULT_CHECKLIST cl = Checklist.read(cl_path) @@ -45,7 +43,5 @@ def create(checklist, output_format, output, clipboard, overwrite): # write output or print to stdout if output: template.write(output, overwrite=overwrite) - elif clipboard: - xerox.copy(str(template.render())) else: return template.render() diff --git a/docs/docs/index.md b/docs/docs/index.md index 4122c20..663d401 100644 --- a/docs/docs/index.md +++ b/docs/docs/index.md @@ -8,7 +8,7 @@ --- **δέον** • (déon) [n.] (_Ancient Greek_) <small><a href="https://en.wiktionary.org/wiki/%CE%B4%CE%AD%CE%BF%CE%BD#Ancient_Greek" target="_blank" style="text-decoration: none; color: #6d6d6d">wikitionary</a></small> - > Duty; that which is binding, needful, right, proper. + > Duty; that which is binding, needful, right, proper. -------- @@ -18,7 +18,7 @@ The conversation about ethics in data science, machine learning, and AI is incre We have a particular perspective with this package that we will use to make decisions about contributions, issues, PRs, and other maintenance and support activities. -First and foremost, our goal is not to be arbitrators of what ethical concerns merit inclusion. We have a [process for changing the default checklist](#changing-the-checklist), but we believe that many domain-specific concerns are not included and teams will benefit from developing [custom checklists](#custom-checklists). Not every checklist item will be relevant. We encourage teams to remove items, sections, or mark items as `N/A` as the concerns of their projects dictate. +First and foremost, our goal is not to be arbitrators of what ethical concerns merit inclusion. We have a [process for changing the default checklist](#changing-the-checklist), but we believe that many domain-specific concerns are not included and teams will benefit from developing [custom checklists](#custom-checklists). Not every checklist item will be relevant. We encourage teams to remove items, sections, or mark items as `N/A` as the concerns of their projects dictate. Second, we built our initial list from a set of proposed items on [multiple checklists that we referenced](#checklist-citations). This checklist was heavily inspired by an article written by Mike Loukides, Hilary Mason, and DJ Patil and published by O'Reilly: ["Of Oaths and Checklists"](https://www.oreilly.com/ideas/of-oaths-and-checklists). We owe a great debt to the thinking that proceeded this, and we look forward to thoughtful engagement with the ongoing discussion about checklists for data science ethics. @@ -43,7 +43,6 @@ Ninth, we want all the checklist items to be as simple as possible (but no simpl ## Prerequisites - Python >3.6: Your project need not be Python 3, but you need Python 3 to execute this tool. - - _(Linux Specific)_: using the `--clipboard` option requires the [`xclip`](https://github.com/astrand/xclip) package, which is easily installable on most distributions (e.g., `sudo apt-get install xclip`). ## Installation @@ -106,6 +105,11 @@ Here are the currently supported file types. We will accept pull requests with n ``` Usage: deon [OPTIONS] + Easily create an ethics checklist for your data science project. + + The checklist will be printed to standard output by default. Use the + --output option to write to a file instead. + Options: -l, --checklist PATH Override default checklist file with a path to a custom checklist.yml file. @@ -115,7 +119,6 @@ Options: -o, --output PATH Output file path. Extension can be one of [.txt, .html, .ipynb, .md, .rmd, .rst] The checklist is appended if the file exists. - -c, --clipboard Whether or not to copy the output to the clipboard. -w, --overwrite Overwrite output file if it exists. Default is False , which will append to existing file. @@ -173,7 +176,7 @@ Custom checklists must follow the same schema as `checklist.yml`. There must be ``` title: TITLE -sections: +sections: - title: SECTION TITLE section_id: SECTION NUMBER lines: @@ -186,7 +189,7 @@ sections: Please see [the framing](#background-and-perspective) for an understanding of our perspective. Given this perspective, we will consider changes to the default checklist that fit with that perspective and follow this process. -Our goal is to have checklist items that are actionable as part of a review of data science work or as part of a plan. Please avoid suggesting items that are too vague (e.g., "do no harm") or too specific (e.g., "remove social security numbers from data"). +Our goal is to have checklist items that are actionable as part of a review of data science work or as part of a plan. Please avoid suggesting items that are too vague (e.g., "do no harm") or too specific (e.g., "remove social security numbers from data"). **Note: This process is an experiment and is subject to change based on how well it works. Our goal is to avoid flame wars in the issue threads while still making a tool that will make adding an ethics checklist to a project easy.** diff --git a/docs/md_templates/_common_body.tpl b/docs/md_templates/_common_body.tpl index 519e607..3e649ae 100644 --- a/docs/md_templates/_common_body.tpl +++ b/docs/md_templates/_common_body.tpl @@ -6,7 +6,7 @@ --- **δέον** • (déon) [n.] (_Ancient Greek_) <small><a href="https://en.wiktionary.org/wiki/%CE%B4%CE%AD%CE%BF%CE%BD#Ancient_Greek" target="_blank" style="text-decoration: none; color: #6d6d6d">wikitionary</a></small> - > Duty; that which is binding, needful, right, proper. + > Duty; that which is binding, needful, right, proper. -------- @@ -16,7 +16,7 @@ The conversation about ethics in data science, machine learning, and AI is incre We have a particular perspective with this package that we will use to make decisions about contributions, issues, PRs, and other maintenance and support activities. -First and foremost, our goal is not to be arbitrators of what ethical concerns merit inclusion. We have a [process for changing the default checklist](#changing-the-checklist), but we believe that many domain-specific concerns are not included and teams will benefit from developing [custom checklists](#custom-checklists). Not every checklist item will be relevant. We encourage teams to remove items, sections, or mark items as `N/A` as the concerns of their projects dictate. +First and foremost, our goal is not to be arbitrators of what ethical concerns merit inclusion. We have a [process for changing the default checklist](#changing-the-checklist), but we believe that many domain-specific concerns are not included and teams will benefit from developing [custom checklists](#custom-checklists). Not every checklist item will be relevant. We encourage teams to remove items, sections, or mark items as `N/A` as the concerns of their projects dictate. Second, we built our initial list from a set of proposed items on [multiple checklists that we referenced](#checklist-citations). This checklist was heavily inspired by an article written by Mike Loukides, Hilary Mason, and DJ Patil and published by O'Reilly: ["Of Oaths and Checklists"](https://www.oreilly.com/ideas/of-oaths-and-checklists). We owe a great debt to the thinking that proceeded this, and we look forward to thoughtful engagement with the ongoing discussion about checklists for data science ethics. @@ -41,7 +41,6 @@ Ninth, we want all the checklist items to be as simple as possible (but no simpl ## Prerequisites - Python >3.6: Your project need not be Python 3, but you need Python 3 to execute this tool. - - _(Linux Specific)_: using the `--clipboard` option requires the [`xclip`](https://github.com/astrand/xclip) package, which is easily installable on most distributions (e.g., `sudo apt-get install xclip`). ## Installation @@ -116,7 +115,7 @@ Custom checklists must follow the same schema as `checklist.yml`. There must be ``` title: TITLE -sections: +sections: - title: SECTION TITLE section_id: SECTION NUMBER lines: @@ -129,7 +128,7 @@ sections: Please see [the framing](#background-and-perspective) for an understanding of our perspective. Given this perspective, we will consider changes to the default checklist that fit with that perspective and follow this process. -Our goal is to have checklist items that are actionable as part of a review of data science work or as part of a plan. Please avoid suggesting items that are too vague (e.g., "do no harm") or too specific (e.g., "remove social security numbers from data"). +Our goal is to have checklist items that are actionable as part of a review of data science work or as part of a plan. Please avoid suggesting items that are too vague (e.g., "do no harm") or too specific (e.g., "remove social security numbers from data"). **Note: This process is an experiment and is subject to change based on how well it works. Our goal is to avoid flame wars in the issue threads while still making a tool that will make adding an ethics checklist to a project easy.** diff --git a/requirements.txt b/requirements.txt index cc2ae64..70c1796 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,4 +1,3 @@ beautifulsoup4>=4.6.1 click>=6.7 pyyaml>=3.13 -xerox>=0.4.1
diff --git a/tests/test_cli.py b/tests/test_cli.py index be9cce5..3fe1cac 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -23,19 +23,12 @@ def test_cli_errors(runner, arg, value, expected): assert expected in result.output -def test_default(runner, checklist): +def test_cli_default(runner, checklist): result = runner.invoke(main, ['--checklist', checklist]) assert result.exit_code == 0 assert assets.known_good_markdown in result.output [email protected]("arg", ['--clipboard', '-c']) -def test_cli_clipboard(runner, checklist, arg): - result = runner.invoke(main, ['--checklist', checklist, arg]) - assert result.exit_code == 0 - assert "Checklist successfully copied to clipboard." in result.output - - @pytest.mark.parametrize("arg", ['--output', '-o']) def test_cli_output(runner, checklist, tmpdir, test_format_configs, arg): temp_file_path = tmpdir.join('checklist.html') diff --git a/tests/test_deon.py b/tests/test_deon.py index 837d3b7..0a56504 100644 --- a/tests/test_deon.py +++ b/tests/test_deon.py @@ -2,16 +2,35 @@ from bs4 import BeautifulSoup import pytest -import xerox import deon import assets +def test_format(checklist, tmpdir, test_format_configs): + for frmt, _, known_good in test_format_configs: + result = str(deon.create(checklist, output_format=frmt, output=None, overwrite=False)) + + if frmt == 'jupyter': + # Jupyter requires json.dumps for double-quoting + assert result == json.dumps(known_good) + # Check that it's also valid json + assert json.loads(result) == known_good + elif frmt == 'html': + # Ensure valid html + print(result) + result_html = BeautifulSoup(result, 'html.parser') + known_good_html = BeautifulSoup(known_good, 'html.parser') + # Check html are equivalent ignoring formatting + assert result_html.prettify() == known_good_html.prettify() + else: + assert result == str(known_good) + + def test_output(checklist, tmpdir, test_format_configs): for frmt, fpath, known_good in test_format_configs: temp_file_path = tmpdir.join(fpath) - deon.create(checklist, None, temp_file_path, False, False) + deon.create(checklist, output_format=None, output=temp_file_path, overwrite=False) if frmt != 'jupyter': assert temp_file_path.read() == known_good @@ -22,21 +41,7 @@ def test_output(checklist, tmpdir, test_format_configs): unsupported_output = tmpdir.join('test.doc') with pytest.raises(deon.ExtensionException): - deon.create(checklist, None, unsupported_output, False, False) - - -def test_format(checklist, tmpdir, test_format_configs): - for frmt, _, known_good in test_format_configs: - result = deon.create(checklist, frmt, None, False, False) - - assert result is not None - - if frmt != 'html': # full doc for html not returned with format - # echo includes new line at end hence checking if known asset is in stdout - assert known_good == result - - with pytest.raises(deon.FormatException): - result = deon.create(checklist, 'doc', None, False, False) + deon.create(checklist, output_format=None, output=unsupported_output, overwrite=False) def test_overwrite(checklist, tmpdir, test_format_configs): @@ -44,7 +49,7 @@ def test_overwrite(checklist, tmpdir, test_format_configs): temp_file_path = tmpdir.join(fpath) with open(temp_file_path, 'w') as f: f.write(assets.existing_text) - deon.create(checklist, None, temp_file_path, False, True) + deon.create(checklist, output_format=None, output=temp_file_path, overwrite=True) if frmt != 'jupyter': assert temp_file_path.read() == known_good @@ -52,22 +57,3 @@ def test_overwrite(checklist, tmpdir, test_format_configs): with open(temp_file_path, 'r') as f: nbdata = json.load(f) assert nbdata == known_good - - -def test_clipboard(checklist, tmpdir, test_format_configs): - for frmt, _, known_good in test_format_configs: - deon.create(checklist, frmt, None, True, False) - - if frmt == 'jupyter': - # Jupyter requires json.dumps for double-quoting - assert xerox.paste() == json.dumps(known_good) - # Check that it's also valid json - assert json.loads(xerox.paste()) == known_good - elif frmt == 'html': - # Ensure valid html - clipboard_html = BeautifulSoup(xerox.paste(), 'html.parser') - known_good_html = BeautifulSoup(known_good, 'html.parser') - # Check html are equivalent ignoring formatting - assert clipboard_html.prettify() == known_good_html.prettify() - else: - assert xerox.paste() == str(known_good)
Proposal: Remove xerox dependency and clipboard manipulation functionality Currently our dependency on xerox has the following issues: 1. Installation on Windows is complicated due to xerox's unexplicit dependency on the pywin32 package. This is described at the [bottom the README](https://github.com/applecrazy/xerox#installation) but will not be handled by pip through a normal `pip install deon`. (See https://github.com/applecrazy/xerox/issues/35) It sounds like pywin32 is also a heavy and brittle dependency. This other projected opted to drop it; see discussion about rationale: https://github.com/storyscript/cli/issues/293 2. We are blocked on adding deon to conda-forge #87 due to xerox not being available on conda-forge. xerox does not appear to be actively maintained, and we probably do not want the maintenance burden of adding a xerox recipe to conda-forge ourselves. Direct clipboard manipulation also may not be the best implementation of a copy-paste feature. If a user is ssh-ed into a remote server, using `--clipboard` with xerox will copy the checklist to the remote machine's clipboard, which is not seamlessly accessible to the user's local machine. --- Instead, I propose that we replace the clipboard functionality with the ability to print the checklist to standard out. That way, a user can copy-paste from their console if they so desire.
2020-01-03T22:35:24.000
-1.0
[ "tests/test_deon.py::test_overwrite", "tests/test_deon.py::test_format", "tests/test_deon.py::test_output" ]
[ "tests/test_cli.py::test_cli_output[--output]", "tests/test_cli.py::test_cli_errors[--format-.doc-Error:", "tests/test_cli.py::test_cli_errors[--output-", "tests/test_cli.py::test_cli_default", "tests/test_cli.py::test_cli_output[-o]" ]
drivendataorg/deon
86
drivendataorg__deon-86
['34', '34']
b8be85b54b46aec4f019e20039fe64d3dc72bfaf
diff --git a/deon/formats.py b/deon/formats.py index 304a34f..4c81bfc 100644 --- a/deon/formats.py +++ b/deon/formats.py @@ -12,6 +12,10 @@ class Format(object): For text formats, simply override the templates below. For other formats, override `render` and `write`. + + `render` should return an object whose string + representation is a fully valid document of + that format. """ template = "{title}\n\n{sections}\n\n{docs_link}" append_delimiter = "\n\n" @@ -93,6 +97,15 @@ class Rst(Format): :target: http://deon.drivendata.org""" +class JsonDict(dict): + """Suclass of dict with valid json string representation.""" + def __str__(self): + return json.dumps(self) + + def __repr__(self): + return json.dumps(self) + + class JupyterNotebook(Markdown): """ Jupyter notebook template items """ @@ -104,11 +117,12 @@ class JupyterNotebook(Markdown): } def render(self): - """ Creates a cell with rendered Markdown of the - checklist. + """ Creates json for a valid blank Jupyter notebook with a cell + containing the rendered Markdown of the checklist. """ text = super().render() - return { + + checklist_cell = { "cell_type": "markdown", "metadata": {}, "source": [ @@ -116,30 +130,31 @@ def render(self): ] } + blank_jupyter_notebook = { + 'nbformat': 4, + 'nbformat_minor': 2, + 'metadata': {}, + 'cells': [checklist_cell] + } + + return JsonDict(blank_jupyter_notebook) + def write(self, filepath, overwrite=False): - """ If notebook does not exist (or `overwrite=True`), create a blank - notebook and add the checklist. Otherwise append a cell with a + """ If notebook does not exist (or `overwrite=True`), write new + notebook with checklist. Otherwise append a cell with a horizontal rule and another cell with the checklist. """ + nbdata = self.render() + filepath = Path(filepath) if filepath.exists() and not overwrite: with open(filepath, 'r') as f: - nbdata = json.load(f) - - nbdata['cells'].append(self.append_delimiter) - else: - # if new notebook, needs these properties - blank_jupyter_notebook = { - 'nbformat': 4, - 'nbformat_minor': 2, - 'metadata': {}, - 'cells': [] - } - nbdata = blank_jupyter_notebook - - cell = self.render() - nbdata['cells'].append(cell) + existing_nbdata = json.load(f) + # Append cells into existing notebook's cells array + existing_nbdata['cells'].append(self.append_delimiter) + existing_nbdata['cells'].extend(nbdata['cells']) + nbdata = existing_nbdata with open(filepath, "w") as f: json.dump(nbdata, f) @@ -181,21 +196,31 @@ class Html(Format): </html> """ + def render(self): + """ Create a new blank HTML document with checklist as the body. + Returned as a BeautifulSoup object. + """ + rendered_html = self.doc_template.format(text=super().render()) + soup = BeautifulSoup(rendered_html, 'html.parser') + # string representation of soup is the raw html, so we can return it + return soup + def write(self, filepath, overwrite=False): + """ If html document does not exist (or `overwrite=True`), write new + html file with checklist. Otherwise append checklist to the end of + the body of the existing html file. + """ filepath = Path(filepath) - if filepath.exists() and not overwrite: - # insert at end of body - checklist = self.render() + soup = self.render() + if filepath.exists() and not overwrite: with open(filepath, "r") as f: - soup = BeautifulSoup(f, 'html.parser') + existing_soup = BeautifulSoup(f, 'html.parser') # add checklist to end of body - soup.body.append(BeautifulSoup(checklist, 'html.parser')) - else: - rendered_html = self.doc_template.format(text=self.render()) - soup = BeautifulSoup(rendered_html, 'html.parser') + existing_soup.body.contents.extend(soup.body.contents) + soup = existing_soup text = soup.prettify()
diff --git a/tests/assets.py b/tests/assets.py index ef6e4d8..edcdf36 100644 --- a/tests/assets.py +++ b/tests/assets.py @@ -46,7 +46,12 @@ *Data Science Ethics Checklist generated with* `deon <http://deon.drivendata.org>`_.""" -known_good_jupyter = ({'cell_type': 'markdown', +known_good_jupyter = ({ + 'nbformat': 4, + 'nbformat_minor': 2, + 'metadata': {}, + 'cells': [ + {'cell_type': 'markdown', 'metadata': {}, 'source': ['# My Checklist\n', '\n', @@ -62,7 +67,9 @@ '\n', "*Data Science Ethics Checklist generated with [deon](http://deon.drivendata.org).*" "\n" - ]}) + ]} + ] +}) known_good_html = """<html> <body> diff --git a/tests/test_deon.py b/tests/test_deon.py index 249eda6..837d3b7 100644 --- a/tests/test_deon.py +++ b/tests/test_deon.py @@ -1,4 +1,5 @@ import json +from bs4 import BeautifulSoup import pytest import xerox @@ -17,7 +18,7 @@ def test_output(checklist, tmpdir, test_format_configs): else: with open(temp_file_path, 'r') as f: nbdata = json.load(f) - assert nbdata['cells'][0] == known_good + assert nbdata == known_good unsupported_output = tmpdir.join('test.doc') with pytest.raises(deon.ExtensionException): @@ -50,12 +51,23 @@ def test_overwrite(checklist, tmpdir, test_format_configs): else: with open(temp_file_path, 'r') as f: nbdata = json.load(f) - assert nbdata['cells'][0] == known_good + assert nbdata == known_good def test_clipboard(checklist, tmpdir, test_format_configs): for frmt, _, known_good in test_format_configs: deon.create(checklist, frmt, None, True, False) - if frmt != 'html': # full doc for html not returned with format + if frmt == 'jupyter': + # Jupyter requires json.dumps for double-quoting + assert xerox.paste() == json.dumps(known_good) + # Check that it's also valid json + assert json.loads(xerox.paste()) == known_good + elif frmt == 'html': + # Ensure valid html + clipboard_html = BeautifulSoup(xerox.paste(), 'html.parser') + known_good_html = BeautifulSoup(known_good, 'html.parser') + # Check html are equivalent ignoring formatting + assert clipboard_html.prettify() == known_good_html.prettify() + else: assert xerox.paste() == str(known_good) diff --git a/tests/test_formats.py b/tests/test_formats.py index 0227abb..2962683 100644 --- a/tests/test_formats.py +++ b/tests/test_formats.py @@ -1,5 +1,6 @@ from pytest import fixture import json +from bs4 import BeautifulSoup from deon.parser import Checklist, Section, Line from deon.formats import Format, Markdown, JupyterNotebook, Html, Rst @@ -102,14 +103,14 @@ def test_jupyter(checklist, tmpdir): j.write(temp_file_path) with open(temp_file_path, 'r') as f: nbdata = json.load(f) - assert nbdata['cells'] == [known_good] + assert nbdata == known_good # append to existing file j.write(temp_file_path, overwrite=False) with open(temp_file_path, 'r') as f: nbdata = json.load(f) assert len(nbdata['cells']) == 3 - assert nbdata['cells'][0] == known_good + assert nbdata['cells'][0] == known_good['cells'][0] assert nbdata['cells'][1] == JupyterNotebook.append_delimiter assert nbdata['cells'][0] == nbdata['cells'][-1] @@ -118,7 +119,7 @@ def test_jupyter(checklist, tmpdir): with open(temp_file_path, 'r') as f: nbdata = json.load(f) print(json.dumps(nbdata, indent=4)) - assert nbdata['cells'] == [known_good] + assert nbdata == known_good def test_html(checklist, tmpdir): @@ -131,16 +132,25 @@ def test_html(checklist, tmpdir): temp_file_path = tmpdir.join('test.html') h.write(temp_file_path) with open(temp_file_path, 'r') as tempf: - assert tempf.read() == known_good + # Read back in bs4 to ensure valid html + temp_soup = BeautifulSoup(tempf, 'html.parser') + known_good_soup = BeautifulSoup(known_good, 'html.parser') + assert temp_soup.prettify() == known_good_soup.prettify() # append to existing file with open(temp_file_path, 'w') as tempf: tempf.write(existing_text) h.write(temp_file_path, overwrite=False) with open(temp_file_path, 'r') as tempf: - assert tempf.read() == inserted_known_good + # Read back in bs4 to ensure valid html + temp_soup = BeautifulSoup(tempf, 'html.parser') + known_good_soup = BeautifulSoup(inserted_known_good, 'html.parser') + assert temp_soup.prettify() == known_good_soup.prettify() # overwrite existing file h.write(temp_file_path, overwrite=True) with open(temp_file_path, 'r') as tempf: - assert tempf.read() == known_good + # Read back in bs4 to ensure valid html + temp_soup = BeautifulSoup(tempf, 'html.parser') + known_good_soup = BeautifulSoup(known_good, 'html.parser') + assert temp_soup.prettify() == known_good_soup.prettify()
Clipboard option for html and jupyter does not return full doc `clipboard` option only calls `.render`, not `.write`, meaning that clipboard paired with html or jupyter will not return the full document (i.e. will not be the same as what is returned with `output`). For example - `ethics-checklist -f html` only returns the html starting with `<h1>` (excludes `doc_template`). - `ethics-checklist -f jupyter` only return the json starting with `cell_type` (excludes `blank_jupyter_notebook`). Clipboard option for html and jupyter does not return full doc `clipboard` option only calls `.render`, not `.write`, meaning that clipboard paired with html or jupyter will not return the full document (i.e. will not be the same as what is returned with `output`). For example - `ethics-checklist -f html` only returns the html starting with `<h1>` (excludes `doc_template`). - `ethics-checklist -f jupyter` only return the json starting with `cell_type` (excludes `blank_jupyter_notebook`).
2019-10-24T14:53:35.000
-1.0
[ "tests/test_deon.py::test_format", "tests/test_formats.py::test_jupyter" ]
[ "tests/test_formats.py::test_format", "tests/test_formats.py::test_markdown", "tests/test_deon.py::test_output", "tests/test_deon.py::test_overwrite", "tests/test_formats.py::test_rst" ]
drivendataorg/deon
51
drivendataorg__deon-51
['50']
d17771c6addf7fb763343b4bc1bcfe58a13a3cc7
diff --git a/Makefile b/Makefile index b4c6368..994d78d 100644 --- a/Makefile +++ b/Makefile @@ -13,6 +13,8 @@ examples: reqs deon --output examples/ethics.ipynb --overwrite deon --output examples/ethics.html --overwrite deon --output examples/ethics.rst --overwrite + deon --output examples/ethics.txt --overwrite + # generates README.md and documentation md pages render_markdown: diff --git a/README.md b/README.md index f5fe6aa..8c15f50 100644 --- a/README.md +++ b/README.md @@ -81,6 +81,7 @@ Here are the currently supported file types. We will accept pull requests with n - `.rst`: rst - `.ipynb`: jupyter - `.html`: html +- `.txt`: ascii # Command line options @@ -90,10 +91,10 @@ Usage: main [OPTIONS] Options: -l, --checklist PATH Override checklist file. -f, --format TEXT Output format. Default is "markdown". Can be one of - [markdown, rst, jupyter, html]. File extension used if - --output is passed. + [markdown, rst, jupyter, html, ascii]. File extension + used if --output is passed. -o, --output PATH Output file path. Extension can be one of [.md, .rst, - .ipynb, .html] + .ipynb, .html, .txt] -c, --clipboard Whether or not to output to clipboard. -w, --overwrite Overwrite output file if it exists. Default is False. diff --git a/deon/assets.py b/deon/assets.py index 63eff8e..d6bde93 100644 --- a/deon/assets.py +++ b/deon/assets.py @@ -1,11 +1,12 @@ existing_text = 'There is existing text in this file.' -known_good_default = """My Checklist: -A. First section: +known_good_ascii = """My Checklist + +A. First section * A.1 First A line * A.2 Second A line -B. Second section: +B. Second section * B.1 First B line * B.2 Second B line""" diff --git a/deon/formats.py b/deon/formats.py index 4bc2654..85b2dcd 100644 --- a/deon/formats.py +++ b/deon/formats.py @@ -13,10 +13,10 @@ class Format(object): below. For other formats, override `render` and `write`. """ - template = "{title}:\n{sections}" + template = "{title}\n\n{sections}" append_delimiter = "\n\n" - section_template = "{title}:\n{lines}" + section_template = "{title}\n{lines}" section_delimiter = "\n\n" line_template = "* {line}" @@ -200,6 +200,7 @@ def write(self, filepath, overwrite=False): 'rst': Rst, 'jupyter': JupyterNotebook, 'html': Html, + 'ascii': Format, } EXTENSIONS = { @@ -207,4 +208,5 @@ def write(self, filepath, overwrite=False): '.rst': 'rst', '.ipynb': 'jupyter', '.html': 'html', + '.txt': 'ascii', } diff --git a/docs/docs/index.md b/docs/docs/index.md index 3e18fde..6125871 100644 --- a/docs/docs/index.md +++ b/docs/docs/index.md @@ -76,6 +76,7 @@ Here are the currently supported file types. We will accept pull requests with n - `.rst`: rst - `.ipynb`: jupyter - `.html`: html +- `.txt`: ascii # Command line options @@ -85,10 +86,10 @@ Usage: main [OPTIONS] Options: -l, --checklist PATH Override checklist file. -f, --format TEXT Output format. Default is "markdown". Can be one of - [markdown, rst, jupyter, html]. File extension used if - --output is passed. + [markdown, rst, jupyter, html, ascii]. File extension + used if --output is passed. -o, --output PATH Output file path. Extension can be one of [.md, .rst, - .ipynb, .html] + .ipynb, .html, .txt] -c, --clipboard Whether or not to output to clipboard. -w, --overwrite Overwrite output file if it exists. Default is False. diff --git a/examples/ethics.txt b/examples/ethics.txt new file mode 100644 index 0000000..c92e0ca --- /dev/null +++ b/examples/ethics.txt @@ -0,0 +1,31 @@ +Data Science Ethics Checklist + +A. Data Collection +* A.1 If there are human subjects, have those subjects have given informed consent, where users clearly understand what they are consenting to and there was a mechanism in place for gathering consent? +* A.2 Have we considered sources of bias that could be introduced during data collection and survey design and taken steps to mitigate those? +* A.3 Have we considered ways to to minimize exposure of PII for example through anonymization or not collecting information that isn't relevant for analysis? + +B. Data Storage +* B.1 Do we have a plan to protect and secure data (e.g., encryption at rest and in transit, access controls on internal users and third parties, access logs, and up-to-date software)? +* B.2 Do we have a mechanism through which an individual can request their personal information be removed? +* B.3 Is there a schedule or plan to delete the data after it is no longer needed? + +C. Analysis +* C.1 Have we sought to address blindspots in the analysis through engagement with relevant stakeholders (e.g., affected community and subject matter experts)? +* C.2 Have we examined the data for possible sources of bias and taken steps to mitigate or address these biases (e.g., stereotype perpetuation, confirmation bias, imbalanced classes, or omitted confounding variables)? +* C.3 Are our visualizations, summary statistics, and reports designed to honestly represent the underlying data? +* C.4 Have we ensured that data with PII are not used or displayed unless necessary for the analysis? +* C.5 Is the process of generating the analysis auditable if we discover issues in the future? + +D. Modeling +* D.1 Have we ensured that the model does not rely on variables or proxies for variables that are unfairly discriminatory? +* D.2 Have we tested model results for fairness with respect to different affected groups (e.g., tested for disparate error rates)? +* D.3 Have we considered the effects of optimizing for our defined metrics and considered additional metrics? +* D.4 Can we explain in understandable terms a decision the model made in cases where a justification is needed? +* D.5 Have we communicated the shortcomings, limitations, and biases of the model to relevant stakeholders in ways that can be generally understood? + +E. Deployment +* E.1 Have we discussed with our organization a plan for response if users are harmed by the results (e.g., how does the data science team evaluate these cases and update analysis and models to prevent future harm)? +* E.2 Is there a way to turn off or roll back the model in production if necessary? +* E.3 Do we test and monitor for concept drift to ensure the model remains fair over time? +* E.4 Have we taken steps to identify and prevent unintended uses and abuse of the model and do we have a plan to monitor these once the model is deployed? \ No newline at end of file
diff --git a/tests/test_cli.py b/tests/test_cli.py index 99d3a32..7ae0dbc 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -42,7 +42,8 @@ def test_dict(): 'markdown': ['test.md', assets.known_good_markdown], 'html': ['test.html', assets.known_good_html], 'rst': ['test.rst', assets.known_good_rst], - 'jupyter': ['test.ipynb', assets.known_good_jupyter] + 'jupyter': ['test.ipynb', assets.known_good_jupyter], + 'ascii': ['test.txt', assets.known_good_ascii], } return test_files_dict @@ -155,5 +156,5 @@ def test_default(checklist): def test_multiple_options(checklist): runner = CliRunner() - runner.invoke(main, ['--checklist', checklist, '-c', '-f', 'rst']) - assert xerox.paste() == assets.known_good_rst + runner.invoke(main, ['--checklist', checklist, '-c', '-f', 'ascii']) + assert xerox.paste() == assets.known_good_ascii diff --git a/tests/test_formats.py b/tests/test_formats.py index 21ef320..882eefc 100644 --- a/tests/test_formats.py +++ b/tests/test_formats.py @@ -18,7 +18,7 @@ def checklist(): def test_format(checklist, tmpdir): - known_good = assets.known_good_default + known_good = assets.known_good_ascii existing_text = assets.existing_text t = Format(checklist)
Support ascii format
2018-08-24T20:02:24.000
-1.0
[ "tests/test_formats.py::test_format" ]
[ "tests/test_formats.py::test_html", "tests/test_formats.py::test_jupyter", "tests/test_formats.py::test_rst", "tests/test_formats.py::test_markdown" ]
amaranth-lang/amaranth
1,570
amaranth-lang__amaranth-1570
['1569']
cf4a29d3a29fd316207aa77c5b63f991a4e81756
diff --git a/amaranth/hdl/_ir.py b/amaranth/hdl/_ir.py index 0bdbb97e6..1370bdea4 100644 --- a/amaranth/hdl/_ir.py +++ b/amaranth/hdl/_ir.py @@ -49,8 +49,8 @@ class DomainRequirementFailed(Exception): class Fragment: @staticmethod def get(obj, platform): - code = None origins = [] + returned_by = "" while True: if isinstance(obj, Fragment): if hasattr(obj, "origins"): @@ -58,19 +58,15 @@ def get(obj, platform): return obj elif isinstance(obj, Elaboratable): code = obj.elaborate.__code__ + returned_by = f", returned by {code.co_filename}:{code.co_firstlineno}" UnusedElaboratable._MustUse__silence = False obj._MustUse__used = True new_obj = obj.elaborate(platform) else: - raise TypeError(f"Object {obj!r} is not an 'Elaboratable' nor 'Fragment'") + raise TypeError( + f"Object {obj!r} is not an 'Elaboratable' nor 'Fragment'{returned_by}") if new_obj is obj: - raise RecursionError(f"Object {obj!r} elaborates to itself") - if new_obj is None and code is not None: - warnings.warn_explicit( - message=".elaborate() returned None; missing return statement?", - category=UserWarning, - filename=code.co_filename, - lineno=code.co_firstlineno) + raise RecursionError(f"Object {obj!r} elaborates to itself{returned_by}") origins.append(obj) obj = new_obj
diff --git a/tests/test_hdl_ir.py b/tests/test_hdl_ir.py index bbfc86ce3..c017f38e9 100644 --- a/tests/test_hdl_ir.py +++ b/tests/test_hdl_ir.py @@ -31,15 +31,13 @@ def test_get_wrong_none(self): r"^Object None is not an 'Elaboratable' nor 'Fragment'$"): Fragment.get(None, platform=None) - with self.assertWarnsRegex(UserWarning, - r"^\.elaborate\(\) returned None; missing return statement\?$"): - with self.assertRaisesRegex(TypeError, - r"^Object None is not an 'Elaboratable' nor 'Fragment'$"): - Fragment.get(ElaboratesToNone(), platform=None) + with self.assertRaisesRegex(TypeError, + r"^Object None is not an 'Elaboratable' nor 'Fragment', returned by .+?:19$"): + Fragment.get(ElaboratesToNone(), platform=None) def test_get_wrong_self(self): with self.assertRaisesRegex(RecursionError, - r"^Object <.+?ElaboratesToSelf.+?> elaborates to itself$"): + r"^Object <.+?ElaboratesToSelf.+?> elaborates to itself, returned by .+?:24$"): Fragment.get(ElaboratesToSelf(), platform=None)
Missing return in elaborate results in cryptic error A missing return gives a useful warning: `UserWarning: .elaborate() returned None; missing return statement?` but this is then followed by a cryptic error: `TypeError: Object None is not an 'Elaboratable' nor 'Fragment'` Would it be better to raise an error instead of a warning?
That seems reasonable. I'll review the code to understand why it is using a warning and then if there is no good reason I'll upgrade it to an error. So there actually *is* a reason for using a warning here. This is because it is possible in Python to override the file and line attached to a warning: https://github.com/amaranth-lang/amaranth/blob/cf4a29d3a29fd316207aa77c5b63f991a4e81756/amaranth/hdl/_ir.py#L69-L73 But it's not possible to add them to the backtrace without some CPython-specific hacks.
2025-03-05T00:26:05.000
-1.0
[ "tests/test_hdl_ir.py::FragmentGetTestCase::test_get_wrong_none", "tests/test_hdl_ir.py::FragmentGetTestCase::test_get_wrong_self" ]
[ "tests/test_hdl_ir.py::AssignTestCase::test_simple_trunc", "tests/test_hdl_ir.py::OriginsTestCase::test_origins_disable", "tests/test_hdl_ir.py::AssignTestCase::test_simple", "tests/test_hdl_ir.py::FragmentDomainsTestCase::test_propagate_create_missing_fragment", "tests/test_hdl_ir.py::DomainLookupTestCase::test_domain_lookup", "tests/test_hdl_ir.py::IOBufferTestCase::test_nir_oe", "tests/test_hdl_ir.py::CycleTestCase::test_assignment_cycle", "tests/test_hdl_ir.py::AssignTestCase::test_simple_operator", "tests/test_hdl_ir.py::InstanceTestCase::test_prepare_attrs", "tests/test_hdl_ir.py::InstanceTestCase::test_wrong_construct_arg", "tests/test_hdl_ir.py::NamesTestCase::test_assign_names_to_fragments_rename_top", "tests/test_hdl_ir.py::AssignTestCase::test_simple_concat_narrow", "tests/test_hdl_ir.py::AssignTestCase::test_mux_en", "tests/test_hdl_ir.py::InstanceTestCase::test_nir_io_slice", "tests/test_hdl_ir.py::RequirePosedgeTestCase::test_require_fail", "tests/test_hdl_ir.py::IOBufferTestCase::test_nir_i", "tests/test_hdl_ir.py::RhsTestCase::test_part", "tests/test_hdl_ir.py::RhsTestCase::test_operator_binary_divmod", "tests/test_hdl_ir.py::SplitDriverTestCase::test_split_domain", "tests/test_hdl_ir.py::RhsTestCase::test_slice", "tests/test_hdl_ir.py::AssignTestCase::test_simple_zext", "tests/test_hdl_ir.py::InstanceTestCase::test_construct", "tests/test_hdl_ir.py::RhsTestCase::test_const", "tests/test_hdl_ir.py::SwitchTestCase::test_assert", "tests/test_hdl_ir.py::SwitchTestCase::test_sync", "tests/test_hdl_ir.py::IOBufferTestCase::test_nir_io", "tests/test_hdl_ir.py::AssignTestCase::test_simple_part", "tests/test_hdl_ir.py::IOBufferTestCase::test_wrong_port", "tests/test_hdl_ir.py::RhsTestCase::test_operator_binary_shift", "tests/test_hdl_ir.py::AssignTestCase::test_part_slice", "tests/test_hdl_ir.py::FragmentPortsTestCase::test_subfragment_simple", "tests/test_hdl_ir.py::FragmentDomainsTestCase::test_propagate_create_missing_fragment_wrong", "tests/test_hdl_ir.py::FieldsTestCase::test_fields", "tests/test_hdl_ir.py::InstanceTestCase::test_cast_ports", "tests/test_hdl_ir.py::ConflictTestCase::test_module_conflict", "tests/test_hdl_ir.py::FragmentPortsTestCase::test_empty", "tests/test_hdl_ir.py::FragmentPortsTestCase::test_port_domain", "tests/test_hdl_ir.py::FragmentPortsTestCase::test_port_wrong", "tests/test_hdl_ir.py::InstanceTestCase::test_init", "tests/test_hdl_ir.py::FragmentPortsTestCase::test_port_partial", "tests/test_hdl_ir.py::AssignTestCase::test_sliced_operator", "tests/test_hdl_ir.py::RhsTestCase::test_operator_binary_bitwise", "tests/test_hdl_ir.py::FragmentDomainsTestCase::test_propagate_missing", "tests/test_hdl_ir.py::ConflictTestCase::test_domain_conflict", "tests/test_hdl_ir.py::FragmentPortsTestCase::test_port_instance", "tests/test_hdl_ir.py::RequirePosedgeTestCase::test_require_renamed", "tests/test_hdl_ir.py::AssignTestCase::test_sliced_array", "tests/test_hdl_ir.py::IOBufferTestCase::test_nir_o", "tests/test_hdl_ir.py::SwitchTestCase::test_print", "tests/test_hdl_ir.py::RhsTestCase::test_switchvalue", "tests/test_hdl_ir.py::AssignTestCase::test_simple_sext", "tests/test_hdl_ir.py::RhsTestCase::test_cat", "tests/test_hdl_ir.py::AssignTestCase::test_simple_part_word_misalign", "tests/test_hdl_ir.py::IOBufferTestCase::test_wrong_oe_without_o", "tests/test_hdl_ir.py::IOBufferTestCase::test_wrong_oe", "tests/test_hdl_ir.py::FragmentPortsTestCase::test_port_not_iterable", "tests/test_hdl_ir.py::FragmentDomainsTestCase::test_domain_conflict_rename_drivers_before_creating_missing", "tests/test_hdl_ir.py::SplitDriverTestCase::test_split_module", "tests/test_hdl_ir.py::InstanceTestCase::test_nir_io_concat", "tests/test_hdl_ir.py::RequirePosedgeTestCase::test_require_ok", "tests/test_hdl_ir.py::NamesTestCase::test_wrong_private_unnamed_toplevel_ports", "tests/test_hdl_ir.py::InstanceTestCase::test_nir_out_slice", "tests/test_hdl_ir.py::NamesTestCase::test_assign_names_to_fragments_duplicate", "tests/test_hdl_ir.py::RhsTestCase::test_operator_binary_eq", "tests/test_hdl_ir.py::IOBufferTestCase::test_wrong_o", "tests/test_hdl_ir.py::FragmentHierarchyConflictTestCase::test_no_conflict_local_domains", "tests/test_hdl_ir.py::RhsTestCase::test_operator_mux", "tests/test_hdl_ir.py::AssignTestCase::test_switchvalue", "tests/test_hdl_ir.py::FragmentGeneratedTestCase::test_find_subfragment", "tests/test_hdl_ir.py::FragmentPortsTestCase::test_port_dict", "tests/test_hdl_ir.py::InstanceTestCase::test_nir_simple", "tests/test_hdl_ir.py::AssignTestCase::test_sliced_part_slice", "tests/test_hdl_ir.py::SwitchTestCase::test_comb", "tests/test_hdl_ir.py::RhsTestCase::test_operator_signed", "tests/test_hdl_ir.py::RhsTestCase::test_operator_binary_ord", "tests/test_hdl_ir.py::FragmentDomainsTestCase::test_propagate", "tests/test_hdl_ir.py::NamesTestCase::test_assign_names_to_fragments_collide_with_signal", "tests/test_hdl_ir.py::InstanceTestCase::test_nir_operator", "tests/test_hdl_ir.py::FragmentDomainsTestCase::test_propagate_down_idempotent", "tests/test_hdl_ir.py::AssignTestCase::test_sliced_concat", "tests/test_hdl_ir.py::FragmentGeneratedTestCase::test_find_generated", "tests/test_hdl_ir.py::RhsTestCase::test_operator_unary", "tests/test_hdl_ir.py::FragmentDomainsTestCase::test_propagate_create_missing", "tests/test_hdl_ir.py::RhsTestCase::test_operator_binary_add", "tests/test_hdl_ir.py::FragmentDomainsTestCase::test_propagate_down", "tests/test_hdl_ir.py::RhsTestCase::test_operator_binary_sub", "tests/test_hdl_ir.py::AssignTestCase::test_simple_part_word", "tests/test_hdl_ir.py::FragmentPortsTestCase::test_port_io", "tests/test_hdl_ir.py::FragmentPortsTestCase::test_tree", "tests/test_hdl_ir.py::UndrivenTestCase::test_undef_to_ff_partial", "tests/test_hdl_ir.py::UndrivenTestCase::test_undef_to_ff", "tests/test_hdl_ir.py::InstanceTestCase::test_nir_out_concat", "tests/test_hdl_ir.py::RhsTestCase::test_arrayproxy", "tests/test_hdl_ir.py::AssignTestCase::test_sliced_part", "tests/test_hdl_ir.py::FragmentGeneratedTestCase::test_find_subfragment_wrong", "tests/test_hdl_ir.py::DuplicateElaboratableTestCase::test_duplicate", "tests/test_hdl_ir.py::AssignTestCase::test_sliced_part_word", "tests/test_hdl_ir.py::FragmentPortsTestCase::test_loopback", "tests/test_hdl_ir.py::NamesTestCase::test_assign_names_to_fragments", "tests/test_hdl_ir.py::AssignTestCase::test_simple_concat", "tests/test_hdl_ir.py::RhsTestCase::test_initial", "tests/test_hdl_ir.py::IOBufferTestCase::test_wrong_i", "tests/test_hdl_ir.py::FragmentPortsTestCase::test_port_autodomain", "tests/test_hdl_ir.py::AssignTestCase::test_simple_slice", "tests/test_hdl_ir.py::NamesTestCase::test_assign_names_to_signals", "tests/test_hdl_ir.py::CycleTestCase::test_cycle", "tests/test_hdl_ir.py::InstanceTestCase::test_wrong_construct_kwarg", "tests/test_hdl_ir.py::AssignTestCase::test_sliced_slice", "tests/test_hdl_ir.py::IOBufferTestCase::test_conflict", "tests/test_hdl_ir.py::RhsTestCase::test_operator_binary_mul", "tests/test_hdl_ir.py::AssignTestCase::test_simple_part_short", "tests/test_hdl_ir.py::FragmentDomainsTestCase::test_propagate_create_missing_fragment_many_domains", "tests/test_hdl_ir.py::UndrivenTestCase::test_undriven", "tests/test_hdl_ir.py::OriginsTestCase::test_origins", "tests/test_hdl_ir.py::ConflictTestCase::test_instance_conflict", "tests/test_hdl_ir.py::AssignTestCase::test_simple_array", "tests/test_hdl_ir.py::RhsTestCase::test_anyvalue", "tests/test_hdl_ir.py::FragmentPortsTestCase::test_port_io_part" ]
amaranth-lang/amaranth
1,520
amaranth-lang__amaranth-1520
['1518']
1f4b2db3207d2ff5ae53bc59f6475e1732f97867
diff --git a/amaranth/back/rtlil.py b/amaranth/back/rtlil.py index cecb11f0f..28f428c1a 100644 --- a/amaranth/back/rtlil.py +++ b/amaranth/back/rtlil.py @@ -1132,7 +1132,7 @@ def emit_print(self, cell_idx, cell): if cell.format is not None: for chunk in cell.format.chunks: if isinstance(chunk, str): - format.append(chunk) + format.append(chunk.replace("{", "{{").replace("}", "}}")) else: spec = _ast.Format._parse_format_spec(chunk.format_desc, _ast.Shape(len(chunk.value), chunk.signed)) type = spec["type"]
diff --git a/tests/test_back_rtlil.py b/tests/test_back_rtlil.py index e99bbdb4a..eefc39911 100644 --- a/tests/test_back_rtlil.py +++ b/tests/test_back_rtlil.py @@ -2008,6 +2008,51 @@ def test_print_align(self): end """) + def test_escape_curly(self): + m = Module() + m.d.comb += [ + Print("{"), + Print("}"), + ] + self.assertRTLIL(m, [], R""" + attribute \generator "Amaranth" + attribute \top 1 + module \top + wire width 1 $1 + wire width 1 $2 + process $3 + assign $1 [0] 1'0 + assign $1 [0] 1'1 + end + cell $print $4 + parameter \FORMAT "{{\n" + parameter \ARGS_WIDTH 0 + parameter signed \PRIORITY 32'11111111111111111111111111111110 + parameter \TRG_ENABLE 0 + parameter \TRG_WIDTH 0 + parameter \TRG_POLARITY 0 + connect \EN $1 [0] + connect \ARGS { } + connect \TRG { } + end + process $5 + assign $2 [0] 1'0 + assign $2 [0] 1'1 + end + cell $print $6 + parameter \FORMAT "}}\n" + parameter \ARGS_WIDTH 0 + parameter signed \PRIORITY 32'11111111111111111111111111111100 + parameter \TRG_ENABLE 0 + parameter \TRG_WIDTH 0 + parameter \TRG_POLARITY 0 + connect \EN $2 [0] + connect \ARGS { } + connect \TRG { } + end + end + """) + class DetailTestCase(RTLILTestCase): def test_enum(self):
Format(data.Struct) gives YosysError Running ```python #!/usr/bin/env python3 from amaranth import Print, Module, Format, Signal from amaranth.lib import data from amaranth.back.verilog import convert class A(data.Struct): x: 8 b: 8 m = Module() a = Signal(A) m.d.sync += Print(Format("{}", a)) print(convert(m, ports=(a.as_value(),))) ``` yields ``` Traceback (most recent call last): File "/tmp/test.py", line 16, in <module> print(convert(m, ports=(a.as_value(),))) File "/data/projects/amaranth/amaranth/back/verilog.py", line 61, in convert verilog_text, name_map = convert_fragment(fragment, ports, name, emit_src=emit_src, strip_internal_attrs=strip_internal_attrs, **kwargs) File "/data/projects/amaranth/amaranth/back/verilog.py", line 40, in convert_fragment return _convert_rtlil_text(rtlil_text, strip_internal_attrs=strip_internal_attrs), name_map File "/data/projects/amaranth/amaranth/back/verilog.py", line 31, in _convert_rtlil_text return yosys.run(["-q", "-"], "\n".join(script), File "/data/projects/amaranth/amaranth/_toolchain/yosys.py", line 177, in run return cls._process_result(popen.returncode, stdout, stderr, ignore_warnings, src_loc_at) File "/data/projects/amaranth/amaranth/_toolchain/yosys.py", line 99, in _process_result raise YosysError(stderr.strip()) amaranth._toolchain.yosys.YosysError: ERROR: Assert `false && "Unexpected character in format substitution"' failed in kernel/fmt.cc:66. ``` When looking at the generated rtlil: ``` attribute \generator "Amaranth" attribute \src "/tmp/test.py:11" attribute \top 1 module \top attribute \src "/tmp/test.py:13" wire width 16 input 0 \a attribute \src "/data/projects/amaranth/amaranth/hdl/_ir.py:215" wire width 1 input 1 \clk attribute \src "/data/projects/amaranth/amaranth/hdl/_ir.py:215" wire width 1 input 2 \rst wire width 1 $1 attribute \src "/tmp/test.py:13" wire width 8 \a.x attribute \src "/tmp/test.py:13" wire width 8 \a.b attribute \src "/tmp/test.py:14" process $2 assign $1 [0] 1'0 assign $1 [0] 1'1 end attribute \src "/tmp/test.py:14" cell $print $3 parameter \FORMAT "{{x={8:> du}, b={8:> du}}}\n" parameter \ARGS_WIDTH 16 parameter signed \PRIORITY 32'11111111111111111111111111111110 parameter \TRG_ENABLE 1 parameter \TRG_WIDTH 1 parameter \TRG_POLARITY 1 connect \EN $1 [0] connect \ARGS \a [15:0] connect \TRG \clk [0] end connect \a.x \a [7:0] connect \a.b \a [15:8] end ``` I guess the `{}` that enclose the struct are the problem, it looks like they need to be esacped.
2024-09-20T17:01:55.000
-1.0
[ "tests/test_back_rtlil.py::PrintTestCase::test_escape_curly" ]
[ "tests/test_back_rtlil.py::InstanceTestCase::test_attr", "tests/test_back_rtlil.py::RHSTestCase::test_operator_unary", "tests/test_back_rtlil.py::DetailTestCase::test_struct", "tests/test_back_rtlil.py::FlopTestCase::test_async", "tests/test_back_rtlil.py::FlopTestCase::test_sync", "tests/test_back_rtlil.py::RHSTestCase::test_operator_eq", "tests/test_back_rtlil.py::RHSTestCase::test_part", "tests/test_back_rtlil.py::InstanceTestCase::test_concat", "tests/test_back_rtlil.py::PrintTestCase::test_print_sync", "tests/test_back_rtlil.py::SwitchTestCase::test_nested", "tests/test_back_rtlil.py::InstanceTestCase::test_ioport", "tests/test_back_rtlil.py::RHSTestCase::test_operator_cmp", "tests/test_back_rtlil.py::PrintTestCase::test_print_sign", "tests/test_back_rtlil.py::TreeTestCase::test_tree", "tests/test_back_rtlil.py::PrintTestCase::test_print_base", "tests/test_back_rtlil.py::SwitchTestCase::test_simple", "tests/test_back_rtlil.py::RHSTestCase::test_operator_shift", "tests/test_back_rtlil.py::RHSTestCase::test_operator_mux", "tests/test_back_rtlil.py::PrintTestCase::test_assume_msg", "tests/test_back_rtlil.py::PrintTestCase::test_print_align", "tests/test_back_rtlil.py::PrintTestCase::test_print_simple", "tests/test_back_rtlil.py::IOBTestCase::test_iob", "tests/test_back_rtlil.py::PrintTestCase::test_assert_simple", "tests/test_back_rtlil.py::InstanceTestCase::test_param", "tests/test_back_rtlil.py::SwitchTestCase::test_aba", "tests/test_back_rtlil.py::RHSTestCase::test_operator_add_imm", "tests/test_back_rtlil.py::RHSTestCase::test_operator_mul", "tests/test_back_rtlil.py::RHSTestCase::test_operator_bitwise", "tests/test_back_rtlil.py::RHSTestCase::test_operator_addsub", "tests/test_back_rtlil.py::PrintTestCase::test_print_char", "tests/test_back_rtlil.py::MemoryTestCase::test_sync_read", "tests/test_back_rtlil.py::MemoryTestCase::test_async_read", "tests/test_back_rtlil.py::ComponentTestCase::test_component", "tests/test_back_rtlil.py::InstanceTestCase::test_instance", "tests/test_back_rtlil.py::RHSTestCase::test_initial", "tests/test_back_rtlil.py::RHSTestCase::test_anyvalue", "tests/test_back_rtlil.py::DetailTestCase::test_enum", "tests/test_back_rtlil.py::RHSTestCase::test_operator_divmod", "tests/test_back_rtlil.py::SwitchTestCase::test_trivial" ]
drivendataorg/deon
13
drivendataorg__deon-13
['1']
b5aaac0eab725cfe1228e82ed59b97e496744688
diff --git a/.gitignore b/.gitignore index 67a5630..82caa9a 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ *.egg-info __pycache__/ -.pytest_cache/ \ No newline at end of file +.pytest_cache/ +.ipynb_checkpoints/ \ No newline at end of file diff --git a/checklist.json b/checklist.json deleted file mode 100644 index 4cf74ee..0000000 --- a/checklist.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "title": "Data Science Ethics Checklist", - "sections": [ - { - "title": "Data Collection", - "lines": [ - "If there are human subjects, those subjects have given informed consent.", - "Data collection does not collect PII which is not relevant to the analysis." - ] - }, - { - "title": "Exploratory Analysis", - "lines": [ - "Visualizations are designed to honestly represent the underlying data.", - "Fields with PII are not used or displayed unless necessary for the analysis." - ] - } - ] -} \ No newline at end of file diff --git a/checklist.yml b/checklist.yml new file mode 100644 index 0000000..4cb72c2 --- /dev/null +++ b/checklist.yml @@ -0,0 +1,10 @@ +title: Data Science Ethics Checklist +sections: + - title: Data Collection + lines: + - If there are human subjects, those subjects have given informed consent. + - Data collection does not collect PII which is not relevant to the analysis. + - title: Exploratory Analysis + lines: + - Visualizations are designed to honestly represent the underlying data. + - Fields with PII are not used or displayed unless necessary for the analysis. \ No newline at end of file diff --git a/ethics_checklist/ethics_checklist.py b/ethics_checklist/ethics_checklist.py index 0a8799f..872c3dc 100644 --- a/ethics_checklist/ethics_checklist.py +++ b/ethics_checklist/ethics_checklist.py @@ -7,7 +7,7 @@ from .parser import Checklist, Section from .formats import FORMATS, EXTENSIONS -DEFAULT_CHECKLIST = Path(__file__).parent.parent / 'checklist.json' +DEFAULT_CHECKLIST = Path(__file__).parent.parent / 'checklist.yml' CHECKLIST_FILE = Path(os.environ.get('ETHICS_CHECKLIST', DEFAULT_CHECKLIST)) @@ -46,4 +46,3 @@ def main(checklist, format, output, clipboard, overwrite): if __name__ == '__main__': main() - diff --git a/ethics_checklist/formats.py b/ethics_checklist/formats.py index a835a02..f12f44f 100644 --- a/ethics_checklist/formats.py +++ b/ethics_checklist/formats.py @@ -13,13 +13,15 @@ class Format(object): below. For other formats, override `render` and `write`. """ - template = "{title}: {sections}" - section_template = "{title}: {lines}" + template = "{title}:\n{sections}" + append_delimiter = "\n\n" + + section_template = "{title}:\n{lines}" section_delimiter = "\n\n" line_template = "* {line}" - section_delimiter = "\n\n" - + line_delimiter = "\n" + def __init__(self, checklist): self.checklist = checklist @@ -37,14 +39,13 @@ def render(self): title=section.title, lines=rendered_lines ) - + rendered_sections.append(rendered_section) all_sections = self.section_delimiter.join(rendered_sections) return self.template.format(title=self.checklist.title, sections=all_sections) - def write(self, filepath, overwrite=False): """ Renders template and writes to `filepath`. @@ -57,6 +58,8 @@ def write(self, filepath, overwrite=False): text = self.render() mode = 'w' if not filepath.exists() or overwrite else 'a' + if mode == 'a': + text = self.append_delimiter + text with open(filepath, mode) as f: f.write(text) @@ -77,14 +80,13 @@ class Markdown(Format): class JupyterNotebook(Markdown): - """ Markdown template items + """ Jupyter notebook template items """ - # if new notebook, needs these properties - nb_file_base = { - 'nbformat': 4, - 'nbformat_minor': 2, - 'metadata': {}, - 'cells': [] + + append_delimiter = { + "cell_type": "markdown", + "metadata": {}, + "source": ["-----\n"] } def render(self): @@ -111,13 +113,16 @@ def write(self, filepath, overwrite=False): with open(filepath, 'r') as f: nbdata = json.load(f) - nbdata['cells'].append({ - "cell_type": "markdown", - "metadata": {}, - "source": ["-----\n"] - }) + nbdata['cells'].append(self.append_delimiter) else: - nbdata = self.nb_file_base + # if new notebook, needs these properties + blank_jupyter_notebook = { + 'nbformat': 4, + 'nbformat_minor': 2, + 'metadata': {}, + 'cells': [] + } + nbdata = blank_jupyter_notebook cell = self.render() nbdata['cells'].append(cell) @@ -127,20 +132,24 @@ def write(self, filepath, overwrite=False): class Html(Format): - template = "<h1>{title}</h1> <br/> <br/> {sections} <br/> <br/>" + template = """<h1>{title}</h1> +<br/> <br/> +{sections} +<br/> <br/>""" section_template = """<h2>{title}</h2> <hr/> <ul> {lines} </ul>""" - section_delimiter = "<br/><br/>" + section_delimiter = """ +<br/><br/> +""" line_template = "<li><input type='checkbox'>{line}</input></li>" line_delimiter = "\n" - doc_template = """ -<html> + doc_template = """<html> <body> {text} </body> @@ -159,13 +168,15 @@ def write(self, filepath, overwrite=False): checklist = self.render() with open(filepath, "r") as f: - soup = BeautifulSoup(f) + soup = BeautifulSoup(f, 'html.parser') # add checklist to end of body - soup.body.append(checklist) - text = soup.prettify() + soup.body.append(BeautifulSoup(checklist, 'html.parser')) else: - text = self.doc_template.format(text=self.render()) + rendered_html = self.doc_template.format(text=self.render()) + soup = BeautifulSoup(rendered_html, 'html.parser') + + text = soup.prettify() with open(filepath, "w") as f: f.write(text) @@ -182,4 +193,3 @@ def write(self, filepath, overwrite=False): '.ipynb': 'jupyter', '.html': 'html', } - diff --git a/ethics_checklist/parser.py b/ethics_checklist/parser.py index 150b4a1..dc58833 100644 --- a/ethics_checklist/parser.py +++ b/ethics_checklist/parser.py @@ -1,4 +1,5 @@ -import json +import yaml + class Checklist(object): """ Stores a checklist data parsed from a yaml file. @@ -10,7 +11,7 @@ def __init__(self, title, sections): @classmethod def read(cls, filepath): with open(filepath, "r") as f: - data = json.load(f) + data = yaml.load(f) title = data['title'] sections = [Section(s['title'], s['lines']) for s in data['sections']] diff --git a/examples/ethics.html b/examples/ethics.html new file mode 100644 index 0000000..ac3bf8e --- /dev/null +++ b/examples/ethics.html @@ -0,0 +1,41 @@ +<html> + <body> + <h1> + Data Science Ethics Checklist + </h1> + <br/> + <br/> + <h2> + Data Collection + </h2> + <hr/> + <ul> + <li> + <input type="checkbox"/> + If there are human subjects, those subjects have given informed consent. + </li> + <li> + <input type="checkbox"/> + Data collection does not collect PII which is not relevant to the analysis. + </li> + </ul> + <br/> + <br/> + <h2> + Exploratory Analysis + </h2> + <hr/> + <ul> + <li> + <input type="checkbox"/> + Visualizations are designed to honestly represent the underlying data. + </li> + <li> + <input type="checkbox"/> + Fields with PII are not used or displayed unless necessary for the analysis. + </li> + </ul> + <br/> + <br/> + </body> +</html> diff --git a/requirements.txt b/requirements.txt index ac4770e..cc2ae64 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,3 +1,4 @@ beautifulsoup4>=4.6.1 click>=6.7 +pyyaml>=3.13 xerox>=0.4.1
diff --git a/tests/test_formats.py b/tests/test_formats.py index f06653a..b541017 100644 --- a/tests/test_formats.py +++ b/tests/test_formats.py @@ -1,28 +1,223 @@ from pytest import fixture +import json from ethics_checklist.parser import Checklist, Section -from ethics_checklist.formats import Markdown +from ethics_checklist.formats import Format, Markdown, JupyterNotebook, Html + @fixture def checklist(): - s1 = Section('Section 1', ['first', 'second']) - s2 = Section('Section 2', ['third', 'fourth']) - cl = Checklist('My Checklist', [s1, s2]) - return cl + s1 = Section('Section 1', ['first', 'second']) + s2 = Section('Section 2', ['third', 'fourth']) + cl = Checklist('My Checklist', [s1, s2]) + return cl + + +def test_format(checklist, tmpdir): + known_good = """My Checklist: +Section 1: +* first +* second + +Section 2: +* third +* fourth""" + existing_text = 'There is existing text in this file.' + + t = Format(checklist) -def test_format(): - pass + # no existing file + temp_file_path = tmpdir.join('test.txt') + assert t.render() == known_good + t.write(temp_file_path) + assert temp_file_path.read() == known_good + + # append to existing file + with open(temp_file_path, 'w') as f: + f.write(existing_text) + t.write(temp_file_path, overwrite=False) + assert temp_file_path.read() == existing_text + Format.append_delimiter + known_good + + # overwrite existing file + t.write(temp_file_path, overwrite=True) + assert temp_file_path.read() == known_good def test_markdown(checklist, tmpdir): - known_good = '# My Checklist\n\n## Section 1\n------\n - [ ] first\n - [ ] second\n\n## Section 2\n------\n - [ ] third\n - [ ] fourth\n\n' + known_good = '# My Checklist\n\n## Section 1\n------\n - [ ] first\n - [ ] ' \ + 'second\n\n## Section 2\n------\n - [ ] third\n - [ ] fourth\n\n' + existing_text = 'There is existing text in this file.' + + m = Markdown(checklist) + assert m.render() == known_good + + # no existing file + temp_file_path = tmpdir.join('test.md') + m.write(temp_file_path) + assert temp_file_path.read() == known_good + + # append to existing file + with open(temp_file_path, 'w') as f: + f.write(existing_text) + m.write(temp_file_path, overwrite=False) + assert temp_file_path.read() == existing_text + Markdown.append_delimiter + known_good + + # overwrite existing file + m.write(temp_file_path, overwrite=True) + assert temp_file_path.read() == known_good + + +def test_jupyter(checklist, tmpdir): + known_good = ({'cell_type': 'markdown', + 'metadata': {}, + 'source': ['# My Checklist\n', + '\n', + '## Section 1\n', + '------\n', + ' - [ ] first\n', + ' - [ ] second\n', + '\n', + '## Section 2\n', + '------\n', + ' - [ ] third\n', + ' - [ ] fourth\n', + '\n', + '\n']}) + + j = JupyterNotebook(checklist) + assert j.render() == known_good + temp_file_path = tmpdir.join('test.ipynb') + + # no existing file + j.write(temp_file_path) + with open(temp_file_path, 'r') as f: + nbdata = json.load(f) + assert nbdata['cells'] == [known_good] + + # append to existing file + j.write(temp_file_path, overwrite=False) + with open(temp_file_path, 'r') as f: + nbdata = json.load(f) + assert len(nbdata['cells']) == 3 + assert nbdata['cells'][0] == known_good + assert nbdata['cells'][1] == JupyterNotebook.append_delimiter + assert nbdata['cells'][0] == nbdata['cells'][-1] + + # overwrite existing file + j.write(temp_file_path, overwrite=True) + with open(temp_file_path, 'r') as f: + nbdata = json.load(f) + print(json.dumps(nbdata, indent=4)) + assert nbdata['cells'] == [known_good] + - m = Markdown(checklist) - assert m.render() == known_good +def test_html(checklist, tmpdir): + known_good = """<html> + <body> + <h1> + My Checklist + </h1> + <br/> + <br/> + <h2> + Section 1 + </h2> + <hr/> + <ul> + <li> + <input type="checkbox"/> + first + </li> + <li> + <input type="checkbox"/> + second + </li> + </ul> + <br/> + <br/> + <h2> + Section 2 + </h2> + <hr/> + <ul> + <li> + <input type="checkbox"/> + third + </li> + <li> + <input type="checkbox"/> + fourth + </li> + </ul> + <br/> + <br/> + </body> +</html> +""" + existing_text = """<html> +<body> +There is existing text in this file. +</body> +</html> +""" + inserted_known_good = """<html> + <body> + There is existing text in this file. + <h1> + My Checklist + </h1> + <br/> + <br/> + <h2> + Section 1 + </h2> + <hr/> + <ul> + <li> + <input type="checkbox"/> + first + </li> + <li> + <input type="checkbox"/> + second + </li> + </ul> + <br/> + <br/> + <h2> + Section 2 + </h2> + <hr/> + <ul> + <li> + <input type="checkbox"/> + third + </li> + <li> + <input type="checkbox"/> + fourth + </li> + </ul> + <br/> + <br/> + </body> +</html> +""" + # no existing file + h = Html(checklist) + temp_file_path = tmpdir.join('test.html') + h.write(temp_file_path) + with open(temp_file_path, 'r') as tempf: + assert tempf.read() == known_good - temp_file_path = tmpdir.join('test.md') - m.write(temp_file_path, overwrite=True) - assert temp_file_path.read() == known_good + # append to existing file + with open(temp_file_path, 'w') as tempf: + tempf.write(existing_text) + h.write(temp_file_path, overwrite=False) + with open(temp_file_path, 'r') as tempf: + assert tempf.read() == inserted_known_good -def test_jupyter(): - pass + # overwrite existing file + h.write(temp_file_path, overwrite=True) + with open(temp_file_path, 'r') as tempf: + assert tempf.read() == known_good diff --git a/tests/test_parser.py b/tests/test_parser.py index e69de29..b2968bf 100644 --- a/tests/test_parser.py +++ b/tests/test_parser.py @@ -0,0 +1,9 @@ +from ethics_checklist.parser import Checklist, Section + + +def test_checklist(): + c = Checklist.read('checklist.yml') + assert c.title == 'Data Science Ethics Checklist' + assert [s.title for s in c.sections] == ['Data Collection', 'Exploratory Analysis'] + lines = [s.lines for s in c.sections] + assert lines[1][1] == 'Fields with PII are not used or displayed unless necessary for the analysis.'
Checklist formats should be yaml or toml Currently the example is a json file which we don't want long term because it doesn't play nicely with source control
2018-08-09T22:24:23.000
-1.0
[ "tests/test_formats.py::test_html", "tests/test_formats.py::test_jupyter", "tests/test_formats.py::test_format", "tests/test_formats.py::test_markdown" ]
[]
amaranth-lang/amaranth
1,519
amaranth-lang__amaranth-1519
['1518']
8c5ed4051dd74a6347af8d52f8e397eb53218ac4
diff --git a/amaranth/back/rtlil.py b/amaranth/back/rtlil.py index cecb11f0f..28f428c1a 100644 --- a/amaranth/back/rtlil.py +++ b/amaranth/back/rtlil.py @@ -1132,7 +1132,7 @@ def emit_print(self, cell_idx, cell): if cell.format is not None: for chunk in cell.format.chunks: if isinstance(chunk, str): - format.append(chunk) + format.append(chunk.replace("{", "{{").replace("}", "}}")) else: spec = _ast.Format._parse_format_spec(chunk.format_desc, _ast.Shape(len(chunk.value), chunk.signed)) type = spec["type"]
diff --git a/tests/test_back_rtlil.py b/tests/test_back_rtlil.py index e99bbdb4a..eefc39911 100644 --- a/tests/test_back_rtlil.py +++ b/tests/test_back_rtlil.py @@ -2008,6 +2008,51 @@ def test_print_align(self): end """) + def test_escape_curly(self): + m = Module() + m.d.comb += [ + Print("{"), + Print("}"), + ] + self.assertRTLIL(m, [], R""" + attribute \generator "Amaranth" + attribute \top 1 + module \top + wire width 1 $1 + wire width 1 $2 + process $3 + assign $1 [0] 1'0 + assign $1 [0] 1'1 + end + cell $print $4 + parameter \FORMAT "{{\n" + parameter \ARGS_WIDTH 0 + parameter signed \PRIORITY 32'11111111111111111111111111111110 + parameter \TRG_ENABLE 0 + parameter \TRG_WIDTH 0 + parameter \TRG_POLARITY 0 + connect \EN $1 [0] + connect \ARGS { } + connect \TRG { } + end + process $5 + assign $2 [0] 1'0 + assign $2 [0] 1'1 + end + cell $print $6 + parameter \FORMAT "}}\n" + parameter \ARGS_WIDTH 0 + parameter signed \PRIORITY 32'11111111111111111111111111111100 + parameter \TRG_ENABLE 0 + parameter \TRG_WIDTH 0 + parameter \TRG_POLARITY 0 + connect \EN $2 [0] + connect \ARGS { } + connect \TRG { } + end + end + """) + class DetailTestCase(RTLILTestCase): def test_enum(self):
Format(data.Struct) gives YosysError Running ```python #!/usr/bin/env python3 from amaranth import Print, Module, Format, Signal from amaranth.lib import data from amaranth.back.verilog import convert class A(data.Struct): x: 8 b: 8 m = Module() a = Signal(A) m.d.sync += Print(Format("{}", a)) print(convert(m, ports=(a.as_value(),))) ``` yields ``` Traceback (most recent call last): File "/tmp/test.py", line 16, in <module> print(convert(m, ports=(a.as_value(),))) File "/data/projects/amaranth/amaranth/back/verilog.py", line 61, in convert verilog_text, name_map = convert_fragment(fragment, ports, name, emit_src=emit_src, strip_internal_attrs=strip_internal_attrs, **kwargs) File "/data/projects/amaranth/amaranth/back/verilog.py", line 40, in convert_fragment return _convert_rtlil_text(rtlil_text, strip_internal_attrs=strip_internal_attrs), name_map File "/data/projects/amaranth/amaranth/back/verilog.py", line 31, in _convert_rtlil_text return yosys.run(["-q", "-"], "\n".join(script), File "/data/projects/amaranth/amaranth/_toolchain/yosys.py", line 177, in run return cls._process_result(popen.returncode, stdout, stderr, ignore_warnings, src_loc_at) File "/data/projects/amaranth/amaranth/_toolchain/yosys.py", line 99, in _process_result raise YosysError(stderr.strip()) amaranth._toolchain.yosys.YosysError: ERROR: Assert `false && "Unexpected character in format substitution"' failed in kernel/fmt.cc:66. ``` When looking at the generated rtlil: ``` attribute \generator "Amaranth" attribute \src "/tmp/test.py:11" attribute \top 1 module \top attribute \src "/tmp/test.py:13" wire width 16 input 0 \a attribute \src "/data/projects/amaranth/amaranth/hdl/_ir.py:215" wire width 1 input 1 \clk attribute \src "/data/projects/amaranth/amaranth/hdl/_ir.py:215" wire width 1 input 2 \rst wire width 1 $1 attribute \src "/tmp/test.py:13" wire width 8 \a.x attribute \src "/tmp/test.py:13" wire width 8 \a.b attribute \src "/tmp/test.py:14" process $2 assign $1 [0] 1'0 assign $1 [0] 1'1 end attribute \src "/tmp/test.py:14" cell $print $3 parameter \FORMAT "{{x={8:> du}, b={8:> du}}}\n" parameter \ARGS_WIDTH 16 parameter signed \PRIORITY 32'11111111111111111111111111111110 parameter \TRG_ENABLE 1 parameter \TRG_WIDTH 1 parameter \TRG_POLARITY 1 connect \EN $1 [0] connect \ARGS \a [15:0] connect \TRG \clk [0] end connect \a.x \a [7:0] connect \a.b \a [15:8] end ``` I guess the `{}` that enclose the struct are the problem, it looks like they need to be esacped.
2024-09-20T14:00:49.000
-1.0
[ "tests/test_back_rtlil.py::PrintTestCase::test_escape_curly" ]
[ "tests/test_back_rtlil.py::InstanceTestCase::test_attr", "tests/test_back_rtlil.py::RHSTestCase::test_operator_unary", "tests/test_back_rtlil.py::DetailTestCase::test_struct", "tests/test_back_rtlil.py::FlopTestCase::test_async", "tests/test_back_rtlil.py::FlopTestCase::test_sync", "tests/test_back_rtlil.py::RHSTestCase::test_operator_eq", "tests/test_back_rtlil.py::RHSTestCase::test_part", "tests/test_back_rtlil.py::InstanceTestCase::test_concat", "tests/test_back_rtlil.py::PrintTestCase::test_print_sync", "tests/test_back_rtlil.py::SwitchTestCase::test_nested", "tests/test_back_rtlil.py::InstanceTestCase::test_ioport", "tests/test_back_rtlil.py::RHSTestCase::test_operator_cmp", "tests/test_back_rtlil.py::PrintTestCase::test_print_sign", "tests/test_back_rtlil.py::TreeTestCase::test_tree", "tests/test_back_rtlil.py::PrintTestCase::test_print_base", "tests/test_back_rtlil.py::SwitchTestCase::test_simple", "tests/test_back_rtlil.py::RHSTestCase::test_operator_shift", "tests/test_back_rtlil.py::RHSTestCase::test_operator_mux", "tests/test_back_rtlil.py::PrintTestCase::test_assume_msg", "tests/test_back_rtlil.py::PrintTestCase::test_print_align", "tests/test_back_rtlil.py::PrintTestCase::test_print_simple", "tests/test_back_rtlil.py::IOBTestCase::test_iob", "tests/test_back_rtlil.py::InstanceTestCase::test_param", "tests/test_back_rtlil.py::PrintTestCase::test_assert_simple", "tests/test_back_rtlil.py::SwitchTestCase::test_aba", "tests/test_back_rtlil.py::RHSTestCase::test_operator_add_imm", "tests/test_back_rtlil.py::RHSTestCase::test_operator_mul", "tests/test_back_rtlil.py::RHSTestCase::test_operator_bitwise", "tests/test_back_rtlil.py::RHSTestCase::test_operator_addsub", "tests/test_back_rtlil.py::PrintTestCase::test_print_char", "tests/test_back_rtlil.py::MemoryTestCase::test_sync_read", "tests/test_back_rtlil.py::MemoryTestCase::test_async_read", "tests/test_back_rtlil.py::ComponentTestCase::test_component", "tests/test_back_rtlil.py::InstanceTestCase::test_instance", "tests/test_back_rtlil.py::RHSTestCase::test_initial", "tests/test_back_rtlil.py::RHSTestCase::test_anyvalue", "tests/test_back_rtlil.py::DetailTestCase::test_enum", "tests/test_back_rtlil.py::RHSTestCase::test_operator_divmod", "tests/test_back_rtlil.py::SwitchTestCase::test_trivial" ]
End of preview. Expand in Data Studio

No dataset card yet

Downloads last month
69