language stringclasses 1 value | repo stringclasses 346 values | path stringlengths 6 201 | class_span dict | source stringlengths 21 2.38M | target stringlengths 1 96 |
|---|---|---|---|---|---|
python | openai__openai-python | src/openai/resources/beta/threads/runs/steps.py | {
"start": 970,
"end": 7896
} | class ____(SyncAPIResource):
@cached_property
def with_raw_response(self) -> StepsWithRawResponse:
"""
This property can be used as a prefix for any HTTP method call to return
the raw response object instead of the parsed content.
For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers
"""
return StepsWithRawResponse(self)
@cached_property
def with_streaming_response(self) -> StepsWithStreamingResponse:
"""
An alternative to `.with_raw_response` that doesn't eagerly read the response body.
For more information, see https://www.github.com/openai/openai-python#with_streaming_response
"""
return StepsWithStreamingResponse(self)
@typing_extensions.deprecated("The Assistants API is deprecated in favor of the Responses API")
def retrieve(
self,
step_id: str,
*,
thread_id: str,
run_id: str,
include: List[RunStepInclude] | Omit = omit,
# Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
# The extra values given here take precedence over values defined on the client or passed to this method.
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> RunStep:
"""
Retrieves a run step.
Args:
include: A list of additional fields to include in the response. Currently the only
supported value is `step_details.tool_calls[*].file_search.results[*].content`
to fetch the file search result content.
See the
[file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search#customizing-file-search-settings)
for more information.
extra_headers: Send extra headers
extra_query: Add additional query parameters to the request
extra_body: Add additional JSON properties to the request
timeout: Override the client-level default timeout for this request, in seconds
"""
if not thread_id:
raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}")
if not run_id:
raise ValueError(f"Expected a non-empty value for `run_id` but received {run_id!r}")
if not step_id:
raise ValueError(f"Expected a non-empty value for `step_id` but received {step_id!r}")
extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})}
return self._get(
f"/threads/{thread_id}/runs/{run_id}/steps/{step_id}",
options=make_request_options(
extra_headers=extra_headers,
extra_query=extra_query,
extra_body=extra_body,
timeout=timeout,
query=maybe_transform({"include": include}, step_retrieve_params.StepRetrieveParams),
),
cast_to=RunStep,
)
@typing_extensions.deprecated("The Assistants API is deprecated in favor of the Responses API")
def list(
self,
run_id: str,
*,
thread_id: str,
after: str | Omit = omit,
before: str | Omit = omit,
include: List[RunStepInclude] | Omit = omit,
limit: int | Omit = omit,
order: Literal["asc", "desc"] | Omit = omit,
# Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
# The extra values given here take precedence over values defined on the client or passed to this method.
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> SyncCursorPage[RunStep]:
"""
Returns a list of run steps belonging to a run.
Args:
after: A cursor for use in pagination. `after` is an object ID that defines your place
in the list. For instance, if you make a list request and receive 100 objects,
ending with obj_foo, your subsequent call can include after=obj_foo in order to
fetch the next page of the list.
before: A cursor for use in pagination. `before` is an object ID that defines your place
in the list. For instance, if you make a list request and receive 100 objects,
starting with obj_foo, your subsequent call can include before=obj_foo in order
to fetch the previous page of the list.
include: A list of additional fields to include in the response. Currently the only
supported value is `step_details.tool_calls[*].file_search.results[*].content`
to fetch the file search result content.
See the
[file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search#customizing-file-search-settings)
for more information.
limit: A limit on the number of objects to be returned. Limit can range between 1 and
100, and the default is 20.
order: Sort order by the `created_at` timestamp of the objects. `asc` for ascending
order and `desc` for descending order.
extra_headers: Send extra headers
extra_query: Add additional query parameters to the request
extra_body: Add additional JSON properties to the request
timeout: Override the client-level default timeout for this request, in seconds
"""
if not thread_id:
raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}")
if not run_id:
raise ValueError(f"Expected a non-empty value for `run_id` but received {run_id!r}")
extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})}
return self._get_api_list(
f"/threads/{thread_id}/runs/{run_id}/steps",
page=SyncCursorPage[RunStep],
options=make_request_options(
extra_headers=extra_headers,
extra_query=extra_query,
extra_body=extra_body,
timeout=timeout,
query=maybe_transform(
{
"after": after,
"before": before,
"include": include,
"limit": limit,
"order": order,
},
step_list_params.StepListParams,
),
),
model=RunStep,
)
| Steps |
python | huggingface__transformers | src/transformers/models/florence2/modeling_florence2.py | {
"start": 8854,
"end": 10390
} | class ____(nn.Module):
def __init__(self, config: Florence2VisionConfig, stage_idx: int):
super().__init__()
self.config = config
self.dim = config.embed_dim[stage_idx]
self.groups = config.num_groups[stage_idx]
self.qkv = nn.Linear(self.dim, self.dim * 3, bias=config.qkv_bias)
self.proj = nn.Linear(self.dim, self.dim)
self.is_causal = False
def forward(self, hidden_states: torch.Tensor):
batch_size, num_tokens, hidden_size = hidden_states.shape
# Reshape for grouped channel attention
qkv = self.qkv(hidden_states).reshape(batch_size, num_tokens, 3, self.groups, hidden_size // self.groups)
qkv = qkv.permute(2, 0, 3, 4, 1)
query, key, value = qkv.unbind(0)
scale = num_tokens**-0.5
# Channel-to-channel attention within groups:
attention_interface: Callable = eager_attention_forward
if self.config._attn_implementation != "eager":
attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
hidden_states, _ = attention_interface(
self,
query,
key,
value,
attention_mask=None,
scaling=scale,
)
hidden_states = hidden_states.permute(0, 3, 2, 1)
hidden_states = hidden_states.reshape(batch_size, num_tokens, hidden_size)
# Final projection
hidden_states = self.proj(hidden_states)
return hidden_states
| Florence2VisionChannelAttention |
python | huggingface__transformers | src/transformers/models/dpt/modeling_dpt.py | {
"start": 16715,
"end": 17408
} | class ____(nn.Module):
def __init__(self, config: DPTConfig):
super().__init__()
self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
if isinstance(config.hidden_act, str):
self.intermediate_act_fn = ACT2FN[config.hidden_act]
else:
self.intermediate_act_fn = config.hidden_act
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
hidden_states = self.dense(hidden_states)
hidden_states = self.intermediate_act_fn(hidden_states)
return hidden_states
# Copied from transformers.models.vit.modeling_vit.ViTOutput with ViTConfig->DPTConfig, ViTOutput->DPTViTOutput
| DPTViTIntermediate |
python | pytorch__pytorch | torch/_dynamo/source.py | {
"start": 37025,
"end": 37378
} | class ____(ChainedSource):
def name(self) -> str:
return f"{self.base.name()}.__tensor_flatten__()[0]"
def guard_source(self) -> GuardSource:
return self.base.guard_source()
# NB: We don't expect you to actually ever generate guards against this
# source, it is ephemeral
@dataclasses.dataclass(frozen=True)
| SubclassAttrListSource |
python | readthedocs__readthedocs.org | readthedocs/projects/admin.py | {
"start": 2483,
"end": 2545
} | class ____(admin.TabularInline):
model = Domain
| DomainInline |
python | ApeWorX__ape | src/ape/pytest/fixtures.py | {
"start": 962,
"end": 1054
} | class ____:
return_scope: Scope
invalid_fixtures: dict[Scope, list[str]]
| FixtureRebase |
python | jazzband__django-simple-history | simple_history/tests/models.py | {
"start": 22849,
"end": 23179
} | class ____(models.Model):
fk_to_self = models.ForeignKey(
"ForeignKeyToSelfModel", null=True, related_name="+", on_delete=models.CASCADE
)
fk_to_self_using_str = models.ForeignKey(
"self", null=True, related_name="+", on_delete=models.CASCADE
)
history = HistoricalRecords()
| ForeignKeyToSelfModel |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 647750,
"end": 648053
} | class ____(sgqlc.types.Type):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("cursor", "node")
cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor")
node = sgqlc.types.Field("Team", graphql_name="node")
| TeamEdge |
python | pypa__virtualenv | src/virtualenv/seed/embed/via_app_data/pip_install/symlink.py | {
"start": 212,
"end": 2015
} | class ____(PipInstall):
def _sync(self, src, dst):
os.symlink(str(src), str(dst))
def _generate_new_files(self):
# create the pyc files, as the build image will be R/O
cmd = [str(self._creator.exe), "-m", "compileall", str(self._image_dir)]
process = Popen(cmd, stdout=PIPE, stderr=PIPE)
process.communicate()
# the root pyc is shared, so we'll not symlink that - but still add the pyc files to the RECORD for close
root_py_cache = self._image_dir / "__pycache__"
new_files = set()
if root_py_cache.exists():
new_files.update(root_py_cache.iterdir())
new_files.add(root_py_cache)
safe_delete(root_py_cache)
core_new_files = super()._generate_new_files()
# remove files that are within the image folder deeper than one level (as these will be not linked directly)
for file in core_new_files:
try:
rel = file.relative_to(self._image_dir)
if len(rel.parts) > 1:
continue
except ValueError:
pass
new_files.add(file)
return new_files
def _fix_records(self, new_files):
new_files.update(i for i in self._image_dir.iterdir())
extra_record_data_str = self._records_text(sorted(new_files, key=str))
(self._dist_info / "RECORD").write_text(extra_record_data_str, encoding="utf-8")
def build_image(self):
super().build_image()
# protect the image by making it read only
set_tree(self._image_dir, S_IREAD | S_IRGRP | S_IROTH)
def clear(self):
if self._image_dir.exists():
safe_delete(self._image_dir)
super().clear()
__all__ = [
"SymlinkPipInstall",
]
| SymlinkPipInstall |
python | bottlepy__bottle | test/test_plugins.py | {
"start": 622,
"end": 5538
} | class ____(tools.ServerTestBase):
def verify_installed(self, plugin, otype, **config):
self.assertEqual(type(plugin), otype)
self.assertEqual(plugin.config, config)
self.assertEqual(plugin.app, self.app)
self.assertTrue(plugin in self.app.plugins)
def test_install_plugin(self):
plugin = MyPlugin()
installed = self.app.install(plugin)
self.assertEqual(plugin, installed)
self.assertTrue(plugin in self.app.plugins)
def test_install_decorator(self):
installed = self.app.install(my_decorator)
self.assertEqual(my_decorator, installed)
self.assertTrue(my_decorator in self.app.plugins)
def test_install_non_plugin(self):
self.assertRaises(TypeError, self.app.install, 'I am not a plugin')
def test_uninstall_by_instance(self):
plugin = self.app.install(MyPlugin())
plugin2 = self.app.install(MyPlugin())
self.app.uninstall(plugin)
self.assertTrue(plugin not in self.app.plugins)
self.assertTrue(plugin2 in self.app.plugins)
def test_uninstall_by_type(self):
plugin = self.app.install(MyPlugin())
plugin2 = self.app.install(MyPlugin())
self.app.uninstall(MyPlugin)
self.assertTrue(plugin not in self.app.plugins)
self.assertTrue(plugin2 not in self.app.plugins)
def test_uninstall_by_name(self):
plugin = self.app.install(MyPlugin())
plugin2 = self.app.install(MyPlugin())
plugin.name = 'myplugin'
self.app.uninstall('myplugin')
self.assertTrue(plugin not in self.app.plugins)
self.assertTrue(plugin2 in self.app.plugins)
def test_uninstall_all(self):
plugin = self.app.install(MyPlugin())
plugin2 = self.app.install(MyPlugin())
self.app.uninstall(True)
self.assertFalse(self.app.plugins)
def test_route_plugin(self):
plugin = MyPlugin()
plugin.add_content = ';foo'
@self.app.route('/a')
@self.app.route('/b', apply=[plugin])
def a(): return 'plugin'
self.assertBody('plugin', '/a')
self.assertBody('plugin;foo', '/b')
def test_plugin_oder(self):
self.app.install(MyPlugin()).add_content = ';global-1'
self.app.install(MyPlugin()).add_content = ';global-2'
l1 = MyPlugin()
l1.add_content = ';local-1'
l2 = MyPlugin()
l2.add_content = ';local-2'
@self.app.route('/a')
@self.app.route('/b', apply=[l1, l2])
def a(): return 'plugin'
self.assertBody('plugin;global-2;global-1', '/a')
self.assertBody('plugin;local-2;local-1;global-2;global-1', '/b')
def test_skip_by_instance(self):
g1 = self.app.install(MyPlugin())
g1.add_content = ';global-1'
g2 = self.app.install(MyPlugin())
g2.add_content = ';global-2'
l1 = MyPlugin()
l1.add_content = ';local-1'
l2 = MyPlugin()
l2.add_content = ';local-2'
@self.app.route('/a', skip=[g2, l2])
@self.app.route('/b', apply=[l1, l2], skip=[g2, l2])
def a(): return 'plugin'
self.assertBody('plugin;global-1', '/a')
self.assertBody('plugin;local-1;global-1', '/b')
def test_skip_by_class(self):
g1 = self.app.install(MyPlugin())
g1.add_content = ';global-1'
@self.app.route('/a')
@self.app.route('/b', skip=[MyPlugin])
def a(): return 'plugin'
self.assertBody('plugin;global-1', '/a')
self.assertBody('plugin', '/b')
def test_skip_by_name(self):
g1 = self.app.install(MyPlugin())
g1.add_content = ';global-1'
g1.name = 'test'
@self.app.route('/a')
@self.app.route('/b', skip=['test'])
def a(): return 'plugin'
self.assertBody('plugin;global-1', '/a')
self.assertBody('plugin', '/b')
def test_skip_all(self):
g1 = self.app.install(MyPlugin())
g1.add_content = ';global-1'
@self.app.route('/a')
@self.app.route('/b', skip=[True])
def a(): return 'plugin'
self.assertBody('plugin;global-1', '/a')
self.assertBody('plugin', '/b')
def test_skip_nonlist(self):
g1 = self.app.install(MyPlugin())
g1.add_content = ';global-1'
@self.app.route('/a')
@self.app.route('/b', skip=g1)
def a(): return 'plugin'
self.assertBody('plugin;global-1', '/a')
self.assertBody('plugin', '/b')
def test_json_plugin_catches_httpresponse(self):
@self.app.get('/return')
def _():
return HTTPResponse({'test': 'ko'}, 402)
@self.app.get('/raise')
def _():
raise HTTPResponse({'test': 'ko2'}, 402)
self.assertBody(json_dumps({'test': 'ko'}), '/return')
self.assertBody(json_dumps({'test': 'ko2'}), '/raise')
| TestPluginManagement |
python | tiangolo__fastapi | fastapi/temp_pydantic_v1_params.py | {
"start": 16462,
"end": 20310
} | class ____(FieldInfo): # type: ignore[misc]
def __init__(
self,
default: Any = Undefined,
*,
default_factory: Union[Callable[[], Any], None] = _Unset,
annotation: Optional[Any] = None,
embed: Union[bool, None] = None,
media_type: str = "application/json",
alias: Optional[str] = None,
alias_priority: Union[int, None] = _Unset,
# TODO: update when deprecating Pydantic v1, import these types
# validation_alias: str | AliasPath | AliasChoices | None
validation_alias: Union[str, None] = None,
serialization_alias: Union[str, None] = None,
title: Optional[str] = None,
description: Optional[str] = None,
gt: Optional[float] = None,
ge: Optional[float] = None,
lt: Optional[float] = None,
le: Optional[float] = None,
min_length: Optional[int] = None,
max_length: Optional[int] = None,
pattern: Optional[str] = None,
regex: Annotated[
Optional[str],
deprecated(
"Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead."
),
] = None,
discriminator: Union[str, None] = None,
strict: Union[bool, None] = _Unset,
multiple_of: Union[float, None] = _Unset,
allow_inf_nan: Union[bool, None] = _Unset,
max_digits: Union[int, None] = _Unset,
decimal_places: Union[int, None] = _Unset,
examples: Optional[List[Any]] = None,
example: Annotated[
Optional[Any],
deprecated(
"Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, "
"although still supported. Use examples instead."
),
] = _Unset,
openapi_examples: Optional[Dict[str, Example]] = None,
deprecated: Union[deprecated, str, bool, None] = None,
include_in_schema: bool = True,
json_schema_extra: Union[Dict[str, Any], None] = None,
**extra: Any,
):
self.embed = embed
self.media_type = media_type
if example is not _Unset:
warnings.warn(
"`example` has been deprecated, please use `examples` instead",
category=DeprecationWarning,
stacklevel=4,
)
self.example = example
self.include_in_schema = include_in_schema
self.openapi_examples = openapi_examples
kwargs = dict(
default=default,
default_factory=default_factory,
alias=alias,
title=title,
description=description,
gt=gt,
ge=ge,
lt=lt,
le=le,
min_length=min_length,
max_length=max_length,
discriminator=discriminator,
multiple_of=multiple_of,
allow_inf_nan=allow_inf_nan,
max_digits=max_digits,
decimal_places=decimal_places,
**extra,
)
if examples is not None:
kwargs["examples"] = examples
if regex is not None:
warnings.warn(
"`regex` has been deprecated, please use `pattern` instead",
category=DeprecationWarning,
stacklevel=4,
)
current_json_schema_extra = json_schema_extra or extra
if PYDANTIC_VERSION_MINOR_TUPLE < (2, 7):
self.deprecated = deprecated
else:
kwargs["deprecated"] = deprecated
kwargs["regex"] = pattern or regex
kwargs.update(**current_json_schema_extra)
use_kwargs = {k: v for k, v in kwargs.items() if v is not _Unset}
super().__init__(**use_kwargs)
def __repr__(self) -> str:
return f"{self.__class__.__name__}({self.default})"
| Body |
python | pypa__pip | src/pip/_vendor/pygments/util.py | {
"start": 657,
"end": 770
} | class ____(ValueError):
"""Raised if one of the lookup functions didn't find a matching class."""
| ClassNotFound |
python | PyCQA__pylint | pylint/checkers/format.py | {
"start": 3622,
"end": 4191
} | class ____:
"""A wrapper for readable access to token information."""
def __init__(self, tokens: list[tokenize.TokenInfo]) -> None:
self._tokens = tokens
def token(self, idx: int) -> str:
return self._tokens[idx][1]
def type(self, idx: int) -> int:
return self._tokens[idx][0]
def start_line(self, idx: int) -> int:
return self._tokens[idx][2][0]
def start_col(self, idx: int) -> int:
return self._tokens[idx][2][1]
def line(self, idx: int) -> str:
return self._tokens[idx][4]
| TokenWrapper |
python | run-llama__llama_index | llama-index-integrations/readers/llama-index-readers-github/tests/test_github_repository_reader.py | {
"start": 27368,
"end": 39254
} | class ____:
"""Test event system functionality."""
@pytest.fixture
def event_handler(self):
"""Create a test event handler."""
class TestEventHandler(BaseEventHandler):
def __init__(self, **data):
super().__init__(**data)
object.__setattr__(self, "events", [])
def handle(self, event):
self.events.append(event)
return TestEventHandler()
@pytest.fixture
def mock_client_for_events(self, monkeypatch):
"""Mock client for event testing."""
async def mock_get_commit(self, *args, **kwargs):
return GitCommitResponseModel.from_json(COMMIT_JSON)
async def mock_get_branch(self, *args, **kwargs):
return GitBranchResponseModel.from_json(BRANCH_JSON)
# Mock tree with one file for simpler event testing
tree_json = {
"sha": "test_tree_sha",
"url": "https://api.github.com/test/tree",
"tree": [
{
"path": "test_file.txt",
"mode": "100644",
"type": "blob",
"sha": "test_blob_sha",
"size": 100,
"url": "https://api.github.com/test/blob",
}
],
"truncated": False,
}
async def mock_get_tree(self, *args, **kwargs):
return GitTreeResponseModel.from_json(json.dumps(tree_json))
async def mock_get_blob(self, *args, **kwargs):
blob_json = {
"sha": "test_blob_sha",
"node_id": "test_node",
"size": 40,
"url": "https://api.github.com/test/blob",
"content": "VGVzdCBjb250ZW50", # "Test content" in base64
"encoding": "base64",
}
from llama_index.readers.github.repository.github_client import (
GitBlobResponseModel,
)
return GitBlobResponseModel.from_json(json.dumps(blob_json))
monkeypatch.setattr(GithubClient, "get_commit", mock_get_commit)
monkeypatch.setattr(GithubClient, "get_branch", mock_get_branch)
monkeypatch.setattr(GithubClient, "get_tree", mock_get_tree)
monkeypatch.setattr(GithubClient, "get_blob", mock_get_blob)
def test_repository_processing_events(self, mock_client_for_events, event_handler):
"""Test repository processing start/complete events."""
dispatcher = get_dispatcher()
dispatcher.add_event_handler(event_handler)
try:
gh_client = GithubClient(GITHUB_TOKEN)
reader = GithubRepositoryReader(gh_client, "run-llama", "llama_index")
documents = reader.load_data(branch="main")
# Check that we have the expected events
event_types = [type(event).__name__ for event in event_handler.events]
assert "GitHubRepositoryProcessingStartedEvent" in event_types
assert "GitHubRepositoryProcessingCompletedEvent" in event_types
assert "GitHubTotalFilesToProcessEvent" in event_types
# Check start event details
start_events = [
e
for e in event_handler.events
if isinstance(e, GitHubRepositoryProcessingStartedEvent)
]
assert len(start_events) == 1
assert start_events[0].repository_name == "run-llama/llama_index"
assert start_events[0].branch_or_commit == "main"
# Check completion event details
complete_events = [
e
for e in event_handler.events
if isinstance(e, GitHubRepositoryProcessingCompletedEvent)
]
assert len(complete_events) == 1
assert complete_events[0].repository_name == "run-llama/llama_index"
assert complete_events[0].total_documents == len(documents)
finally:
# Clean up by clearing the handler's events list
pass
def test_file_processing_events(self, mock_client_for_events, event_handler):
"""Test file processing events."""
dispatcher = get_dispatcher()
dispatcher.add_event_handler(event_handler)
try:
gh_client = GithubClient(GITHUB_TOKEN)
reader = GithubRepositoryReader(gh_client, "run-llama", "llama_index")
documents = reader.load_data(branch="main")
# Check file processing events
event_types = [type(event).__name__ for event in event_handler.events]
assert "GitHubFileProcessingStartedEvent" in event_types
assert "GitHubFileProcessedEvent" in event_types
# Check file processed event details
processed_events = [
e
for e in event_handler.events
if isinstance(e, GitHubFileProcessedEvent)
]
assert len(processed_events) == 1
assert processed_events[0].file_path == "test_file.txt"
assert processed_events[0].file_type == ".txt"
assert processed_events[0].document is not None
finally:
pass
def test_file_skipped_events(self, mock_client_for_events, event_handler):
"""Test file skipped events."""
def skip_all_files(file_path: str, file_size: int) -> tuple[bool, str]:
return False, "Skipping for test"
dispatcher = get_dispatcher()
dispatcher.add_event_handler(event_handler)
try:
gh_client = GithubClient(GITHUB_TOKEN)
reader = GithubRepositoryReader(
gh_client,
"run-llama",
"llama_index",
process_file_callback=skip_all_files,
)
documents = reader.load_data(branch="main")
# Check that files were skipped
skipped_events = [
e for e in event_handler.events if isinstance(e, GitHubFileSkippedEvent)
]
assert len(skipped_events) == 1
assert skipped_events[0].file_path == "test_file.txt"
assert skipped_events[0].reason == "Skipping for test"
finally:
pass
def test_file_failed_events(self, mock_client_for_events, event_handler):
"""Test file failed events with fail_on_error=False."""
# Mock a blob that will cause a decoding error
async def mock_get_blob_fail(self, *args, **kwargs):
blob_json = {
"sha": "test_blob_sha",
"node_id": "test_node",
"size": 40,
"url": "https://api.github.com/test/blob",
"content": "invalid_base64!!!", # Invalid base64
"encoding": "base64",
}
from llama_index.readers.github.repository.github_client import (
GitBlobResponseModel,
)
return GitBlobResponseModel.from_json(json.dumps(blob_json))
dispatcher = get_dispatcher()
dispatcher.add_event_handler(event_handler)
try:
with patch.object(GithubClient, "get_blob", mock_get_blob_fail):
gh_client = GithubClient(GITHUB_TOKEN)
reader = GithubRepositoryReader(
gh_client, "run-llama", "llama_index", fail_on_error=False
)
documents = reader.load_data(branch="main")
# Check that files failed
failed_events = [
e
for e in event_handler.events
if isinstance(e, GitHubFileFailedEvent)
]
assert len(failed_events) == 1
assert failed_events[0].file_path == "test_file.txt"
assert "Could not decode as base64" in failed_events[0].error
finally:
pass
def test_total_files_to_process_event(self, mock_client_for_events, event_handler):
"""Test total files to process event."""
dispatcher = get_dispatcher()
dispatcher.add_event_handler(event_handler)
try:
gh_client = GithubClient(GITHUB_TOKEN)
reader = GithubRepositoryReader(gh_client, "run-llama", "llama_index")
documents = reader.load_data(branch="main")
# Check total files event
total_files_events = [
e
for e in event_handler.events
if isinstance(e, GitHubTotalFilesToProcessEvent)
]
assert len(total_files_events) == 1
assert total_files_events[0].repository_name == "run-llama/llama_index"
assert total_files_events[0].branch_or_commit == "main"
assert total_files_events[0].total_files == 1 # Only one file in our mock
finally:
pass
def test_file_processing_started_event(self, mock_client_for_events, event_handler):
"""Test file processing started event."""
dispatcher = get_dispatcher()
dispatcher.add_event_handler(event_handler)
try:
gh_client = GithubClient(GITHUB_TOKEN)
reader = GithubRepositoryReader(gh_client, "run-llama", "llama_index")
documents = reader.load_data(branch="main")
# Check file processing started events
started_events = [
e
for e in event_handler.events
if isinstance(e, GitHubFileProcessingStartedEvent)
]
assert len(started_events) == 1
assert started_events[0].file_path == "test_file.txt"
assert started_events[0].file_type == ".txt"
finally:
pass
def test_all_events_in_correct_order(self, mock_client_for_events, event_handler):
"""Test that all events are fired in the correct order."""
dispatcher = get_dispatcher()
dispatcher.add_event_handler(event_handler)
try:
gh_client = GithubClient(GITHUB_TOKEN)
reader = GithubRepositoryReader(gh_client, "run-llama", "llama_index")
documents = reader.load_data(branch="main")
# Check event order
event_types = [type(event).__name__ for event in event_handler.events]
# Expected order: Started -> TotalFiles -> FileStarted -> FileProcessed -> Completed
expected_order = [
"GitHubRepositoryProcessingStartedEvent",
"GitHubTotalFilesToProcessEvent",
"GitHubFileProcessingStartedEvent",
"GitHubFileProcessedEvent",
"GitHubRepositoryProcessingCompletedEvent",
]
# Check that all expected events are present
for expected_event in expected_order:
assert expected_event in event_types
# Check the order - find indices of each event type
indices = {}
for event_type in expected_order:
indices[event_type] = event_types.index(event_type)
# Verify order is correct
assert (
indices["GitHubRepositoryProcessingStartedEvent"]
< indices["GitHubTotalFilesToProcessEvent"]
)
assert (
indices["GitHubTotalFilesToProcessEvent"]
< indices["GitHubFileProcessingStartedEvent"]
)
assert (
indices["GitHubFileProcessingStartedEvent"]
< indices["GitHubFileProcessedEvent"]
)
assert (
indices["GitHubFileProcessedEvent"]
< indices["GitHubRepositoryProcessingCompletedEvent"]
)
finally:
pass
| TestGithubRepositoryReaderEvents |
python | apache__airflow | airflow-core/src/airflow/example_dags/plugins/workday.py | {
"start": 4177,
"end": 4327
} | class ____(AirflowPlugin):
name = "workday_timetable_plugin"
timetables = [AfterWorkdayTimetable]
# [END howto_timetable]
| WorkdayTimetablePlugin |
python | scrapy__scrapy | scrapy/exceptions.py | {
"start": 564,
"end": 663
} | class ____(Exception):
"""Indicates a decision was made not to process a request"""
| IgnoreRequest |
python | python-attrs__attrs | typing-examples/mypy.py | {
"start": 2318,
"end": 5637
} | class ____:
a = attr.ib(
type=List[C],
validator=attr.validators.deep_iterable(
attr.validators.instance_of(C), attr.validators.instance_of(list)
),
)
a2 = attr.ib(
type=Tuple[C],
validator=attr.validators.deep_iterable(
attr.validators.instance_of(C), attr.validators.instance_of(tuple)
),
)
a3 = attr.ib(
type=Tuple[C],
validator=attr.validators.deep_iterable(
[attr.validators.instance_of(C)],
[attr.validators.instance_of(tuple)],
),
)
b = attr.ib(
type=List[C],
validator=attr.validators.deep_iterable(
attr.validators.instance_of(C)
),
)
c = attr.ib(
type=Dict[C, D],
validator=attr.validators.deep_mapping(
attr.validators.instance_of(C),
attr.validators.instance_of(D),
attr.validators.instance_of(dict),
),
)
d = attr.ib(
type=Dict[C, D],
validator=attr.validators.deep_mapping(
attr.validators.instance_of(C), attr.validators.instance_of(D)
),
)
d2 = attr.ib(
type=Dict[C, D],
validator=attr.validators.deep_mapping(attr.validators.instance_of(C)),
)
d3 = attr.ib(
type=Dict[C, D],
validator=attr.validators.deep_mapping(
value_validator=attr.validators.instance_of(C)
),
)
d4 = attr.ib(
type=Dict[C, D],
validator=attr.validators.deep_mapping(
key_validator=[attr.validators.instance_of(C)],
value_validator=[attr.validators.instance_of(C)],
mapping_validator=[attr.validators.instance_of(dict)],
),
)
e: str = attr.ib(validator=attr.validators.matches_re(re.compile(r"foo")))
f: str = attr.ib(
validator=attr.validators.matches_re(r"foo", flags=42, func=re.search)
)
# Test different forms of instance_of
g: int = attr.ib(validator=attr.validators.instance_of(int))
h: int = attr.ib(validator=attr.validators.instance_of((int,)))
j: int | str = attr.ib(validator=attr.validators.instance_of((int, str)))
k: int | str | C = attr.ib(
validator=attrs.validators.instance_of((int, C, str))
)
kk: int | str | C = attr.ib(
validator=attrs.validators.instance_of(int | C | str)
)
l: Any = attr.ib(
validator=attr.validators.not_(attr.validators.in_("abc"))
)
m: Any = attr.ib(
validator=attr.validators.not_(
attr.validators.in_("abc"), exc_types=ValueError
)
)
n: Any = attr.ib(
validator=attr.validators.not_(
attr.validators.in_("abc"), exc_types=(ValueError,)
)
)
o: Any = attr.ib(
validator=attr.validators.not_(attr.validators.in_("abc"), msg="spam")
)
p: Any = attr.ib(
validator=attr.validators.not_(attr.validators.in_("abc"), msg=None)
)
q: Any = attr.ib(
validator=attrs.validators.optional(attrs.validators.instance_of(C))
)
r: Any = attr.ib(
validator=attrs.validators.optional([attrs.validators.instance_of(C)])
)
s: Any = attr.ib(
validator=attrs.validators.optional((attrs.validators.instance_of(C),))
)
@attr.define
| Validated |
python | pydata__xarray | xarray/tests/test_units.py | {
"start": 186454,
"end": 187021
} | class ____:
def test_duck_array_ops(self):
import dask.array
d = dask.array.array([1, 2, 3])
q = unit_registry.Quantity(d, units="m")
da = xr.DataArray(q, dims="x")
actual = da.mean().compute()
actual.name = None
expected = xr.DataArray(unit_registry.Quantity(np.array(2.0), units="m"))
assert_units_equal(expected, actual)
# Don't use isinstance b/c we don't want to allow subclasses through
assert type(expected.data) is type(actual.data)
@requires_matplotlib
| TestPintWrappingDask |
python | django__django | tests/forms_tests/tests/test_forms.py | {
"start": 1914,
"end": 208068
} | class ____(SimpleTestCase):
# A Form is a collection of Fields. It knows how to validate a set of data
# and it knows how to render itself in a couple of default ways (e.g., an
# HTML table). You can pass it data in __init__(), as a dictionary.
def test_form(self):
# Pass a dictionary to a Form's __init__().
p = Person(
{"first_name": "John", "last_name": "Lennon", "birthday": "1940-10-9"}
)
self.assertTrue(p.is_bound)
self.assertEqual(p.errors, {})
self.assertIsInstance(p.errors, dict)
self.assertTrue(p.is_valid())
self.assertHTMLEqual(p.errors.as_ul(), "")
self.assertEqual(p.errors.as_text(), "")
self.assertEqual(p.cleaned_data["first_name"], "John")
self.assertEqual(p.cleaned_data["last_name"], "Lennon")
self.assertEqual(p.cleaned_data["birthday"], datetime.date(1940, 10, 9))
self.assertHTMLEqual(
str(p["first_name"]),
'<input type="text" name="first_name" value="John" id="id_first_name" '
"required>",
)
self.assertHTMLEqual(
str(p["last_name"]),
'<input type="text" name="last_name" value="Lennon" id="id_last_name" '
"required>",
)
self.assertHTMLEqual(
str(p["birthday"]),
'<input type="text" name="birthday" value="1940-10-9" id="id_birthday" '
"required>",
)
msg = (
"Key 'nonexistentfield' not found in 'Person'. Choices are: birthday, "
"first_name, last_name."
)
with self.assertRaisesMessage(KeyError, msg):
p["nonexistentfield"]
form_output = []
for boundfield in p:
form_output.append(str(boundfield))
self.assertHTMLEqual(
"\n".join(form_output),
'<input type="text" name="first_name" value="John" id="id_first_name" '
"required>"
'<input type="text" name="last_name" value="Lennon" id="id_last_name" '
"required>"
'<input type="text" name="birthday" value="1940-10-9" id="id_birthday" '
"required>",
)
form_output = []
for boundfield in p:
form_output.append([boundfield.label, boundfield.data])
self.assertEqual(
form_output,
[
["First name", "John"],
["Last name", "Lennon"],
["Birthday", "1940-10-9"],
],
)
self.assertHTMLEqual(
str(p),
'<div><label for="id_first_name">First name:</label><input type="text" '
'name="first_name" value="John" required id="id_first_name"></div><div>'
'<label for="id_last_name">Last name:</label><input type="text" '
'name="last_name" value="Lennon" required id="id_last_name"></div><div>'
'<label for="id_birthday">Birthday:</label><input type="text" '
'name="birthday" value="1940-10-9" required id="id_birthday"></div>',
)
self.assertHTMLEqual(
p.as_div(),
'<div><label for="id_first_name">First name:</label><input type="text" '
'name="first_name" value="John" required id="id_first_name"></div><div>'
'<label for="id_last_name">Last name:</label><input type="text" '
'name="last_name" value="Lennon" required id="id_last_name"></div><div>'
'<label for="id_birthday">Birthday:</label><input type="text" '
'name="birthday" value="1940-10-9" required id="id_birthday"></div>',
)
def test_empty_dict(self):
# Empty dictionaries are valid, too.
p = Person({})
self.assertTrue(p.is_bound)
self.assertEqual(p.errors["first_name"], ["This field is required."])
self.assertEqual(p.errors["last_name"], ["This field is required."])
self.assertEqual(p.errors["birthday"], ["This field is required."])
self.assertFalse(p.is_valid())
self.assertEqual(p.cleaned_data, {})
self.assertHTMLEqual(
str(p),
'<div><label for="id_first_name">First name:</label>'
'<ul class="errorlist" id="id_first_name_error"><li>This field is required.'
'</li></ul><input type="text" name="first_name" aria-invalid="true" '
'required id="id_first_name" aria-describedby="id_first_name_error"></div>'
'<div><label for="id_last_name">Last name:</label>'
'<ul class="errorlist" id="id_last_name_error"><li>This field is required.'
'</li></ul><input type="text" name="last_name" aria-invalid="true" '
'required id="id_last_name" aria-describedby="id_last_name_error"></div>'
'<div><label for="id_birthday">Birthday:</label>'
'<ul class="errorlist" id="id_birthday_error"><li>This field is required.'
'</li></ul><input type="text" name="birthday" aria-invalid="true" required '
'id="id_birthday" aria-describedby="id_birthday_error"></div>',
)
self.assertHTMLEqual(
p.as_table(),
"""<tr><th><label for="id_first_name">First name:</label></th><td>
<ul class="errorlist" id="id_first_name_error"><li>This field is required.</li></ul>
<input type="text" name="first_name" id="id_first_name" aria-invalid="true" required
aria-describedby="id_first_name_error">
</td></tr><tr><th><label for="id_last_name">Last name:</label></th>
<td><ul class="errorlist" id="id_last_name_error"><li>This field is required.</li></ul>
<input type="text" name="last_name" id="id_last_name" aria-invalid="true" required
aria-describedby="id_last_name_error">
</td></tr><tr><th><label for="id_birthday">Birthday:</label></th>
<td><ul class="errorlist" id="id_birthday_error"><li>This field is required.</li></ul>
<input type="text" name="birthday" id="id_birthday" aria-invalid="true" required
aria-describedby="id_birthday_error">
</td></tr>""",
)
self.assertHTMLEqual(
p.as_ul(),
"""<li><ul class="errorlist" id="id_first_name_error">
<li>This field is required.</li></ul>
<label for="id_first_name">First name:</label>
<input type="text" name="first_name" id="id_first_name" aria-invalid="true" required
aria-describedby="id_first_name_error">
</li><li><ul class="errorlist" id="id_last_name_error"><li>This field is required.</li>
</ul><label for="id_last_name">Last name:</label>
<input type="text" name="last_name" id="id_last_name" aria-invalid="true" required
aria-describedby="id_last_name_error">
</li><li><ul class="errorlist" id="id_birthday_error"><li>This field is required.</li>
</ul><label for="id_birthday">Birthday:</label>
<input type="text" name="birthday" id="id_birthday" aria-invalid="true" required
aria-describedby="id_birthday_error">
</li>""",
)
self.assertHTMLEqual(
p.as_p(),
"""<ul class="errorlist" id="id_first_name_error"><li>
This field is required.</li></ul>
<p><label for="id_first_name">First name:</label>
<input type="text" name="first_name" id="id_first_name" aria-invalid="true" required
aria-describedby="id_first_name_error">
</p><ul class="errorlist" id="id_last_name_error"><li>This field is required.</li></ul>
<p><label for="id_last_name">Last name:</label>
<input type="text" name="last_name" id="id_last_name" aria-invalid="true" required
aria-describedby="id_last_name_error">
</p><ul class="errorlist" id="id_birthday_error"><li>This field is required.</li></ul>
<p><label for="id_birthday">Birthday:</label>
<input type="text" name="birthday" id="id_birthday" aria-invalid="true" required
aria-describedby="id_birthday_error">
</p>""",
)
self.assertHTMLEqual(
p.as_div(),
'<div><label for="id_first_name">First name:</label>'
'<ul class="errorlist" id="id_first_name_error"><li>This field is required.'
'</li></ul><input type="text" name="first_name" aria-invalid="true" '
'required id="id_first_name" aria-describedby="id_first_name_error"></div>'
'<div><label for="id_last_name">Last name:</label>'
'<ul class="errorlist" id="id_last_name_error"><li>This field is required.'
'</li></ul><input type="text" name="last_name" aria-invalid="true" '
'required id="id_last_name" aria-describedby="id_last_name_error"></div>'
'<div><label for="id_birthday">Birthday:</label>'
'<ul class="errorlist" id="id_birthday_error"><li>This field is required.'
'</li></ul><input type="text" name="birthday" aria-invalid="true" required '
'id="id_birthday" aria-describedby="id_birthday_error"></div>',
)
def test_empty_querydict_args(self):
data = QueryDict()
files = QueryDict()
p = Person(data, files)
self.assertIs(p.data, data)
self.assertIs(p.files, files)
def test_unbound_form(self):
# If you don't pass any values to the Form's __init__(), or if you pass
# None, the Form will be considered unbound and won't do any
# validation. Form.errors will be an empty dictionary *but*
# Form.is_valid() will return False.
p = Person()
self.assertFalse(p.is_bound)
self.assertEqual(p.errors, {})
self.assertFalse(p.is_valid())
with self.assertRaises(AttributeError):
p.cleaned_data
self.assertHTMLEqual(
str(p),
'<div><label for="id_first_name">First name:</label><input type="text" '
'name="first_name" id="id_first_name" required></div><div><label '
'for="id_last_name">Last name:</label><input type="text" name="last_name" '
'id="id_last_name" required></div><div><label for="id_birthday">'
'Birthday:</label><input type="text" name="birthday" id="id_birthday" '
"required></div>",
)
self.assertHTMLEqual(
p.as_table(),
"""<tr><th><label for="id_first_name">First name:</label></th><td>
<input type="text" name="first_name" id="id_first_name" required></td></tr>
<tr><th><label for="id_last_name">Last name:</label></th><td>
<input type="text" name="last_name" id="id_last_name" required></td></tr>
<tr><th><label for="id_birthday">Birthday:</label></th><td>
<input type="text" name="birthday" id="id_birthday" required></td></tr>""",
)
self.assertHTMLEqual(
p.as_ul(),
"""<li><label for="id_first_name">First name:</label>
<input type="text" name="first_name" id="id_first_name" required></li>
<li><label for="id_last_name">Last name:</label>
<input type="text" name="last_name" id="id_last_name" required></li>
<li><label for="id_birthday">Birthday:</label>
<input type="text" name="birthday" id="id_birthday" required></li>""",
)
self.assertHTMLEqual(
p.as_p(),
"""<p><label for="id_first_name">First name:</label>
<input type="text" name="first_name" id="id_first_name" required></p>
<p><label for="id_last_name">Last name:</label>
<input type="text" name="last_name" id="id_last_name" required></p>
<p><label for="id_birthday">Birthday:</label>
<input type="text" name="birthday" id="id_birthday" required></p>""",
)
self.assertHTMLEqual(
p.as_div(),
'<div><label for="id_first_name">First name:</label><input type="text" '
'name="first_name" id="id_first_name" required></div><div><label '
'for="id_last_name">Last name:</label><input type="text" name="last_name" '
'id="id_last_name" required></div><div><label for="id_birthday">'
'Birthday:</label><input type="text" name="birthday" id="id_birthday" '
"required></div>",
)
def test_unicode_values(self):
# Unicode values are handled properly.
p = Person(
{
"first_name": "John",
"last_name": "\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111",
"birthday": "1940-10-9",
}
)
self.assertHTMLEqual(
p.as_table(),
'<tr><th><label for="id_first_name">First name:</label></th><td>'
'<input type="text" name="first_name" value="John" id="id_first_name" '
"required></td></tr>\n"
'<tr><th><label for="id_last_name">Last name:</label>'
'</th><td><input type="text" name="last_name" '
'value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111"'
'id="id_last_name" required></td></tr>\n'
'<tr><th><label for="id_birthday">Birthday:</label></th><td>'
'<input type="text" name="birthday" value="1940-10-9" id="id_birthday" '
"required></td></tr>",
)
self.assertHTMLEqual(
p.as_ul(),
'<li><label for="id_first_name">First name:</label> '
'<input type="text" name="first_name" value="John" id="id_first_name" '
"required></li>\n"
'<li><label for="id_last_name">Last name:</label> '
'<input type="text" name="last_name" '
'value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" '
'id="id_last_name" required></li>\n'
'<li><label for="id_birthday">Birthday:</label> '
'<input type="text" name="birthday" value="1940-10-9" id="id_birthday" '
"required></li>",
)
self.assertHTMLEqual(
p.as_p(),
'<p><label for="id_first_name">First name:</label> '
'<input type="text" name="first_name" value="John" id="id_first_name" '
"required></p>\n"
'<p><label for="id_last_name">Last name:</label> '
'<input type="text" name="last_name" '
'value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" '
'id="id_last_name" required></p>\n'
'<p><label for="id_birthday">Birthday:</label> '
'<input type="text" name="birthday" value="1940-10-9" id="id_birthday" '
"required></p>",
)
self.assertHTMLEqual(
p.as_div(),
'<div><label for="id_first_name">First name:</label>'
'<input type="text" name="first_name" value="John" id="id_first_name" '
'required></div><div><label for="id_last_name">Last name:</label>'
'<input type="text" name="last_name"'
'value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" '
'id="id_last_name" required></div><div><label for="id_birthday">'
'Birthday:</label><input type="text" name="birthday" value="1940-10-9" '
'id="id_birthday" required></div>',
)
p = Person({"last_name": "Lennon"})
self.assertEqual(p.errors["first_name"], ["This field is required."])
self.assertEqual(p.errors["birthday"], ["This field is required."])
self.assertFalse(p.is_valid())
self.assertEqual(
p.errors,
{
"birthday": ["This field is required."],
"first_name": ["This field is required."],
},
)
self.assertEqual(p.cleaned_data, {"last_name": "Lennon"})
self.assertEqual(p["first_name"].errors, ["This field is required."])
self.assertHTMLEqual(
p["first_name"].errors.as_ul(),
'<ul class="errorlist" id="id_first_name_error">'
"<li>This field is required.</li></ul>",
)
self.assertEqual(p["first_name"].errors.as_text(), "* This field is required.")
p = Person()
self.assertHTMLEqual(
str(p["first_name"]),
'<input type="text" name="first_name" id="id_first_name" required>',
)
self.assertHTMLEqual(
str(p["last_name"]),
'<input type="text" name="last_name" id="id_last_name" required>',
)
self.assertHTMLEqual(
str(p["birthday"]),
'<input type="text" name="birthday" id="id_birthday" required>',
)
def test_cleaned_data_only_fields(self):
# cleaned_data will always *only* contain a key for fields defined in
# the Form, even if you pass extra data when you define the Form. In
# this example, we pass a bunch of extra fields to the form
# constructor, but cleaned_data contains only the form's fields.
data = {
"first_name": "John",
"last_name": "Lennon",
"birthday": "1940-10-9",
"extra1": "hello",
"extra2": "hello",
}
p = Person(data)
self.assertTrue(p.is_valid())
self.assertEqual(p.cleaned_data["first_name"], "John")
self.assertEqual(p.cleaned_data["last_name"], "Lennon")
self.assertEqual(p.cleaned_data["birthday"], datetime.date(1940, 10, 9))
def test_optional_data(self):
# cleaned_data will include a key and value for *all* fields defined in
# the Form, even if the Form's data didn't include a value for fields
# that are not required. In this example, the data dictionary doesn't
# include a value for the "nick_name" field, but cleaned_data includes
# it. For CharFields, it's set to the empty string.
class OptionalPersonForm(Form):
first_name = CharField()
last_name = CharField()
nick_name = CharField(required=False)
data = {"first_name": "John", "last_name": "Lennon"}
f = OptionalPersonForm(data)
self.assertTrue(f.is_valid())
self.assertEqual(f.cleaned_data["nick_name"], "")
self.assertEqual(f.cleaned_data["first_name"], "John")
self.assertEqual(f.cleaned_data["last_name"], "Lennon")
# For DateFields, it's set to None.
class OptionalPersonForm(Form):
first_name = CharField()
last_name = CharField()
birth_date = DateField(required=False)
data = {"first_name": "John", "last_name": "Lennon"}
f = OptionalPersonForm(data)
self.assertTrue(f.is_valid())
self.assertIsNone(f.cleaned_data["birth_date"])
self.assertEqual(f.cleaned_data["first_name"], "John")
self.assertEqual(f.cleaned_data["last_name"], "Lennon")
def test_auto_id(self):
# "auto_id" tells the Form to add an "id" attribute to each form
# element. If it's a string that contains '%s', Django will use that as
# a format string into which the field's name will be inserted. It will
# also put a <label> around the human-readable labels for a field.
p = Person(auto_id="%s_id")
self.assertHTMLEqual(
p.as_table(),
"""<tr><th><label for="first_name_id">First name:</label></th><td>
<input type="text" name="first_name" id="first_name_id" required></td></tr>
<tr><th><label for="last_name_id">Last name:</label></th><td>
<input type="text" name="last_name" id="last_name_id" required></td></tr>
<tr><th><label for="birthday_id">Birthday:</label></th><td>
<input type="text" name="birthday" id="birthday_id" required></td></tr>""",
)
self.assertHTMLEqual(
p.as_ul(),
"""<li><label for="first_name_id">First name:</label>
<input type="text" name="first_name" id="first_name_id" required></li>
<li><label for="last_name_id">Last name:</label>
<input type="text" name="last_name" id="last_name_id" required></li>
<li><label for="birthday_id">Birthday:</label>
<input type="text" name="birthday" id="birthday_id" required></li>""",
)
self.assertHTMLEqual(
p.as_p(),
"""<p><label for="first_name_id">First name:</label>
<input type="text" name="first_name" id="first_name_id" required></p>
<p><label for="last_name_id">Last name:</label>
<input type="text" name="last_name" id="last_name_id" required></p>
<p><label for="birthday_id">Birthday:</label>
<input type="text" name="birthday" id="birthday_id" required></p>""",
)
self.assertHTMLEqual(
p.as_div(),
'<div><label for="first_name_id">First name:</label><input type="text" '
'name="first_name" id="first_name_id" required></div><div><label '
'for="last_name_id">Last name:</label><input type="text" '
'name="last_name" id="last_name_id" required></div><div><label '
'for="birthday_id">Birthday:</label><input type="text" name="birthday" '
'id="birthday_id" required></div>',
)
def test_auto_id_true(self):
# If auto_id is any True value whose str() does not contain '%s', the
# "id" attribute will be the name of the field.
p = Person(auto_id=True)
self.assertHTMLEqual(
p.as_ul(),
"""<li><label for="first_name">First name:</label>
<input type="text" name="first_name" id="first_name" required></li>
<li><label for="last_name">Last name:</label>
<input type="text" name="last_name" id="last_name" required></li>
<li><label for="birthday">Birthday:</label>
<input type="text" name="birthday" id="birthday" required></li>""",
)
def test_auto_id_false(self):
# If auto_id is any False value, an "id" attribute won't be output
# unless it was manually entered.
p = Person(auto_id=False)
self.assertHTMLEqual(
p.as_ul(),
"""<li>First name: <input type="text" name="first_name" required></li>
<li>Last name: <input type="text" name="last_name" required></li>
<li>Birthday: <input type="text" name="birthday" required></li>""",
)
def test_id_on_field(self):
# In this example, auto_id is False, but the "id" attribute for the
# "first_name" field is given. Also note that field gets a <label>,
# while the others don't.
p = PersonNew(auto_id=False)
self.assertHTMLEqual(
p.as_ul(),
"""<li><label for="first_name_id">First name:</label>
<input type="text" id="first_name_id" name="first_name" required></li>
<li>Last name: <input type="text" name="last_name" required></li>
<li>Birthday: <input type="text" name="birthday" required></li>""",
)
def test_auto_id_on_form_and_field(self):
# If the "id" attribute is specified in the Form and auto_id is True,
# the "id" attribute in the Form gets precedence.
p = PersonNew(auto_id=True)
self.assertHTMLEqual(
p.as_ul(),
"""<li><label for="first_name_id">First name:</label>
<input type="text" id="first_name_id" name="first_name" required></li>
<li><label for="last_name">Last name:</label>
<input type="text" name="last_name" id="last_name" required></li>
<li><label for="birthday">Birthday:</label>
<input type="text" name="birthday" id="birthday" required></li>""",
)
def test_various_boolean_values(self):
class SignupForm(Form):
email = EmailField()
get_spam = BooleanField()
f = SignupForm(auto_id=False)
self.assertHTMLEqual(
str(f["email"]),
'<input type="email" name="email" maxlength="320" required>',
)
self.assertHTMLEqual(
str(f["get_spam"]), '<input type="checkbox" name="get_spam" required>'
)
f = SignupForm({"email": "test@example.com", "get_spam": True}, auto_id=False)
self.assertHTMLEqual(
str(f["email"]),
'<input type="email" name="email" maxlength="320" value="test@example.com" '
"required>",
)
self.assertHTMLEqual(
str(f["get_spam"]),
'<input checked type="checkbox" name="get_spam" required>',
)
# 'True' or 'true' should be rendered without a value attribute
f = SignupForm({"email": "test@example.com", "get_spam": "True"}, auto_id=False)
self.assertHTMLEqual(
str(f["get_spam"]),
'<input checked type="checkbox" name="get_spam" required>',
)
f = SignupForm({"email": "test@example.com", "get_spam": "true"}, auto_id=False)
self.assertHTMLEqual(
str(f["get_spam"]),
'<input checked type="checkbox" name="get_spam" required>',
)
# A value of 'False' or 'false' should be rendered unchecked
f = SignupForm(
{"email": "test@example.com", "get_spam": "False"}, auto_id=False
)
self.assertHTMLEqual(
str(f["get_spam"]),
'<input type="checkbox" name="get_spam" aria-invalid="true" required>',
)
f = SignupForm(
{"email": "test@example.com", "get_spam": "false"}, auto_id=False
)
self.assertHTMLEqual(
str(f["get_spam"]),
'<input type="checkbox" name="get_spam" aria-invalid="true" required>',
)
# A value of '0' should be interpreted as a True value (#16820)
f = SignupForm({"email": "test@example.com", "get_spam": "0"})
self.assertTrue(f.is_valid())
self.assertTrue(f.cleaned_data.get("get_spam"))
def test_widget_output(self):
# Any Field can have a Widget class passed to its constructor:
class ContactForm(Form):
subject = CharField()
message = CharField(widget=Textarea)
f = ContactForm(auto_id=False)
self.assertHTMLEqual(
str(f["subject"]), '<input type="text" name="subject" required>'
)
self.assertHTMLEqual(
str(f["message"]),
'<textarea name="message" rows="10" cols="40" required></textarea>',
)
# as_textarea(), as_text() and as_hidden() are shortcuts for changing
# the output widget type:
self.assertHTMLEqual(
f["subject"].as_textarea(),
'<textarea name="subject" rows="10" cols="40" required></textarea>',
)
self.assertHTMLEqual(
f["message"].as_text(), '<input type="text" name="message" required>'
)
self.assertHTMLEqual(
f["message"].as_hidden(), '<input type="hidden" name="message">'
)
# The 'widget' parameter to a Field can also be an instance:
class ContactForm(Form):
subject = CharField()
message = CharField(widget=Textarea(attrs={"rows": 80, "cols": 20}))
f = ContactForm(auto_id=False)
self.assertHTMLEqual(
str(f["message"]),
'<textarea name="message" rows="80" cols="20" required></textarea>',
)
# Instance-level attrs are *not* carried over to as_textarea(),
# as_text() and as_hidden():
self.assertHTMLEqual(
f["message"].as_text(), '<input type="text" name="message" required>'
)
f = ContactForm({"subject": "Hello", "message": "I love you."}, auto_id=False)
self.assertHTMLEqual(
f["subject"].as_textarea(),
'<textarea rows="10" cols="40" name="subject" required>Hello</textarea>',
)
self.assertHTMLEqual(
f["message"].as_text(),
'<input type="text" name="message" value="I love you." required>',
)
self.assertHTMLEqual(
f["message"].as_hidden(),
'<input type="hidden" name="message" value="I love you.">',
)
def test_forms_with_choices(self):
# For a form with a <select>, use ChoiceField:
class FrameworkForm(Form):
name = CharField()
language = ChoiceField(choices=[("P", "Python"), ("J", "Java")])
f = FrameworkForm(auto_id=False)
self.assertHTMLEqual(
str(f["language"]),
"""<select name="language">
<option value="P">Python</option>
<option value="J">Java</option>
</select>""",
)
f = FrameworkForm({"name": "Django", "language": "P"}, auto_id=False)
self.assertHTMLEqual(
str(f["language"]),
"""<select name="language">
<option value="P" selected>Python</option>
<option value="J">Java</option>
</select>""",
)
# A subtlety: If one of the choices' value is the empty string and the
# form is unbound, then the <option> for the empty-string choice will
# get selected.
class FrameworkForm(Form):
name = CharField()
language = ChoiceField(
choices=[("", "------"), ("P", "Python"), ("J", "Java")]
)
f = FrameworkForm(auto_id=False)
self.assertHTMLEqual(
str(f["language"]),
"""<select name="language" required>
<option value="" selected>------</option>
<option value="P">Python</option>
<option value="J">Java</option>
</select>""",
)
# You can specify widget attributes in the Widget constructor.
class FrameworkForm(Form):
name = CharField()
language = ChoiceField(
choices=[("P", "Python"), ("J", "Java")],
widget=Select(attrs={"class": "foo"}),
)
f = FrameworkForm(auto_id=False)
self.assertHTMLEqual(
str(f["language"]),
"""<select class="foo" name="language">
<option value="P">Python</option>
<option value="J">Java</option>
</select>""",
)
f = FrameworkForm({"name": "Django", "language": "P"}, auto_id=False)
self.assertHTMLEqual(
str(f["language"]),
"""<select class="foo" name="language">
<option value="P" selected>Python</option>
<option value="J">Java</option>
</select>""",
)
# When passing a custom widget instance to ChoiceField, note that
# setting 'choices' on the widget is meaningless. The widget will use
# the choices defined on the Field, not the ones defined on the Widget.
class FrameworkForm(Form):
name = CharField()
language = ChoiceField(
choices=[("P", "Python"), ("J", "Java")],
widget=Select(
choices=[("R", "Ruby"), ("P", "Perl")], attrs={"class": "foo"}
),
)
f = FrameworkForm(auto_id=False)
self.assertHTMLEqual(
str(f["language"]),
"""<select class="foo" name="language">
<option value="P">Python</option>
<option value="J">Java</option>
</select>""",
)
f = FrameworkForm({"name": "Django", "language": "P"}, auto_id=False)
self.assertHTMLEqual(
str(f["language"]),
"""<select class="foo" name="language">
<option value="P" selected>Python</option>
<option value="J">Java</option>
</select>""",
)
# You can set a ChoiceField's choices after the fact.
class FrameworkForm(Form):
name = CharField()
language = ChoiceField()
f = FrameworkForm(auto_id=False)
self.assertHTMLEqual(
str(f["language"]),
"""<select name="language">
</select>""",
)
f.fields["language"].choices = [("P", "Python"), ("J", "Java")]
self.assertHTMLEqual(
str(f["language"]),
"""<select name="language">
<option value="P">Python</option>
<option value="J">Java</option>
</select>""",
)
def test_forms_with_radio(self):
# Add widget=RadioSelect to use that widget with a ChoiceField.
f = FrameworkForm(auto_id=False)
self.assertHTMLEqual(
str(f["language"]),
"""<div>
<div><label><input type="radio" name="language" value="P" required> Python</label></div>
<div><label><input type="radio" name="language" value="J" required> Java</label></div>
</div>""",
)
self.assertHTMLEqual(
f.as_table(),
"""<tr><th>Name:</th><td><input type="text" name="name" required></td></tr>
<tr><th>Language:</th><td><div>
<div><label><input type="radio" name="language" value="P" required> Python</label></div>
<div><label><input type="radio" name="language" value="J" required> Java</label></div>
</div></td></tr>""",
)
self.assertHTMLEqual(
f.as_ul(),
"""<li>Name: <input type="text" name="name" required></li>
<li>Language: <div>
<div><label><input type="radio" name="language" value="P" required> Python</label></div>
<div><label><input type="radio" name="language" value="J" required> Java</label></div>
</div></li>""",
)
# Need an auto_id to generate legend.
self.assertHTMLEqual(
f.render(f.template_name_div),
'<div> Name: <input type="text" name="name" required></div><div><fieldset>'
'Language:<div><div><label><input type="radio" name="language" value="P" '
'required> Python</label></div><div><label><input type="radio" '
'name="language" value="J" required> Java</label></div></div></fieldset>'
"</div>",
)
# Regarding auto_id and <label>, RadioSelect is a special case. Each
# radio button gets a distinct ID, formed by appending an underscore
# plus the button's zero-based index.
f = FrameworkForm(auto_id="id_%s")
self.assertHTMLEqual(
str(f["language"]),
"""
<div id="id_language">
<div><label for="id_language_0">
<input type="radio" id="id_language_0" value="P" name="language" required>
Python</label></div>
<div><label for="id_language_1">
<input type="radio" id="id_language_1" value="J" name="language" required>
Java</label></div>
</div>""",
)
# When RadioSelect is used with auto_id, and the whole form is printed
# using either as_table() or as_ul(), the label for the RadioSelect
# will **not** point to the ID of the *first* radio button to improve
# accessibility for screen reader users.
self.assertHTMLEqual(
f.as_table(),
"""
<tr><th><label for="id_name">Name:</label></th><td>
<input type="text" name="name" id="id_name" required></td></tr>
<tr><th><label>Language:</label></th><td><div id="id_language">
<div><label for="id_language_0">
<input type="radio" id="id_language_0" value="P" name="language" required>
Python</label></div>
<div><label for="id_language_1">
<input type="radio" id="id_language_1" value="J" name="language" required>
Java</label></div>
</div></td></tr>""",
)
self.assertHTMLEqual(
f.as_ul(),
"""
<li><label for="id_name">Name:</label>
<input type="text" name="name" id="id_name" required></li>
<li><label>Language:</label> <div id="id_language">
<div><label for="id_language_0">
<input type="radio" id="id_language_0" value="P" name="language" required>
Python</label></div>
<div><label for="id_language_1">
<input type="radio" id="id_language_1" value="J" name="language" required>
Java</label></div>
</div></li>
""",
)
self.assertHTMLEqual(
f.as_p(),
"""
<p><label for="id_name">Name:</label>
<input type="text" name="name" id="id_name" required></p>
<p><label>Language:</label> <div id="id_language">
<div><label for="id_language_0">
<input type="radio" id="id_language_0" value="P" name="language" required>
Python</label></div>
<div><label for="id_language_1">
<input type="radio" id="id_language_1" value="J" name="language" required>
Java</label></div>
</div></p>
""",
)
self.assertHTMLEqual(
f.render(f.template_name_div),
'<div><label for="id_name">Name:</label><input type="text" name="name" '
'required id="id_name"></div><div><fieldset><legend>Language:</legend>'
'<div id="id_language"><div><label for="id_language_0"><input '
'type="radio" name="language" value="P" required id="id_language_0">'
'Python</label></div><div><label for="id_language_1"><input type="radio" '
'name="language" value="J" required id="id_language_1">Java</label></div>'
"</div></fieldset></div>",
)
def test_form_with_iterable_boundfield(self):
class BeatleForm(Form):
name = ChoiceField(
choices=[
("john", "John"),
("paul", "Paul"),
("george", "George"),
("ringo", "Ringo"),
],
widget=RadioSelect,
)
f = BeatleForm(auto_id=False)
self.assertHTMLEqual(
"\n".join(str(bf) for bf in f["name"]),
'<label><input type="radio" name="name" value="john" required> John</label>'
'<label><input type="radio" name="name" value="paul" required> Paul</label>'
'<label><input type="radio" name="name" value="george" required> George'
"</label>"
'<label><input type="radio" name="name" value="ringo" required> Ringo'
"</label>",
)
self.assertHTMLEqual(
"\n".join("<div>%s</div>" % bf for bf in f["name"]),
"""
<div><label>
<input type="radio" name="name" value="john" required> John</label></div>
<div><label>
<input type="radio" name="name" value="paul" required> Paul</label></div>
<div><label>
<input type="radio" name="name" value="george" required> George
</label></div>
<div><label>
<input type="radio" name="name" value="ringo" required> Ringo</label></div>
""",
)
def test_form_with_iterable_boundfield_id(self):
class BeatleForm(Form):
name = ChoiceField(
choices=[
("john", "John"),
("paul", "Paul"),
("george", "George"),
("ringo", "Ringo"),
],
widget=RadioSelect,
)
fields = list(BeatleForm()["name"])
self.assertEqual(len(fields), 4)
self.assertEqual(fields[0].id_for_label, "id_name_0")
self.assertEqual(fields[0].choice_label, "John")
self.assertHTMLEqual(
fields[0].tag(),
'<input type="radio" name="name" value="john" id="id_name_0" required>',
)
self.assertHTMLEqual(
str(fields[0]),
'<label for="id_name_0"><input type="radio" name="name" '
'value="john" id="id_name_0" required> John</label>',
)
self.assertEqual(fields[1].id_for_label, "id_name_1")
self.assertEqual(fields[1].choice_label, "Paul")
self.assertHTMLEqual(
fields[1].tag(),
'<input type="radio" name="name" value="paul" id="id_name_1" required>',
)
self.assertHTMLEqual(
str(fields[1]),
'<label for="id_name_1"><input type="radio" name="name" '
'value="paul" id="id_name_1" required> Paul</label>',
)
def test_iterable_boundfield_select(self):
class BeatleForm(Form):
name = ChoiceField(
choices=[
("john", "John"),
("paul", "Paul"),
("george", "George"),
("ringo", "Ringo"),
]
)
fields = list(BeatleForm(auto_id=False)["name"])
self.assertEqual(len(fields), 4)
self.assertIsNone(fields[0].id_for_label)
self.assertEqual(fields[0].choice_label, "John")
self.assertHTMLEqual(fields[0].tag(), '<option value="john">John</option>')
self.assertHTMLEqual(str(fields[0]), '<option value="john">John</option>')
def test_form_with_noniterable_boundfield(self):
# You can iterate over any BoundField, not just those with
# widget=RadioSelect.
class BeatleForm(Form):
name = CharField()
f = BeatleForm(auto_id=False)
self.assertHTMLEqual(
"\n".join(str(bf) for bf in f["name"]),
'<input type="text" name="name" required>',
)
def test_boundfield_slice(self):
class BeatleForm(Form):
name = ChoiceField(
choices=[
("john", "John"),
("paul", "Paul"),
("george", "George"),
("ringo", "Ringo"),
],
widget=RadioSelect,
)
f = BeatleForm()
bf = f["name"]
self.assertEqual(
[str(item) for item in bf[1:]],
[str(bf[1]), str(bf[2]), str(bf[3])],
)
def test_boundfield_invalid_index(self):
class TestForm(Form):
name = ChoiceField(choices=[])
field = TestForm()["name"]
msg = "BoundField indices must be integers or slices, not str."
with self.assertRaisesMessage(TypeError, msg):
field["foo"]
def test_boundfield_bool(self):
"""BoundField without any choices (subwidgets) evaluates to True."""
class TestForm(Form):
name = ChoiceField(choices=[])
self.assertIs(bool(TestForm()["name"]), True)
def test_forms_with_multiple_choice(self):
# MultipleChoiceField is a special case, as its data is required to be
# a list:
class SongForm(Form):
name = CharField()
composers = MultipleChoiceField()
f = SongForm(auto_id=False)
self.assertHTMLEqual(
str(f["composers"]),
"""<select multiple name="composers" required>
</select>""",
)
class SongForm(Form):
name = CharField()
composers = MultipleChoiceField(
choices=[("J", "John Lennon"), ("P", "Paul McCartney")]
)
f = SongForm(auto_id=False)
self.assertHTMLEqual(
str(f["composers"]),
"""<select multiple name="composers" required>
<option value="J">John Lennon</option>
<option value="P">Paul McCartney</option>
</select>""",
)
f = SongForm({"name": "Yesterday", "composers": ["P"]}, auto_id=False)
self.assertHTMLEqual(
str(f["name"]), '<input type="text" name="name" value="Yesterday" required>'
)
self.assertHTMLEqual(
str(f["composers"]),
"""<select multiple name="composers" required>
<option value="J">John Lennon</option>
<option value="P" selected>Paul McCartney</option>
</select>""",
)
f = SongForm()
self.assertHTMLEqual(
f.as_table(),
'<tr><th><label for="id_name">Name:</label></th>'
'<td><input type="text" name="name" required id="id_name"></td>'
'</tr><tr><th><label for="id_composers">Composers:</label></th>'
'<td><select name="composers" required id="id_composers" multiple>'
'<option value="J">John Lennon</option>'
'<option value="P">Paul McCartney</option>'
"</select></td></tr>",
)
self.assertHTMLEqual(
f.as_ul(),
'<li><label for="id_name">Name:</label>'
'<input type="text" name="name" required id="id_name"></li>'
'<li><label for="id_composers">Composers:</label>'
'<select name="composers" required id="id_composers" multiple>'
'<option value="J">John Lennon</option>'
'<option value="P">Paul McCartney</option>'
"</select></li>",
)
self.assertHTMLEqual(
f.as_p(),
'<p><label for="id_name">Name:</label>'
'<input type="text" name="name" required id="id_name"></p>'
'<p><label for="id_composers">Composers:</label>'
'<select name="composers" required id="id_composers" multiple>'
'<option value="J">John Lennon</option>'
'<option value="P">Paul McCartney</option>'
"</select></p>",
)
self.assertHTMLEqual(
f.render(f.template_name_div),
'<div><label for="id_name">Name:</label><input type="text" name="name" '
'required id="id_name"></div><div><label for="id_composers">Composers:'
'</label><select name="composers" required id="id_composers" multiple>'
'<option value="J">John Lennon</option><option value="P">Paul McCartney'
"</option></select></div>",
)
def test_multiple_checkbox_render(self):
f = SongForm()
self.assertHTMLEqual(
f.as_table(),
'<tr><th><label for="id_name">Name:</label></th><td>'
'<input type="text" name="name" required id="id_name"></td></tr>'
'<tr><th><label>Composers:</label></th><td><div id="id_composers">'
'<div><label for="id_composers_0">'
'<input type="checkbox" name="composers" value="J" '
'id="id_composers_0">John Lennon</label></div>'
'<div><label for="id_composers_1">'
'<input type="checkbox" name="composers" value="P" '
'id="id_composers_1">Paul McCartney</label></div>'
"</div></td></tr>",
)
self.assertHTMLEqual(
f.as_ul(),
'<li><label for="id_name">Name:</label>'
'<input type="text" name="name" required id="id_name"></li>'
'<li><label>Composers:</label><div id="id_composers">'
'<div><label for="id_composers_0">'
'<input type="checkbox" name="composers" value="J" '
'id="id_composers_0">John Lennon</label></div>'
'<div><label for="id_composers_1">'
'<input type="checkbox" name="composers" value="P" '
'id="id_composers_1">Paul McCartney</label></div>'
"</div></li>",
)
self.assertHTMLEqual(
f.as_p(),
'<p><label for="id_name">Name:</label>'
'<input type="text" name="name" required id="id_name"></p>'
'<p><label>Composers:</label><div id="id_composers">'
'<div><label for="id_composers_0">'
'<input type="checkbox" name="composers" value="J" '
'id="id_composers_0">John Lennon</label></div>'
'<div><label for="id_composers_1">'
'<input type="checkbox" name="composers" value="P" '
'id="id_composers_1">Paul McCartney</label></div>'
"</div></p>",
)
self.assertHTMLEqual(
f.render(f.template_name_div),
'<div><label for="id_name">Name:</label><input type="text" name="name" '
'required id="id_name"></div><div><fieldset><legend>Composers:</legend>'
'<div id="id_composers"><div><label for="id_composers_0"><input '
'type="checkbox" name="composers" value="J" id="id_composers_0">'
'John Lennon</label></div><div><label for="id_composers_1"><input '
'type="checkbox" name="composers" value="P" id="id_composers_1">'
"Paul McCartney</label></div></div></fieldset></div>",
)
def test_form_with_disabled_fields(self):
class PersonForm(Form):
name = CharField()
birthday = DateField(disabled=True)
class PersonFormFieldInitial(Form):
name = CharField()
birthday = DateField(disabled=True, initial=datetime.date(1974, 8, 16))
# Disabled fields are generally not transmitted by user agents.
# The value from the form's initial data is used.
f1 = PersonForm(
{"name": "John Doe"}, initial={"birthday": datetime.date(1974, 8, 16)}
)
f2 = PersonFormFieldInitial({"name": "John Doe"})
for form in (f1, f2):
self.assertTrue(form.is_valid())
self.assertEqual(
form.cleaned_data,
{"birthday": datetime.date(1974, 8, 16), "name": "John Doe"},
)
# Values provided in the form's data are ignored.
data = {"name": "John Doe", "birthday": "1984-11-10"}
f1 = PersonForm(data, initial={"birthday": datetime.date(1974, 8, 16)})
f2 = PersonFormFieldInitial(data)
for form in (f1, f2):
self.assertTrue(form.is_valid())
self.assertEqual(
form.cleaned_data,
{"birthday": datetime.date(1974, 8, 16), "name": "John Doe"},
)
# Initial data remains present on invalid forms.
data = {}
f1 = PersonForm(data, initial={"birthday": datetime.date(1974, 8, 16)})
f2 = PersonFormFieldInitial(data)
for form in (f1, f2):
self.assertFalse(form.is_valid())
self.assertEqual(form["birthday"].value(), datetime.date(1974, 8, 16))
def test_hidden_data(self):
class SongForm(Form):
name = CharField()
composers = MultipleChoiceField(
choices=[("J", "John Lennon"), ("P", "Paul McCartney")]
)
# MultipleChoiceField rendered as_hidden() is a special case. Because
# it can have multiple values, its as_hidden() renders multiple <input
# type="hidden"> tags.
f = SongForm({"name": "Yesterday", "composers": ["P"]}, auto_id=False)
self.assertHTMLEqual(
f["composers"].as_hidden(),
'<input type="hidden" name="composers" value="P">',
)
f = SongForm({"name": "From Me To You", "composers": ["P", "J"]}, auto_id=False)
self.assertHTMLEqual(
f["composers"].as_hidden(),
"""<input type="hidden" name="composers" value="P">
<input type="hidden" name="composers" value="J">""",
)
# DateTimeField rendered as_hidden() is special too
class MessageForm(Form):
when = SplitDateTimeField()
f = MessageForm({"when_0": "1992-01-01", "when_1": "01:01"})
self.assertTrue(f.is_valid())
self.assertHTMLEqual(
str(f["when"]),
'<input type="text" name="when_0" value="1992-01-01" id="id_when_0" '
"required>"
'<input type="text" name="when_1" value="01:01" id="id_when_1" required>',
)
self.assertHTMLEqual(
f["when"].as_hidden(),
'<input type="hidden" name="when_0" value="1992-01-01" id="id_when_0">'
'<input type="hidden" name="when_1" value="01:01" id="id_when_1">',
)
def test_multiple_choice_checkbox(self):
# MultipleChoiceField can also be used with the CheckboxSelectMultiple
# widget.
f = SongForm(auto_id=False)
self.assertHTMLEqual(
str(f["composers"]),
"""
<div>
<div><label><input type="checkbox" name="composers" value="J">
John Lennon</label></div>
<div><label><input type="checkbox" name="composers" value="P">
Paul McCartney</label></div>
</div>
""",
)
f = SongForm({"composers": ["J"]}, auto_id=False)
self.assertHTMLEqual(
str(f["composers"]),
"""
<div>
<div><label><input checked type="checkbox" name="composers" value="J">
John Lennon</label></div>
<div><label><input type="checkbox" name="composers" value="P">
Paul McCartney</label></div>
</div>
""",
)
f = SongForm({"composers": ["J", "P"]}, auto_id=False)
self.assertHTMLEqual(
str(f["composers"]),
"""
<div>
<div><label><input checked type="checkbox" name="composers" value="J">
John Lennon</label></div>
<div><label><input checked type="checkbox" name="composers" value="P">
Paul McCartney</label></div>
</div>
""",
)
def test_checkbox_auto_id(self):
# Regarding auto_id, CheckboxSelectMultiple is a special case. Each
# checkbox gets a distinct ID, formed by appending an underscore plus
# the checkbox's zero-based index.
class SongForm(Form):
name = CharField()
composers = MultipleChoiceField(
choices=[("J", "John Lennon"), ("P", "Paul McCartney")],
widget=CheckboxSelectMultiple,
)
f = SongForm(auto_id="%s_id")
self.assertHTMLEqual(
str(f["composers"]),
"""
<div id="composers_id">
<div><label for="composers_id_0">
<input type="checkbox" name="composers" value="J" id="composers_id_0">
John Lennon</label></div>
<div><label for="composers_id_1">
<input type="checkbox" name="composers" value="P" id="composers_id_1">
Paul McCartney</label></div>
</div>
""",
)
def test_multiple_choice_list_data(self):
# Data for a MultipleChoiceField should be a list. QueryDict and
# MultiValueDict conveniently work with this.
class SongForm(Form):
name = CharField()
composers = MultipleChoiceField(
choices=[("J", "John Lennon"), ("P", "Paul McCartney")],
widget=CheckboxSelectMultiple,
)
data = {"name": "Yesterday", "composers": ["J", "P"]}
f = SongForm(data)
self.assertEqual(f.errors, {})
data = QueryDict("name=Yesterday&composers=J&composers=P")
f = SongForm(data)
self.assertEqual(f.errors, {})
data = MultiValueDict({"name": ["Yesterday"], "composers": ["J", "P"]})
f = SongForm(data)
self.assertEqual(f.errors, {})
# SelectMultiple uses ducktyping so that MultiValueDictLike.getlist()
# is called.
f = SongForm(MultiValueDictLike({"name": "Yesterday", "composers": "J"}))
self.assertEqual(f.errors, {})
self.assertEqual(f.cleaned_data["composers"], ["J"])
def test_multiple_hidden(self):
class SongForm(Form):
name = CharField()
composers = MultipleChoiceField(
choices=[("J", "John Lennon"), ("P", "Paul McCartney")],
widget=CheckboxSelectMultiple,
)
# The MultipleHiddenInput widget renders multiple values as hidden
# fields.
class SongFormHidden(Form):
name = CharField()
composers = MultipleChoiceField(
choices=[("J", "John Lennon"), ("P", "Paul McCartney")],
widget=MultipleHiddenInput,
)
f = SongFormHidden(
MultiValueDict({"name": ["Yesterday"], "composers": ["J", "P"]}),
auto_id=False,
)
self.assertHTMLEqual(
f.as_ul(),
"""<li>Name: <input type="text" name="name" value="Yesterday" required>
<input type="hidden" name="composers" value="J">
<input type="hidden" name="composers" value="P"></li>""",
)
# When using CheckboxSelectMultiple, the framework expects a list of
# input and returns a list of input.
f = SongForm({"name": "Yesterday"}, auto_id=False)
self.assertEqual(f.errors["composers"], ["This field is required."])
f = SongForm({"name": "Yesterday", "composers": ["J"]}, auto_id=False)
self.assertEqual(f.errors, {})
self.assertEqual(f.cleaned_data["composers"], ["J"])
self.assertEqual(f.cleaned_data["name"], "Yesterday")
f = SongForm({"name": "Yesterday", "composers": ["J", "P"]}, auto_id=False)
self.assertEqual(f.errors, {})
self.assertEqual(f.cleaned_data["composers"], ["J", "P"])
self.assertEqual(f.cleaned_data["name"], "Yesterday")
# MultipleHiddenInput uses ducktyping so that
# MultiValueDictLike.getlist() is called.
f = SongForm(MultiValueDictLike({"name": "Yesterday", "composers": "J"}))
self.assertEqual(f.errors, {})
self.assertEqual(f.cleaned_data["composers"], ["J"])
def test_escaping(self):
# Validation errors are HTML-escaped when output as HTML.
class EscapingForm(Form):
special_name = CharField(label="<em>Special</em> Field")
special_safe_name = CharField(label=mark_safe("<em>Special</em> Field"))
def clean_special_name(self):
raise ValidationError(
"Something's wrong with '%s'" % self.cleaned_data["special_name"]
)
def clean_special_safe_name(self):
raise ValidationError(
mark_safe(
"'<b>%s</b>' is a safe string"
% self.cleaned_data["special_safe_name"]
)
)
f = EscapingForm(
{
"special_name": "Nothing to escape",
"special_safe_name": "Nothing to escape",
},
auto_id=False,
)
self.assertHTMLEqual(
f.as_table(),
"""
<tr><th><em>Special</em> Field:</th><td>
<ul class="errorlist">
<li>Something's wrong with 'Nothing to escape'</li></ul>
<input type="text" name="special_name" value="Nothing to escape"
aria-invalid="true" required></td></tr>
<tr><th><em>Special</em> Field:</th><td>
<ul class="errorlist">
<li>'<b>Nothing to escape</b>' is a safe string</li></ul>
<input type="text" name="special_safe_name" value="Nothing to escape"
aria-invalid="true" required></td></tr>
""",
)
f = EscapingForm(
{
"special_name": "Should escape < & > and <script>alert('xss')</script>",
"special_safe_name": "<i>Do not escape</i>",
},
auto_id=False,
)
self.assertHTMLEqual(
f.as_table(),
"<tr><th><em>Special</em> Field:</th><td>"
'<ul class="errorlist"><li>'
"Something's wrong with 'Should escape < & > and "
"<script>alert('xss')</script>'</li></ul>"
'<input type="text" name="special_name" value="Should escape < & '
'> and <script>alert('xss')</script>" '
'aria-invalid="true" required></td></tr>'
"<tr><th><em>Special</em> Field:</th><td>"
'<ul class="errorlist">'
"<li>'<b><i>Do not escape</i></b>' is a safe string</li></ul>"
'<input type="text" name="special_safe_name" '
'value="<i>Do not escape</i>" aria-invalid="true" required>'
"</td></tr>",
)
def test_validating_multiple_fields(self):
# There are a couple of ways to do multiple-field validation. If you
# want the validation message to be associated with a particular field,
# implement the clean_XXX() method on the Form, where XXX is the field
# name. As in Field.clean(), the clean_XXX() method should return the
# cleaned value. In the clean_XXX() method, you have access to
# self.cleaned_data, which is a dictionary of all the data that has
# been cleaned *so far*, in order by the fields, including the current
# field (e.g., the field XXX if you're in clean_XXX()).
class UserRegistration(Form):
username = CharField(max_length=10)
password1 = CharField(widget=PasswordInput)
password2 = CharField(widget=PasswordInput)
def clean_password2(self):
if (
self.cleaned_data.get("password1")
and self.cleaned_data.get("password2")
and self.cleaned_data["password1"] != self.cleaned_data["password2"]
):
raise ValidationError("Please make sure your passwords match.")
return self.cleaned_data["password2"]
f = UserRegistration(auto_id=False)
self.assertEqual(f.errors, {})
f = UserRegistration({}, auto_id=False)
self.assertEqual(f.errors["username"], ["This field is required."])
self.assertEqual(f.errors["password1"], ["This field is required."])
self.assertEqual(f.errors["password2"], ["This field is required."])
f = UserRegistration(
{"username": "adrian", "password1": "foo", "password2": "bar"},
auto_id=False,
)
self.assertEqual(
f.errors["password2"], ["Please make sure your passwords match."]
)
f = UserRegistration(
{"username": "adrian", "password1": "foo", "password2": "foo"},
auto_id=False,
)
self.assertEqual(f.errors, {})
self.assertEqual(f.cleaned_data["username"], "adrian")
self.assertEqual(f.cleaned_data["password1"], "foo")
self.assertEqual(f.cleaned_data["password2"], "foo")
# Another way of doing multiple-field validation is by implementing the
# Form's clean() method. Usually ValidationError raised by that method
# will not be associated with a particular field and will have a
# special-case association with the field named '__all__'. It's
# possible to associate the errors to particular field with the
# Form.add_error() method or by passing a dictionary that maps each
# field to one or more errors.
#
# Note that in Form.clean(), you have access to self.cleaned_data, a
# dictionary of all the fields/values that have *not* raised a
# ValidationError. Also note Form.clean() is required to return a
# dictionary of all clean data.
class UserRegistration(Form):
username = CharField(max_length=10)
password1 = CharField(widget=PasswordInput)
password2 = CharField(widget=PasswordInput)
def clean(self):
# Test raising a ValidationError as NON_FIELD_ERRORS.
if (
self.cleaned_data.get("password1")
and self.cleaned_data.get("password2")
and self.cleaned_data["password1"] != self.cleaned_data["password2"]
):
raise ValidationError("Please make sure your passwords match.")
# Test raising ValidationError that targets multiple fields.
errors = {}
if self.cleaned_data.get("password1") == "FORBIDDEN_VALUE":
errors["password1"] = "Forbidden value."
if self.cleaned_data.get("password2") == "FORBIDDEN_VALUE":
errors["password2"] = ["Forbidden value."]
if errors:
raise ValidationError(errors)
# Test Form.add_error()
if self.cleaned_data.get("password1") == "FORBIDDEN_VALUE2":
self.add_error(None, "Non-field error 1.")
self.add_error("password1", "Forbidden value 2.")
if self.cleaned_data.get("password2") == "FORBIDDEN_VALUE2":
self.add_error("password2", "Forbidden value 2.")
raise ValidationError("Non-field error 2.")
return self.cleaned_data
f = UserRegistration(auto_id=False)
self.assertEqual(f.errors, {})
f = UserRegistration({}, auto_id=False)
self.assertHTMLEqual(
f.as_table(),
"""<tr><th>Username:</th><td>
<ul class="errorlist"><li>This field is required.</li></ul>
<input type="text" name="username" maxlength="10" aria-invalid="true" required>
</td></tr>
<tr><th>Password1:</th><td><ul class="errorlist"><li>This field is required.</li></ul>
<input type="password" name="password1" aria-invalid="true" required></td></tr>
<tr><th>Password2:</th><td><ul class="errorlist"><li>This field is required.</li></ul>
<input type="password" name="password2" aria-invalid="true" required></td></tr>""",
)
self.assertEqual(f.errors["username"], ["This field is required."])
self.assertEqual(f.errors["password1"], ["This field is required."])
self.assertEqual(f.errors["password2"], ["This field is required."])
f = UserRegistration(
{"username": "adrian", "password1": "foo", "password2": "bar"},
auto_id=False,
)
self.assertEqual(
f.errors["__all__"], ["Please make sure your passwords match."]
)
self.assertHTMLEqual(
f.as_table(),
"""
<tr><td colspan="2">
<ul class="errorlist nonfield">
<li>Please make sure your passwords match.</li></ul></td></tr>
<tr><th>Username:</th><td>
<input type="text" name="username" value="adrian" maxlength="10" required>
</td></tr>
<tr><th>Password1:</th><td>
<input type="password" name="password1" required></td></tr>
<tr><th>Password2:</th><td>
<input type="password" name="password2" required></td></tr>
""",
)
self.assertHTMLEqual(
f.as_ul(),
"""
<li><ul class="errorlist nonfield">
<li>Please make sure your passwords match.</li></ul></li>
<li>Username:
<input type="text" name="username" value="adrian" maxlength="10" required>
</li>
<li>Password1: <input type="password" name="password1" required></li>
<li>Password2: <input type="password" name="password2" required></li>
""",
)
self.assertHTMLEqual(
f.render(f.template_name_div),
'<ul class="errorlist nonfield"><li>Please make sure your passwords match.'
'</li></ul><div>Username: <input type="text" name="username" '
'value="adrian" maxlength="10" required></div><div>Password1: <input '
'type="password" name="password1" required></div><div>Password2: <input '
'type="password" name="password2" required></div>',
)
f = UserRegistration(
{"username": "adrian", "password1": "foo", "password2": "foo"},
auto_id=False,
)
self.assertEqual(f.errors, {})
self.assertEqual(f.cleaned_data["username"], "adrian")
self.assertEqual(f.cleaned_data["password1"], "foo")
self.assertEqual(f.cleaned_data["password2"], "foo")
f = UserRegistration(
{
"username": "adrian",
"password1": "FORBIDDEN_VALUE",
"password2": "FORBIDDEN_VALUE",
},
auto_id=False,
)
self.assertEqual(f.errors["password1"], ["Forbidden value."])
self.assertEqual(f.errors["password2"], ["Forbidden value."])
f = UserRegistration(
{
"username": "adrian",
"password1": "FORBIDDEN_VALUE2",
"password2": "FORBIDDEN_VALUE2",
},
auto_id=False,
)
self.assertEqual(
f.errors["__all__"], ["Non-field error 1.", "Non-field error 2."]
)
self.assertEqual(f.errors["password1"], ["Forbidden value 2."])
self.assertEqual(f.errors["password2"], ["Forbidden value 2."])
with self.assertRaisesMessage(ValueError, "has no field named"):
f.add_error("missing_field", "Some error.")
def test_update_error_dict(self):
class CodeForm(Form):
code = CharField(max_length=10)
def clean(self):
try:
raise ValidationError({"code": [ValidationError("Code error 1.")]})
except ValidationError as e:
self._errors = e.update_error_dict(self._errors)
try:
raise ValidationError({"code": [ValidationError("Code error 2.")]})
except ValidationError as e:
self._errors = e.update_error_dict(self._errors)
try:
raise ValidationError({"code": ErrorList(["Code error 3."])})
except ValidationError as e:
self._errors = e.update_error_dict(self._errors)
try:
raise ValidationError("Non-field error 1.")
except ValidationError as e:
self._errors = e.update_error_dict(self._errors)
try:
raise ValidationError([ValidationError("Non-field error 2.")])
except ValidationError as e:
self._errors = e.update_error_dict(self._errors)
# The newly added list of errors is an instance of ErrorList.
for field, error_list in self._errors.items():
if not isinstance(error_list, self.error_class):
self._errors[field] = self.error_class(error_list)
form = CodeForm({"code": "hello"})
# Trigger validation.
self.assertFalse(form.is_valid())
# update_error_dict didn't lose track of the ErrorDict type.
self.assertIsInstance(form._errors, ErrorDict)
self.assertEqual(
dict(form.errors),
{
"code": ["Code error 1.", "Code error 2.", "Code error 3."],
NON_FIELD_ERRORS: ["Non-field error 1.", "Non-field error 2."],
},
)
def test_has_error(self):
class UserRegistration(Form):
username = CharField(max_length=10)
password1 = CharField(widget=PasswordInput, min_length=5)
password2 = CharField(widget=PasswordInput)
def clean(self):
if (
self.cleaned_data.get("password1")
and self.cleaned_data.get("password2")
and self.cleaned_data["password1"] != self.cleaned_data["password2"]
):
raise ValidationError(
"Please make sure your passwords match.",
code="password_mismatch",
)
f = UserRegistration(data={})
self.assertTrue(f.has_error("password1"))
self.assertTrue(f.has_error("password1", "required"))
self.assertFalse(f.has_error("password1", "anything"))
f = UserRegistration(data={"password1": "Hi", "password2": "Hi"})
self.assertTrue(f.has_error("password1"))
self.assertTrue(f.has_error("password1", "min_length"))
self.assertFalse(f.has_error("password1", "anything"))
self.assertFalse(f.has_error("password2"))
self.assertFalse(f.has_error("password2", "anything"))
f = UserRegistration(data={"password1": "Bonjour", "password2": "Hello"})
self.assertFalse(f.has_error("password1"))
self.assertFalse(f.has_error("password1", "required"))
self.assertTrue(f.has_error(NON_FIELD_ERRORS))
self.assertTrue(f.has_error(NON_FIELD_ERRORS, "password_mismatch"))
self.assertFalse(f.has_error(NON_FIELD_ERRORS, "anything"))
def test_html_output_with_hidden_input_field_errors(self):
class TestForm(Form):
hidden_input = CharField(widget=HiddenInput)
def clean(self):
self.add_error(None, "Form error")
f = TestForm(data={})
error_dict = {
"hidden_input": ["This field is required."],
"__all__": ["Form error"],
}
self.assertEqual(f.errors, error_dict)
f.as_table()
self.assertEqual(f.errors, error_dict)
self.assertHTMLEqual(
f.as_table(),
'<tr><td colspan="2"><ul class="errorlist nonfield"><li>Form error</li>'
"<li>(Hidden field hidden_input) This field is required.</li></ul>"
'<input type="hidden" name="hidden_input" id="id_hidden_input"></td></tr>',
)
self.assertHTMLEqual(
f.as_ul(),
'<li><ul class="errorlist nonfield"><li>Form error</li>'
"<li>(Hidden field hidden_input) This field is required.</li></ul>"
'<input type="hidden" name="hidden_input" id="id_hidden_input"></li>',
)
self.assertHTMLEqual(
f.as_p(),
'<ul class="errorlist nonfield"><li>Form error</li>'
"<li>(Hidden field hidden_input) This field is required.</li></ul>"
'<p><input type="hidden" name="hidden_input" id="id_hidden_input"></p>',
)
self.assertHTMLEqual(
f.render(f.template_name_div),
'<ul class="errorlist nonfield"><li>Form error</li>'
"<li>(Hidden field hidden_input) This field is required.</li></ul>"
'<div><input type="hidden" name="hidden_input" id="id_hidden_input"></div>',
)
def test_dynamic_construction(self):
# It's possible to construct a Form dynamically by adding to the
# self.fields dictionary in __init__(). Don't forget to call
# Form.__init__() within the subclass' __init__().
class Person(Form):
first_name = CharField()
last_name = CharField()
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields["birthday"] = DateField()
p = Person(auto_id=False)
self.assertHTMLEqual(
p.as_table(),
"""
<tr><th>First name:</th><td>
<input type="text" name="first_name" required></td></tr>
<tr><th>Last name:</th><td>
<input type="text" name="last_name" required></td></tr>
<tr><th>Birthday:</th><td>
<input type="text" name="birthday" required></td></tr>
""",
)
# Instances of a dynamic Form do not persist fields from one Form
# instance to the next.
class MyForm(Form):
def __init__(self, data=None, auto_id=False, field_list=[]):
Form.__init__(self, data, auto_id=auto_id)
for field in field_list:
self.fields[field[0]] = field[1]
field_list = [("field1", CharField()), ("field2", CharField())]
my_form = MyForm(field_list=field_list)
self.assertHTMLEqual(
my_form.as_table(),
"""
<tr><th>Field1:</th><td><input type="text" name="field1" required></td></tr>
<tr><th>Field2:</th><td><input type="text" name="field2" required></td></tr>
""",
)
field_list = [("field3", CharField()), ("field4", CharField())]
my_form = MyForm(field_list=field_list)
self.assertHTMLEqual(
my_form.as_table(),
"""
<tr><th>Field3:</th><td><input type="text" name="field3" required></td></tr>
<tr><th>Field4:</th><td><input type="text" name="field4" required></td></tr>
""",
)
class MyForm(Form):
default_field_1 = CharField()
default_field_2 = CharField()
def __init__(self, data=None, auto_id=False, field_list=[]):
Form.__init__(self, data, auto_id=auto_id)
for field in field_list:
self.fields[field[0]] = field[1]
field_list = [("field1", CharField()), ("field2", CharField())]
my_form = MyForm(field_list=field_list)
self.assertHTMLEqual(
my_form.as_table(),
"""
<tr><th>Default field 1:</th><td>
<input type="text" name="default_field_1" required></td></tr>
<tr><th>Default field 2:</th><td>
<input type="text" name="default_field_2" required></td></tr>
<tr><th>Field1:</th><td><input type="text" name="field1" required></td></tr>
<tr><th>Field2:</th><td><input type="text" name="field2" required></td></tr>
""",
)
field_list = [("field3", CharField()), ("field4", CharField())]
my_form = MyForm(field_list=field_list)
self.assertHTMLEqual(
my_form.as_table(),
"""
<tr><th>Default field 1:</th><td>
<input type="text" name="default_field_1" required></td></tr>
<tr><th>Default field 2:</th><td>
<input type="text" name="default_field_2" required></td></tr>
<tr><th>Field3:</th><td><input type="text" name="field3" required></td></tr>
<tr><th>Field4:</th><td><input type="text" name="field4" required></td></tr>
""",
)
# Similarly, changes to field attributes do not persist from one Form
# instance to the next.
class Person(Form):
first_name = CharField(required=False)
last_name = CharField(required=False)
def __init__(self, names_required=False, *args, **kwargs):
super().__init__(*args, **kwargs)
if names_required:
self.fields["first_name"].required = True
self.fields["first_name"].widget.attrs["class"] = "required"
self.fields["last_name"].required = True
self.fields["last_name"].widget.attrs["class"] = "required"
f = Person(names_required=False)
self.assertEqual(
f["first_name"].field.required,
f["last_name"].field.required,
(False, False),
)
self.assertEqual(
f["first_name"].field.widget.attrs,
f["last_name"].field.widget.attrs,
({}, {}),
)
f = Person(names_required=True)
self.assertEqual(
f["first_name"].field.required, f["last_name"].field.required, (True, True)
)
self.assertEqual(
f["first_name"].field.widget.attrs,
f["last_name"].field.widget.attrs,
({"class": "reuired"}, {"class": "required"}),
)
f = Person(names_required=False)
self.assertEqual(
f["first_name"].field.required,
f["last_name"].field.required,
(False, False),
)
self.assertEqual(
f["first_name"].field.widget.attrs,
f["last_name"].field.widget.attrs,
({}, {}),
)
class Person(Form):
first_name = CharField(max_length=30)
last_name = CharField(max_length=30)
def __init__(self, name_max_length=None, *args, **kwargs):
super().__init__(*args, **kwargs)
if name_max_length:
self.fields["first_name"].max_length = name_max_length
self.fields["last_name"].max_length = name_max_length
f = Person(name_max_length=None)
self.assertEqual(
f["first_name"].field.max_length, f["last_name"].field.max_length, (30, 30)
)
f = Person(name_max_length=20)
self.assertEqual(
f["first_name"].field.max_length, f["last_name"].field.max_length, (20, 20)
)
f = Person(name_max_length=None)
self.assertEqual(
f["first_name"].field.max_length, f["last_name"].field.max_length, (30, 30)
)
# Similarly, choices do not persist from one Form instance to the next.
# Refs #15127.
class Person(Form):
first_name = CharField(required=False)
last_name = CharField(required=False)
gender = ChoiceField(choices=(("f", "Female"), ("m", "Male")))
def __init__(self, allow_unspec_gender=False, *args, **kwargs):
super().__init__(*args, **kwargs)
if allow_unspec_gender:
self.fields["gender"].choices += (("u", "Unspecified"),)
f = Person()
self.assertEqual(f["gender"].field.choices, [("f", "Female"), ("m", "Male")])
f = Person(allow_unspec_gender=True)
self.assertEqual(
f["gender"].field.choices,
[("f", "Female"), ("m", "Male"), ("u", "Unspecified")],
)
f = Person()
self.assertEqual(f["gender"].field.choices, [("f", "Female"), ("m", "Male")])
def test_validators_independence(self):
"""
The list of form field validators can be modified without polluting
other forms.
"""
class MyForm(Form):
myfield = CharField(max_length=25)
f1 = MyForm()
f2 = MyForm()
f1.fields["myfield"].validators[0] = MaxValueValidator(12)
self.assertNotEqual(
f1.fields["myfield"].validators[0], f2.fields["myfield"].validators[0]
)
def test_hidden_widget(self):
# HiddenInput widgets are displayed differently in the as_table(),
# as_ul()) and as_p() output of a Form -- their verbose names are not
# displayed, and a separate row is not displayed. They're displayed in
# the last row of the form, directly after that row's form element.
class Person(Form):
first_name = CharField()
last_name = CharField()
hidden_text = CharField(widget=HiddenInput)
birthday = DateField()
p = Person(auto_id=False)
self.assertHTMLEqual(
p.as_table(),
"""
<tr><th>First name:</th><td><input type="text" name="first_name" required>
</td></tr>
<tr><th>Last name:</th><td><input type="text" name="last_name" required>
</td></tr>
<tr><th>Birthday:</th>
<td><input type="text" name="birthday" required>
<input type="hidden" name="hidden_text"></td></tr>
""",
)
self.assertHTMLEqual(
p.as_ul(),
"""
<li>First name: <input type="text" name="first_name" required></li>
<li>Last name: <input type="text" name="last_name" required></li>
<li>Birthday: <input type="text" name="birthday" required>
<input type="hidden" name="hidden_text"></li>
""",
)
self.assertHTMLEqual(
p.as_p(),
"""
<p>First name: <input type="text" name="first_name" required></p>
<p>Last name: <input type="text" name="last_name" required></p>
<p>Birthday: <input type="text" name="birthday" required>
<input type="hidden" name="hidden_text"></p>
""",
)
self.assertHTMLEqual(
p.as_div(),
'<div>First name: <input type="text" name="first_name" required></div>'
'<div>Last name: <input type="text" name="last_name" required></div><div>'
'Birthday: <input type="text" name="birthday" required><input '
'type="hidden" name="hidden_text"></div>',
)
# With auto_id set, a HiddenInput still gets an ID, but it doesn't get
# a label.
p = Person(auto_id="id_%s")
self.assertHTMLEqual(
p.as_table(),
"""<tr><th><label for="id_first_name">First name:</label></th><td>
<input type="text" name="first_name" id="id_first_name" required></td></tr>
<tr><th><label for="id_last_name">Last name:</label></th><td>
<input type="text" name="last_name" id="id_last_name" required></td></tr>
<tr><th><label for="id_birthday">Birthday:</label></th><td>
<input type="text" name="birthday" id="id_birthday" required>
<input type="hidden" name="hidden_text" id="id_hidden_text"></td></tr>""",
)
self.assertHTMLEqual(
p.as_ul(),
"""<li><label for="id_first_name">First name:</label>
<input type="text" name="first_name" id="id_first_name" required></li>
<li><label for="id_last_name">Last name:</label>
<input type="text" name="last_name" id="id_last_name" required></li>
<li><label for="id_birthday">Birthday:</label>
<input type="text" name="birthday" id="id_birthday" required>
<input type="hidden" name="hidden_text" id="id_hidden_text"></li>""",
)
self.assertHTMLEqual(
p.as_p(),
"""<p><label for="id_first_name">First name:</label>
<input type="text" name="first_name" id="id_first_name" required></p>
<p><label for="id_last_name">Last name:</label>
<input type="text" name="last_name" id="id_last_name" required></p>
<p><label for="id_birthday">Birthday:</label>
<input type="text" name="birthday" id="id_birthday" required>
<input type="hidden" name="hidden_text" id="id_hidden_text"></p>""",
)
self.assertHTMLEqual(
p.as_div(),
'<div><label for="id_first_name">First name:</label><input type="text" '
'name="first_name" id="id_first_name" required></div><div><label '
'for="id_last_name">Last name:</label><input type="text" name="last_name" '
'id="id_last_name" required></div><div><label for="id_birthday">Birthday:'
'</label><input type="text" name="birthday" id="id_birthday" required>'
'<input type="hidden" name="hidden_text" id="id_hidden_text"></div>',
)
# If a field with a HiddenInput has errors, the as_table() and as_ul()
# output will include the error message(s) with the text "(Hidden field
# [fieldname]) " prepended. This message is displayed at the top of the
# output, regardless of its field's order in the form.
p = Person(
{"first_name": "John", "last_name": "Lennon", "birthday": "1940-10-9"},
auto_id=False,
)
self.assertHTMLEqual(
p.as_table(),
"""
<tr><td colspan="2">
<ul class="errorlist nonfield"><li>
(Hidden field hidden_text) This field is required.</li></ul></td></tr>
<tr><th>First name:</th><td>
<input type="text" name="first_name" value="John" required></td></tr>
<tr><th>Last name:</th><td>
<input type="text" name="last_name" value="Lennon" required></td></tr>
<tr><th>Birthday:</th><td>
<input type="text" name="birthday" value="1940-10-9" required>
<input type="hidden" name="hidden_text"></td></tr>
""",
)
self.assertHTMLEqual(
p.as_ul(),
"""
<li><ul class="errorlist nonfield"><li>
(Hidden field hidden_text) This field is required.</li></ul></li>
<li>First name: <input type="text" name="first_name" value="John" required>
</li>
<li>Last name: <input type="text" name="last_name" value="Lennon" required>
</li>
<li>Birthday: <input type="text" name="birthday" value="1940-10-9" required>
<input type="hidden" name="hidden_text"></li>
""",
)
self.assertHTMLEqual(
p.as_p(),
"""
<ul class="errorlist nonfield"><li>
(Hidden field hidden_text) This field is required.</li></ul>
<p>First name: <input type="text" name="first_name" value="John" required>
</p>
<p>Last name: <input type="text" name="last_name" value="Lennon" required>
</p>
<p>Birthday: <input type="text" name="birthday" value="1940-10-9" required>
<input type="hidden" name="hidden_text"></p>
""",
)
self.assertHTMLEqual(
p.as_div(),
'<ul class="errorlist nonfield"><li>(Hidden field hidden_text) This field '
'is required.</li></ul><div>First name: <input type="text" '
'name="first_name" value="John" required></div><div>Last name: <input '
'type="text" name="last_name" value="Lennon" required></div><div>'
'Birthday: <input type="text" name="birthday" value="1940-10-9" required>'
'<input type="hidden" name="hidden_text"></div>',
)
# A corner case: It's possible for a form to have only HiddenInputs.
class TestForm(Form):
foo = CharField(widget=HiddenInput)
bar = CharField(widget=HiddenInput)
p = TestForm(auto_id=False)
self.assertHTMLEqual(
p.as_table(),
'<input type="hidden" name="foo"><input type="hidden" name="bar">',
)
self.assertHTMLEqual(
p.as_ul(),
'<input type="hidden" name="foo"><input type="hidden" name="bar">',
)
self.assertHTMLEqual(
p.as_p(), '<input type="hidden" name="foo"><input type="hidden" name="bar">'
)
def test_hidden_widget_does_not_have_aria_describedby(self):
class TestForm(Form):
hidden_text = CharField(widget=HiddenInput, help_text="Help Text")
f = TestForm()
self.assertEqual(
str(f), '<input type="hidden" name="hidden_text" id="id_hidden_text">'
)
def test_field_order(self):
# A Form's fields are displayed in the same order in which they were
# defined.
class TestForm(Form):
field1 = CharField()
field2 = CharField()
field3 = CharField()
field4 = CharField()
field5 = CharField()
field6 = CharField()
field7 = CharField()
field8 = CharField()
field9 = CharField()
field10 = CharField()
field11 = CharField()
field12 = CharField()
field13 = CharField()
field14 = CharField()
p = TestForm(auto_id=False)
self.assertHTMLEqual(
p.as_table(),
"".join(
f"<tr><th>Field{i}:</th><td>"
f'<input type="text" name="field{i}" required></td></tr>'
for i in range(1, 15)
),
)
def test_explicit_field_order(self):
class TestFormParent(Form):
field1 = CharField()
field2 = CharField()
field4 = CharField()
field5 = CharField()
field6 = CharField()
field_order = ["field6", "field5", "field4", "field2", "field1"]
class TestForm(TestFormParent):
field3 = CharField()
field_order = ["field2", "field4", "field3", "field5", "field6"]
class TestFormRemove(TestForm):
field1 = None
class TestFormMissing(TestForm):
field_order = ["field2", "field4", "field3", "field5", "field6", "field1"]
field1 = None
class TestFormInit(TestFormParent):
field3 = CharField()
field_order = None
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.order_fields(field_order=TestForm.field_order)
p = TestFormParent()
self.assertEqual(list(p.fields), TestFormParent.field_order)
p = TestFormRemove()
self.assertEqual(list(p.fields), TestForm.field_order)
p = TestFormMissing()
self.assertEqual(list(p.fields), TestForm.field_order)
p = TestForm()
self.assertEqual(list(p.fields), TestFormMissing.field_order)
p = TestFormInit()
order = [*TestForm.field_order, "field1"]
self.assertEqual(list(p.fields), order)
TestForm.field_order = ["unknown"]
p = TestForm()
self.assertEqual(
list(p.fields), ["field1", "field2", "field4", "field5", "field6", "field3"]
)
def test_form_html_attributes(self):
# Some Field classes have an effect on the HTML attributes of their
# associated Widget. If you set max_length in a CharField and its
# associated widget is either a TextInput or PasswordInput, then the
# widget's rendered HTML will include the "maxlength" attribute.
class UserRegistration(Form):
username = CharField(max_length=10) # uses TextInput by default
password = CharField(max_length=10, widget=PasswordInput)
realname = CharField(
max_length=10, widget=TextInput
) # redundantly define widget, just to test
address = CharField() # no max_length defined here
p = UserRegistration(auto_id=False)
self.assertHTMLEqual(
p.as_ul(),
"""
<li>Username: <input type="text" name="username" maxlength="10" required>
</li>
<li>Password: <input type="password" name="password" maxlength="10"
required></li>
<li>Realname: <input type="text" name="realname" maxlength="10" required>
</li>
<li>Address: <input type="text" name="address" required></li>
""",
)
# If you specify a custom "attrs" that includes the "maxlength"
# attribute, the Field's max_length attribute will override whatever
# "maxlength" you specify in "attrs".
class UserRegistration(Form):
username = CharField(
max_length=10, widget=TextInput(attrs={"maxlength": 20})
)
password = CharField(max_length=10, widget=PasswordInput)
p = UserRegistration(auto_id=False)
self.assertHTMLEqual(
p.as_ul(),
'<li>Username: <input type="text" name="username" maxlength="10" required>'
"</li>"
'<li>Password: <input type="password" name="password" maxlength="10" '
"required></li>",
)
def test_specifying_labels(self):
# You can specify the label for a field by using the 'label' argument
# to a Field class. If you don't specify 'label', Django will use the
# field name with underscores converted to spaces, and the initial
# letter capitalized.
class UserRegistration(Form):
username = CharField(max_length=10, label="Your username")
password1 = CharField(widget=PasswordInput)
password2 = CharField(widget=PasswordInput, label="Contraseña (de nuevo)")
p = UserRegistration(auto_id=False)
self.assertHTMLEqual(
p.as_ul(),
"""
<li>Your username:
<input type="text" name="username" maxlength="10" required></li>
<li>Password1: <input type="password" name="password1" required></li>
<li>Contraseña (de nuevo):
<input type="password" name="password2" required></li>
""",
)
# Labels for as_* methods will only end in a colon if they don't end in
# other punctuation already.
class Questions(Form):
q1 = CharField(label="The first question")
q2 = CharField(label="What is your name?")
q3 = CharField(label="The answer to life is:")
q4 = CharField(label="Answer this question!")
q5 = CharField(label="The last question. Period.")
self.assertHTMLEqual(
Questions(auto_id=False).as_p(),
"""<p>The first question: <input type="text" name="q1" required></p>
<p>What is your name? <input type="text" name="q2" required></p>
<p>The answer to life is: <input type="text" name="q3" required></p>
<p>Answer this question! <input type="text" name="q4" required></p>
<p>The last question. Period. <input type="text" name="q5" required></p>""",
)
self.assertHTMLEqual(
Questions().as_p(),
"""
<p><label for="id_q1">The first question:</label>
<input type="text" name="q1" id="id_q1" required></p>
<p><label for="id_q2">What is your name?</label>
<input type="text" name="q2" id="id_q2" required></p>
<p><label for="id_q3">The answer to life is:</label>
<input type="text" name="q3" id="id_q3" required></p>
<p><label for="id_q4">Answer this question!</label>
<input type="text" name="q4" id="id_q4" required></p>
<p><label for="id_q5">The last question. Period.</label>
<input type="text" name="q5" id="id_q5" required></p>
""",
)
# If a label is set to the empty string for a field, that field won't
# get a label.
class UserRegistration(Form):
username = CharField(max_length=10, label="")
password = CharField(widget=PasswordInput)
p = UserRegistration(auto_id=False)
self.assertHTMLEqual(
p.as_ul(),
"""<li> <input type="text" name="username" maxlength="10" required></li>
<li>Password: <input type="password" name="password" required></li>""",
)
p = UserRegistration(auto_id="id_%s")
self.assertHTMLEqual(
p.as_ul(),
"""
<li>
<input id="id_username" type="text" name="username" maxlength="10" required>
</li>
<li><label for="id_password">Password:</label>
<input type="password" name="password" id="id_password" required></li>
""",
)
# If label is None, Django will auto-create the label from the field
# name. This is default behavior.
class UserRegistration(Form):
username = CharField(max_length=10, label=None)
password = CharField(widget=PasswordInput)
p = UserRegistration(auto_id=False)
self.assertHTMLEqual(
p.as_ul(),
'<li>Username: <input type="text" name="username" maxlength="10" required>'
"</li>"
'<li>Password: <input type="password" name="password" required></li>',
)
p = UserRegistration(auto_id="id_%s")
self.assertHTMLEqual(
p.as_ul(),
"""<li><label for="id_username">Username:</label>
<input id="id_username" type="text" name="username" maxlength="10" required></li>
<li><label for="id_password">Password:</label>
<input type="password" name="password" id="id_password" required></li>""",
)
def test_label_suffix(self):
# You can specify the 'label_suffix' argument to a Form class to modify
# the punctuation symbol used at the end of a label. By default, the
# colon (:) is used, and is only appended to the label if the label
# doesn't already end with a punctuation symbol: ., !, ? or :. If you
# specify a different suffix, it will be appended regardless of the
# last character of the label.
class FavoriteForm(Form):
color = CharField(label="Favorite color?")
animal = CharField(label="Favorite animal")
answer = CharField(label="Secret answer", label_suffix=" =")
f = FavoriteForm(auto_id=False)
self.assertHTMLEqual(
f.as_ul(),
"""<li>Favorite color? <input type="text" name="color" required></li>
<li>Favorite animal: <input type="text" name="animal" required></li>
<li>Secret answer = <input type="text" name="answer" required></li>""",
)
f = FavoriteForm(auto_id=False, label_suffix="?")
self.assertHTMLEqual(
f.as_ul(),
"""<li>Favorite color? <input type="text" name="color" required></li>
<li>Favorite animal? <input type="text" name="animal" required></li>
<li>Secret answer = <input type="text" name="answer" required></li>""",
)
f = FavoriteForm(auto_id=False, label_suffix="")
self.assertHTMLEqual(
f.as_ul(),
"""<li>Favorite color? <input type="text" name="color" required></li>
<li>Favorite animal <input type="text" name="animal" required></li>
<li>Secret answer = <input type="text" name="answer" required></li>""",
)
f = FavoriteForm(auto_id=False, label_suffix="\u2192")
self.assertHTMLEqual(
f.as_ul(),
'<li>Favorite color? <input type="text" name="color" required></li>\n'
"<li>Favorite animal\u2192 "
'<input type="text" name="animal" required></li>\n'
'<li>Secret answer = <input type="text" name="answer" required></li>',
)
def test_initial_data(self):
# You can specify initial data for a field by using the 'initial'
# argument to a Field class. This initial data is displayed when a Form
# is rendered with *no* data. It is not displayed when a Form is
# rendered with any data (including an empty dictionary). Also, the
# initial value is *not* used if data for a particular required field
# isn't provided.
class UserRegistration(Form):
username = CharField(max_length=10, initial="django")
password = CharField(widget=PasswordInput)
# Here, we're not submitting any data, so the initial value will be
# displayed.)
p = UserRegistration(auto_id=False)
self.assertHTMLEqual(
p.as_ul(),
"""
<li>Username: <input type="text" name="username" value="django"
maxlength="10" required></li>
<li>Password: <input type="password" name="password" required></li>
""",
)
# Here, we're submitting data, so the initial value will *not* be
# displayed.
p = UserRegistration({}, auto_id=False)
self.assertHTMLEqual(
p.as_ul(),
"""<li><ul class="errorlist"><li>This field is required.</li></ul>
Username: <input type="text" name="username" maxlength="10" aria-invalid="true"
required></li><li><ul class="errorlist"><li>This field is required.</li></ul>
Password: <input type="password" name="password" aria-invalid="true" required></li>""",
)
p = UserRegistration({"username": ""}, auto_id=False)
self.assertHTMLEqual(
p.as_ul(),
"""<li><ul class="errorlist"><li>This field is required.</li></ul>
Username: <input type="text" name="username" maxlength="10" aria-invalid="true"
required></li><li><ul class="errorlist"><li>This field is required.</li></ul>
Password: <input type="password" name="password" aria-invalid="true" required></li>""",
)
p = UserRegistration({"username": "foo"}, auto_id=False)
self.assertHTMLEqual(
p.as_ul(),
"""
<li>Username: <input type="text" name="username" value="foo" maxlength="10"
required></li>
<li><ul class="errorlist"><li>This field is required.</li></ul>
Password: <input type="password" name="password" aria-invalid="true"
required></li>
""",
)
# An 'initial' value is *not* used as a fallback if data is not
# provided. In this example, we don't provide a value for 'username',
# and the form raises a validation error rather than using the initial
# value for 'username'.
p = UserRegistration({"password": "secret"})
self.assertEqual(p.errors["username"], ["This field is required."])
self.assertFalse(p.is_valid())
def test_dynamic_initial_data(self):
# The previous technique dealt with "hard-coded" initial data, but it's
# also possible to specify initial data after you've already created
# the Form class (i.e., at runtime). Use the 'initial' parameter to the
# Form constructor. This should be a dictionary containing initial
# values for one or more fields in the form, keyed by field name.
class UserRegistration(Form):
username = CharField(max_length=10)
password = CharField(widget=PasswordInput)
# Here, we're not submitting any data, so the initial value will be
# displayed.)
p = UserRegistration(initial={"username": "django"}, auto_id=False)
self.assertHTMLEqual(
p.as_ul(),
"""
<li>Username: <input type="text" name="username" value="django"
maxlength="10" required></li>
<li>Password: <input type="password" name="password" required></li>
""",
)
p = UserRegistration(initial={"username": "stephane"}, auto_id=False)
self.assertHTMLEqual(
p.as_ul(),
"""
<li>Username: <input type="text" name="username" value="stephane"
maxlength="10" required></li>
<li>Password: <input type="password" name="password" required></li>
""",
)
# The 'initial' parameter is meaningless if you pass data.
p = UserRegistration({}, initial={"username": "django"}, auto_id=False)
self.assertHTMLEqual(
p.as_ul(),
"""<li><ul class="errorlist"><li>This field is required.</li></ul>
Username: <input type="text" name="username" maxlength="10" aria-invalid="true"
required></li><li><ul class="errorlist"><li>This field is required.</li></ul>
Password: <input type="password" name="password" aria-invalid="true" required></li>""",
)
p = UserRegistration(
{"username": ""}, initial={"username": "django"}, auto_id=False
)
self.assertHTMLEqual(
p.as_ul(),
"""<li><ul class="errorlist"><li>This field is required.</li></ul>
Username: <input type="text" name="username" maxlength="10" aria-invalid="true"
required></li><li><ul class="errorlist"><li>This field is required.</li></ul>
Password: <input type="password" name="password" aria-invalid="true" required></li>""",
)
p = UserRegistration(
{"username": "foo"}, initial={"username": "django"}, auto_id=False
)
self.assertHTMLEqual(
p.as_ul(),
"""
<li>Username: <input type="text" name="username" value="foo" maxlength="10"
required></li>
<li><ul class="errorlist"><li>This field is required.</li></ul>
Password: <input type="password" name="password" aria-invalid="true"
required></li>
""",
)
# A dynamic 'initial' value is *not* used as a fallback if data is not
# provided. In this example, we don't provide a value for 'username',
# and the form raises a validation error rather than using the initial
# value for 'username'.
p = UserRegistration({"password": "secret"}, initial={"username": "django"})
self.assertEqual(p.errors["username"], ["This field is required."])
self.assertFalse(p.is_valid())
# If a Form defines 'initial' *and* 'initial' is passed as a parameter
# to Form(), then the latter will get precedence.
class UserRegistration(Form):
username = CharField(max_length=10, initial="django")
password = CharField(widget=PasswordInput)
p = UserRegistration(initial={"username": "babik"}, auto_id=False)
self.assertHTMLEqual(
p.as_ul(),
"""
<li>Username: <input type="text" name="username" value="babik"
maxlength="10" required></li>
<li>Password: <input type="password" name="password" required></li>
""",
)
def test_callable_initial_data(self):
# The previous technique dealt with raw values as initial data, but
# it's also possible to specify callable data.
class UserRegistration(Form):
username = CharField(max_length=10)
password = CharField(widget=PasswordInput)
options = MultipleChoiceField(
choices=[("f", "foo"), ("b", "bar"), ("w", "whiz")]
)
# We need to define functions that get called later.)
def initial_django():
return "django"
def initial_stephane():
return "stephane"
def initial_options():
return ["f", "b"]
def initial_other_options():
return ["b", "w"]
# Here, we're not submitting any data, so the initial value will be
# displayed.)
p = UserRegistration(
initial={"username": initial_django, "options": initial_options},
auto_id=False,
)
self.assertHTMLEqual(
p.as_ul(),
"""
<li>Username: <input type="text" name="username" value="django"
maxlength="10" required></li>
<li>Password: <input type="password" name="password" required></li>
<li>Options: <select multiple name="options" required>
<option value="f" selected>foo</option>
<option value="b" selected>bar</option>
<option value="w">whiz</option>
</select></li>
""",
)
# The 'initial' parameter is meaningless if you pass data.
p = UserRegistration(
{},
initial={"username": initial_django, "options": initial_options},
auto_id=False,
)
self.assertHTMLEqual(
p.as_ul(),
"""<li><ul class="errorlist"><li>This field is required.</li></ul>
Username: <input type="text" name="username" maxlength="10" aria-invalid="true"
required></li><li><ul class="errorlist"><li>This field is required.</li></ul>
Password: <input type="password" name="password" aria-invalid="true"
required></li><li><ul class="errorlist"><li>This field is required.</li></ul>
Options: <select multiple name="options" aria-invalid="true" required>
<option value="f">foo</option>
<option value="b">bar</option>
<option value="w">whiz</option>
</select></li>""",
)
p = UserRegistration(
{"username": ""}, initial={"username": initial_django}, auto_id=False
)
self.assertHTMLEqual(
p.as_ul(),
"""<li><ul class="errorlist"><li>This field is required.</li></ul>
Username: <input type="text" name="username" maxlength="10" aria-invalid="true"
required></li><li><ul class="errorlist"><li>This field is required.</li></ul>
Password: <input type="password" name="password" aria-invalid="true" required></li>
<li><ul class="errorlist"><li>This field is required.</li></ul>
Options: <select multiple name="options" aria-invalid="true" required>
<option value="f">foo</option>
<option value="b">bar</option>
<option value="w">whiz</option>
</select></li>""",
)
p = UserRegistration(
{"username": "foo", "options": ["f", "b"]},
initial={"username": initial_django},
auto_id=False,
)
self.assertHTMLEqual(
p.as_ul(),
"""
<li>Username: <input type="text" name="username" value="foo" maxlength="10"
required></li>
<li><ul class="errorlist"><li>This field is required.</li></ul>
Password: <input type="password" name="password" aria-invalid="true"
required></li><li>Options: <select multiple name="options" required>
<option value="f" selected>foo</option>
<option value="b" selected>bar</option>
<option value="w">whiz</option>
</select></li>
""",
)
# A callable 'initial' value is *not* used as a fallback if data is not
# provided. In this example, we don't provide a value for 'username',
# and the form raises a validation error rather than using the initial
# value for 'username'.
p = UserRegistration(
{"password": "secret"},
initial={"username": initial_django, "options": initial_options},
)
self.assertEqual(p.errors["username"], ["This field is required."])
self.assertFalse(p.is_valid())
# If a Form defines 'initial' *and* 'initial' is passed as a parameter
# to Form(), then the latter will get precedence.
class UserRegistration(Form):
username = CharField(max_length=10, initial=initial_django)
password = CharField(widget=PasswordInput)
options = MultipleChoiceField(
choices=[("f", "foo"), ("b", "bar"), ("w", "whiz")],
initial=initial_other_options,
)
p = UserRegistration(auto_id=False)
self.assertHTMLEqual(
p.as_ul(),
"""
<li>Username: <input type="text" name="username" value="django"
maxlength="10" required></li>
<li>Password: <input type="password" name="password" required></li>
<li>Options: <select multiple name="options" required>
<option value="f">foo</option>
<option value="b" selected>bar</option>
<option value="w" selected>whiz</option>
</select></li>
""",
)
p = UserRegistration(
initial={"username": initial_stephane, "options": initial_options},
auto_id=False,
)
self.assertHTMLEqual(
p.as_ul(),
"""
<li>Username: <input type="text" name="username" value="stephane"
maxlength="10" required></li>
<li>Password: <input type="password" name="password" required></li>
<li>Options: <select multiple name="options" required>
<option value="f" selected>foo</option>
<option value="b" selected>bar</option>
<option value="w">whiz</option>
</select></li>
""",
)
def test_get_initial_for_field(self):
now = datetime.datetime(2006, 10, 25, 14, 30, 45, 123456)
class PersonForm(Form):
first_name = CharField(initial="John")
last_name = CharField(initial="Doe")
age = IntegerField()
occupation = CharField(initial=lambda: "Unknown")
dt_fixed = DateTimeField(initial=now)
dt_callable = DateTimeField(initial=lambda: now)
form = PersonForm(initial={"first_name": "Jane"})
cases = [
("age", None),
("last_name", "Doe"),
# Form.initial overrides Field.initial.
("first_name", "Jane"),
# Callables are evaluated.
("occupation", "Unknown"),
# Microseconds are removed from datetimes.
("dt_fixed", datetime.datetime(2006, 10, 25, 14, 30, 45)),
("dt_callable", datetime.datetime(2006, 10, 25, 14, 30, 45)),
]
for field_name, expected in cases:
with self.subTest(field_name=field_name):
field = form.fields[field_name]
actual = form.get_initial_for_field(field, field_name)
self.assertEqual(actual, expected)
def test_changed_data(self):
class Person(Form):
first_name = CharField(initial="Hans")
last_name = CharField(initial="Greatel")
birthday = DateField(initial=datetime.date(1974, 8, 16))
p = Person(
data={"first_name": "Hans", "last_name": "Scrmbl", "birthday": "1974-08-16"}
)
self.assertTrue(p.is_valid())
self.assertNotIn("first_name", p.changed_data)
self.assertIn("last_name", p.changed_data)
self.assertNotIn("birthday", p.changed_data)
# A field raising ValidationError is always in changed_data
class PedanticField(Field):
def to_python(self, value):
raise ValidationError("Whatever")
class Person2(Person):
pedantic = PedanticField(initial="whatever", show_hidden_initial=True)
p = Person2(
data={
"first_name": "Hans",
"last_name": "Scrmbl",
"birthday": "1974-08-16",
"initial-pedantic": "whatever",
}
)
self.assertFalse(p.is_valid())
self.assertIn("pedantic", p.changed_data)
def test_boundfield_values(self):
# It's possible to get to the value which would be used for rendering
# the widget for a field by using the BoundField's value method.
class UserRegistration(Form):
username = CharField(max_length=10, initial="djangonaut")
password = CharField(widget=PasswordInput)
unbound = UserRegistration()
bound = UserRegistration({"password": "foo"})
self.assertIsNone(bound["username"].value())
self.assertEqual(unbound["username"].value(), "djangonaut")
self.assertEqual(bound["password"].value(), "foo")
self.assertIsNone(unbound["password"].value())
def test_boundfield_initial_called_once(self):
"""
Multiple calls to BoundField().value() in an unbound form should return
the same result each time (#24391).
"""
class MyForm(Form):
name = CharField(max_length=10, initial=uuid.uuid4)
form = MyForm()
name = form["name"]
self.assertEqual(name.value(), name.value())
# BoundField is also cached
self.assertIs(form["name"], name)
def test_boundfield_value_disabled_callable_initial(self):
class PersonForm(Form):
name = CharField(initial=lambda: "John Doe", disabled=True)
# Without form data.
form = PersonForm()
self.assertEqual(form["name"].value(), "John Doe")
# With form data. As the field is disabled, the value should not be
# affected by the form data.
form = PersonForm({})
self.assertEqual(form["name"].value(), "John Doe")
def test_custom_boundfield(self):
class CustomField(CharField):
def get_bound_field(self, form, name):
return (form, name)
class SampleForm(Form):
name = CustomField()
f = SampleForm()
self.assertEqual(f["name"], (f, "name"))
def test_initial_datetime_values(self):
now = datetime.datetime.now()
# Nix microseconds (since they should be ignored). #22502
now_no_ms = now.replace(microsecond=0)
if now == now_no_ms:
now = now.replace(microsecond=1)
def delayed_now():
return now
def delayed_now_time():
return now.time()
class HiddenInputWithoutMicrosec(HiddenInput):
supports_microseconds = False
class TextInputWithoutMicrosec(TextInput):
supports_microseconds = False
class DateTimeForm(Form):
# Test a non-callable.
fixed = DateTimeField(initial=now)
auto_timestamp = DateTimeField(initial=delayed_now)
auto_time_only = TimeField(initial=delayed_now_time)
supports_microseconds = DateTimeField(initial=delayed_now, widget=TextInput)
hi_default_microsec = DateTimeField(initial=delayed_now, widget=HiddenInput)
hi_without_microsec = DateTimeField(
initial=delayed_now, widget=HiddenInputWithoutMicrosec
)
ti_without_microsec = DateTimeField(
initial=delayed_now, widget=TextInputWithoutMicrosec
)
unbound = DateTimeForm()
cases = [
("fixed", now_no_ms),
("auto_timestamp", now_no_ms),
("auto_time_only", now_no_ms.time()),
("supports_microseconds", now),
("hi_default_microsec", now),
("hi_without_microsec", now_no_ms),
("ti_without_microsec", now_no_ms),
]
for field_name, expected in cases:
with self.subTest(field_name=field_name):
actual = unbound[field_name].value()
self.assertEqual(actual, expected)
# Also check get_initial_for_field().
field = unbound.fields[field_name]
actual = unbound.get_initial_for_field(field, field_name)
self.assertEqual(actual, expected)
def get_datetime_form_with_callable_initial(self, disabled, microseconds=0):
class FakeTime:
def __init__(self):
self.elapsed_seconds = 0
def now(self):
self.elapsed_seconds += 1
return datetime.datetime(
2006,
10,
25,
14,
30,
45 + self.elapsed_seconds,
microseconds,
)
class DateTimeForm(Form):
dt = DateTimeField(initial=FakeTime().now, disabled=disabled)
return DateTimeForm({})
def test_datetime_clean_disabled_callable_initial_microseconds(self):
"""
Cleaning a form with a disabled DateTimeField and callable initial
removes microseconds.
"""
form = self.get_datetime_form_with_callable_initial(
disabled=True,
microseconds=123456,
)
self.assertEqual(form.errors, {})
self.assertEqual(
form.cleaned_data,
{
"dt": datetime.datetime(2006, 10, 25, 14, 30, 46),
},
)
def test_datetime_clean_disabled_callable_initial_bound_field(self):
"""
The cleaned value for a form with a disabled DateTimeField and callable
initial matches the bound field's cached initial value.
"""
form = self.get_datetime_form_with_callable_initial(disabled=True)
self.assertEqual(form.errors, {})
cleaned = form.cleaned_data["dt"]
self.assertEqual(cleaned, datetime.datetime(2006, 10, 25, 14, 30, 46))
bf = form["dt"]
self.assertEqual(cleaned, bf.initial)
def test_datetime_changed_data_callable_with_microseconds(self):
class DateTimeForm(Form):
dt = DateTimeField(
initial=lambda: datetime.datetime(2006, 10, 25, 14, 30, 45, 123456),
disabled=True,
)
form = DateTimeForm({"dt": "2006-10-25 14:30:45"})
self.assertEqual(form.changed_data, [])
def test_help_text(self):
# You can specify descriptive text for a field by using the 'help_text'
# argument.
class UserRegistration(Form):
username = CharField(max_length=10, help_text="e.g., user@example.com")
password = CharField(
widget=PasswordInput, help_text="Wählen Sie mit Bedacht."
)
p = UserRegistration(auto_id=False)
self.assertHTMLEqual(
p.as_ul(),
"""<li>Username: <input type="text" name="username" maxlength="10" required>
<span class="helptext">e.g., user@example.com</span></li>
<li>Password: <input type="password" name="password" required>
<span class="helptext">Wählen Sie mit Bedacht.</span></li>""",
)
self.assertHTMLEqual(
p.as_p(),
"""<p>Username: <input type="text" name="username" maxlength="10" required>
<span class="helptext">e.g., user@example.com</span></p>
<p>Password: <input type="password" name="password" required>
<span class="helptext">Wählen Sie mit Bedacht.</span></p>""",
)
self.assertHTMLEqual(
p.as_table(),
"""
<tr><th>Username:</th><td>
<input type="text" name="username" maxlength="10" required><br>
<span class="helptext">e.g., user@example.com</span></td></tr>
<tr><th>Password:</th><td><input type="password" name="password" required>
<br>
<span class="helptext">Wählen Sie mit Bedacht.</span></td></tr>""",
)
self.assertHTMLEqual(
p.as_div(),
'<div>Username: <div class="helptext">e.g., user@example.com</div>'
'<input type="text" name="username" maxlength="10" required></div>'
'<div>Password: <div class="helptext">Wählen Sie mit Bedacht.</div>'
'<input type="password" name="password" required></div>',
)
# The help text is displayed whether or not data is provided for the
# form.
p = UserRegistration({"username": "foo"}, auto_id=False)
self.assertHTMLEqual(
p.as_ul(),
'<li>Username: <input type="text" name="username" value="foo" '
'maxlength="10" required>'
'<span class="helptext">e.g., user@example.com</span></li>'
'<li><ul class="errorlist"><li>This field is required.</li></ul>'
'Password: <input type="password" name="password" aria-invalid="true" '
'required><span class="helptext">Wählen Sie mit Bedacht.</span></li>',
)
# help_text is not displayed for hidden fields. It can be used for
# documentation purposes, though.
class UserRegistration(Form):
username = CharField(max_length=10, help_text="e.g., user@example.com")
password = CharField(widget=PasswordInput)
next = CharField(
widget=HiddenInput, initial="/", help_text="Redirect destination"
)
p = UserRegistration(auto_id=False)
self.assertHTMLEqual(
p.as_ul(),
"""<li>Username: <input type="text" name="username" maxlength="10" required>
<span class="helptext">e.g., user@example.com</span></li>
<li>Password: <input type="password" name="password" required>
<input type="hidden" name="next" value="/"></li>""",
)
def test_help_text_html_safe(self):
"""help_text should not be escaped."""
class UserRegistration(Form):
username = CharField(max_length=10, help_text="e.g., user@example.com")
password = CharField(
widget=PasswordInput,
help_text="Help text is <strong>escaped</strong>.",
)
p = UserRegistration(auto_id=False)
self.assertHTMLEqual(
p.as_ul(),
'<li>Username: <input type="text" name="username" maxlength="10" required>'
'<span class="helptext">e.g., user@example.com</span></li>'
'<li>Password: <input type="password" name="password" required>'
'<span class="helptext">Help text is <strong>escaped</strong>.</span></li>',
)
self.assertHTMLEqual(
p.as_p(),
'<p>Username: <input type="text" name="username" maxlength="10" required>'
'<span class="helptext">e.g., user@example.com</span></p>'
'<p>Password: <input type="password" name="password" required>'
'<span class="helptext">Help text is <strong>escaped</strong>.</span></p>',
)
self.assertHTMLEqual(
p.as_table(),
"<tr><th>Username:</th><td>"
'<input type="text" name="username" maxlength="10" required><br>'
'<span class="helptext">e.g., user@example.com</span></td></tr>'
"<tr><th>Password:</th><td>"
'<input type="password" name="password" required><br>'
'<span class="helptext">Help text is <strong>escaped</strong>.</span>'
"</td></tr>",
)
def test_widget_attrs_custom_aria_describedby(self):
# aria-describedby provided to the widget overrides the default.
class UserRegistration(Form):
username = CharField(
max_length=255,
help_text="e.g., user@example.com",
widget=TextInput(attrs={"aria-describedby": "custom-description"}),
)
password = CharField(
widget=PasswordInput, help_text="Wählen Sie mit Bedacht."
)
p = UserRegistration()
self.assertHTMLEqual(
p.as_div(),
'<div><label for="id_username">Username:</label>'
'<div class="helptext" id="id_username_helptext">e.g., user@example.com'
'</div><input type="text" name="username" maxlength="255" required '
'aria-describedby="custom-description" id="id_username">'
"</div><div>"
'<label for="id_password">Password:</label>'
'<div class="helptext" id="id_password_helptext">Wählen Sie mit Bedacht.'
'</div><input type="password" name="password" required '
'aria-describedby="id_password_helptext" id="id_password"></div>',
)
self.assertHTMLEqual(
p.as_ul(),
'<li><label for="id_username">Username:</label><input type="text" '
'name="username" maxlength="255" required '
'aria-describedby="custom-description" id="id_username">'
'<span class="helptext" id="id_username_helptext">e.g., user@example.com'
"</span></li><li>"
'<label for="id_password">Password:</label>'
'<input type="password" name="password" required '
'aria-describedby="id_password_helptext" id="id_password">'
'<span class="helptext" id="id_password_helptext">Wählen Sie mit Bedacht.'
"</span></li>",
)
self.assertHTMLEqual(
p.as_p(),
'<p><label for="id_username">Username:</label><input type="text" '
'name="username" maxlength="255" required '
'aria-describedby="custom-description" id="id_username">'
'<span class="helptext" id="id_username_helptext">e.g., user@example.com'
"</span></p><p>"
'<label for="id_password">Password:</label>'
'<input type="password" name="password" required '
'aria-describedby="id_password_helptext" id="id_password">'
'<span class="helptext" id="id_password_helptext">Wählen Sie mit Bedacht.'
"</span></p>",
)
self.assertHTMLEqual(
p.as_table(),
'<tr><th><label for="id_username">Username:</label></th><td>'
'<input type="text" name="username" maxlength="255" required '
'aria-describedby="custom-description" id="id_username"><br>'
'<span class="helptext" id="id_username_helptext">e.g., user@example.com'
"</span></td></tr><tr><th>"
'<label for="id_password">Password:</label></th><td>'
'<input type="password" name="password" required '
'aria-describedby="id_password_helptext" id="id_password"><br>'
'<span class="helptext" id="id_password_helptext">Wählen Sie mit Bedacht.'
"</span></td></tr>",
)
def test_aria_describedby_custom_widget_id(self):
class UserRegistration(Form):
username = CharField(
max_length=255,
help_text="e.g., user@example.com",
widget=TextInput(attrs={"id": "custom-id"}),
)
f = UserRegistration()
self.assertHTMLEqual(
str(f),
'<div><label for="custom-id">Username:</label>'
'<div class="helptext" id="id_username_helptext">e.g., user@example.com'
'</div><input type="text" name="username" id="custom-id" maxlength="255" '
'required aria-describedby="id_username_helptext"></div>',
)
def test_select_aria_describedby(self):
class TestForm(Form):
color = MultipleChoiceField(
choices=[("red", "Red"), ("green", "Green")],
help_text="Select Color",
)
f = TestForm({"color": "Blue"})
self.assertHTMLEqual(
str(f),
'<div><label for="id_color">Color:</label><div class="helptext" '
'id="id_color_helptext">Select Color</div>'
'<ul class="errorlist" id="id_color_error"><li>Enter a list of values.'
'</li></ul><select name="color" required aria-invalid="true" '
'aria-describedby="id_color_helptext id_color_error" id="id_color" '
'multiple><option value="red">Red</option>'
'<option value="green">Green</option></select></div>',
)
def test_textarea_aria_describedby(self):
class TestForm(Form):
color = CharField(widget=Textarea, max_length=5, help_text="Enter Color")
f = TestForm({"color": "Purple"})
self.assertHTMLEqual(
str(f),
'<div><label for="id_color">Color:</label>'
'<div class="helptext" id="id_color_helptext">Enter Color</div>'
'<ul class="errorlist" id="id_color_error">'
"<li>Ensure this value has at most 5 characters (it has 6).</li></ul>"
'<textarea name="color" cols="40" rows="10" maxlength="5" required '
'aria-invalid="true" aria-describedby="id_color_helptext id_color_error" '
'id="id_color">Purple</textarea></div>',
)
def test_aria_describedby_called_multiple_times(self):
class TestForm(Form):
color = CharField(widget=Textarea, help_text="Enter Color")
f = TestForm({"color": "Purple"})
self.assertEqual(f["color"].aria_describedby, "id_color_helptext")
f.add_error("color", "An error about Purple.")
self.assertEqual(
f["color"].aria_describedby, "id_color_helptext id_color_error"
)
def test_fieldset_aria_describedby(self):
class FieldsetForm(Form):
checkbox = MultipleChoiceField(
choices=[("a", "A"), ("b", "B")],
widget=CheckboxSelectMultiple,
help_text="Checkbox help text",
)
radio = MultipleChoiceField(
choices=[("a", "A"), ("b", "B")],
widget=RadioSelect,
help_text="Radio help text",
)
datetime = SplitDateTimeField(help_text="Enter Date and Time")
f = FieldsetForm()
self.assertHTMLEqual(
str(f),
'<div><fieldset aria-describedby="id_checkbox_helptext">'
"<legend>Checkbox:</legend>"
'<div class="helptext" id="id_checkbox_helptext">Checkbox help text</div>'
'<div id="id_checkbox"><div>'
'<label for="id_checkbox_0"><input type="checkbox" name="checkbox" '
'value="a" id="id_checkbox_0" /> A</label>'
"</div><div>"
'<label for="id_checkbox_1"><input type="checkbox" name="checkbox" '
'value="b" id="id_checkbox_1" /> B</label>'
"</div></div></fieldset></div>"
'<div><fieldset aria-describedby="id_radio_helptext">'
"<legend>Radio:</legend>"
'<div class="helptext" id="id_radio_helptext">Radio help text</div>'
'<div id="id_radio"><div>'
'<label for="id_radio_0"><input type="radio" name="radio" value="a" '
'required id="id_radio_0" />A</label>'
"</div><div>"
'<label for="id_radio_1"><input type="radio" name="radio" value="b" '
'required id="id_radio_1" /> B</label>'
"</div></div></fieldset></div>"
'<div><fieldset aria-describedby="id_datetime_helptext">'
"<legend>Datetime:</legend>"
'<div class="helptext" id="id_datetime_helptext">Enter Date and Time</div>'
'<input type="text" name="datetime_0" required id="id_datetime_0" />'
'<input type="text" name="datetime_1" required id="id_datetime_1" />'
"</fieldset></div>",
)
f = FieldsetForm({})
self.assertHTMLEqual(
'<div><fieldset aria-describedby="id_checkbox_helptext '
'id_checkbox_error"> <legend>Checkbox:</legend> <div class="helptext" '
'id="id_checkbox_helptext">Checkbox help text</div> <ul class="errorlist" '
'id="id_checkbox_error"> <li>This field is required.</li> </ul> '
'<div id="id_checkbox"> <div> <label for="id_checkbox_0"><input '
'type="checkbox" name="checkbox" value="a" aria-invalid="true" '
'id="id_checkbox_0" /> A</label> </div> <div> <label for="id_checkbox_1">'
'<input type="checkbox" name="checkbox" value="b" aria-invalid="true" '
'id="id_checkbox_1" /> B</label> </div> </div> </fieldset> </div> <div> '
'<fieldset aria-describedby="id_radio_helptext id_radio_error"> '
'<legend>Radio:</legend> <div class="helptext" id="id_radio_helptext">'
'Radio help text</div> <ul class="errorlist" id="id_radio_error"><li>'
'This field is required.</li> </ul> <div id="id_radio"><div><label '
'for="id_radio_0"><input type="radio" name="radio" value="a" required '
'aria-invalid="true" id="id_radio_0" />A</label></div><div><label '
'for="id_radio_1"><input type="radio" name="radio" value="b" required '
'aria-invalid="true" id="id_radio_1" />B</label></div></div></fieldset>'
'</div><div><fieldset aria-describedby="id_datetime_helptext '
'id_datetime_error"><legend>Datetime:</legend><div class="helptext" '
'id="id_datetime_helptext">Enter Date and Time</div><ul class="errorlist" '
'id="id_datetime_error"><li>This field is required.</li></ul><input '
'type="text" name="datetime_0" required aria-invalid="true" '
'id="id_datetime_0" /><input type="text" name="datetime_1" required '
'aria-invalid="true" id="id_datetime_1" /></fieldset></div>',
str(f),
)
f = FieldsetForm(auto_id=False)
# aria-describedby is not included.
self.assertIn("<fieldset>", str(f))
self.assertIn('<div class="helptext">', str(f))
f = FieldsetForm(auto_id="custom_%s")
# aria-describedby uses custom auto_id.
self.assertIn('fieldset aria-describedby="custom_checkbox_helptext"', str(f))
self.assertIn('<div class="helptext" id="custom_checkbox_helptext">', str(f))
def test_fieldset_custom_aria_describedby(self):
# aria-describedby set on widget results in aria-describedby being
# added to widget and not the <fieldset>.
class FieldsetForm(Form):
checkbox = MultipleChoiceField(
choices=[("a", "A"), ("b", "B")],
widget=CheckboxSelectMultiple(attrs={"aria-describedby": "custom-id"}),
help_text="Checkbox help text",
)
f = FieldsetForm()
self.assertHTMLEqual(
str(f),
"<div><fieldset><legend>Checkbox:</legend>"
'<div class="helptext" id="id_checkbox_helptext">Checkbox help text</div>'
'<div id="id_checkbox"><div>'
'<label for="id_checkbox_0"><input type="checkbox" name="checkbox" '
'value="a" aria-describedby="custom-id" id="id_checkbox_0" />A</label>'
"</div><div>"
'<label for="id_checkbox_1"><input type="checkbox" name="checkbox" '
'value="b" aria-describedby="custom-id" id="id_checkbox_1" />B</label>'
"</div></div></fieldset></div>",
)
def test_as_widget_custom_aria_describedby(self):
class FoodForm(Form):
intl_name = CharField(help_text="The food's international name.")
form = FoodForm({"intl_name": "Rendang"})
self.assertHTMLEqual(
form["intl_name"].as_widget(attrs={"aria-describedby": "some_custom_id"}),
'<input type="text" name="intl_name" value="Rendang"'
'aria-describedby="some_custom_id" required id="id_intl_name">',
)
def test_subclassing_forms(self):
# You can subclass a Form to add fields. The resulting form subclass
# will have all of the fields of the parent Form, plus whichever fields
# you define in the subclass.
class Person(Form):
first_name = CharField()
last_name = CharField()
birthday = DateField()
class Musician(Person):
instrument = CharField()
p = Person(auto_id=False)
self.assertHTMLEqual(
p.as_ul(),
"""<li>First name: <input type="text" name="first_name" required></li>
<li>Last name: <input type="text" name="last_name" required></li>
<li>Birthday: <input type="text" name="birthday" required></li>""",
)
m = Musician(auto_id=False)
self.assertHTMLEqual(
m.as_ul(),
"""<li>First name: <input type="text" name="first_name" required></li>
<li>Last name: <input type="text" name="last_name" required></li>
<li>Birthday: <input type="text" name="birthday" required></li>
<li>Instrument: <input type="text" name="instrument" required></li>""",
)
# Yes, you can subclass multiple forms. The fields are added in the
# order in which the parent classes are listed.
class Person(Form):
first_name = CharField()
last_name = CharField()
birthday = DateField()
class Instrument(Form):
instrument = CharField()
class Beatle(Person, Instrument):
haircut_type = CharField()
b = Beatle(auto_id=False)
self.assertHTMLEqual(
b.as_ul(),
"""<li>Instrument: <input type="text" name="instrument" required></li>
<li>First name: <input type="text" name="first_name" required></li>
<li>Last name: <input type="text" name="last_name" required></li>
<li>Birthday: <input type="text" name="birthday" required></li>
<li>Haircut type: <input type="text" name="haircut_type" required></li>""",
)
def test_forms_with_prefixes(self):
# Sometimes it's necessary to have multiple forms display on the same
# HTML page, or multiple copies of the same form. We can accomplish
# this with form prefixes. Pass the keyword argument 'prefix' to the
# Form constructor to use this feature. This value will be prepended to
# each HTML form field name. One way to think about this is "namespaces
# for HTML forms". Notice that in the data argument, each field's key
# has the prefix, in this case 'person1', prepended to the actual field
# name.
class Person(Form):
first_name = CharField()
last_name = CharField()
birthday = DateField()
data = {
"person1-first_name": "John",
"person1-last_name": "Lennon",
"person1-birthday": "1940-10-9",
}
p = Person(data, prefix="person1")
self.assertHTMLEqual(
p.as_ul(),
"""
<li><label for="id_person1-first_name">First name:</label>
<input type="text" name="person1-first_name" value="John"
id="id_person1-first_name" required></li>
<li><label for="id_person1-last_name">Last name:</label>
<input type="text" name="person1-last_name" value="Lennon"
id="id_person1-last_name" required></li>
<li><label for="id_person1-birthday">Birthday:</label>
<input type="text" name="person1-birthday" value="1940-10-9"
id="id_person1-birthday" required></li>
""",
)
self.assertHTMLEqual(
str(p["first_name"]),
'<input type="text" name="person1-first_name" value="John" '
'id="id_person1-first_name" required>',
)
self.assertHTMLEqual(
str(p["last_name"]),
'<input type="text" name="person1-last_name" value="Lennon" '
'id="id_person1-last_name" required>',
)
self.assertHTMLEqual(
str(p["birthday"]),
'<input type="text" name="person1-birthday" value="1940-10-9" '
'id="id_person1-birthday" required>',
)
self.assertEqual(p.errors, {})
self.assertTrue(p.is_valid())
self.assertEqual(p.cleaned_data["first_name"], "John")
self.assertEqual(p.cleaned_data["last_name"], "Lennon")
self.assertEqual(p.cleaned_data["birthday"], datetime.date(1940, 10, 9))
# Let's try submitting some bad data to make sure form.errors and
# field.errors work as expected.
data = {
"person1-first_name": "",
"person1-last_name": "",
"person1-birthday": "",
}
p = Person(data, prefix="person1")
self.assertEqual(p.errors["first_name"], ["This field is required."])
self.assertEqual(p.errors["last_name"], ["This field is required."])
self.assertEqual(p.errors["birthday"], ["This field is required."])
self.assertEqual(p["first_name"].errors, ["This field is required."])
# Accessing a nonexistent field.
with self.assertRaises(KeyError):
p["person1-first_name"].errors
# In this example, the data doesn't have a prefix, but the form
# requires it, so the form doesn't "see" the fields.
data = {"first_name": "John", "last_name": "Lennon", "birthday": "1940-10-9"}
p = Person(data, prefix="person1")
self.assertEqual(p.errors["first_name"], ["This field is required."])
self.assertEqual(p.errors["last_name"], ["This field is required."])
self.assertEqual(p.errors["birthday"], ["This field is required."])
# With prefixes, a single data dictionary can hold data for multiple
# instances of the same form.
data = {
"person1-first_name": "John",
"person1-last_name": "Lennon",
"person1-birthday": "1940-10-9",
"person2-first_name": "Jim",
"person2-last_name": "Morrison",
"person2-birthday": "1943-12-8",
}
p1 = Person(data, prefix="person1")
self.assertTrue(p1.is_valid())
self.assertEqual(p1.cleaned_data["first_name"], "John")
self.assertEqual(p1.cleaned_data["last_name"], "Lennon")
self.assertEqual(p1.cleaned_data["birthday"], datetime.date(1940, 10, 9))
p2 = Person(data, prefix="person2")
self.assertTrue(p2.is_valid())
self.assertEqual(p2.cleaned_data["first_name"], "Jim")
self.assertEqual(p2.cleaned_data["last_name"], "Morrison")
self.assertEqual(p2.cleaned_data["birthday"], datetime.date(1943, 12, 8))
# By default, forms append a hyphen between the prefix and the field
# name, but a form can alter that behavior by implementing the
# add_prefix() method. This method takes a field name and returns the
# prefixed field, according to self.prefix.
class Person(Form):
first_name = CharField()
last_name = CharField()
birthday = DateField()
def add_prefix(self, field_name):
return (
"%s-prefix-%s" % (self.prefix, field_name)
if self.prefix
else field_name
)
p = Person(prefix="foo")
self.assertHTMLEqual(
p.as_ul(),
"""
<li><label for="id_foo-prefix-first_name">First name:</label>
<input type="text" name="foo-prefix-first_name"
id="id_foo-prefix-first_name" required></li>
<li><label for="id_foo-prefix-last_name">Last name:</label>
<input type="text" name="foo-prefix-last_name" id="id_foo-prefix-last_name"
required></li>
<li><label for="id_foo-prefix-birthday">Birthday:</label>
<input type="text" name="foo-prefix-birthday" id="id_foo-prefix-birthday"
required></li>
""",
)
data = {
"foo-prefix-first_name": "John",
"foo-prefix-last_name": "Lennon",
"foo-prefix-birthday": "1940-10-9",
}
p = Person(data, prefix="foo")
self.assertTrue(p.is_valid())
self.assertEqual(p.cleaned_data["first_name"], "John")
self.assertEqual(p.cleaned_data["last_name"], "Lennon")
self.assertEqual(p.cleaned_data["birthday"], datetime.date(1940, 10, 9))
def test_class_prefix(self):
# Prefix can be also specified at the class level.
class Person(Form):
first_name = CharField()
prefix = "foo"
p = Person()
self.assertEqual(p.prefix, "foo")
p = Person(prefix="bar")
self.assertEqual(p.prefix, "bar")
def test_forms_with_null_boolean(self):
# NullBooleanField is a bit of a special case because its presentation
# (widget) is different than its data. This is handled transparently,
# though.
class Person(Form):
name = CharField()
is_cool = NullBooleanField()
p = Person({"name": "Joe"}, auto_id=False)
self.assertHTMLEqual(
str(p["is_cool"]),
"""<select name="is_cool">
<option value="unknown" selected>Unknown</option>
<option value="true">Yes</option>
<option value="false">No</option>
</select>""",
)
p = Person({"name": "Joe", "is_cool": "1"}, auto_id=False)
self.assertHTMLEqual(
str(p["is_cool"]),
"""<select name="is_cool">
<option value="unknown" selected>Unknown</option>
<option value="true">Yes</option>
<option value="false">No</option>
</select>""",
)
p = Person({"name": "Joe", "is_cool": "2"}, auto_id=False)
self.assertHTMLEqual(
str(p["is_cool"]),
"""<select name="is_cool">
<option value="unknown">Unknown</option>
<option value="true" selected>Yes</option>
<option value="false">No</option>
</select>""",
)
p = Person({"name": "Joe", "is_cool": "3"}, auto_id=False)
self.assertHTMLEqual(
str(p["is_cool"]),
"""<select name="is_cool">
<option value="unknown">Unknown</option>
<option value="true">Yes</option>
<option value="false" selected>No</option>
</select>""",
)
p = Person({"name": "Joe", "is_cool": True}, auto_id=False)
self.assertHTMLEqual(
str(p["is_cool"]),
"""<select name="is_cool">
<option value="unknown">Unknown</option>
<option value="true" selected>Yes</option>
<option value="false">No</option>
</select>""",
)
p = Person({"name": "Joe", "is_cool": False}, auto_id=False)
self.assertHTMLEqual(
str(p["is_cool"]),
"""<select name="is_cool">
<option value="unknown">Unknown</option>
<option value="true">Yes</option>
<option value="false" selected>No</option>
</select>""",
)
p = Person({"name": "Joe", "is_cool": "unknown"}, auto_id=False)
self.assertHTMLEqual(
str(p["is_cool"]),
"""<select name="is_cool">
<option value="unknown" selected>Unknown</option>
<option value="true">Yes</option>
<option value="false">No</option>
</select>""",
)
p = Person({"name": "Joe", "is_cool": "true"}, auto_id=False)
self.assertHTMLEqual(
str(p["is_cool"]),
"""<select name="is_cool">
<option value="unknown">Unknown</option>
<option value="true" selected>Yes</option>
<option value="false">No</option>
</select>""",
)
p = Person({"name": "Joe", "is_cool": "false"}, auto_id=False)
self.assertHTMLEqual(
str(p["is_cool"]),
"""<select name="is_cool">
<option value="unknown">Unknown</option>
<option value="true">Yes</option>
<option value="false" selected>No</option>
</select>""",
)
def test_forms_with_file_fields(self):
# FileFields are a special case because they take their data from the
# request.FILES, not request.POST.
class FileForm(Form):
file1 = FileField()
f = FileForm(auto_id=False)
self.assertHTMLEqual(
f.as_table(),
"<tr><th>File1:</th><td>"
'<input type="file" name="file1" required></td></tr>',
)
f = FileForm(data={}, files={}, auto_id=False)
self.assertHTMLEqual(
f.as_table(),
"<tr><th>File1:</th><td>"
'<ul class="errorlist"><li>This field is required.</li></ul>'
'<input type="file" name="file1" aria-invalid="true" required></td></tr>',
)
f = FileForm(
data={}, files={"file1": SimpleUploadedFile("name", b"")}, auto_id=False
)
self.assertHTMLEqual(
f.as_table(),
"<tr><th>File1:</th><td>"
'<ul class="errorlist"><li>The submitted file is empty.</li></ul>'
'<input type="file" name="file1" aria-invalid="true" required></td></tr>',
)
f = FileForm(
data={}, files={"file1": "something that is not a file"}, auto_id=False
)
self.assertHTMLEqual(
f.as_table(),
"<tr><th>File1:</th><td>"
'<ul class="errorlist"><li>No file was submitted. Check the '
"encoding type on the form.</li></ul>"
'<input type="file" name="file1" aria-invalid="true" required></td></tr>',
)
f = FileForm(
data={},
files={"file1": SimpleUploadedFile("name", b"some content")},
auto_id=False,
)
self.assertHTMLEqual(
f.as_table(),
"<tr><th>File1:</th><td>"
'<input type="file" name="file1" required></td></tr>',
)
self.assertTrue(f.is_valid())
file1 = SimpleUploadedFile(
"我隻氣墊船裝滿晒鱔.txt", "मेरी मँडराने वाली नाव सर्पमीनों से भरी ह".encode()
)
f = FileForm(data={}, files={"file1": file1}, auto_id=False)
self.assertHTMLEqual(
f.as_table(),
"<tr><th>File1:</th><td>"
'<input type="file" name="file1" required></td></tr>',
)
# A required file field with initial data should not contain the
# required HTML attribute. The file input is left blank by the user to
# keep the existing, initial value.
f = FileForm(initial={"file1": "resume.txt"}, auto_id=False)
self.assertHTMLEqual(
f.as_table(),
'<tr><th>File1:</th><td><input type="file" name="file1"></td></tr>',
)
def test_filefield_initial_callable(self):
class FileForm(Form):
file1 = FileField(initial=lambda: "resume.txt")
f = FileForm({})
self.assertEqual(f.errors, {})
self.assertEqual(f.cleaned_data["file1"], "resume.txt")
def test_filefield_with_fileinput_required(self):
class FileForm(Form):
file1 = FileField(widget=FileInput)
f = FileForm(auto_id=False)
self.assertHTMLEqual(
f.as_table(),
"<tr><th>File1:</th><td>"
'<input type="file" name="file1" required></td></tr>',
)
# A required file field with initial data doesn't contain the required
# HTML attribute. The file input is left blank by the user to keep the
# existing, initial value.
f = FileForm(initial={"file1": "resume.txt"}, auto_id=False)
self.assertHTMLEqual(
f.as_table(),
'<tr><th>File1:</th><td><input type="file" name="file1"></td></tr>',
)
def test_empty_permitted(self):
# Sometimes (pretty much in formsets) we want to allow a form to pass
# validation if it is completely empty. We can accomplish this by using
# the empty_permitted argument to a form constructor.
class SongForm(Form):
artist = CharField()
name = CharField()
# First let's show what happens id empty_permitted=False (the default):
data = {"artist": "", "song": ""}
form = SongForm(data, empty_permitted=False)
self.assertFalse(form.is_valid())
self.assertEqual(
form.errors,
{
"name": ["This field is required."],
"artist": ["This field is required."],
},
)
self.assertEqual(form.cleaned_data, {})
# Now let's show what happens when empty_permitted=True and the form is
# empty.
form = SongForm(data, empty_permitted=True, use_required_attribute=False)
self.assertTrue(form.is_valid())
self.assertEqual(form.errors, {})
self.assertEqual(form.cleaned_data, {})
# But if we fill in data for one of the fields, the form is no longer
# empty and the whole thing must pass validation.
data = {"artist": "The Doors", "song": ""}
form = SongForm(data, empty_permitted=False)
self.assertFalse(form.is_valid())
self.assertEqual(form.errors, {"name": ["This field is required."]})
self.assertEqual(form.cleaned_data, {"artist": "The Doors"})
# If a field is not given in the data then None is returned for its
# data. Lets make sure that when checking for empty_permitted that None
# is treated accordingly.
data = {"artist": None, "song": ""}
form = SongForm(data, empty_permitted=True, use_required_attribute=False)
self.assertTrue(form.is_valid())
# However, we *really* need to be sure we are checking for None as any
# data in initial that returns False on a boolean call needs to be
# treated literally.
class PriceForm(Form):
amount = FloatField()
qty = IntegerField()
data = {"amount": "0.0", "qty": ""}
form = PriceForm(
data,
initial={"amount": 0.0},
empty_permitted=True,
use_required_attribute=False,
)
self.assertTrue(form.is_valid())
def test_empty_permitted_and_use_required_attribute(self):
msg = (
"The empty_permitted and use_required_attribute arguments may not "
"both be True."
)
with self.assertRaisesMessage(ValueError, msg):
Person(empty_permitted=True, use_required_attribute=True)
def test_extracting_hidden_and_visible(self):
class SongForm(Form):
token = CharField(widget=HiddenInput)
artist = CharField()
name = CharField()
form = SongForm()
self.assertEqual([f.name for f in form.hidden_fields()], ["token"])
self.assertEqual([f.name for f in form.visible_fields()], ["artist", "name"])
def test_hidden_initial_gets_id(self):
class MyForm(Form):
field1 = CharField(max_length=50, show_hidden_initial=True)
self.assertHTMLEqual(
MyForm().as_table(),
'<tr><th><label for="id_field1">Field1:</label></th><td>'
'<input id="id_field1" type="text" name="field1" maxlength="50" required>'
'<input type="hidden" name="initial-field1" id="initial-id_field1">'
"</td></tr>",
)
def test_error_html_required_html_classes(self):
class Person(Form):
name = CharField()
is_cool = NullBooleanField()
email = EmailField(required=False)
age = IntegerField()
p = Person({})
p.error_css_class = "error"
p.required_css_class = "required"
self.assertHTMLEqual(
p.as_ul(),
"""
<li class="required error"><ul class="errorlist" id="id_name_error">
<li>This field is required.</li></ul>
<label class="required" for="id_name">Name:</label>
<input type="text" name="name" id="id_name" aria-invalid="true" required
aria-describedby="id_name_error">
</li><li class="required">
<label class="required" for="id_is_cool">Is cool:</label>
<select name="is_cool" id="id_is_cool">
<option value="unknown" selected>Unknown</option>
<option value="true">Yes</option>
<option value="false">No</option>
</select></li>
<li><label for="id_email">Email:</label>
<input type="email" name="email" id="id_email" maxlength="320"></li>
<li class="required error"><ul class="errorlist" id="id_age_error">
<li>This field is required.</li></ul>
<label class="required" for="id_age">Age:</label>
<input type="number" name="age" id="id_age" aria-invalid="true" required
aria-describedby="id_age_error">
</li>""",
)
self.assertHTMLEqual(
p.as_p(),
"""
<ul class="errorlist" id="id_name_error"><li>This field is required.</li>
</ul><p class="required error">
<label class="required" for="id_name">Name:</label>
<input type="text" name="name" id="id_name" aria-invalid="true" required
aria-describedby="id_name_error">
</p><p class="required">
<label class="required" for="id_is_cool">Is cool:</label>
<select name="is_cool" id="id_is_cool">
<option value="unknown" selected>Unknown</option>
<option value="true">Yes</option>
<option value="false">No</option>
</select></p>
<p><label for="id_email">Email:</label>
<input type="email" name="email" id="id_email" maxlength="320"></p>
<ul class="errorlist" id="id_age_error"><li>This field is required.</li>
</ul><p class="required error"><label class="required" for="id_age">
Age:</label><input type="number" name="age" id="id_age" aria-invalid="true"
required aria-describedby="id_age_error"></p>""",
)
self.assertHTMLEqual(
p.as_table(),
"""<tr class="required error">
<th><label class="required" for="id_name">Name:</label></th>
<td><ul class="errorlist" id="id_name_error"><li>This field is required.</li></ul>
<input type="text" name="name" id="id_name" aria-invalid="true" required
aria-describedby="id_name_error"></td></tr>
<tr class="required"><th><label class="required" for="id_is_cool">Is cool:</label></th>
<td><select name="is_cool" id="id_is_cool">
<option value="unknown" selected>Unknown</option>
<option value="true">Yes</option>
<option value="false">No</option>
</select></td></tr>
<tr><th><label for="id_email">Email:</label></th><td>
<input type="email" name="email" id="id_email" maxlength="320"></td></tr>
<tr class="required error"><th><label class="required" for="id_age">Age:</label></th>
<td><ul class="errorlist" id="id_age_error"><li>This field is required.</li></ul>
<input type="number" name="age" id="id_age" aria-invalid="true" required
aria-describedby="id_age_error"></td></tr>""",
)
self.assertHTMLEqual(
p.as_div(),
'<div class="required error"><label for="id_name" class="required">Name:'
'</label><ul class="errorlist" id="id_name_error"><li>This field is '
'required.</li></ul><input type="text" name="name" required id="id_name" '
'aria-invalid="true" aria-describedby="id_name_error" /></div>'
'<div class="required"><label for="id_is_cool" class="required">Is cool:'
'</label><select name="is_cool" id="id_is_cool">'
'<option value="unknown" selected>Unknown</option>'
'<option value="true">Yes</option><option value="false">No</option>'
'</select></div><div><label for="id_email">Email:</label>'
'<input type="email" name="email" id="id_email" maxlength="320"/></div>'
'<div class="required error"><label for="id_age" class="required">Age:'
'</label><ul class="errorlist" id="id_age_error"><li>This field is '
'required.</li></ul><input type="number" name="age" required id="id_age" '
'aria-invalid="true" aria-describedby="id_age_error" /></div>',
)
def test_label_has_required_css_class(self):
"""
required_css_class is added to label_tag() and legend_tag() of required
fields.
"""
class SomeForm(Form):
required_css_class = "required"
field = CharField(max_length=10)
field2 = IntegerField(required=False)
f = SomeForm({"field": "test"})
self.assertHTMLEqual(
f["field"].label_tag(),
'<label for="id_field" class="required">Field:</label>',
)
self.assertHTMLEqual(
f["field"].legend_tag(),
'<legend class="required">Field:</legend>',
)
self.assertHTMLEqual(
f["field"].label_tag(attrs={"class": "foo"}),
'<label for="id_field" class="foo required">Field:</label>',
)
self.assertHTMLEqual(
f["field"].legend_tag(attrs={"class": "foo"}),
'<legend class="foo required">Field:</legend>',
)
self.assertHTMLEqual(
f["field2"].label_tag(), '<label for="id_field2">Field2:</label>'
)
self.assertHTMLEqual(
f["field2"].legend_tag(),
"<legend>Field2:</legend>",
)
def test_label_split_datetime_not_displayed(self):
class EventForm(Form):
happened_at = SplitDateTimeField(widget=SplitHiddenDateTimeWidget)
form = EventForm()
self.assertHTMLEqual(
form.as_ul(),
'<input type="hidden" name="happened_at_0" id="id_happened_at_0">'
'<input type="hidden" name="happened_at_1" id="id_happened_at_1">',
)
def test_multivalue_field_validation(self):
def bad_names(value):
if value == "bad value":
raise ValidationError("bad value not allowed")
class NameField(MultiValueField):
def __init__(self, fields=(), *args, **kwargs):
fields = (
CharField(label="First name", max_length=10),
CharField(label="Last name", max_length=10),
)
super().__init__(fields=fields, *args, **kwargs)
def compress(self, data_list):
return " ".join(data_list)
class NameForm(Form):
name = NameField(validators=[bad_names])
form = NameForm(data={"name": ["bad", "value"]})
form.full_clean()
self.assertFalse(form.is_valid())
self.assertEqual(form.errors, {"name": ["bad value not allowed"]})
form = NameForm(data={"name": ["should be overly", "long for the field names"]})
self.assertFalse(form.is_valid())
self.assertEqual(
form.errors,
{
"name": [
"Ensure this value has at most 10 characters (it has 16).",
"Ensure this value has at most 10 characters (it has 24).",
],
},
)
form = NameForm(data={"name": ["fname", "lname"]})
self.assertTrue(form.is_valid())
self.assertEqual(form.cleaned_data, {"name": "fname lname"})
def test_multivalue_deep_copy(self):
"""
#19298 -- MultiValueField needs to override the default as it needs
to deep-copy subfields:
"""
class ChoicesField(MultiValueField):
def __init__(self, fields=(), *args, **kwargs):
fields = (
ChoiceField(label="Rank", choices=((1, 1), (2, 2))),
CharField(label="Name", max_length=10),
)
super().__init__(fields=fields, *args, **kwargs)
field = ChoicesField()
field2 = copy.deepcopy(field)
self.assertIsInstance(field2, ChoicesField)
self.assertIsNot(field2.fields, field.fields)
self.assertIsNot(field2.fields[0].choices, field.fields[0].choices)
def test_multivalue_initial_data(self):
"""
#23674 -- invalid initial data should not break form.changed_data()
"""
class DateAgeField(MultiValueField):
def __init__(self, fields=(), *args, **kwargs):
fields = (DateField(label="Date"), IntegerField(label="Age"))
super().__init__(fields=fields, *args, **kwargs)
class DateAgeForm(Form):
date_age = DateAgeField()
data = {"date_age": ["1998-12-06", 16]}
form = DateAgeForm(data, initial={"date_age": ["200-10-10", 14]})
self.assertTrue(form.has_changed())
def test_multivalue_optional_subfields(self):
class PhoneField(MultiValueField):
def __init__(self, *args, **kwargs):
fields = (
CharField(
label="Country Code",
validators=[
RegexValidator(
r"^\+[0-9]{1,2}$", message="Enter a valid country code."
)
],
),
CharField(label="Phone Number"),
CharField(
label="Extension",
error_messages={"incomplete": "Enter an extension."},
),
CharField(
label="Label", required=False, help_text="E.g. home, work."
),
)
super().__init__(fields, *args, **kwargs)
def compress(self, data_list):
if data_list:
return "%s.%s ext. %s (label: %s)" % tuple(data_list)
return None
# An empty value for any field will raise a `required` error on a
# required `MultiValueField`.
f = PhoneField()
with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
f.clean("")
with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
f.clean(None)
with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
f.clean([])
with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
f.clean(["+61"])
with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
f.clean(["+61", "287654321", "123"])
self.assertEqual(
"+61.287654321 ext. 123 (label: Home)",
f.clean(["+61", "287654321", "123", "Home"]),
)
with self.assertRaisesMessage(ValidationError, "'Enter a valid country code.'"):
f.clean(["61", "287654321", "123", "Home"])
# Empty values for fields will NOT raise a `required` error on an
# optional `MultiValueField`
f = PhoneField(required=False)
self.assertIsNone(f.clean(""))
self.assertIsNone(f.clean(None))
self.assertIsNone(f.clean([]))
self.assertEqual("+61. ext. (label: )", f.clean(["+61"]))
self.assertEqual(
"+61.287654321 ext. 123 (label: )", f.clean(["+61", "287654321", "123"])
)
self.assertEqual(
"+61.287654321 ext. 123 (label: Home)",
f.clean(["+61", "287654321", "123", "Home"]),
)
with self.assertRaisesMessage(ValidationError, "'Enter a valid country code.'"):
f.clean(["61", "287654321", "123", "Home"])
# For a required `MultiValueField` with `require_all_fields=False`, a
# `required` error will only be raised if all fields are empty. Fields
# can individually be required or optional. An empty value for any
# required field will raise an `incomplete` error.
f = PhoneField(require_all_fields=False)
with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
f.clean("")
with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
f.clean(None)
with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
f.clean([])
with self.assertRaisesMessage(ValidationError, "'Enter a complete value.'"):
f.clean(["+61"])
self.assertEqual(
"+61.287654321 ext. 123 (label: )", f.clean(["+61", "287654321", "123"])
)
with self.assertRaisesMessage(
ValidationError, "'Enter a complete value.', 'Enter an extension.'"
):
f.clean(["", "", "", "Home"])
with self.assertRaisesMessage(ValidationError, "'Enter a valid country code.'"):
f.clean(["61", "287654321", "123", "Home"])
# For an optional `MultiValueField` with `require_all_fields=False`, we
# don't get any `required` error but we still get `incomplete` errors.
f = PhoneField(required=False, require_all_fields=False)
self.assertIsNone(f.clean(""))
self.assertIsNone(f.clean(None))
self.assertIsNone(f.clean([]))
with self.assertRaisesMessage(ValidationError, "'Enter a complete value.'"):
f.clean(["+61"])
self.assertEqual(
"+61.287654321 ext. 123 (label: )", f.clean(["+61", "287654321", "123"])
)
with self.assertRaisesMessage(
ValidationError, "'Enter a complete value.', 'Enter an extension.'"
):
f.clean(["", "", "", "Home"])
with self.assertRaisesMessage(ValidationError, "'Enter a valid country code.'"):
f.clean(["61", "287654321", "123", "Home"])
def test_multivalue_optional_subfields_rendering(self):
class PhoneWidget(MultiWidget):
def __init__(self, attrs=None):
widgets = [TextInput(), TextInput()]
super().__init__(widgets, attrs)
def decompress(self, value):
return [None, None]
class PhoneField(MultiValueField):
def __init__(self, *args, **kwargs):
fields = [CharField(), CharField(required=False)]
super().__init__(fields, *args, **kwargs)
class PhoneForm(Form):
phone1 = PhoneField(widget=PhoneWidget)
phone2 = PhoneField(widget=PhoneWidget, required=False)
phone3 = PhoneField(widget=PhoneWidget, require_all_fields=False)
phone4 = PhoneField(
widget=PhoneWidget,
required=False,
require_all_fields=False,
)
form = PhoneForm(auto_id=False)
self.assertHTMLEqual(
form.as_p(),
"""
<p>Phone1:<input type="text" name="phone1_0" required>
<input type="text" name="phone1_1" required></p>
<p>Phone2:<input type="text" name="phone2_0">
<input type="text" name="phone2_1"></p>
<p>Phone3:<input type="text" name="phone3_0" required>
<input type="text" name="phone3_1"></p>
<p>Phone4:<input type="text" name="phone4_0">
<input type="text" name="phone4_1"></p>
""",
)
def test_custom_empty_values(self):
"""
Form fields can customize what is considered as an empty value
for themselves (#19997).
"""
class CustomJSONField(CharField):
empty_values = [None, ""]
def to_python(self, value):
# Fake json.loads
if value == "{}":
return {}
return super().to_python(value)
class JSONForm(Form):
json = CustomJSONField()
form = JSONForm(data={"json": "{}"})
form.full_clean()
self.assertEqual(form.cleaned_data, {"json": {}})
def test_boundfield_label_tag(self):
class SomeForm(Form):
field = CharField()
boundfield = SomeForm()["field"]
testcases = [ # (args, kwargs, expected_label, expected_legend)
# without anything: just print the <label>/<legend>
((), {}, '<label for="id_field">Field:</label>', "<legend>Field:</legend>"),
# passing just one argument: overrides the field's label
(
("custom",),
{},
'<label for="id_field">custom:</label>',
"<legend>custom:</legend>",
),
# the overridden label is escaped
(
("custom&",),
{},
'<label for="id_field">custom&:</label>',
"<legend>custom&:</legend>",
),
(
(mark_safe("custom&"),),
{},
'<label for="id_field">custom&:</label>',
"<legend>custom&:</legend>",
),
# Passing attrs to add extra attributes on the <label>/<legend>
(
(),
{"attrs": {"class": "pretty"}},
'<label for="id_field" class="pretty">Field:</label>',
'<legend class="pretty">Field:</legend>',
),
]
for args, kwargs, expected_label, expected_legend in testcases:
with self.subTest(args=args, kwargs=kwargs):
self.assertHTMLEqual(
boundfield.label_tag(*args, **kwargs),
expected_label,
)
self.assertHTMLEqual(
boundfield.legend_tag(*args, **kwargs),
expected_legend,
)
def test_boundfield_label_tag_no_id(self):
"""
If a widget has no id, label_tag() and legend_tag() return the text
with no surrounding <label>.
"""
class SomeForm(Form):
field = CharField()
boundfield = SomeForm(auto_id="")["field"]
self.assertHTMLEqual(boundfield.label_tag(), "Field:")
self.assertHTMLEqual(boundfield.legend_tag(), "Field:")
self.assertHTMLEqual(boundfield.label_tag("Custom&"), "Custom&:")
self.assertHTMLEqual(boundfield.legend_tag("Custom&"), "Custom&:")
def test_boundfield_label_tag_custom_widget_id_for_label(self):
class CustomIdForLabelTextInput(TextInput):
def id_for_label(self, id):
return "custom_" + id
class EmptyIdForLabelTextInput(TextInput):
def id_for_label(self, id):
return None
class SomeForm(Form):
custom = CharField(widget=CustomIdForLabelTextInput)
empty = CharField(widget=EmptyIdForLabelTextInput)
form = SomeForm()
self.assertHTMLEqual(
form["custom"].label_tag(), '<label for="custom_id_custom">Custom:</label>'
)
self.assertHTMLEqual(
form["custom"].legend_tag(),
"<legend>Custom:</legend>",
)
self.assertHTMLEqual(form["empty"].label_tag(), "<label>Empty:</label>")
self.assertHTMLEqual(form["empty"].legend_tag(), "<legend>Empty:</legend>")
def test_boundfield_empty_label(self):
class SomeForm(Form):
field = CharField(label="")
boundfield = SomeForm()["field"]
self.assertHTMLEqual(boundfield.label_tag(), '<label for="id_field"></label>')
self.assertHTMLEqual(
boundfield.legend_tag(),
"<legend></legend>",
)
def test_boundfield_id_for_label(self):
class SomeForm(Form):
field = CharField(label="")
self.assertEqual(SomeForm()["field"].id_for_label, "id_field")
def test_boundfield_id_for_label_override_by_attrs(self):
"""
If an id is provided in `Widget.attrs`, it overrides the generated ID,
unless it is `None`.
"""
class SomeForm(Form):
field = CharField(widget=TextInput(attrs={"id": "myCustomID"}))
field_none = CharField(widget=TextInput(attrs={"id": None}))
form = SomeForm()
self.assertEqual(form["field"].id_for_label, "myCustomID")
self.assertEqual(form["field_none"].id_for_label, "id_field_none")
def test_boundfield_subwidget_id_for_label(self):
"""
If auto_id is provided when initializing the form, the generated ID in
subwidgets must reflect that prefix.
"""
class SomeForm(Form):
field = MultipleChoiceField(
choices=[("a", "A"), ("b", "B")],
widget=CheckboxSelectMultiple,
)
form = SomeForm(auto_id="prefix_%s")
subwidgets = form["field"].subwidgets
self.assertEqual(subwidgets[0].id_for_label, "prefix_field_0")
self.assertEqual(subwidgets[1].id_for_label, "prefix_field_1")
def test_boundfield_widget_type(self):
class SomeForm(Form):
first_name = CharField()
birthday = SplitDateTimeField(widget=SplitHiddenDateTimeWidget)
f = SomeForm()
self.assertEqual(f["first_name"].widget_type, "text")
self.assertEqual(f["birthday"].widget_type, "splithiddendatetime")
def test_boundfield_css_classes(self):
form = Person()
field = form["first_name"]
self.assertEqual(field.css_classes(), "")
self.assertEqual(field.css_classes(extra_classes=""), "")
self.assertEqual(field.css_classes(extra_classes="test"), "test")
self.assertEqual(field.css_classes(extra_classes="test test"), "test")
def test_label_suffix_override(self):
"""
BoundField label_suffix (if provided) overrides Form label_suffix
"""
class SomeForm(Form):
field = CharField()
boundfield = SomeForm(label_suffix="!")["field"]
self.assertHTMLEqual(
boundfield.label_tag(label_suffix="$"),
'<label for="id_field">Field$</label>',
)
self.assertHTMLEqual(
boundfield.legend_tag(label_suffix="$"),
"<legend>Field$</legend>",
)
def test_error_dict(self):
class MyForm(Form):
foo = CharField()
bar = CharField()
def clean(self):
raise ValidationError(
"Non-field error.", code="secret", params={"a": 1, "b": 2}
)
form = MyForm({})
self.assertIs(form.is_valid(), False)
errors = form.errors.as_text()
control = [
"* foo\n * This field is required.",
"* bar\n * This field is required.",
"* __all__\n * Non-field error.",
]
for error in control:
self.assertIn(error, errors)
errors = form.errors.as_ul()
control = [
'<li>foo<ul class="errorlist" id="id_foo_error"><li>This field is required.'
"</li></ul></li>",
'<li>bar<ul class="errorlist" id="id_bar_error"><li>This field is required.'
"</li></ul></li>",
'<li>__all__<ul class="errorlist nonfield"><li>Non-field error.</li></ul>'
"</li>",
]
for error in control:
self.assertInHTML(error, errors)
errors = form.errors.get_json_data()
control = {
"foo": [{"code": "required", "message": "This field is required."}],
"bar": [{"code": "required", "message": "This field is required."}],
"__all__": [{"code": "secret", "message": "Non-field error."}],
}
self.assertEqual(errors, control)
self.assertEqual(json.dumps(errors), form.errors.as_json())
def test_error_dict_as_json_escape_html(self):
"""#21962 - adding html escape flag to ErrorDict"""
class MyForm(Form):
foo = CharField()
bar = CharField()
def clean(self):
raise ValidationError(
"<p>Non-field error.</p>",
code="secret",
params={"a": 1, "b": 2},
)
control = {
"foo": [{"code": "required", "message": "This field is required."}],
"bar": [{"code": "required", "message": "This field is required."}],
"__all__": [{"code": "secret", "message": "<p>Non-field error.</p>"}],
}
form = MyForm({})
self.assertFalse(form.is_valid())
errors = json.loads(form.errors.as_json())
self.assertEqual(errors, control)
escaped_error = "<p>Non-field error.</p>"
self.assertEqual(
form.errors.get_json_data(escape_html=True)["__all__"][0]["message"],
escaped_error,
)
errors = json.loads(form.errors.as_json(escape_html=True))
control["__all__"][0]["message"] = escaped_error
self.assertEqual(errors, control)
def test_error_list(self):
e = ErrorList()
e.append("Foo")
e.append(ValidationError("Foo%(bar)s", code="foobar", params={"bar": "bar"}))
self.assertIsInstance(e, list)
self.assertIn("Foo", e)
self.assertIn("Foo", ValidationError(e))
self.assertEqual(e.as_text(), "* Foo\n* Foobar")
self.assertEqual(
e.as_ul(), '<ul class="errorlist"><li>Foo</li><li>Foobar</li></ul>'
)
errors = e.get_json_data()
self.assertEqual(
errors,
[{"message": "Foo", "code": ""}, {"message": "Foobar", "code": "foobar"}],
)
self.assertEqual(json.dumps(errors), e.as_json())
def test_error_list_class_not_specified(self):
e = ErrorList()
e.append("Foo")
e.append(ValidationError("Foo%(bar)s", code="foobar", params={"bar": "bar"}))
self.assertEqual(
e.as_ul(), '<ul class="errorlist"><li>Foo</li><li>Foobar</li></ul>'
)
def test_error_list_class_has_one_class_specified(self):
e = ErrorList(error_class="foobar-error-class")
e.append("Foo")
e.append(ValidationError("Foo%(bar)s", code="foobar", params={"bar": "bar"}))
self.assertEqual(
e.as_ul(),
'<ul class="errorlist foobar-error-class"><li>Foo</li><li>Foobar</li></ul>',
)
def test_error_list_with_hidden_field_errors_has_correct_class(self):
class Person(Form):
first_name = CharField()
last_name = CharField(widget=HiddenInput)
p = Person({"first_name": "John"})
self.assertHTMLEqual(
p.as_ul(),
"""<li><ul class="errorlist nonfield">
<li>(Hidden field last_name) This field is required.</li></ul></li><li>
<label for="id_first_name">First name:</label>
<input id="id_first_name" name="first_name" type="text" value="John" required>
<input id="id_last_name" name="last_name" type="hidden"></li>""",
)
self.assertHTMLEqual(
p.as_p(),
"""
<ul class="errorlist nonfield">
<li>(Hidden field last_name) This field is required.</li></ul>
<p><label for="id_first_name">First name:</label>
<input id="id_first_name" name="first_name" type="text" value="John"
required>
<input id="id_last_name" name="last_name" type="hidden"></p>
""",
)
self.assertHTMLEqual(
p.as_table(),
"""<tr><td colspan="2"><ul class="errorlist nonfield">
<li>(Hidden field last_name) This field is required.</li></ul></td></tr>
<tr><th><label for="id_first_name">First name:</label></th><td>
<input id="id_first_name" name="first_name" type="text" value="John" required>
<input id="id_last_name" name="last_name" type="hidden"></td></tr>""",
)
self.assertHTMLEqual(
p.as_div(),
'<ul class="errorlist nonfield"><li>(Hidden field last_name) This field '
'is required.</li></ul><div><label for="id_first_name">First name:</label>'
'<input id="id_first_name" name="first_name" type="text" value="John" '
'required><input id="id_last_name" name="last_name" type="hidden"></div>',
)
def test_error_list_with_non_field_errors_has_correct_class(self):
class Person(Form):
first_name = CharField()
last_name = CharField()
def clean(self):
raise ValidationError("Generic validation error")
p = Person({"first_name": "John", "last_name": "Lennon"})
self.assertHTMLEqual(
str(p.non_field_errors()),
'<ul class="errorlist nonfield"><li>Generic validation error</li></ul>',
)
self.assertHTMLEqual(
p.as_ul(),
"""<li>
<ul class="errorlist nonfield"><li>Generic validation error</li></ul></li>
<li><label for="id_first_name">First name:</label>
<input id="id_first_name" name="first_name" type="text" value="John" required></li>
<li><label for="id_last_name">Last name:</label>
<input id="id_last_name" name="last_name" type="text" value="Lennon" required></li>""",
)
self.assertHTMLEqual(
p.non_field_errors().as_text(), "* Generic validation error"
)
self.assertHTMLEqual(
p.as_p(),
"""<ul class="errorlist nonfield"><li>Generic validation error</li></ul>
<p><label for="id_first_name">First name:</label>
<input id="id_first_name" name="first_name" type="text" value="John" required></p>
<p><label for="id_last_name">Last name:</label>
<input id="id_last_name" name="last_name" type="text" value="Lennon" required></p>""",
)
self.assertHTMLEqual(
p.as_table(),
"""
<tr><td colspan="2"><ul class="errorlist nonfield">
<li>Generic validation error</li></ul></td></tr>
<tr><th><label for="id_first_name">First name:</label></th><td>
<input id="id_first_name" name="first_name" type="text" value="John"
required>
</td></tr>
<tr><th><label for="id_last_name">Last name:</label></th><td>
<input id="id_last_name" name="last_name" type="text" value="Lennon"
required>
</td></tr>
""",
)
self.assertHTMLEqual(
p.as_div(),
'<ul class="errorlist nonfield"><li>Generic validation error</li></ul>'
'<div><label for="id_first_name">First name:</label><input '
'id="id_first_name" name="first_name" type="text" value="John" required>'
'</div><div><label for="id_last_name">Last name:</label><input '
'id="id_last_name" name="last_name" type="text" value="Lennon" required>'
"</div>",
)
def test_error_escaping(self):
class TestForm(Form):
hidden = CharField(widget=HiddenInput(), required=False)
visible = CharField()
def clean_hidden(self):
raise ValidationError('Foo & "bar"!')
clean_visible = clean_hidden
form = TestForm({"hidden": "a", "visible": "b"})
form.is_valid()
self.assertHTMLEqual(
form.as_ul(),
'<li><ul class="errorlist nonfield">'
"<li>(Hidden field hidden) Foo & "bar"!</li></ul></li>"
'<li><ul class="errorlist" id="id_visible_error"><li>Foo & '
""bar"!</li></ul>"
'<label for="id_visible">Visible:</label> '
'<input type="text" name="visible" aria-invalid="true" value="b" '
'id="id_visible" required aria-describedby="id_visible_error">'
'<input type="hidden" name="hidden" value="a" id="id_hidden"></li>',
)
def test_baseform_repr(self):
"""
BaseForm.__repr__() should contain some basic information about the
form.
"""
p = Person()
self.assertEqual(
repr(p),
"<Person bound=False, valid=Unknown, "
"fields=(first_name;last_name;birthday)>",
)
p = Person(
{"first_name": "John", "last_name": "Lennon", "birthday": "1940-10-9"}
)
self.assertEqual(
repr(p),
"<Person bound=True, valid=Unknown, "
"fields=(first_name;last_name;birthday)>",
)
p.is_valid()
self.assertEqual(
repr(p),
"<Person bound=True, valid=True, fields=(first_name;last_name;birthday)>",
)
p = Person(
{"first_name": "John", "last_name": "Lennon", "birthday": "fakedate"}
)
p.is_valid()
self.assertEqual(
repr(p),
"<Person bound=True, valid=False, fields=(first_name;last_name;birthday)>",
)
def test_baseform_repr_dont_trigger_validation(self):
"""
BaseForm.__repr__() shouldn't trigger the form validation.
"""
p = Person(
{"first_name": "John", "last_name": "Lennon", "birthday": "fakedate"}
)
repr(p)
with self.assertRaises(AttributeError):
p.cleaned_data
self.assertFalse(p.is_valid())
self.assertEqual(p.cleaned_data, {"first_name": "John", "last_name": "Lennon"})
def test_accessing_clean(self):
class UserForm(Form):
username = CharField(max_length=10)
password = CharField(widget=PasswordInput)
def clean(self):
data = self.cleaned_data
if not self.errors:
data["username"] = data["username"].lower()
return data
f = UserForm({"username": "SirRobin", "password": "blue"})
self.assertTrue(f.is_valid())
self.assertEqual(f.cleaned_data["username"], "sirrobin")
def test_changing_cleaned_data_nothing_returned(self):
class UserForm(Form):
username = CharField(max_length=10)
password = CharField(widget=PasswordInput)
def clean(self):
self.cleaned_data["username"] = self.cleaned_data["username"].lower()
# don't return anything
f = UserForm({"username": "SirRobin", "password": "blue"})
self.assertTrue(f.is_valid())
self.assertEqual(f.cleaned_data["username"], "sirrobin")
def test_changing_cleaned_data_in_clean(self):
class UserForm(Form):
username = CharField(max_length=10)
password = CharField(widget=PasswordInput)
def clean(self):
data = self.cleaned_data
# Return a different dict. We have not changed
# self.cleaned_data.
return {
"username": data["username"].lower(),
"password": "this_is_not_a_secret",
}
f = UserForm({"username": "SirRobin", "password": "blue"})
self.assertTrue(f.is_valid())
self.assertEqual(f.cleaned_data["username"], "sirrobin")
def test_multipart_encoded_form(self):
class FormWithoutFile(Form):
username = CharField()
class FormWithFile(Form):
username = CharField()
file = FileField()
class FormWithImage(Form):
image = ImageField()
self.assertFalse(FormWithoutFile().is_multipart())
self.assertTrue(FormWithFile().is_multipart())
self.assertTrue(FormWithImage().is_multipart())
def test_html_safe(self):
class SimpleForm(Form):
username = CharField()
form = SimpleForm()
self.assertTrue(hasattr(SimpleForm, "__html__"))
self.assertEqual(str(form), form.__html__())
self.assertTrue(hasattr(form["username"], "__html__"))
self.assertEqual(str(form["username"]), form["username"].__html__())
def test_use_required_attribute_true(self):
class MyForm(Form):
use_required_attribute = True
f1 = CharField(max_length=30)
f2 = CharField(max_length=30, required=False)
f3 = CharField(widget=Textarea)
f4 = ChoiceField(choices=[("P", "Python"), ("J", "Java")])
form = MyForm()
self.assertHTMLEqual(
form.as_p(),
'<p><label for="id_f1">F1:</label>'
'<input id="id_f1" maxlength="30" name="f1" type="text" required></p>'
'<p><label for="id_f2">F2:</label>'
'<input id="id_f2" maxlength="30" name="f2" type="text"></p>'
'<p><label for="id_f3">F3:</label>'
'<textarea cols="40" id="id_f3" name="f3" rows="10" required>'
"</textarea></p>"
'<p><label for="id_f4">F4:</label> <select id="id_f4" name="f4">'
'<option value="P">Python</option>'
'<option value="J">Java</option>'
"</select></p>",
)
self.assertHTMLEqual(
form.as_ul(),
'<li><label for="id_f1">F1:</label> '
'<input id="id_f1" maxlength="30" name="f1" type="text" required></li>'
'<li><label for="id_f2">F2:</label>'
'<input id="id_f2" maxlength="30" name="f2" type="text"></li>'
'<li><label for="id_f3">F3:</label>'
'<textarea cols="40" id="id_f3" name="f3" rows="10" required>'
"</textarea></li>"
'<li><label for="id_f4">F4:</label> <select id="id_f4" name="f4">'
'<option value="P">Python</option>'
'<option value="J">Java</option>'
"</select></li>",
)
self.assertHTMLEqual(
form.as_table(),
'<tr><th><label for="id_f1">F1:</label></th>'
'<td><input id="id_f1" maxlength="30" name="f1" type="text" required>'
"</td></tr>"
'<tr><th><label for="id_f2">F2:</label></th>'
'<td><input id="id_f2" maxlength="30" name="f2" type="text"></td></tr>'
'<tr><th><label for="id_f3">F3:</label></th>'
'<td><textarea cols="40" id="id_f3" name="f3" rows="10" required>'
"</textarea></td></tr>"
'<tr><th><label for="id_f4">F4:</label></th><td>'
'<select id="id_f4" name="f4">'
'<option value="P">Python</option>'
'<option value="J">Java</option>'
"</select></td></tr>",
)
self.assertHTMLEqual(
form.render(form.template_name_div),
'<div><label for="id_f1">F1:</label><input id="id_f1" maxlength="30" '
'name="f1" type="text" required></div><div><label for="id_f2">F2:</label>'
'<input id="id_f2" maxlength="30" name="f2" type="text"></div><div><label '
'for="id_f3">F3:</label><textarea cols="40" id="id_f3" name="f3" '
'rows="10" required></textarea></div><div><label for="id_f4">F4:</label>'
'<select id="id_f4" name="f4"><option value="P">Python</option>'
'<option value="J">Java</option></select></div>',
)
def test_use_required_attribute_false(self):
class MyForm(Form):
use_required_attribute = False
f1 = CharField(max_length=30)
f2 = CharField(max_length=30, required=False)
f3 = CharField(widget=Textarea)
f4 = ChoiceField(choices=[("P", "Python"), ("J", "Java")])
form = MyForm()
self.assertHTMLEqual(
form.as_p(),
'<p><label for="id_f1">F1:</label>'
'<input id="id_f1" maxlength="30" name="f1" type="text"></p>'
'<p><label for="id_f2">F2:</label>'
'<input id="id_f2" maxlength="30" name="f2" type="text"></p>'
'<p><label for="id_f3">F3:</label>'
'<textarea cols="40" id="id_f3" name="f3" rows="10"></textarea></p>'
'<p><label for="id_f4">F4:</label> <select id="id_f4" name="f4">'
'<option value="P">Python</option>'
'<option value="J">Java</option>'
"</select></p>",
)
self.assertHTMLEqual(
form.as_ul(),
'<li><label for="id_f1">F1:</label>'
'<input id="id_f1" maxlength="30" name="f1" type="text"></li>'
'<li><label for="id_f2">F2:</label>'
'<input id="id_f2" maxlength="30" name="f2" type="text"></li>'
'<li><label for="id_f3">F3:</label>'
'<textarea cols="40" id="id_f3" name="f3" rows="10"></textarea></li>'
'<li><label for="id_f4">F4:</label> <select id="id_f4" name="f4">'
'<option value="P">Python</option>'
'<option value="J">Java</option>'
"</select></li>",
)
self.assertHTMLEqual(
form.as_table(),
'<tr><th><label for="id_f1">F1:</label></th>'
'<td><input id="id_f1" maxlength="30" name="f1" type="text"></td></tr>'
'<tr><th><label for="id_f2">F2:</label></th>'
'<td><input id="id_f2" maxlength="30" name="f2" type="text"></td></tr>'
'<tr><th><label for="id_f3">F3:</label></th><td>'
'<textarea cols="40" id="id_f3" name="f3" rows="10">'
"</textarea></td></tr>"
'<tr><th><label for="id_f4">F4:</label></th><td>'
'<select id="id_f4" name="f4">'
'<option value="P">Python</option>'
'<option value="J">Java</option>'
"</select></td></tr>",
)
self.assertHTMLEqual(
form.render(form.template_name_div),
'<div><label for="id_f1">F1:</label> <input id="id_f1" maxlength="30" '
'name="f1" type="text"></div><div><label for="id_f2">F2:</label>'
'<input id="id_f2" maxlength="30" name="f2" type="text"></div><div>'
'<label for="id_f3">F3:</label> <textarea cols="40" id="id_f3" name="f3" '
'rows="10"></textarea></div><div><label for="id_f4">F4:</label>'
'<select id="id_f4" name="f4"><option value="P">Python</option>'
'<option value="J">Java</option></select></div>',
)
def test_only_hidden_fields(self):
# A form with *only* hidden fields that has errors is going to be very
# unusual.
class HiddenForm(Form):
data = IntegerField(widget=HiddenInput)
f = HiddenForm({})
self.assertHTMLEqual(
f.as_p(),
'<ul class="errorlist nonfield">'
"<li>(Hidden field data) This field is required.</li></ul>\n<p> "
'<input type="hidden" name="data" id="id_data"></p>',
)
self.assertHTMLEqual(
f.as_table(),
'<tr><td colspan="2"><ul class="errorlist nonfield">'
"<li>(Hidden field data) This field is required.</li></ul>"
'<input type="hidden" name="data" id="id_data"></td></tr>',
)
def test_field_named_data(self):
class DataForm(Form):
data = CharField(max_length=10)
f = DataForm({"data": "xyzzy"})
self.assertTrue(f.is_valid())
self.assertEqual(f.cleaned_data, {"data": "xyzzy"})
def test_empty_data_files_multi_value_dict(self):
p = Person()
self.assertIsInstance(p.data, MultiValueDict)
self.assertIsInstance(p.files, MultiValueDict)
def test_field_deep_copy_error_messages(self):
class CustomCharField(CharField):
def __init__(self, **kwargs):
kwargs["error_messages"] = {"invalid": "Form custom error message."}
super().__init__(**kwargs)
field = CustomCharField()
field_copy = copy.deepcopy(field)
self.assertIsInstance(field_copy, CustomCharField)
self.assertIsNot(field_copy.error_messages, field.error_messages)
def test_label_does_not_include_new_line(self):
form = Person()
field = form["first_name"]
self.assertEqual(
field.label_tag(), '<label for="id_first_name">First name:</label>'
)
self.assertEqual(
field.legend_tag(),
"<legend>First name:</legend>",
)
@override_settings(USE_THOUSAND_SEPARATOR=True)
def test_label_attrs_not_localized(self):
form = Person()
field = form["first_name"]
self.assertHTMLEqual(
field.label_tag(attrs={"number": 9999}),
'<label number="9999" for="id_first_name">First name:</label>',
)
self.assertHTMLEqual(
field.legend_tag(attrs={"number": 9999}),
'<legend number="9999">First name:</legend>',
)
def test_remove_cached_field(self):
class TestForm(Form):
name = CharField(max_length=10)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# Populate fields cache.
[field for field in self]
# Removed cached field.
del self.fields["name"]
f = TestForm({"name": "abcde"})
with self.assertRaises(KeyError):
f["name"]
def test_aria_describedby_property(self):
class TestForm(Form):
name = CharField(help_text="Some help text")
form = TestForm({"name": "MyName"})
self.assertEqual(form["name"].aria_describedby, "id_name_helptext")
form = TestForm(auto_id=None)
self.assertEqual(form["name"].aria_describedby, "")
class TestFormHidden(Form):
name = CharField(help_text="Some help text", widget=HiddenInput)
form = TestFormHidden()
self.assertEqual(form["name"].aria_describedby, "")
class TestFormWithAttrs(Form):
name = CharField(widget=TextInput(attrs={"aria-describedby": "my-id"}))
form = TestFormWithAttrs({"name": "MyName"})
self.assertIs(form["name"].aria_describedby, None)
class TestFormWithoutHelpText(Form):
name = CharField()
form = TestFormWithoutHelpText()
self.assertEqual(form["name"].aria_describedby, "")
@jinja2_tests
| FormsTestCase |
python | ansible__ansible | test/units/plugins/callback/test_callback.py | {
"start": 1062,
"end": 2254
} | class ____(unittest.TestCase):
# FIXME: This doesn't really test anything...
def test_init(self):
CallbackBase()
def test_display(self):
display_mock = MagicMock()
display_mock.verbosity = 0
cb = CallbackBase(display=display_mock)
self.assertIs(cb._display, display_mock)
def test_display_verbose(self):
display_mock = MagicMock()
display_mock.verbosity = 5
cb = CallbackBase(display=display_mock)
self.assertIs(cb._display, display_mock)
def test_host_label(self):
result = CallbackTaskResult(host=Host('host1'), task=mock_task, return_data={}, task_fields={})
self.assertEqual(CallbackBase.host_label(result), 'host1')
def test_host_label_delegated(self):
mock_task.delegate_to = 'host2'
result = CallbackTaskResult(
host=Host('host1'),
task=mock_task,
return_data={'_ansible_delegated_vars': {'ansible_host': 'host2'}},
task_fields={},
)
self.assertEqual(CallbackBase.host_label(result), 'host1 -> host2')
# TODO: import callback module so we can patch callback.cli/callback.C
| TestCallback |
python | dask__distributed | distributed/comm/ws.py | {
"start": 14113,
"end": 14634
} | class ____(WSConnector):
prefix = "wss://"
comm_class = WSS
def _get_connect_args(self, **connection_args):
wss_args = {
"ssl_options": connection_args.get("ssl_context"),
**connection_args.get("extra_conn_args", {}),
}
if connection_args.get("server_hostname"):
wss_args["headers"] = {
**wss_args.get("headers", {}),
**{"Host": connection_args["server_hostname"]},
}
return wss_args
| WSSConnector |
python | RaRe-Technologies__gensim | gensim/test/test_text_analysis.py | {
"start": 5423,
"end": 6474
} | class ____(unittest.TestCase):
def setUp(self):
self.dictionary = BaseTestCases.TextAnalyzerTestBase.dictionary
self.top_ids = BaseTestCases.TextAnalyzerTestBase.top_ids
self.corpus = \
[self.dictionary.doc2bow(doc) for doc in BaseTestCases.TextAnalyzerTestBase.texts]
def test_index_accumulation(self):
accumulator = CorpusAccumulator(self.top_ids).accumulate(self.corpus)
inverted_index = accumulator.index_to_dict()
expected = {
10: {0, 2, 3},
15: {0},
20: {0},
21: {1, 2, 3},
17: {1, 2}
}
self.assertDictEqual(expected, inverted_index)
self.assertEqual(3, accumulator.get_occurrences(10))
self.assertEqual(2, accumulator.get_occurrences(17))
self.assertEqual(2, accumulator.get_co_occurrences(10, 21))
self.assertEqual(1, accumulator.get_co_occurrences(10, 17))
if __name__ == '__main__':
logging.root.setLevel(logging.WARNING)
unittest.main()
| TestCorpusAnalyzer |
python | kamyu104__LeetCode-Solutions | Python/median-of-a-row-wise-sorted-matrix.py | {
"start": 120,
"end": 646
} | class ____(object):
def matrixMedian(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
def check(x):
return sum(bisect_right(row, x) for row in grid) > (len(grid)*len(grid[0]))//2
left, right = min(row[0] for row in grid), max(row[-1] for row in grid)
while left <= right:
mid = left + (right-left)//2
if check(mid):
right = mid-1
else:
left = mid+1
return left
| Solution |
python | getsentry__sentry | src/sentry/api/serializers/models/recentsearch.py | {
"start": 134,
"end": 487
} | class ____(Serializer):
def serialize(self, obj, attrs, user, **kwargs):
return {
"id": str(obj.id),
"organizationId": str(obj.organization_id),
"type": obj.type,
"query": obj.query,
"lastSeen": obj.last_seen,
"dateCreated": obj.date_added,
}
| RecentSearchSerializer |
python | Textualize__textual | tests/test_animator.py | {
"start": 226,
"end": 506
} | class ____:
"""An animatable object."""
def __init__(self, value):
self.value = value
def blend(self, destination: Animatable, factor: float) -> Animatable:
return Animatable(self.value + (destination.value - self.value) * factor)
@dataclass
| Animatable |
python | jmcnamara__XlsxWriter | xlsxwriter/color.py | {
"start": 2509,
"end": 2625
} | class ____(Enum):
"""
Enum to represent different types of URLS.
"""
RGB = 1
THEME = 2
| ColorTypes |
python | django__django | tests/servers/test_basehttp.py | {
"start": 319,
"end": 490
} | class ____(ThreadingMixIn):
def __init__(self, **kwargs):
self.__dict__.update(kwargs)
def sendall(self, data):
self.makefile("wb").write(data)
| Stub |
python | python-excel__xlwt | xlwt/Formatting.py | {
"start": 6596,
"end": 7900
} | class ____(object):
NO_LINE = 0x00
THIN = 0x01
MEDIUM = 0x02
DASHED = 0x03
DOTTED = 0x04
THICK = 0x05
DOUBLE = 0x06
HAIR = 0x07
#The following for BIFF8
MEDIUM_DASHED = 0x08
THIN_DASH_DOTTED = 0x09
MEDIUM_DASH_DOTTED = 0x0A
THIN_DASH_DOT_DOTTED = 0x0B
MEDIUM_DASH_DOT_DOTTED = 0x0C
SLANTED_MEDIUM_DASH_DOTTED = 0x0D
NEED_DIAG1 = 0x01
NEED_DIAG2 = 0x01
NO_NEED_DIAG1 = 0x00
NO_NEED_DIAG2 = 0x00
def __init__(self):
self.left = self.NO_LINE
self.right = self.NO_LINE
self.top = self.NO_LINE
self.bottom = self.NO_LINE
self.diag = self.NO_LINE
self.left_colour = 0x40
self.right_colour = 0x40
self.top_colour = 0x40
self.bottom_colour = 0x40
self.diag_colour = 0x40
self.need_diag1 = self.NO_NEED_DIAG1
self.need_diag2 = self.NO_NEED_DIAG2
def _search_key(self):
return (
self.left, self.right, self.top, self.bottom, self.diag,
self.left_colour, self.right_colour, self.top_colour,
self.bottom_colour, self.diag_colour,
self.need_diag1, self.need_diag2,
)
| Borders |
python | bokeh__bokeh | tests/unit/bokeh/core/property/test_visual.py | {
"start": 10865,
"end": 12195
} | class ____:
def test_valid_no_datetime(self) -> None:
prop = bcpv.MinMaxBounds(accept_datetime=False)
assert prop.is_valid('auto')
assert prop.is_valid((12, 13))
assert prop.is_valid((-32, -13))
assert prop.is_valid((12.1, 13.1))
assert prop.is_valid((None, 13.1))
assert prop.is_valid((-22, None))
def test_invalid_no_datetime(self) -> None:
prop = bcpv.MinMaxBounds(accept_datetime=False)
assert not prop.is_valid(None)
assert not prop.is_valid('string')
assert not prop.is_valid(12)
assert not prop.is_valid(('a', 'b'))
assert not prop.is_valid((13, 12))
assert not prop.is_valid((13.1, 12.2))
assert not prop.is_valid((datetime.date(2012, 10, 1), datetime.date(2012, 12, 2)))
def test_MinMaxBounds_with_datetime(self) -> None:
prop = bcpv.MinMaxBounds(accept_datetime=True)
assert prop.is_valid((datetime.datetime(2012, 10, 1), datetime.datetime(2012, 12, 2)))
assert not prop.is_valid((datetime.datetime(2012, 10, 1), 22))
def test_has_ref(self) -> None:
prop = bcpv.MinMaxBounds()
assert not prop.has_ref
def test_str(self) -> None:
prop = bcpv.MinMaxBounds()
assert str(prop).startswith("MinMaxBounds(")
| Test_MinMaxBounds |
python | celery__celery | celery/backends/asynchronous.py | {
"start": 585,
"end": 1229
} | class ____:
"""
An adapted eventlet event, designed to match the API of `threading.Event` and
`gevent.event.Event`.
"""
def __init__(self):
import eventlet
self.evt = eventlet.Event()
def is_set(self):
return self.evt.ready()
def set(self):
return self.evt.send()
def wait(self, timeout=None):
return self.evt.wait(timeout)
drainers = {}
def register_drainer(name):
"""Decorator used to register a new result drainer type."""
def _inner(cls):
drainers[name] = cls
return cls
return _inner
@register_drainer('default')
| EventletAdaptedEvent |
python | mlflow__mlflow | mlflow/telemetry/events.py | {
"start": 7874,
"end": 8263
} | class ____(Event):
name: str = "log_batch"
@classmethod
def parse(cls, arguments: dict[str, Any]) -> dict[str, Any] | None:
return {
"metrics": bool(arguments.get("metrics")),
"params": bool(arguments.get("params")),
"tags": bool(arguments.get("tags")),
"synchronous": arguments.get("synchronous"),
}
| LogBatchEvent |
python | walkccc__LeetCode | solutions/1457. Pseudo-Palindromic Paths in a Binary Tree/1457.py | {
"start": 0,
"end": 466
} | class ____:
def pseudoPalindromicPaths(self, root: TreeNode | None) -> int:
ans = 0
def dfs(root: TreeNode | None, path: int) -> None:
nonlocal ans
if not root:
return
if not root.left and not root.right:
path ^= 1 << root.val
if path & (path - 1) == 0:
ans += 1
return
dfs(root.left, path ^ 1 << root.val)
dfs(root.right, path ^ 1 << root.val)
dfs(root, 0)
return ans
| Solution |
python | numba__numba | numba/tests/test_parallel_backend.py | {
"start": 2498,
"end": 2869
} | class ____(object):
def __init__(self, runner, mask, **options):
self.runner = runner
self.mask = mask
def __call__(self):
if self.mask:
# Tests are all run in isolated subprocesses, so we
# don't have to worry about this affecting other tests
set_num_threads(self.mask)
self.runner()
| mask_runner |
python | facebook__pyre-check | tools/incremental_test/specification.py | {
"start": 11508,
"end": 11863
} | class ____(RepositoryUpdate):
_updates: List[SingleUpdate]
def to_json(self) -> Dict[str, Any]:
return {
"kind": "batch",
"updates": [update.to_json() for update in self._updates],
}
def update_steps(self) -> List[SingleUpdate]:
return self._updates
@dataclass(frozen=True)
| BatchRepositoryUpdate |
python | ray-project__ray | python/ray/util/scheduling_strategies.py | {
"start": 5086,
"end": 5524
} | class ____:
"""An expression used to select node by node's labels
Attributes:
key: the key of label
operator: In、NotIn、Exists、DoesNotExist
"""
def __init__(self, key: str, operator: Union[In, NotIn, Exists, DoesNotExist]):
self.key = key
self.operator = operator
LabelMatchExpressionsT = Dict[str, Union[In, NotIn, Exists, DoesNotExist]]
@PublicAPI(stability="alpha")
| _LabelMatchExpression |
python | mwaskom__seaborn | tests/test_statistics.py | {
"start": 793,
"end": 4122
} | class ____:
def integrate(self, y, x):
y = np.asarray(y)
x = np.asarray(x)
dx = np.diff(x)
return (dx * y[:-1] + dx * y[1:]).sum() / 2
def test_gridsize(self, rng):
x = rng.normal(0, 3, 1000)
n = 200
kde = KDE(gridsize=n)
density, support = kde(x)
assert density.size == n
assert support.size == n
def test_cut(self, rng):
x = rng.normal(0, 3, 1000)
kde = KDE(cut=0)
_, support = kde(x)
assert support.min() == x.min()
assert support.max() == x.max()
cut = 2
bw_scale = .5
bw = x.std() * bw_scale
kde = KDE(cut=cut, bw_method=bw_scale, gridsize=1000)
_, support = kde(x)
assert support.min() == pytest.approx(x.min() - bw * cut, abs=1e-2)
assert support.max() == pytest.approx(x.max() + bw * cut, abs=1e-2)
def test_clip(self, rng):
x = rng.normal(0, 3, 100)
clip = -1, 1
kde = KDE(clip=clip)
_, support = kde(x)
assert support.min() >= clip[0]
assert support.max() <= clip[1]
def test_density_normalization(self, rng):
x = rng.normal(0, 3, 1000)
kde = KDE()
density, support = kde(x)
assert self.integrate(density, support) == pytest.approx(1, abs=1e-5)
@pytest.mark.skipif(_no_scipy, reason="Test requires scipy")
def test_cumulative(self, rng):
x = rng.normal(0, 3, 1000)
kde = KDE(cumulative=True)
density, _ = kde(x)
assert density[0] == pytest.approx(0, abs=1e-5)
assert density[-1] == pytest.approx(1, abs=1e-5)
def test_cached_support(self, rng):
x = rng.normal(0, 3, 100)
kde = KDE()
kde.define_support(x)
_, support = kde(x[(x > -1) & (x < 1)])
assert_array_equal(support, kde.support)
def test_bw_method(self, rng):
x = rng.normal(0, 3, 100)
kde1 = KDE(bw_method=.2)
kde2 = KDE(bw_method=2)
d1, _ = kde1(x)
d2, _ = kde2(x)
assert np.abs(np.diff(d1)).mean() > np.abs(np.diff(d2)).mean()
def test_bw_adjust(self, rng):
x = rng.normal(0, 3, 100)
kde1 = KDE(bw_adjust=.2)
kde2 = KDE(bw_adjust=2)
d1, _ = kde1(x)
d2, _ = kde2(x)
assert np.abs(np.diff(d1)).mean() > np.abs(np.diff(d2)).mean()
def test_bivariate_grid(self, rng):
n = 100
x, y = rng.normal(0, 3, (2, 50))
kde = KDE(gridsize=n)
density, (xx, yy) = kde(x, y)
assert density.shape == (n, n)
assert xx.size == n
assert yy.size == n
def test_bivariate_normalization(self, rng):
x, y = rng.normal(0, 3, (2, 50))
kde = KDE(gridsize=100)
density, (xx, yy) = kde(x, y)
dx = xx[1] - xx[0]
dy = yy[1] - yy[0]
total = density.sum() * (dx * dy)
assert total == pytest.approx(1, abs=1e-2)
@pytest.mark.skipif(_no_scipy, reason="Test requires scipy")
def test_bivariate_cumulative(self, rng):
x, y = rng.normal(0, 3, (2, 50))
kde = KDE(gridsize=100, cumulative=True)
density, _ = kde(x, y)
assert density[0, 0] == pytest.approx(0, abs=1e-2)
assert density[-1, -1] == pytest.approx(1, abs=1e-2)
| TestKDE |
python | pytorch__pytorch | test/inductor/test_torchinductor_opinfo.py | {
"start": 40588,
"end": 51219
} | class ____(TestCase):
def tearDown(self):
torch._dynamo.reset()
check_model = check_model
check_model_gpu = check_model_gpu
@onlyNativeDeviceTypes
@suppress_warnings
@skipCUDAMemoryLeakCheckIf(
True
) # inductor kernels failing this test intermittently
@requires_gpu_and_triton
@skipXPUIf(
not HAS_XPU_AND_TRITON, "Skipped! Supported XPU compiler and Triton not found"
)
@skipCPUIf(not HAS_CPU, "Skipped! Supported CPU compiler not found")
@unittest.skipIf(TEST_WITH_ASAN, "Skipped under ASAN")
@skipIfTorchDynamo("Test uses dynamo already")
@skipIfCrossRef
@_ops(op_db[START:END])
@skipOps("TestInductorOpInfo", "test_comprehensive", test_skips_or_fails)
@patch("torch._dynamo.config.raise_on_unsafe_aot_autograd", True)
@torch._inductor.config.patch(
{"implicit_fallbacks": False, "triton.autotune_pointwise": False}
)
@torch._inductor.config.patch("test_configs.runtime_triton_dtype_assert", True)
@torch._inductor.config.patch("test_configs.static_cpp_dtype_assert", True)
@collection_decorator
def test_comprehensive(self, device, dtype, op):
device_type = torch.device(device).type
assert device_type in (GPU_TYPE, "cpu")
torch._dynamo.reset()
with torch.no_grad():
# TODO: should we move empty_cache to the common device interface
if device_type == "cuda":
torch.cuda.empty_cache()
elif device == "xpu":
torch.xpu.empty_cache()
op_name = op.name
if op.variant_test_name:
op_name += f".{op.variant_test_name}"
# Skip dtype=torch.uint8 for all ops except upsample and interpolate:
allowed_dtypes = [f16, f32, f64, i32, i64, b8]
if op_name not in (
"nn.functional.interpolate.bilinear",
"nn.functional.interpolate.bicubic",
"nn.functional.upsample_bilinear",
"nn.functional.upsample_nearest",
"fill",
"full_like",
):
if dtype not in allowed_dtypes:
raise unittest.SkipTest("Skipped!")
# with open("test_output.txt", "a") as f:
# print(f"CONSIDERING OP {op_name} on {device_type} with {dtype} |
# {inductor_skips[device_type].get(op_name, set())}", flush=True, file=f)
# print(f"CONSIDERING OP {op_name} on {device_type} with {dtype} |
# {inductor_skips[device_type].get(op_name, set())}", flush=True)
if dtype in inductor_skips[device_type].get(op_name, set()):
test_expect = ExpectedTestResult.SKIP # noqa: F841
# with open("test_output.txt", "a") as f:
# print(f"SKIPPING OP {op_name} on {device_type}", flush=True, file=f)
# print(f"SKIPPING OP {op_name} on {device_type}", flush=True)
elif dtype in inductor_expected_failures_single_sample[device_type].get(
op_name, set()
) or dtype in inductor_gradient_expected_failures_single_sample[
device_type
].get(op_name, set()):
test_expect = ExpectedTestResult.XFAILURE # noqa: F841
else:
test_expect = ExpectedTestResult.SUCCESS # noqa: F841
overridden_kwargs = {}
overridden_kwargs.update(
inductor_override_kwargs.get(device_type, {}).get(op_name, {})
)
overridden_kwargs.update(
inductor_override_kwargs.get(device_type, {}).get((op_name, dtype), {})
)
func = op.get_op()
def fn(*args, **kwargs):
return func(*args, **kwargs)
requires_grad = (
op.supports_autograd
and dtype in op.supported_backward_dtypes(device_type)
# TODO: OpInfo really ought to error out for this case, but it's
# not exercised in test_ops_gradients atm. The problem is not
# complex32 per-se (which is supported by data movement only ops)
# but that when we do backwards we expect other ops like add to work
and dtype != torch.complex32
)
samples = op.sample_inputs(device, dtype, requires_grad=requires_grad)
if (
dtype in inductor_one_sample.get(device_type, {}).get(op_name, {})
) and not ALL_SAMPLES:
if isinstance(samples, (list, tuple)):
samples = [samples[0]]
else:
samples = [next(samples)]
class HasRngOp(TorchDispatchMode):
def __init__(self) -> None:
super().__init__()
self.has_rng_op = False
def __torch_dispatch__(self, func, types, args, kwargs=None):
kwargs = kwargs if kwargs else {}
if torch.Tag.nondeterministic_seeded in func.tags:
self.has_rng_op = True
return func(*args, **kwargs)
def do_nopython_and_has_rng(fn, args, kwargs):
try:
mode = FakeTensorMode()
def map_to_fake(e):
if isinstance(e, torch.Tensor):
return mode.from_tensor(e)
else:
return e
args, kwargs = tree_map(map_to_fake, (args, kwargs))
with HasRngOp() as rng_mode, mode:
with enable_python_dispatcher():
fn(*args, **kwargs)
except (DataDependentOutputException, DynamicOutputShapeException):
return False, rng_mode.has_rng_op
return True, rng_mode.has_rng_op
def get_contexts(has_rng_op, args, kwargs):
if has_rng_op:
# TODO - enable this, running into errors
return (
# (
# lambda: torch._inductor.config.patch(
# {"fallback_random": True, "implicit_fallbacks": True}
# ),
# {"assert_equal": True},
# ),
(
contextlib.nullcontext,
{"assert_equal": False},
),
)
ctx = functools.partial(maybe_skip_size_asserts, op)
if op_name in CUSTOM_ASSERT_EQUALS_FNS:
assert_equal_fn = CUSTOM_ASSERT_EQUALS_FNS[op_name](args, kwargs)
return (
(
ctx,
{"assert_equal": assert_equal_fn},
),
)
return ((ctx, {}),)
try:
def _get_tolerances(dtype):
_custom_tolerances = {
torch.float32: (1.3e-5, 1.5e-5),
}
# When we are running opportunistic_fastatomics, we will expect some floating point rounding
# errors as the order of operation is not guaranteed.
if dtype in _custom_tolerances:
return _custom_tolerances[dtype]
else:
return None, None
for sample_input in samples:
args = [sample_input.input] + list(sample_input.args)
kwargs = sample_input.kwargs
# UNCOMMENT TO DEBUG SEGFAULTS
# with open("test_output.txt", "a") as f:
# print(f"RUNNING OP {op_name} on {device_type} with {dtype}", flush=True, file=f)
# print(f"RUNNING OP {op_name} on {device_type} with {dtype}", flush=True)
rtol, atol = _get_tolerances(dtype)
no_python, has_rng_op = do_nopython_and_has_rng(fn, args, kwargs)
for context_fn, kwarg_overrides in get_contexts(
has_rng_op, args, kwargs
):
with context_fn():
# Base kwargs
adjusted_kwargs = {
"check_lowp": False,
"nopython": no_python,
"check_has_compiled": no_python,
"atol": atol,
"rtol": rtol,
}
# Backend-specific adjustments
# Triton
if has_triton():
adjusted_kwargs.update(
copy_to_gpu=False, reference_in_float=False
)
# skip checking gradient on CPU for now
if device_type == GPU_TYPE:
adjusted_kwargs.update(
check_gradient=requires_grad,
output_process_fn_grad=sample_input.output_process_fn_grad,
)
else:
adjusted_kwargs["check_gradient"] = False
# Update with overridden kwargs and context-specific overrides
adjusted_kwargs.update(overridden_kwargs)
adjusted_kwargs.update(kwarg_overrides)
# Call the appropriate check method based on device type
if device_type == GPU_TYPE:
self.check_model_gpu(
fn,
args,
kwargs,
**adjusted_kwargs,
)
else:
self.check_model(
fn,
args,
kwargs,
**adjusted_kwargs,
)
except Exception as e:
known_failure = False
if dtype in inductor_should_fail_with_exception[device_type].get(
op_name, set()
):
failure = inductor_should_fail_with_exception[device_type][op_name][
dtype
]
if failure in str(e):
known_failure = True
if not known_failure:
raise e
# with open("test_output.txt", "a") as f:
# print(f"SUCCEEDED OP {op_name} on {device_type} with {dtype}", flush=True, file=f)
instantiate_device_type_tests(TestInductorOpInfo, globals(), allow_xpu=True)
if __name__ == "__main__":
run_tests()
| TestInductorOpInfo |
python | streamlit__streamlit | lib/tests/streamlit/web/server/websocket_headers_test.py | {
"start": 1019,
"end": 3049
} | class ____(ServerTestCase):
@tornado.testing.gen_test
async def test_get_websocket_headers(self):
"""`get_websocket_headers()` returns the current session's
`BrowserWebSocketHandler.request.headers`.
"""
with self._patch_app_session():
await self.server.start()
await self.ws_connect()
session_mgr = self.server._runtime._session_mgr
# Get our client's session_id and some other stuff
assert session_mgr.num_active_sessions() == 1
session_info = session_mgr.list_active_sessions()[0]
session_id = session_info.session.id
assert isinstance(session_info.client, BrowserWebSocketHandler)
# Mock get_script_run_ctx() to return our session_id
mock_script_run_ctx = MagicMock(spec=ScriptRunContext)
mock_script_run_ctx.session_id = session_id
with patch(
"streamlit.web.server.websocket_headers.get_script_run_ctx",
return_value=mock_script_run_ctx,
):
# Assert that our headers are equal to our BrowserWebSocketHandler's
# request headers.
headers = websocket_headers._get_websocket_headers()
assert headers == dict(session_info.client.request.headers)
# Assert the presence of some (arbitrary) headers that should always
# be in a WebSocket request.
assert "Host" in headers
assert "Upgrade" in headers
assert "Connection" in headers
@patch("streamlit.web.server.websocket_headers.show_deprecation_warning")
def test_deprecation_warnings(self, show_warning_mock: Mock):
"""We show deprecation warnings when using `_get_websocket_headers()`."""
websocket_headers._get_websocket_headers()
show_warning_mock.assert_called_once_with(
websocket_headers._GET_WEBSOCKET_HEADERS_DEPRECATE_MSG
)
| WebSocketHeadersTest |
python | keras-team__keras | keras/src/ops/numpy.py | {
"start": 124012,
"end": 124531
} | class ____(Operation):
def call(self, x):
return backend.numpy.isposinf(x)
def compute_output_spec(self, x):
return KerasTensor(x.shape, dtype="bool")
@keras_export(["keras.ops.isposinf", "keras.ops.numpy.isposinf"])
def isposinf(x):
"""Test element-wise for positive infinity.
Args:
x: Input tensor.
Returns:
Output boolean tensor.
"""
if any_symbolic_tensors((x,)):
return Isposinf().symbolic_call(x)
return backend.numpy.isposinf(x)
| Isposinf |
python | psf__black | tests/data/cases/fmtskip6.py | {
"start": 0,
"end": 123
} | class ____:
def f(self):
for line in range(10):
if True:
pass # fmt: skip
# output
| A |
python | spyder-ide__spyder | spyder/plugins/debugger/widgets/main_widget.py | {
"start": 1589,
"end": 1889
} | class ____:
ToggleBreakpoint = 'toggle breakpoint'
ToggleConditionalBreakpoint = 'toggle conditional breakpoint'
ClearAllBreakpoints = 'clear all breakpoints'
ShowBreakpointsTable = 'show breakpoint table'
ToggleBreakpointsTable = 'toggle breakpoint table'
| DebuggerBreakpointActions |
python | getsentry__sentry | src/sentry/integrations/slack/analytics.py | {
"start": 816,
"end": 1013
} | class ____(analytics.Event):
user_id: int | None = None
organization_id: int
unfurls_count: int
@analytics.eventclass("integrations.slack.chart_unfurl_action")
| SlackIntegrationChartUnfurl |
python | google__jax | tests/optimizers_test.py | {
"start": 867,
"end": 10229
} | class ____(jtu.JaxTestCase):
def _CheckOptimizer(self, optimizer, loss, x0, num_steps, *args, **kwargs):
self._CheckFuns(optimizer, loss, x0, *args)
self._CheckRun(optimizer, loss, x0, num_steps, *args, **kwargs)
def _CheckFuns(self, optimizer, loss, x0, *args):
init_fun, update_fun, get_params = optimizer(*args)
opt_state = init_fun(x0)
self.assertAllClose(x0, get_params(opt_state))
opt_state2 = update_fun(0, grad(loss)(x0), opt_state) # doesn't crash
self.assertEqual(jax.tree.structure(opt_state),
jax.tree.structure(opt_state2))
@jtu.skip_on_devices('gpu')
def _CheckRun(self, optimizer, loss, x0, num_steps, *args, **kwargs):
init_fun, update_fun, get_params = optimizer(*args)
opt_state = init_fun(x0)
for i in range(num_steps):
x = get_params(opt_state)
g = grad(loss)(x)
opt_state = update_fun(i, g, opt_state)
xstar = get_params(opt_state)
self.assertLess(loss(xstar), 1e-2)
update_fun_jitted = jit(update_fun)
opt_state = init_fun(x0)
for i in range(num_steps):
x = get_params(opt_state)
g = grad(loss)(x)
opt_state = update_fun_jitted(i, g, opt_state)
xstar = get_params(opt_state)
self.assertLess(loss(xstar), 1e-2)
def testSgdScalar(self):
def loss(x): return x**2
x0 = 1.
num_iters = 100
step_size = 0.1
self._CheckOptimizer(optimizers.sgd, loss, x0, num_iters, step_size)
def testSgdVector(self):
def loss(x): return jnp.dot(x, x)
x0 = jnp.ones(2)
num_iters = 100
step_size = 0.1
self._CheckOptimizer(optimizers.sgd, loss, x0, num_iters, step_size)
def testSgdNestedTuple(self):
def loss(xyz):
x, (y, z) = xyz
return sum(jnp.dot(a, a) for a in [x, y, z])
x0 = (jnp.ones(2), (jnp.ones(2), jnp.ones(2)))
num_iters = 100
step_size = 0.1
self._CheckOptimizer(optimizers.sgd, loss, x0, num_iters, step_size)
def testMomentumVector(self):
def loss(x): return jnp.dot(x, x)
x0 = jnp.ones(2)
num_iters = 100
step_size = 0.1
mass = 0.
self._CheckOptimizer(optimizers.momentum, loss, x0, num_iters, step_size, mass)
def testMomentumDict(self):
def loss(dct): return jnp.dot(dct['x'], dct['x'])
x0 = {'x': jnp.ones(2)}
num_iters = 100
step_size = 0.1
mass = 0.
self._CheckOptimizer(optimizers.momentum, loss, x0, num_iters, step_size, mass)
def testRmspropVector(self):
def loss(x): return jnp.dot(x, x)
x0 = jnp.ones(2)
num_iters = 100
step_size = 0.1
self._CheckOptimizer(optimizers.rmsprop, loss, x0, num_iters, step_size)
def testAdamVector(self):
def loss(x): return jnp.dot(x, x)
x0 = jnp.ones(2)
num_iters = 100
step_size = 0.1
self._CheckOptimizer(optimizers.adam, loss, x0, num_iters, step_size)
def testSgdClosure(self):
def loss(y, x): return y**2 * x**2
x0 = 1.
y = 1.
num_iters = 20
step_size = 0.1
partial_loss = functools.partial(loss, y)
self._CheckRun(optimizers.sgd, partial_loss, x0, num_iters, step_size)
def testAdagrad(self):
def loss(xs):
x1, x2 = xs
return jnp.sum(x1**2) + jnp.sum(x2**2)
num_iters = 100
step_size = 0.1
x0 = (jnp.ones(2), jnp.ones((2, 2)))
self._CheckOptimizer(optimizers.adagrad, loss, x0, num_iters, step_size)
def testSM3Scalar(self):
def loss(x): return x**2
x0 = jnp.array(1.)
num_iters = 100
step_size = 0.1
self._CheckOptimizer(optimizers.sm3, loss, x0, num_iters, step_size)
def testSM3Vector(self):
def loss(xs):
x1, x2 = xs
return jnp.sum(x1 ** 2) + jnp.sum(x2 ** 2)
num_iters = 100
step_size = 0.1
x0 = (jnp.ones(2), jnp.ones((2, 2)))
self._CheckOptimizer(optimizers.sm3, loss, x0, num_iters, step_size)
def testAdaMaxVector(self):
def loss(x): return jnp.dot(x, x)
x0 = jnp.ones(2)
num_iters = 100
step_size = 0.1
self._CheckOptimizer(optimizers.adamax, loss, x0, num_iters, step_size)
def testSgdVectorExponentialDecaySchedule(self):
def loss(x): return jnp.dot(x, x)
x0 = jnp.ones(2)
step_schedule = optimizers.exponential_decay(0.1, 3, 2.)
self._CheckFuns(optimizers.sgd, loss, x0, step_schedule)
def testSgdVectorInverseTimeDecaySchedule(self):
def loss(x): return jnp.dot(x, x)
x0 = jnp.ones(2)
step_schedule = optimizers.inverse_time_decay(0.1, 3, 2.)
self._CheckFuns(optimizers.sgd, loss, x0, step_schedule)
def testAdamVectorInverseTimeDecaySchedule(self):
def loss(x): return jnp.dot(x, x)
x0 = jnp.ones(2)
step_schedule = optimizers.inverse_time_decay(0.1, 3, 2.)
self._CheckFuns(optimizers.adam, loss, x0, step_schedule)
def testMomentumVectorInverseTimeDecayStaircaseSchedule(self):
def loss(x): return jnp.dot(x, x)
x0 = jnp.ones(2)
step_sched = optimizers.inverse_time_decay(0.1, 3, 2., staircase=True)
mass = 0.9
self._CheckFuns(optimizers.momentum, loss, x0, step_sched, mass)
def testRmspropmomentumVectorPolynomialDecaySchedule(self):
def loss(x): return jnp.dot(x, x)
x0 = jnp.ones(2)
step_schedule = optimizers.polynomial_decay(1.0, 50, 0.1)
self._CheckFuns(optimizers.rmsprop_momentum, loss, x0, step_schedule)
def testRmspropVectorPiecewiseConstantSchedule(self):
def loss(x): return jnp.dot(x, x)
x0 = jnp.ones(2)
step_schedule = optimizers.piecewise_constant([25, 75], [1.0, 0.5, 0.1])
self._CheckFuns(optimizers.rmsprop, loss, x0, step_schedule)
def testTracedStepSize(self):
def loss(x): return jnp.dot(x, x)
x0 = jnp.ones(2)
step_size = 0.1
init_fun, _, _ = optimizers.sgd(step_size)
opt_state = init_fun(x0)
@jit
def update(opt_state, step_size):
_, update_fun, get_params = optimizers.sgd(step_size)
x = get_params(opt_state)
g = grad(loss)(x)
return update_fun(0, g, opt_state)
update(opt_state, 0.9) # doesn't crash
# TODO(mattjj): re-enable
# def testDeviceTupleState(self):
# init_fun, update_fun, _ = optimizers.sgd(0.1)
# opt_state = init_fun(jnp.zeros(3))
# self.assertIsInstance(opt_state, optimizers.OptimizerState)
# self.assertIsInstance(opt_state.packed_state, core.JaxTuple)
# opt_state = jit(update_fun)(0, jnp.zeros(3), opt_state)
# self.assertIsInstance(opt_state, optimizers.OptimizerState)
# self.assertIsInstance(opt_state.packed_state, xla.DeviceTuple)
def testUpdateFunStructureMismatchErrorMessage(self):
@optimizers.optimizer
def opt_maker():
def init_fun(x0):
return {'x': x0}
def update_fun(i, g, opt_state):
x = opt_state['x']
return {'x': x - 0.1 * g, 'v': g} # bug!
def get_params(opt_state):
return opt_state['x']
return init_fun, update_fun, get_params
init_fun, update_fun, get_params = opt_maker()
opt_state = init_fun(jnp.zeros(3))
self.assertRaises(TypeError, lambda: update_fun(opt_state))
def testUtilityNorm(self):
x0 = (jnp.ones(2), (jnp.ones(3), jnp.ones(4)))
norm = optimizers.l2_norm(x0)
expected = np.sqrt(np.sum(np.ones(2+3+4)**2))
self.assertAllClose(norm, expected, check_dtypes=False)
def testUtilityClipGrads(self):
g = (jnp.ones(2), (jnp.ones(3), jnp.ones(4)))
norm = optimizers.l2_norm(g)
ans = optimizers.clip_grads(g, 1.1 * norm)
expected = g
self.assertAllClose(ans, expected, check_dtypes=False)
ans = optimizers.l2_norm(optimizers.clip_grads(g, 0.9 * norm))
expected = 0.9 * norm
self.assertAllClose(ans, expected, check_dtypes=False)
def testIssue758(self):
# code from https://github.com/jax-ml/jax/issues/758
# this is more of a scan + jacfwd/jacrev test, but it lives here to use the
# optimizers.py code
def harmonic_bond(conf, params):
return jnp.sum(conf * params)
opt_init, opt_update, get_params = optimizers.sgd(5e-2)
x0 = np.array([0.5], dtype=np.float64)
def minimize_structure(test_params):
energy_fn = functools.partial(harmonic_bond, params=test_params)
grad_fn = grad(energy_fn, argnums=(0,))
opt_state = opt_init(x0)
def apply_carry(carry, _):
i, x = carry
g = grad_fn(get_params(x))[0]
new_state = opt_update(i, g, x)
new_carry = (i+1, new_state)
return new_carry, _
carry_final, _ = lax.scan(apply_carry, (0, opt_state), jnp.zeros((75, 0)))
trip, opt_final = carry_final
assert trip == 75
return opt_final
initial_params = jnp.array(0.5)
minimize_structure(initial_params)
def loss(test_params):
opt_final = minimize_structure(test_params)
return 1.0 - get_params(opt_final)[0]
loss_opt_init, loss_opt_update, loss_get_params = optimizers.sgd(5e-2)
J1 = jacrev(loss, argnums=(0,))(initial_params)
J2 = jacfwd(loss, argnums=(0,))(initial_params)
self.assertAllClose(J1, J2, rtol=1e-6)
def testUnpackPackRoundTrip(self):
opt_init, _, _ = optimizers.momentum(0.1, mass=0.9)
params = [{'w': self.rng().randn(1, 2), 'bias': self.rng().randn(2)}]
expected = opt_init(params)
ans = optimizers.pack_optimizer_state(
optimizers.unpack_optimizer_state(expected))
self.assertEqual(ans, expected)
if __name__ == '__main__':
absltest.main(testLoader=jtu.JaxTestLoader())
| OptimizerTests |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/log/cloudwatch_task_handler.py | {
"start": 8718,
"end": 11469
} | class ____(FileTaskHandler, LoggingMixin):
"""
CloudwatchTaskHandler is a python log handler that handles and reads task instance logs.
It extends airflow FileTaskHandler and uploads to and reads from Cloudwatch.
:param base_log_folder: base folder to store logs locally
:param log_group_arn: ARN of the Cloudwatch log group for remote log storage
with format ``arn:aws:logs:{region name}:{account id}:log-group:{group name}``
"""
trigger_should_wrap = True
def __init__(
self,
base_log_folder: str,
log_group_arn: str,
max_bytes: int = 0,
backup_count: int = 0,
delay: bool = False,
**kwargs,
) -> None:
# support log file size handling of FileTaskHandler
super().__init__(
base_log_folder=base_log_folder, max_bytes=max_bytes, backup_count=backup_count, delay=delay
)
split_arn = log_group_arn.split(":")
self.handler = None
self.log_group = split_arn[6]
self.region_name = split_arn[3]
self.closed = False
self.io = CloudWatchRemoteLogIO(
base_log_folder=base_log_folder,
log_group_arn=log_group_arn,
)
@cached_property
def hook(self):
"""Returns AwsLogsHook."""
return AwsLogsHook(
aws_conn_id=conf.get("logging", "REMOTE_LOG_CONN_ID"), region_name=self.region_name
)
def _render_filename(self, ti, try_number):
# Replace unsupported log group name characters
return super()._render_filename(ti, try_number).replace(":", "_")
def set_context(self, ti: TaskInstance, *, identifier: str | None = None):
super().set_context(ti)
self.io.log_stream_name = self._render_filename(ti, ti.try_number)
self.handler = self.io.handler
def close(self):
"""Close the handler responsible for the upload of the local log file to Cloudwatch."""
# When application exit, system shuts down all handlers by
# calling close method. Here we check if logger is already
# closed to prevent uploading the log to remote storage multiple
# times when `logging.shutdown` is called.
if self.closed:
return
if self.handler is not None:
self.handler.close()
# Mark closed so we don't double write if close is called twice
self.closed = True
def _read_remote_logs(
self, task_instance, try_number, metadata=None
) -> tuple[LogSourceInfo, LogMessages]:
stream_name = self._render_filename(task_instance, try_number)
messages, logs = self.io.read(stream_name, task_instance)
return messages, logs or []
| CloudwatchTaskHandler |
python | pypa__pip | tests/unit/test_models.py | {
"start": 1589,
"end": 1965
} | class ____:
def test_sets_correct_variables(self) -> None:
obj = candidate.InstallationCandidate(
"A", "1.0.0", Link("https://somewhere.com/path/A-1.0.0.tar.gz")
)
assert obj.name == "A"
assert obj.version == parse_version("1.0.0")
assert obj.link.url == "https://somewhere.com/path/A-1.0.0.tar.gz"
| TestInstallationCandidate |
python | huggingface__transformers | src/transformers/models/visual_bert/modeling_visual_bert.py | {
"start": 18837,
"end": 19716
} | class ____(PreTrainedModel):
config: VisualBertConfig
base_model_prefix = "visual_bert"
input_modalities = ("image", "text")
supports_gradient_checkpointing = True
@torch.no_grad()
def _init_weights(self, module):
"""Initialize the weights"""
if isinstance(module, (nn.Linear, nn.Embedding)):
init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
if hasattr(module, "bias") and module.bias is not None:
init.zeros_(module.bias)
elif isinstance(module, nn.LayerNorm):
init.zeros_(module.bias)
init.ones_(module.weight)
elif isinstance(module, VisualBertLMPredictionHead):
init.zeros_(module.bias)
@dataclass
@auto_docstring(
custom_intro="""
Output type of [`VisualBertForPreTraining`].
"""
)
| VisualBertPreTrainedModel |
python | pytorch__pytorch | test/inductor/test_indexing.py | {
"start": 1004,
"end": 11994
} | class ____(InductorTestCase):
def test_indexing_simplification(self):
sizevars = SizeVarAllocator()
i0 = sympy.Symbol("i0", integer=True)
i1 = sympy.Symbol("i1", integer=True)
i2 = sympy.Symbol("i2", integer=True)
r3 = sympy.Symbol("r3", integer=True)
var_ranges = {i0: 3136, i1: 64, i2: 32, r3: 3}
expr = (
128 * i2
+ ModularIndexing(i1, 1, 64)
+ 64 * ModularIndexing(i1 + 64 * r3, 64, 2)
)
# check that `i1//64` is removed when i1 is always less than 64,
# and the next simplificaton doesn't happen
self.assertEqual(
sizevars.simplify_with_ranges(expr, var_ranges),
i1 + 128 * i2 + 64 * ModularIndexing(r3, 1, 2),
)
# all the modular indexing should be removed when the body can't be larger than the modulus
var_ranges[r3] = 2
self.assertEqual(
sizevars.simplify_with_ranges(expr, var_ranges), i1 + 128 * i2 + 64 * r3
)
# if there are negative terms in ModularIndexing base, we cannot replace it with FloorDiv
expr = ModularIndexing(i1 - 15, 1, 64)
self.assertEqual(
sizevars.simplify_with_ranges(expr, var_ranges),
ModularIndexing(i1 - 15, 1, 64),
)
# small terms should be kept if the rest is not guaranteed to be divisible
self.assertEqual(
sizevars.simplify_with_ranges(FloorDiv(r3 + i2 + i1, 32), var_ranges),
FloorDiv(r3 + i2 + i1, 32),
)
expr = ModularIndexing(2 * i2 + r3, 1, 64)
# modular indexing is removed if base is smaller than modulo
self.assertEqual(sizevars.simplify_with_ranges(expr, var_ranges), 2 * i2 + r3)
# check the same thing but with symbolic divisor
self.assertEqual(FloorDiv(r3 * i0, r3), i0)
self.assertEqual(ModularIndexing(r3 * i0, r3, 10), ModularIndexing(i0, 1, 10))
# (10*i) % 10 is always zero and should get optimized away
self.assertEqual(
ModularIndexing(i0 + i1 * 10, 1, 10), ModularIndexing(i0, 1, 10)
)
# ((20*i)//2) % 10 is always zero and should get optimized away
self.assertEqual(
ModularIndexing(i0 + i1 * 20, 2, 10), ModularIndexing(i0, 2, 10)
)
# the same things happens with symbolic divisor
self.assertEqual(
ModularIndexing(i0 + i1 * i2 * r3, i2, r3), ModularIndexing(i0, i2, r3)
)
# if there are negative terms, we cannot optimize away zero terms due to https://github.com/triton-lang/triton/issues/619
self.assertEqual(
ModularIndexing(-i0 + i1 * 20, 2, 10), ModularIndexing(-i0 + i1 * 20, 2, 10)
)
self.assertEqual(
ModularIndexing(-15 + i1 * 20, 2, 10), ModularIndexing(-15 + i1 * 20, 2, 10)
)
# Constant fold from divisor into base
self.assertEqual(ModularIndexing(i0 * 4, 2, 10), ModularIndexing(i0 * 2, 1, 10))
self.assertEqual(FloorDiv(i0 * 4, 2), i0 * 2)
# Nested modular indexing is correctly simplified
var_ranges = {i1: 13, i2: 121}
expr = ModularIndexing(ModularIndexing(121 * i1 + i2, 1, 784), 1, 28)
self.assertEqual(sizevars.simplify_with_ranges(expr, var_ranges), expr)
expr = ModularIndexing(ModularIndexing(121 * i1 + i2, 1, 784) + 1, 1, 28)
self.assertEqual(sizevars.simplify_with_ranges(expr, var_ranges), expr)
var_ranges = {i2: 784}
expr = ModularIndexing(ModularIndexing(i2, 1, 28), 7, 4)
expected = FloorDiv(ModularIndexing(i2, 1, 28), 7)
self.assertEqual(sizevars.simplify_with_ranges(expr, var_ranges), expected)
expr = ModularIndexing(ModularIndexing(i2, 1, 28) + 1, 7, 4)
self.assertEqual(sizevars.simplify_with_ranges(expr, var_ranges), expr)
def test_indexing_join(self):
sizevars = SizeVarAllocator()
i0 = sympy.Symbol("i0", integer=True)
i1 = sympy.Symbol("i1", integer=True)
i2 = sympy.Symbol("i2", integer=True)
# join two ModularIndexing calls into one larger one when possible
expr1 = ModularIndexing(i0, 1, 32) + 32 * ModularIndexing(i0, 32, 4)
self.assertEqual(
sizevars.simplify_with_ranges(expr1, {}), ModularIndexing(i0, 1, 128)
)
# it should also work with a scale
self.assertEqual(
sizevars.simplify_with_ranges(2 * expr1, {}),
2 * ModularIndexing(i0, 1, 128),
)
# it should work when divisor is not 1
expr2 = ModularIndexing(i0, 3, 32) + 32 * ModularIndexing(i0, 32 * 3, 4)
simplified = sizevars.simplify_with_ranges(expr2, {})
self.assertEqual(simplified, ModularIndexing(i0, 3, 128))
self.assertEqual(expr2.subs({i0: 39485}), simplified.subs({i0: 39485}))
# it should not happen in this case as the modulus is wrong
expr3 = ModularIndexing(i0, 1, 30) + 32 * ModularIndexing(i0, 32, 4)
self.assertEqual(sizevars.simplify_with_ranges(expr3, {}), expr3)
# check that it also works with a modulus>1
expr4 = ModularIndexing(i0, 10, i1) + i1 * ModularIndexing(i0, i1 * 10, i2)
res0 = expr4.subs({i0: 24056, i1: 13, i2: 19})
simplified = sizevars.simplify_with_ranges(expr4, {})
res1 = simplified.subs({i0: 24056, i1: 13, i2: 19})
self.assertEqual(res0, res1)
self.assertEqual(simplified, ModularIndexing(i0, 10, i1 * i2))
# and also works with an offset
self.assertEqual(
sizevars.simplify_with_ranges(expr4 + 10, {}),
ModularIndexing(i0, 10, i1 * i2) + 10,
)
# works for ModularIndexing + FloorDiv
expr5 = 197 * FloorDiv(i0, 197) + ModularIndexing(i0, 1, 197)
simplified = sizevars.simplify_with_ranges(expr5, {})
self.assertEqual(simplified, i0)
self.assertEqual(expr5.subs({i0: 39485}), simplified.subs({i0: 39485}))
# works with a scale
self.assertEqual(
sizevars.simplify_with_ranges(2 * expr5, {}),
2 * i0,
)
# divisor != 1
expr6 = 197 * FloorDiv(i0, 197 * 3) + ModularIndexing(i0, 3, 197)
simplified = sizevars.simplify_with_ranges(expr6, {})
self.assertEqual(simplified, FloorDiv(i0, 3))
self.assertEqual(expr6.subs({i0: 39485}), simplified.subs({i0: 39485}))
def test_modular_indexing_pairs_merged(self):
sizevars = SizeVarAllocator()
x = sympy.Symbol("x", integer=True, positive=True)
a = 1024
b = 32
expr1 = ModularIndexing(x, 1, a)
expr2 = ModularIndexing(expr1, 1, b)
expected = ModularIndexing(x, 1, b)
actual = sizevars.combine_modular_indexing_pairs(expr2)
self.assertEqual(expected, actual)
self.assertNotEqual(expr2, actual)
def test_modular_indexing_pairs_not_merged(self):
sizevars = SizeVarAllocator()
x = sympy.Symbol("x", integer=True, positive=True)
a = 1024
b = 3 # pick a 'b' that we can not merge
expr1 = ModularIndexing(x, 1, a)
expr2 = ModularIndexing(expr1, 1, b)
actual = sizevars.combine_modular_indexing_pairs(expr2)
self.assertEqual(expr2, actual)
self.assertNotEqual(ModularIndexing(x, 1, b), actual)
def test_modular_indexing_positive(self):
x = sympy.Symbol("x", integer=True, positive=True)
expr = ModularIndexing(x, 1, 1024) - 1
expr2 = abs(expr)
self.assertNotEqual(expr2, expr)
def test_expand_floor_div_skipped(self):
sizevars = SizeVarAllocator()
x = sympy.Symbol("x", integer=True, positive=True)
y = sympy.Symbol("y", integer=True, positive=True)
expr = FloorDiv(x, 2) + FloorDiv(y, 3)
# The expression can not be simplified since there are multiple
# FloorDiv. We return False in that case
self.assertFalse(sizevars.expand_floor_div(expr))
def test_expand_floor_div_applied(self):
sizevars = SizeVarAllocator()
x = sympy.Symbol("x", integer=True, positive=True)
y = sympy.Symbol("y", integer=True, positive=True)
expr = x * 5 + FloorDiv(y, 3)
actual, denominator = sizevars.expand_floor_div(expr)
self.assertNotEqual(expr, actual)
expected = FloorDiv(x * 15 + y, 3)
self.assertEqual(expected, FloorDiv(actual, denominator))
@unittest.skipUnless(HAS_GPU, "Need GPU for this test")
def test_int8_unpack(self):
@torch.compile
def f(x):
first_elements = x >> 4
second_elements = x & 15
unpacked = torch.stack([first_elements, second_elements], dim=-1).view(
*x.size()[:-1], -1
)
return unpacked * 2
x = torch.randint(0, 255, (2, 4096, 5504), dtype=torch.uint8, device=GPU_TYPE)
triton_code = run_and_get_triton_code(f, x)
# Make sure the 2 load uses simplified indexing rather than something like
# tl.load(in_ptr0 + ((5504*x1) + (x0 // 2)),
self.assertEqual(2, triton_code.count("tl.load(in_ptr0 + (x2 // 2),"))
if DO_PERF_TEST:
ms = benchmarker.benchmark_gpu(lambda: f(x))
print(f"{ms=:.03f}")
@unittest.skipUnless(HAS_GPU, "Need GPU for this test")
def test_floordiv_div_sympy_is_integer_bug(self):
def foo(arg0, arg1, arg2, arg3, arg4, sentinel):
t0 = arg0
t1 = t0.reshape((28, 24, 3, 127))
t2 = t1.var(dim=2)
t3 = arg1
t4 = arg2
t5 = torch.nn.functional.embedding(
torch.clamp(t3, 0, t4.size(0) - 1).to(torch.long), t4
)
t6 = arg3
t7 = torch.nn.functional.pad(t6, [0, 1], mode="constant", value=0.0)
t8 = arg4
t9 = t8.sum(dim=1)
t10 = torch.baddbmm(t5, t7, t9)
t11 = torch.cat([t2, t10], dim=0)
output = t11 + sentinel
return output
arg0 = torch.rand(
[36, 7112, 1, 1], dtype=torch.bfloat16, device=GPU_TYPE, requires_grad=True
)
arg1 = torch.randint(0, 512, [30, 24], dtype=torch.int64, device=GPU_TYPE)
arg2 = torch.rand(
[512, 127], dtype=torch.bfloat16, device=GPU_TYPE, requires_grad=True
)
arg3 = torch.rand(
[30, 24, 15], dtype=torch.bfloat16, device=GPU_TYPE, requires_grad=True
)
arg4 = torch.rand(
[30, 4, 16, 127], dtype=torch.bfloat16, device=GPU_TYPE, requires_grad=True
)
sentinel = torch.tensor(
0.0, dtype=torch.bfloat16, device=GPU_TYPE, requires_grad=True
)
compiled_foo = torch.compile(foo, fullgraph=True, dynamic=True)
out_compiled = compiled_foo(arg0, arg1, arg2, arg3, arg4, sentinel)
out_compiled.sum().backward()
| TestIndexingSimplification |
python | mlflow__mlflow | mlflow/entities/multipart_upload.py | {
"start": 727,
"end": 1273
} | class ____:
url: str
part_number: int
headers: dict[str, Any]
def to_proto(self):
credential = ProtoMultipartUploadCredential()
credential.url = self.url
credential.part_number = self.part_number
credential.headers.update(self.headers)
return credential
@classmethod
def from_dict(cls, dict_):
return cls(
url=dict_["url"],
part_number=dict_["part_number"],
headers=dict_.get("headers", {}),
)
@dataclass
| MultipartUploadCredential |
python | xlwings__xlwings | xlwings/constants.py | {
"start": 45487,
"end": 45622
} | class ____:
xlColorIndexAutomatic = -4105 # from enum XlColorIndex
xlColorIndexNone = -4142 # from enum XlColorIndex
| ColorIndex |
python | getsentry__sentry | src/sentry/notifications/notifications/codeowners_auto_sync.py | {
"start": 425,
"end": 1700
} | class ____(ProjectNotification):
metrics_key = "auto_sync"
notification_setting_type_enum = NotificationSettingEnum.DEPLOY
template_path = "sentry/emails/codeowners-auto-sync-failure"
def determine_recipients(self) -> list[Actor]:
return Actor.many_from_object(self.organization.get_owners())
@property
def reference(self) -> Model | None:
return None
def get_notification_providers(self) -> Iterable[ExternalProviders]:
# For now, return only email.
return [ExternalProviders.EMAIL]
def get_subject(self, context: Mapping[str, Any] | None = None) -> str:
return "Unable to Complete CODEOWNERS Auto-Sync"
def get_context(self) -> MutableMapping[str, Any]:
return {"project_name": self.project.name}
def get_recipient_context(
self, recipient: Actor, extra_context: Mapping[str, Any]
) -> MutableMapping[str, Any]:
context = super().get_recipient_context(recipient, extra_context)
context["url"] = self.organization.absolute_url(
f"/settings/{self.organization.slug}/projects/{self.project.slug}/ownership/",
query=self.get_sentry_query_params(ExternalProviders.EMAIL, recipient),
)
return context
| AutoSyncNotification |
python | kamyu104__LeetCode-Solutions | Python/number-of-nodes-with-value-one.py | {
"start": 1374,
"end": 1746
} | class ____(object):
def numberOfNodes(self, n, queries):
"""
:type n: int
:type queries: List[int]
:rtype: int
"""
def dfs(u, curr):
curr ^= cnt[u]%2
return curr+sum(dfs(v, curr) for v in xrange(2*u, min(2*u+1, n)+1))
cnt = collections.Counter(queries)
return dfs(1, 0)
| Solution3 |
python | numpy__numpy | numpy/_core/tests/test_multiarray.py | {
"start": 416309,
"end": 420032
} | class ____:
@pytest.mark.parametrize(
"methodname",
[
"__array__", "__array_finalize__", "__array_function__", "__array_ufunc__",
"__array_wrap__", "__complex__", "__copy__", "__deepcopy__",
"__reduce__", "__reduce_ex__", "__setstate__",
"all", "any", "argmax", "argmin", "argsort", "argpartition", "astype",
"byteswap", "choose", "clip", "compress", "conj", "conjugate", "copy",
"cumprod", "cumsum", "diagonal", "dot", "dump", "dumps", "fill", "flatten",
"getfield", "item", "max", "mean", "min", "nonzero", "prod", "put", "ravel",
"repeat", "reshape", "resize", "round", "searchsorted", "setfield",
"setflags", "sort", "partition", "squeeze", "std", "sum", "swapaxes",
"take", "tofile", "tolist", "tobytes", "trace", "transpose", "var", "view",
"__array_namespace__", "__dlpack__", "__dlpack_device__", "to_device",
],
)
def test_array_method_signatures(self, methodname: str):
method = getattr(np.ndarray, methodname)
assert callable(method)
try:
sig = inspect.signature(method)
except ValueError as e:
pytest.fail(f"Could not get signature for np.ndarray.{methodname}: {e}")
assert "self" in sig.parameters
assert sig.parameters["self"].kind is inspect.Parameter.POSITIONAL_ONLY
@pytest.mark.parametrize("func", [np.empty_like, np.concatenate])
def test_c_func_dispatcher_text_signature(self, func):
text_sig = func.__wrapped__.__text_signature__
assert text_sig.startswith("(") and text_sig.endswith(")")
sig = inspect.signature(func)
assert sig == inspect.signature(func.__wrapped__)
assert not hasattr(func, "__signature__")
with pytest.raises(ValueError):
inspect.signature(func, follow_wrapped=False)
@pytest.mark.parametrize(
"func",
[
np.inner, np.where, np.lexsort, np.can_cast, np.min_scalar_type,
np.result_type, np.dot, np.vdot, np.bincount, np.ravel_multi_index,
np.unravel_index, np.copyto, np.putmask, np.packbits, np.unpackbits,
np.shares_memory, np.may_share_memory, np.is_busday, np.busday_offset,
np.busday_count, np.datetime_as_string,
],
)
def test_c_func_dispatcher_signature(self, func):
sig = inspect.signature(func)
assert hasattr(func, "__signature__")
assert sig == func.__signature__
assert sig.parameters
@pytest.mark.parametrize(("func", "parameter_names"), [
(np.arange, ("start_or_stop", "stop", "step", "dtype", "device", "like")),
(np.busdaycalendar, ("weekmask", "holidays")),
(np.char.compare_chararrays, ("a1", "a2", "cmp", "rstrip")),
(np.datetime_data, ("dtype",)),
(np.from_dlpack, ("x", "device", "copy")),
(np.frombuffer, ("buffer", "dtype", "count", "offset", "like")),
(np.fromfile, ("file", "dtype", "count", "sep", "offset", "like")),
(np.fromiter, ("iter", "dtype", "count", "like")),
(np.frompyfunc, ("func", "nin", "nout", "kwargs")),
(np.nested_iters, (
"op", "axes", "flags", "op_flags", "op_dtypes", "order", "casting",
"buffersize",
)),
(np.promote_types, ("type1", "type2")),
])
def test_add_newdoc_function_signature(self, func, parameter_names):
assert not hasattr(func, "__signature__")
assert getattr(func, "__text_signature__", None)
sig = inspect.signature(func)
assert sig.parameters
assert tuple(sig.parameters) == parameter_names
| TestTextSignatures |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/pipelines/config.py | {
"start": 7759,
"end": 7987
} | class ____(graphene.ObjectType):
fields = non_null_list(GrapheneConfigTypeField)
class Meta:
interfaces = (GrapheneConfigValidationError,)
name = "MissingFieldsConfigError"
| GrapheneMissingFieldsConfigError |
python | langchain-ai__langchain | libs/langchain_v1/langchain/agents/middleware/human_in_the_loop.py | {
"start": 638,
"end": 1067
} | class ____(TypedDict):
"""Represents an action request with a name, args, and description."""
name: str
"""The name of the action being requested."""
args: dict[str, Any]
"""Key-value pairs of args needed for the action (e.g., `{"a": 1, "b": 2}`)."""
description: NotRequired[str]
"""The description of the action to be reviewed."""
DecisionType = Literal["approve", "edit", "reject"]
| ActionRequest |
python | google__flatbuffers | goldens/py/flatbuffers/goldens/Universe.py | {
"start": 176,
"end": 2541
} | class ____(object):
__slots__ = ['_tab']
@classmethod
def GetRootAs(cls, buf, offset=0):
n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset)
x = Universe()
x.Init(buf, n + offset)
return x
@classmethod
def GetRootAsUniverse(cls, buf, offset=0):
"""This method is deprecated. Please switch to GetRootAs."""
return cls.GetRootAs(buf, offset)
# Universe
def Init(self, buf, pos):
self._tab = flatbuffers.table.Table(buf, pos)
# Universe
def Age(self):
o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4))
if o != 0:
return self._tab.Get(flatbuffers.number_types.Float64Flags, o + self._tab.Pos)
return 0.0
# Universe
def Galaxies(self, j):
o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6))
if o != 0:
x = self._tab.Vector(o)
x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4
x = self._tab.Indirect(x)
from flatbuffers.goldens.Galaxy import Galaxy
obj = Galaxy()
obj.Init(self._tab.Bytes, x)
return obj
return None
# Universe
def GalaxiesLength(self):
o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6))
if o != 0:
return self._tab.VectorLen(o)
return 0
# Universe
def GalaxiesIsNone(self):
o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6))
return o == 0
def UniverseStart(builder):
builder.StartObject(2)
def Start(builder):
UniverseStart(builder)
def UniverseAddAge(builder, age):
builder.PrependFloat64Slot(0, age, 0.0)
def AddAge(builder, age):
UniverseAddAge(builder, age)
def UniverseAddGalaxies(builder, galaxies):
builder.PrependUOffsetTRelativeSlot(1, flatbuffers.number_types.UOffsetTFlags.py_type(galaxies), 0)
def AddGalaxies(builder, galaxies):
UniverseAddGalaxies(builder, galaxies)
def UniverseStartGalaxiesVector(builder, numElems):
return builder.StartVector(4, numElems, 4)
def StartGalaxiesVector(builder, numElems):
return UniverseStartGalaxiesVector(builder, numElems)
def UniverseEnd(builder):
return builder.EndObject()
def End(builder):
return UniverseEnd(builder)
| Universe |
python | huggingface__transformers | examples/pytorch/question-answering/run_qa_beam_search.py | {
"start": 1799,
"end": 3065
} | class ____:
"""
Arguments pertaining to which model/config/tokenizer we are going to fine-tune from.
"""
model_name_or_path: str = field(
metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"}
)
config_name: Optional[str] = field(
default=None, metadata={"help": "Pretrained config name or path if not the same as model_name"}
)
tokenizer_name: Optional[str] = field(
default=None, metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"}
)
cache_dir: Optional[str] = field(
default=None,
metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"},
)
model_revision: str = field(
default="main",
metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."},
)
token: str = field(
default=None,
metadata={
"help": (
"The token to use as HTTP bearer authorization for remote files. If not specified, will use the token "
"generated when running `hf auth login` (stored in `~/.huggingface`)."
)
},
)
@dataclass
| ModelArguments |
python | allegroai__clearml | clearml/backend_api/services/v2_23/tasks.py | {
"start": 155922,
"end": 157884
} | class ____(Response):
"""
Response of tasks.clone endpoint.
:param id: ID of the new task
:type id: str
:param new_project: In case the new_project_name was specified returns the
target project details
:type new_project: dict
"""
_service = "tasks"
_action = "clone"
_version = "2.23"
_schema = {
"definitions": {},
"properties": {
"id": {"description": "ID of the new task", "type": ["string", "null"]},
"new_project": {
"description": "In case the new_project_name was specified returns the target project details",
"properties": {
"id": {
"description": "The ID of the target project",
"type": "string",
},
"name": {
"description": "The name of the target project",
"type": "string",
},
},
"type": ["object", "null"],
},
},
"type": "object",
}
def __init__(self, id=None, new_project=None, **kwargs):
super(CloneResponse, self).__init__(**kwargs)
self.id = id
self.new_project = new_project
@schema_property("id")
def id(self):
return self._property_id
@id.setter
def id(self, value):
if value is None:
self._property_id = None
return
self.assert_isinstance(value, "id", six.string_types)
self._property_id = value
@schema_property("new_project")
def new_project(self):
return self._property_new_project
@new_project.setter
def new_project(self, value):
if value is None:
self._property_new_project = None
return
self.assert_isinstance(value, "new_project", (dict,))
self._property_new_project = value
| CloneResponse |
python | langchain-ai__langchain | libs/langchain/langchain_classic/retrievers/multi_query.py | {
"start": 691,
"end": 1667
} | class ____(BaseOutputParser[list[str]]):
"""Output parser for a list of lines."""
@override
def parse(self, text: str) -> list[str]:
lines = text.strip().split("\n")
return list(filter(None, lines)) # Remove empty lines
# Default prompt
DEFAULT_QUERY_PROMPT = PromptTemplate(
input_variables=["question"],
template="""You are an AI language model assistant. Your task is
to generate 3 different versions of the given user
question to retrieve relevant documents from a vector database.
By generating multiple perspectives on the user question,
your goal is to help the user overcome some of the limitations
of distance-based similarity search. Provide these alternative
questions separated by newlines. Original question: {question}""",
)
def _unique_documents(documents: Sequence[Document]) -> list[Document]:
return [doc for i, doc in enumerate(documents) if doc not in documents[:i]]
| LineListOutputParser |
python | pytorch__pytorch | tools/test/heuristics/test_interface.py | {
"start": 14726,
"end": 21043
} | class ____(TestTD):
def test_get_test_stats_with_whole_tests(self) -> None:
self.maxDiff = None
tests = ["test1", "test2", "test3", "test4", "test5"]
heuristic1 = interface.TestPrioritizations(
tests,
{
TestRun("test3"): 0.3,
TestRun("test4"): 0.1,
},
)
heuristic2 = interface.TestPrioritizations(
tests,
{
TestRun("test5"): 0.5,
},
)
aggregator = interface.AggregatedHeuristics(tests)
aggregator.add_heuristic_results(self.make_heuristic("H1")(), heuristic1)
aggregator.add_heuristic_results(self.make_heuristic("H2")(), heuristic2)
expected_test3_stats = {
"test_name": "test3",
"test_filters": "",
"heuristics": [
{
"position": 0,
"score": 0.3,
"heuristic_name": "H1",
"trial_mode": False,
},
{
"position": 3,
"score": 0.0,
"heuristic_name": "H2",
"trial_mode": False,
},
],
"aggregated": {"position": 1, "score": 0.3},
"aggregated_trial": {"position": 1, "score": 0.3},
}
test3_stats = aggregator.get_test_stats(TestRun("test3"))
self.assertDictEqual(test3_stats, expected_test3_stats)
def test_get_test_stats_only_contains_allowed_types(self) -> None:
self.maxDiff = None
tests = ["test1", "test2", "test3", "test4", "test5"]
heuristic1 = interface.TestPrioritizations(
tests,
{
TestRun("test3"): 0.3,
TestRun("test4"): 0.1,
},
)
heuristic2 = interface.TestPrioritizations(
tests,
{
TestRun("test5::classA"): 0.5,
},
)
aggregator = interface.AggregatedHeuristics(tests)
aggregator.add_heuristic_results(self.make_heuristic("H1")(), heuristic1)
aggregator.add_heuristic_results(self.make_heuristic("H2")(), heuristic2)
stats3 = aggregator.get_test_stats(TestRun("test3"))
stats5 = aggregator.get_test_stats(TestRun("test5::classA"))
def assert_valid_dict(dict_contents: dict[str, Any]) -> None:
for key, value in dict_contents.items():
self.assertTrue(isinstance(key, str))
self.assertTrue(
isinstance(value, (str, float, int, list, dict)),
f"{value} is not a str, float, or dict",
)
if isinstance(value, dict):
assert_valid_dict(value)
elif isinstance(value, list):
for item in value:
assert_valid_dict(item)
assert_valid_dict(stats3)
assert_valid_dict(stats5)
def test_get_test_stats_gets_rank_for_test_classes(self) -> None:
self.maxDiff = None
tests = ["test1", "test2", "test3", "test4", "test5"]
heuristic1 = interface.TestPrioritizations(
tests,
{
TestRun("test3"): 0.3,
TestRun("test4"): 0.1,
},
)
heuristic2 = interface.TestPrioritizations(
tests,
{
TestRun("test5::classA"): 0.5,
},
)
aggregator = interface.AggregatedHeuristics(tests)
aggregator.add_heuristic_results(self.make_heuristic("H1")(), heuristic1)
aggregator.add_heuristic_results(self.make_heuristic("H2")(), heuristic2)
stats_inclusive = aggregator.get_test_stats(
TestRun("test5", included=["classA"])
)
stats_exclusive = aggregator.get_test_stats(
TestRun("test5", excluded=["classA"])
)
expected_inclusive = {
"test_name": "test5",
"test_filters": "classA",
"heuristics": [
{
"position": 4,
"score": 0.0,
"heuristic_name": "H1",
"trial_mode": False,
},
{
"position": 0,
"score": 0.5,
"heuristic_name": "H2",
"trial_mode": False,
},
],
"aggregated": {"position": 0, "score": 0.5},
"aggregated_trial": {"position": 0, "score": 0.5},
}
expected_exclusive = {
"test_name": "test5",
"test_filters": "not (classA)",
"heuristics": [
{
"position": 4,
"score": 0.0,
"heuristic_name": "H1",
"trial_mode": False,
},
{
"position": 5,
"score": 0.0,
"heuristic_name": "H2",
"trial_mode": False,
},
],
"aggregated": {"position": 5, "score": 0.0},
"aggregated_trial": {"position": 5, "score": 0.0},
}
self.assertDictEqual(stats_inclusive, expected_inclusive)
self.assertDictEqual(stats_exclusive, expected_exclusive)
def test_get_test_stats_works_with_class_granularity_heuristics(self) -> None:
tests = ["test1", "test2", "test3", "test4", "test5"]
heuristic1 = interface.TestPrioritizations(
tests,
{
TestRun("test2"): 0.3,
},
)
heuristic2 = interface.TestPrioritizations(
tests,
{
TestRun("test2::TestFooClass"): 0.5,
},
)
aggregator = interface.AggregatedHeuristics(tests)
aggregator.add_heuristic_results(self.make_heuristic("H1")(), heuristic1)
aggregator.add_heuristic_results(self.make_heuristic("H2")(), heuristic2)
# These should not throw an error
aggregator.get_test_stats(TestRun("test2::TestFooClass"))
aggregator.get_test_stats(TestRun("test2"))
| TestAggregatedHeuristicsTestStats |
python | huggingface__transformers | src/transformers/models/ibert/quant_modules.py | {
"start": 25851,
"end": 27043
} | class ____(Function):
"""
Straight-through Estimator(STE) for torch.round()
"""
@staticmethod
def forward(ctx, x):
return torch.round(x)
@staticmethod
def backward(ctx, grad_output):
return grad_output.clone()
def batch_frexp(inputs, max_bit=31):
"""
Decompose the scaling factor into mantissa and twos exponent.
Args:
scaling_factor (`torch.Tensor`):
Target scaling factor to decompose.
Returns:
``Tuple(torch.Tensor, torch.Tensor)`: mantisa and exponent
"""
shape_of_input = inputs.size()
# trans the input to be a 1-d tensor
inputs = inputs.view(-1)
output_m, output_e = np.frexp(inputs.cpu().numpy())
tmp_m = []
for m in output_m:
int_m_shifted = int(
decimal.Decimal(m * (2**max_bit)).quantize(decimal.Decimal(1), rounding=decimal.ROUND_HALF_UP)
)
tmp_m.append(int_m_shifted)
output_m = np.array(tmp_m)
output_e = float(max_bit) - output_e
return (
torch.from_numpy(output_m).to(inputs.device).view(shape_of_input),
torch.from_numpy(output_e).to(inputs.device).view(shape_of_input),
)
| round_ste |
python | pallets__jinja | src/jinja2/exceptions.py | {
"start": 77,
"end": 354
} | class ____(Exception):
"""Baseclass for all template errors."""
def __init__(self, message: str | None = None) -> None:
super().__init__(message)
@property
def message(self) -> str | None:
return self.args[0] if self.args else None
| TemplateError |
python | PyCQA__pylint | doc/data/messages/n/no-self-use/good/use_self.py | {
"start": 0,
"end": 120
} | class ____:
name: str = "Amelia"
def greeting(self):
print(f"Greetings {self.name} the pythonista!")
| Person |
python | sympy__sympy | sympy/utilities/codegen.py | {
"start": 64114,
"end": 81670
} | class ____(CodeGen):
"""Generator for Rust code.
The .write() method inherited from CodeGen will output a code file
<prefix>.rs
"""
code_extension = "rs"
def __init__(self, project="project", printer=None):
super().__init__(project=project)
self.printer = printer or RustCodePrinter()
def routine(self, name, expr, argument_sequence, global_vars):
"""Specialized Routine creation for Rust."""
if is_sequence(expr) and not isinstance(expr, (MatrixBase, MatrixExpr)):
if not expr:
raise ValueError("No expression given")
expressions = Tuple(*expr)
else:
expressions = Tuple(expr)
# local variables
local_vars = {i.label for i in expressions.atoms(Idx)}
# global variables
global_vars = set() if global_vars is None else set(global_vars)
# symbols that should be arguments
symbols = expressions.free_symbols - local_vars - global_vars - expressions.atoms(Indexed)
# Rust supports multiple return values
return_vals = []
output_args = []
for (i, expr) in enumerate(expressions):
if isinstance(expr, Equality):
out_arg = expr.lhs
expr = expr.rhs
symbol = out_arg
if isinstance(out_arg, Indexed):
dims = tuple([ (S.One, dim) for dim in out_arg.shape])
symbol = out_arg.base.label
output_args.append(InOutArgument(symbol, out_arg, expr, dimensions=dims))
if not isinstance(out_arg, (Indexed, Symbol, MatrixSymbol)):
raise CodeGenError("Only Indexed, Symbol, or MatrixSymbol "
"can define output arguments.")
return_vals.append(Result(expr, name=symbol, result_var=out_arg))
if not expr.has(symbol):
# this is a pure output: remove from the symbols list, so
# it doesn't become an input.
symbols.remove(symbol)
else:
# we have no name for this output
return_vals.append(Result(expr, name='out%d' % (i+1)))
# setup input argument list
output_args.sort(key=lambda x: str(x.name))
arg_list = list(output_args)
array_symbols = {}
for array in expressions.atoms(Indexed):
array_symbols[array.base.label] = array
for array in expressions.atoms(MatrixSymbol):
array_symbols[array] = array
for symbol in sorted(symbols, key=str):
arg_list.append(InputArgument(symbol))
if argument_sequence is not None:
# if the user has supplied IndexedBase instances, we'll accept that
new_sequence = []
for arg in argument_sequence:
if isinstance(arg, IndexedBase):
new_sequence.append(arg.label)
else:
new_sequence.append(arg)
argument_sequence = new_sequence
missing = [x for x in arg_list if x.name not in argument_sequence]
if missing:
msg = "Argument list didn't specify: {0} "
msg = msg.format(", ".join([str(m.name) for m in missing]))
raise CodeGenArgumentListError(msg, missing)
# create redundant arguments to produce the requested sequence
name_arg_dict = {x.name: x for x in arg_list}
new_args = []
for symbol in argument_sequence:
try:
new_args.append(name_arg_dict[symbol])
except KeyError:
new_args.append(InputArgument(symbol))
arg_list = new_args
return Routine(name, arg_list, return_vals, local_vars, global_vars)
def _get_header(self):
"""Writes a common header for the generated files."""
code_lines = []
code_lines.append("/*\n")
tmp = header_comment % {"version": sympy_version,
"project": self.project}
for line in tmp.splitlines():
code_lines.append((" *%s" % line.center(76)).rstrip() + "\n")
code_lines.append(" */\n")
return code_lines
def get_prototype(self, routine):
"""Returns a string for the function prototype of the routine.
If the routine has multiple result objects, an CodeGenError is
raised.
See: https://en.wikipedia.org/wiki/Function_prototype
"""
results = [i.get_datatype('Rust') for i in routine.results]
if len(results) == 1:
rstype = " -> " + results[0]
elif len(routine.results) > 1:
rstype = " -> (" + ", ".join(results) + ")"
else:
rstype = ""
type_args = []
for arg in routine.arguments:
name = self.printer.doprint(arg.name)
if arg.dimensions or isinstance(arg, ResultBase):
type_args.append(("*%s" % name, arg.get_datatype('Rust')))
else:
type_args.append((name, arg.get_datatype('Rust')))
arguments = ", ".join([ "%s: %s" % t for t in type_args])
return "fn %s(%s)%s" % (routine.name, arguments, rstype)
def _preprocessor_statements(self, prefix):
code_lines = []
# code_lines.append("use std::f64::consts::*;\n")
return code_lines
def _get_routine_opening(self, routine):
prototype = self.get_prototype(routine)
return ["%s {\n" % prototype]
def _declare_arguments(self, routine):
# arguments are declared in prototype
return []
def _declare_globals(self, routine):
# global variables are not explicitly declared within C functions
return []
def _declare_locals(self, routine):
# loop variables are declared in loop statement
return []
def _call_printer(self, routine):
code_lines = []
declarations = []
returns = []
# Compose a list of symbols to be dereferenced in the function
# body. These are the arguments that were passed by a reference
# pointer, excluding arrays.
dereference = []
for arg in routine.arguments:
if isinstance(arg, ResultBase) and not arg.dimensions:
dereference.append(arg.name)
for result in routine.results:
if isinstance(result, Result):
assign_to = result.result_var
returns.append(str(result.result_var))
else:
raise CodeGenError("unexpected object in Routine results")
constants, not_supported, rs_expr = self._printer_method_with_settings(
'doprint', {"human": False, "strict": False}, result.expr, assign_to=assign_to)
for name, value in sorted(constants, key=str):
declarations.append("const %s: f64 = %s;\n" % (name, value))
for obj in sorted(not_supported, key=str):
if isinstance(obj, Function):
name = obj.func
else:
name = obj
declarations.append("// unsupported: %s\n" % (name))
code_lines.append("let %s\n" % rs_expr)
if len(returns) > 1:
returns = ['(' + ', '.join(returns) + ')']
returns.append('\n')
return declarations + code_lines + returns
def _get_routine_ending(self, routine):
return ["}\n"]
def dump_rs(self, routines, f, prefix, header=True, empty=True):
self.dump_code(routines, f, prefix, header, empty)
dump_rs.extension = code_extension # type: ignore
dump_rs.__doc__ = CodeGen.dump_code.__doc__
# This list of dump functions is used by CodeGen.write to know which dump
# functions it has to call.
dump_fns = [dump_rs]
def get_code_generator(language, project=None, standard=None, printer = None):
if language == 'C':
if standard is None:
pass
elif standard.lower() == 'c89':
language = 'C89'
elif standard.lower() == 'c99':
language = 'C99'
CodeGenClass = {"C": CCodeGen, "C89": C89CodeGen, "C99": C99CodeGen,
"F95": FCodeGen, "JULIA": JuliaCodeGen,
"OCTAVE": OctaveCodeGen,
"RUST": RustCodeGen}.get(language.upper())
if CodeGenClass is None:
raise ValueError("Language '%s' is not supported." % language)
return CodeGenClass(project, printer)
#
# Friendly functions
#
def codegen(name_expr, language=None, prefix=None, project="project",
to_files=False, header=True, empty=True, argument_sequence=None,
global_vars=None, standard=None, code_gen=None, printer=None):
"""Generate source code for expressions in a given language.
Parameters
==========
name_expr : tuple, or list of tuples
A single (name, expression) tuple or a list of (name, expression)
tuples. Each tuple corresponds to a routine. If the expression is
an equality (an instance of class Equality) the left hand side is
considered an output argument. If expression is an iterable, then
the routine will have multiple outputs.
language : string,
A string that indicates the source code language. This is case
insensitive. Currently, 'C', 'F95' and 'Octave' are supported.
'Octave' generates code compatible with both Octave and Matlab.
prefix : string, optional
A prefix for the names of the files that contain the source code.
Language-dependent suffixes will be appended. If omitted, the name
of the first name_expr tuple is used.
project : string, optional
A project name, used for making unique preprocessor instructions.
[default: "project"]
to_files : bool, optional
When True, the code will be written to one or more files with the
given prefix, otherwise strings with the names and contents of
these files are returned. [default: False]
header : bool, optional
When True, a header is written on top of each source file.
[default: True]
empty : bool, optional
When True, empty lines are used to structure the code.
[default: True]
argument_sequence : iterable, optional
Sequence of arguments for the routine in a preferred order. A
CodeGenError is raised if required arguments are missing.
Redundant arguments are used without warning. If omitted,
arguments will be ordered alphabetically, but with all input
arguments first, and then output or in-out arguments.
global_vars : iterable, optional
Sequence of global variables used by the routine. Variables
listed here will not show up as function arguments.
standard : string, optional
code_gen : CodeGen instance, optional
An instance of a CodeGen subclass. Overrides ``language``.
printer : Printer instance, optional
An instance of a Printer subclass.
Examples
========
>>> from sympy.utilities.codegen import codegen
>>> from sympy.abc import x, y, z
>>> [(c_name, c_code), (h_name, c_header)] = codegen(
... ("f", x+y*z), "C89", "test", header=False, empty=False)
>>> print(c_name)
test.c
>>> print(c_code)
#include "test.h"
#include <math.h>
double f(double x, double y, double z) {
double f_result;
f_result = x + y*z;
return f_result;
}
<BLANKLINE>
>>> print(h_name)
test.h
>>> print(c_header)
#ifndef PROJECT__TEST__H
#define PROJECT__TEST__H
double f(double x, double y, double z);
#endif
<BLANKLINE>
Another example using Equality objects to give named outputs. Here the
filename (prefix) is taken from the first (name, expr) pair.
>>> from sympy.abc import f, g
>>> from sympy import Eq
>>> [(c_name, c_code), (h_name, c_header)] = codegen(
... [("myfcn", x + y), ("fcn2", [Eq(f, 2*x), Eq(g, y)])],
... "C99", header=False, empty=False)
>>> print(c_name)
myfcn.c
>>> print(c_code)
#include "myfcn.h"
#include <math.h>
double myfcn(double x, double y) {
double myfcn_result;
myfcn_result = x + y;
return myfcn_result;
}
void fcn2(double x, double y, double *f, double *g) {
(*f) = 2*x;
(*g) = y;
}
<BLANKLINE>
If the generated function(s) will be part of a larger project where various
global variables have been defined, the 'global_vars' option can be used
to remove the specified variables from the function signature
>>> from sympy.utilities.codegen import codegen
>>> from sympy.abc import x, y, z
>>> [(f_name, f_code), header] = codegen(
... ("f", x+y*z), "F95", header=False, empty=False,
... argument_sequence=(x, y), global_vars=(z,))
>>> print(f_code)
REAL*8 function f(x, y)
implicit none
REAL*8, intent(in) :: x
REAL*8, intent(in) :: y
f = x + y*z
end function
<BLANKLINE>
"""
# Initialize the code generator.
if language is None:
if code_gen is None:
raise ValueError("Need either language or code_gen")
else:
if code_gen is not None:
raise ValueError("You cannot specify both language and code_gen.")
code_gen = get_code_generator(language, project, standard, printer)
if isinstance(name_expr[0], str):
# single tuple is given, turn it into a singleton list with a tuple.
name_expr = [name_expr]
if prefix is None:
prefix = name_expr[0][0]
# Construct Routines appropriate for this code_gen from (name, expr) pairs.
routines = []
for name, expr in name_expr:
routines.append(code_gen.routine(name, expr, argument_sequence,
global_vars))
# Write the code.
return code_gen.write(routines, prefix, to_files, header, empty)
def make_routine(name, expr, argument_sequence=None,
global_vars=None, language="F95"):
"""A factory that makes an appropriate Routine from an expression.
Parameters
==========
name : string
The name of this routine in the generated code.
expr : expression or list/tuple of expressions
A SymPy expression that the Routine instance will represent. If
given a list or tuple of expressions, the routine will be
considered to have multiple return values and/or output arguments.
argument_sequence : list or tuple, optional
List arguments for the routine in a preferred order. If omitted,
the results are language dependent, for example, alphabetical order
or in the same order as the given expressions.
global_vars : iterable, optional
Sequence of global variables used by the routine. Variables
listed here will not show up as function arguments.
language : string, optional
Specify a target language. The Routine itself should be
language-agnostic but the precise way one is created, error
checking, etc depend on the language. [default: "F95"].
Notes
=====
A decision about whether to use output arguments or return values is made
depending on both the language and the particular mathematical expressions.
For an expression of type Equality, the left hand side is typically made
into an OutputArgument (or perhaps an InOutArgument if appropriate).
Otherwise, typically, the calculated expression is made a return values of
the routine.
Examples
========
>>> from sympy.utilities.codegen import make_routine
>>> from sympy.abc import x, y, f, g
>>> from sympy import Eq
>>> r = make_routine('test', [Eq(f, 2*x), Eq(g, x + y)])
>>> [arg.result_var for arg in r.results]
[]
>>> [arg.name for arg in r.arguments]
[x, y, f, g]
>>> [arg.name for arg in r.result_variables]
[f, g]
>>> r.local_vars
set()
Another more complicated example with a mixture of specified and
automatically-assigned names. Also has Matrix output.
>>> from sympy import Matrix
>>> r = make_routine('fcn', [x*y, Eq(f, 1), Eq(g, x + g), Matrix([[x, 2]])])
>>> [arg.result_var for arg in r.results] # doctest: +SKIP
[result_5397460570204848505]
>>> [arg.expr for arg in r.results]
[x*y]
>>> [arg.name for arg in r.arguments] # doctest: +SKIP
[x, y, f, g, out_8598435338387848786]
We can examine the various arguments more closely:
>>> from sympy.utilities.codegen import (InputArgument, OutputArgument,
... InOutArgument)
>>> [a.name for a in r.arguments if isinstance(a, InputArgument)]
[x, y]
>>> [a.name for a in r.arguments if isinstance(a, OutputArgument)] # doctest: +SKIP
[f, out_8598435338387848786]
>>> [a.expr for a in r.arguments if isinstance(a, OutputArgument)]
[1, Matrix([[x, 2]])]
>>> [a.name for a in r.arguments if isinstance(a, InOutArgument)]
[g]
>>> [a.expr for a in r.arguments if isinstance(a, InOutArgument)]
[g + x]
"""
# initialize a new code generator
code_gen = get_code_generator(language)
return code_gen.routine(name, expr, argument_sequence, global_vars)
| RustCodeGen |
python | jmcnamara__XlsxWriter | xlsxwriter/test/utility/test_xl_cell_to_rowcol_abs.py | {
"start": 287,
"end": 1653
} | class ____(unittest.TestCase):
"""
Test xl_cell_to_rowcol_abs() utility function.
"""
def test_xl_cell_to_rowcol_abs(self):
"""Test xl_cell_to_rowcol_abs()"""
tests = [
# row, col, A1 string
(0, 0, "A1"),
(0, 1, "B1"),
(0, 2, "C1"),
(0, 9, "J1"),
(1, 0, "A2"),
(2, 0, "A3"),
(9, 0, "A10"),
(1, 24, "Y2"),
(7, 25, "Z8"),
(9, 26, "AA10"),
(1, 254, "IU2"),
(1, 255, "IV2"),
(1, 256, "IW2"),
(0, 16383, "XFD1"),
(1048576, 16384, "XFE1048577"),
]
for row, col, string in tests:
exp = (row, col, 0, 0)
got = xl_cell_to_rowcol_abs(string)
self.assertEqual(exp, got)
def test_xl_cell_to_rowcol_abs_abs(self):
"""Test xl_cell_to_rowcol_abs() with absolute references"""
tests = [
# row, col, row_abs, col_abs, A1 string
(0, 0, 0, 0, "A1"),
(0, 0, 1, 0, "A$1"),
(0, 0, 0, 1, "$A1"),
(0, 0, 1, 1, "$A$1"),
]
for row, col, row_abs, col_abs, string in tests:
exp = (row, col, row_abs, col_abs)
got = xl_cell_to_rowcol_abs(string)
self.assertEqual(exp, got)
| TestUtility |
python | crytic__slither | slither/core/solidity_types/function_type.py | {
"start": 168,
"end": 2469
} | class ____(Type):
def __init__(
self,
params: List[FunctionTypeVariable],
return_values: List[FunctionTypeVariable],
) -> None:
assert all(isinstance(x, FunctionTypeVariable) for x in params)
assert all(isinstance(x, FunctionTypeVariable) for x in return_values)
super().__init__()
self._params: List[FunctionTypeVariable] = params
self._return_values: List[FunctionTypeVariable] = return_values
@property
def params(self) -> List[FunctionTypeVariable]:
return self._params
@property
def return_values(self) -> List[FunctionTypeVariable]:
return self._return_values
@property
def return_type(self) -> List[Type]:
return [x.type for x in self.return_values]
@property
def storage_size(self) -> Tuple[int, bool]:
return 24, False
@property
def is_dynamic(self) -> bool:
return False
def __str__(self) -> str:
# Use x.type
# x.name may be empty
params = ",".join([str(x.type) for x in self._params])
return_values = ",".join([str(x.type) for x in self._return_values])
if return_values:
return f"function({params}) returns({return_values})"
return f"function({params})"
@property
def parameters_signature(self) -> str:
"""
Return the parameters signature(without the return statetement)
"""
# Use x.type
# x.name may be empty
params = ",".join([str(x.type) for x in self._params])
return f"({params})"
@property
def signature(self) -> str:
"""
Return the signature(with the return statetement if it exists)
"""
# Use x.type
# x.name may be empty
params = ",".join([str(x.type) for x in self._params])
return_values = ",".join([str(x.type) for x in self._return_values])
if return_values:
return f"({params}) returns({return_values})"
return f"({params})"
def __eq__(self, other: Any) -> bool:
if not isinstance(other, FunctionType):
return False
return self.params == other.params and self.return_values == other.return_values
def __hash__(self):
return hash(str(self))
| FunctionType |
python | dagster-io__dagster | python_modules/libraries/dagster-airbyte/dagster_airbyte/managed/generated/sources.py | {
"start": 268196,
"end": 269342
} | class ____(GeneratedAirbyteSource):
@public
def __init__(
self, name: str, access_token: str, start_date: str, survey_ids: Optional[list[str]] = None
):
"""Airbyte Source for Surveymonkey.
Documentation can be found at https://docs.airbyte.com/integrations/sources/surveymonkey
Args:
name (str): The name of the destination.
access_token (str): Access Token for making authenticated requests. See the docs for information on how to generate this key.
start_date (str): UTC date and time in the format 2017-01-25T00:00:00Z. Any data before this date will not be replicated.
survey_ids (Optional[List[str]]): IDs of the surveys from which you'd like to replicate data. If left empty, data from all boards to which you have access will be replicated.
"""
self.access_token = check.str_param(access_token, "access_token")
self.start_date = check.str_param(start_date, "start_date")
self.survey_ids = check.opt_nullable_list_param(survey_ids, "survey_ids", str)
super().__init__("Surveymonkey", name)
| SurveymonkeySource |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/util/_collections.py | {
"start": 3568,
"end": 4402
} | class ____(ImmutableDictBase[_KT, _VT]):
"""A dictionary that is not publicly mutable."""
def __new__(cls, *args: Any) -> FacadeDict[Any, Any]:
new: FacadeDict[Any, Any] = ImmutableDictBase.__new__(cls)
return new
def copy(self) -> NoReturn:
raise NotImplementedError(
"an immutabledict shouldn't need to be copied. use dict(d) "
"if you need a mutable dictionary."
)
def __reduce__(self) -> Any:
return FacadeDict, (dict(self),)
def _insert_item(self, key: _KT, value: _VT) -> None:
"""insert an item into the dictionary directly."""
dict.__setitem__(self, key, value)
def __repr__(self) -> str:
return "FacadeDict(%s)" % dict.__repr__(self)
_DT = TypeVar("_DT", bound=Any)
_F = TypeVar("_F", bound=Any)
| FacadeDict |
python | getsentry__sentry | src/sentry/integrations/slack/spec.py | {
"start": 778,
"end": 3459
} | class ____(MessagingIntegrationSpec):
@property
def provider_slug(self) -> str:
return IntegrationProviderSlug.SLACK.value
@property
def action_service(self) -> ActionService:
return ActionService.SLACK
@property
def integration_provider(self) -> type[IntegrationProvider]:
from sentry.integrations.slack.integration import SlackIntegrationProvider
return SlackIntegrationProvider
@property
def identity_view_set(self) -> MessagingIdentityLinkViewSet:
from sentry.integrations.slack.views.link_identity import SlackLinkIdentityView
from sentry.integrations.slack.views.link_team import SlackLinkTeamView
from sentry.integrations.slack.views.unlink_identity import SlackUnlinkIdentityView
from sentry.integrations.slack.views.unlink_team import SlackUnlinkTeamView
return MessagingIdentityLinkViewSet(
link_personal_identity=SlackLinkIdentityView,
unlink_personal_identity=SlackUnlinkIdentityView,
link_team_identity=SlackLinkTeamView,
unlink_team_identity=SlackUnlinkTeamView,
)
def send_incident_alert_notification(
self,
organization: Organization,
alert_context: AlertContext,
notification_context: NotificationContext,
metric_issue_context: MetricIssueContext,
open_period_context: OpenPeriodContext,
alert_rule_serialized_response: AlertRuleSerializerResponse,
incident_serialized_response: DetailedIncidentSerializerResponse,
notification_uuid: str | None = None,
) -> bool:
from sentry.integrations.slack.utils.notifications import send_incident_alert_notification
return send_incident_alert_notification(
organization=organization,
alert_context=alert_context,
notification_context=notification_context,
metric_issue_context=metric_issue_context,
open_period_context=open_period_context,
alert_rule_serialized_response=alert_rule_serialized_response,
incident_serialized_response=incident_serialized_response,
notification_uuid=notification_uuid,
)
@property
def notify_service_action(self) -> type[IntegrationEventAction] | None:
from sentry.integrations.slack.actions.notification import SlackNotifyServiceAction
return SlackNotifyServiceAction
@property
def notification_sent(self) -> type[analytics.Event] | None:
from sentry.integrations.slack.analytics import SlackIntegrationNotificationSent
return SlackIntegrationNotificationSent
| SlackMessagingSpec |
python | django__django | tests/bulk_create/models.py | {
"start": 4186,
"end": 4418
} | class ____(models.Model):
name = models.CharField(max_length=15, null=True)
country = models.OneToOneField(Country, models.CASCADE, primary_key=True)
big_auto_fields = models.ManyToManyField(BigAutoFieldModel)
| RelatedModel |
python | openai__openai-python | src/openai/types/chat/chat_completion_tool_message_param.py | {
"start": 354,
"end": 730
} | class ____(TypedDict, total=False):
content: Required[Union[str, Iterable[ChatCompletionContentPartTextParam]]]
"""The contents of the tool message."""
role: Required[Literal["tool"]]
"""The role of the messages author, in this case `tool`."""
tool_call_id: Required[str]
"""Tool call that this message is responding to."""
| ChatCompletionToolMessageParam |
python | wandb__wandb | wandb/plot/custom_chart.py | {
"start": 2131,
"end": 5010
} | class ____:
table: wandb.Table
spec: CustomChartSpec
def set_key(self, key: str):
"""Sets the key for the spec and updates dependent configurations."""
self.spec.key = key
def plot_table(
vega_spec_name: str,
data_table: wandb.Table,
fields: dict[str, Any],
string_fields: dict[str, Any] | None = None,
split_table: bool = False,
) -> CustomChart:
"""Creates a custom charts using a Vega-Lite specification and a `wandb.Table`.
This function creates a custom chart based on a Vega-Lite specification and
a data table represented by a `wandb.Table` object. The specification needs
to be predefined and stored in the W&B backend. The function returns a custom
chart object that can be logged to W&B using `wandb.Run.log()`.
Args:
vega_spec_name: The name or identifier of the Vega-Lite spec
that defines the visualization structure.
data_table: A `wandb.Table` object containing the data to be
visualized.
fields: A mapping between the fields in the Vega-Lite spec and the
corresponding columns in the data table to be visualized.
string_fields: A dictionary for providing values for any string constants
required by the custom visualization.
split_table: Whether the table should be split into a separate section
in the W&B UI. If `True`, the table will be displayed in a section named
"Custom Chart Tables". Default is `False`.
Returns:
CustomChart: A custom chart object that can be logged to W&B. To log the
chart, pass the chart object as argument to `wandb.Run.log()`.
Raises:
wandb.Error: If `data_table` is not a `wandb.Table` object.
Example:
```python
# Create a custom chart using a Vega-Lite spec and the data table.
import wandb
data = [[1, 1], [2, 2], [3, 3], [4, 4], [5, 5]]
table = wandb.Table(data=data, columns=["x", "y"])
fields = {"x": "x", "y": "y", "title": "MY TITLE"}
with wandb.init() as run:
# Training code goes here
# Create a custom title with `string_fields`.
my_custom_chart = wandb.plot_table(
vega_spec_name="wandb/line/v0",
data_table=table,
fields=fields,
string_fields={"title": "Title"},
)
run.log({"custom_chart": my_custom_chart})
```
"""
if not isinstance(data_table, wandb.Table):
raise wandb.Error(
f"Expected `data_table` to be `wandb.Table` type, instead got {type(data_table).__name__}"
)
return CustomChart(
table=data_table,
spec=CustomChartSpec(
spec_name=vega_spec_name,
fields=fields,
string_fields=string_fields or {},
split_table=split_table,
),
)
| CustomChart |
python | giampaolo__psutil | tests/test_connections.py | {
"start": 9196,
"end": 18157
} | class ____(ConnectionTestCase):
def test_filters(self):
def check(kind, families, types):
for conn in this_proc_net_connections(kind=kind):
assert conn.family in families
assert conn.type in types
if not SKIP_SYSCONS:
for conn in psutil.net_connections(kind=kind):
assert conn.family in families
assert conn.type in types
with create_sockets():
check(
'all',
[AF_INET, AF_INET6, AF_UNIX],
[SOCK_STREAM, SOCK_DGRAM, SOCK_SEQPACKET],
)
check('inet', [AF_INET, AF_INET6], [SOCK_STREAM, SOCK_DGRAM])
check('inet4', [AF_INET], [SOCK_STREAM, SOCK_DGRAM])
check('tcp', [AF_INET, AF_INET6], [SOCK_STREAM])
check('tcp4', [AF_INET], [SOCK_STREAM])
check('tcp6', [AF_INET6], [SOCK_STREAM])
check('udp', [AF_INET, AF_INET6], [SOCK_DGRAM])
check('udp4', [AF_INET], [SOCK_DGRAM])
check('udp6', [AF_INET6], [SOCK_DGRAM])
if HAS_NET_CONNECTIONS_UNIX:
check(
'unix',
[AF_UNIX],
[SOCK_STREAM, SOCK_DGRAM, SOCK_SEQPACKET],
)
@skip_on_access_denied(only_if=MACOS)
def test_combos(self):
reap_children()
def check_conn(proc, conn, family, type, laddr, raddr, status, kinds):
all_kinds = (
"all",
"inet",
"inet4",
"inet6",
"tcp",
"tcp4",
"tcp6",
"udp",
"udp4",
"udp6",
)
check_connection_ntuple(conn)
assert conn.family == family
assert conn.type == type
assert conn.laddr == laddr
assert conn.raddr == raddr
assert conn.status == status
for kind in all_kinds:
cons = proc.net_connections(kind=kind)
if kind in kinds:
assert cons != []
else:
assert cons == []
# compare against system-wide connections
# XXX Solaris can't retrieve system-wide UNIX
# sockets.
if HAS_NET_CONNECTIONS_UNIX:
self.compare_procsys_connections(proc.pid, [conn])
tcp_template = textwrap.dedent("""
import socket, time
s = socket.socket({family}, socket.SOCK_STREAM)
s.bind(('{addr}', 0))
s.listen(5)
with open('{testfn}', 'w') as f:
f.write(str(s.getsockname()[:2]))
[time.sleep(0.1) for x in range(100)]
""")
udp_template = textwrap.dedent("""
import socket, time
s = socket.socket({family}, socket.SOCK_DGRAM)
s.bind(('{addr}', 0))
with open('{testfn}', 'w') as f:
f.write(str(s.getsockname()[:2]))
[time.sleep(0.1) for x in range(100)]
""")
# must be relative on Windows
testfile = os.path.basename(self.get_testfn(dir=os.getcwd()))
tcp4_template = tcp_template.format(
family=int(AF_INET), addr="127.0.0.1", testfn=testfile
)
udp4_template = udp_template.format(
family=int(AF_INET), addr="127.0.0.1", testfn=testfile
)
tcp6_template = tcp_template.format(
family=int(AF_INET6), addr="::1", testfn=testfile
)
udp6_template = udp_template.format(
family=int(AF_INET6), addr="::1", testfn=testfile
)
# launch various subprocess instantiating a socket of various
# families and types to enrich psutil results
tcp4_proc = self.pyrun(tcp4_template)
tcp4_addr = eval(wait_for_file(testfile, delete=True))
udp4_proc = self.pyrun(udp4_template)
udp4_addr = eval(wait_for_file(testfile, delete=True))
if supports_ipv6():
tcp6_proc = self.pyrun(tcp6_template)
tcp6_addr = eval(wait_for_file(testfile, delete=True))
udp6_proc = self.pyrun(udp6_template)
udp6_addr = eval(wait_for_file(testfile, delete=True))
else:
tcp6_proc = None
udp6_proc = None
tcp6_addr = None
udp6_addr = None
for p in psutil.Process().children():
cons = p.net_connections()
assert len(cons) == 1
for conn in cons:
# TCP v4
if p.pid == tcp4_proc.pid:
check_conn(
p,
conn,
AF_INET,
SOCK_STREAM,
tcp4_addr,
(),
psutil.CONN_LISTEN,
("all", "inet", "inet4", "tcp", "tcp4"),
)
# UDP v4
elif p.pid == udp4_proc.pid:
check_conn(
p,
conn,
AF_INET,
SOCK_DGRAM,
udp4_addr,
(),
psutil.CONN_NONE,
("all", "inet", "inet4", "udp", "udp4"),
)
# TCP v6
elif p.pid == getattr(tcp6_proc, "pid", None):
check_conn(
p,
conn,
AF_INET6,
SOCK_STREAM,
tcp6_addr,
(),
psutil.CONN_LISTEN,
("all", "inet", "inet6", "tcp", "tcp6"),
)
# UDP v6
elif p.pid == getattr(udp6_proc, "pid", None):
check_conn(
p,
conn,
AF_INET6,
SOCK_DGRAM,
udp6_addr,
(),
psutil.CONN_NONE,
("all", "inet", "inet6", "udp", "udp6"),
)
def test_count(self):
with create_sockets():
# tcp
cons = this_proc_net_connections(kind='tcp')
assert len(cons) == (2 if supports_ipv6() else 1)
for conn in cons:
assert conn.family in {AF_INET, AF_INET6}
assert conn.type == SOCK_STREAM
# tcp4
cons = this_proc_net_connections(kind='tcp4')
assert len(cons) == 1
assert cons[0].family == AF_INET
assert cons[0].type == SOCK_STREAM
# tcp6
if supports_ipv6():
cons = this_proc_net_connections(kind='tcp6')
assert len(cons) == 1
assert cons[0].family == AF_INET6
assert cons[0].type == SOCK_STREAM
# udp
cons = this_proc_net_connections(kind='udp')
assert len(cons) == (2 if supports_ipv6() else 1)
for conn in cons:
assert conn.family in {AF_INET, AF_INET6}
assert conn.type == SOCK_DGRAM
# udp4
cons = this_proc_net_connections(kind='udp4')
assert len(cons) == 1
assert cons[0].family == AF_INET
assert cons[0].type == SOCK_DGRAM
# udp6
if supports_ipv6():
cons = this_proc_net_connections(kind='udp6')
assert len(cons) == 1
assert cons[0].family == AF_INET6
assert cons[0].type == SOCK_DGRAM
# inet
cons = this_proc_net_connections(kind='inet')
assert len(cons) == (4 if supports_ipv6() else 2)
for conn in cons:
assert conn.family in {AF_INET, AF_INET6}
assert conn.type in {SOCK_STREAM, SOCK_DGRAM}
# inet6
if supports_ipv6():
cons = this_proc_net_connections(kind='inet6')
assert len(cons) == 2
for conn in cons:
assert conn.family == AF_INET6
assert conn.type in {SOCK_STREAM, SOCK_DGRAM}
# Skipped on BSD becayse by default the Python process
# creates a UNIX socket to '/var/run/log'.
if HAS_NET_CONNECTIONS_UNIX and not (FREEBSD or NETBSD):
cons = this_proc_net_connections(kind='unix')
assert len(cons) == 3
for conn in cons:
assert conn.family == AF_UNIX
assert conn.type in {SOCK_STREAM, SOCK_DGRAM}
@pytest.mark.skipif(SKIP_SYSCONS, reason="requires root")
| TestFilters |
python | walkccc__LeetCode | solutions/1206. Design Skiplist/1206.py | {
"start": 47,
"end": 121
} | class ____:
val: int = -1
next: 'Node' = None
down: 'Node' = None
| Node |
python | getsentry__sentry | tests/snuba/api/endpoints/test_discover_homepage_query.py | {
"start": 502,
"end": 9146
} | class ____(DiscoverSavedQueryBase):
def setUp(self) -> None:
super().setUp()
self.url = reverse("sentry-api-0-discover-homepage-query", args=[self.org.slug])
self.query = {"fields": ["test"], "conditions": [], "limit": 10}
self.project_ids = [
self.create_project(organization=self.org).id,
self.create_project(organization=self.org).id,
]
def test_returns_no_response_if_no_homepage_query_for_user(self) -> None:
with self.feature(FEATURES):
response = self.client.get(self.url)
assert response.status_code == 204, response.content
assert response.data is None
def test_returns_serialized_saved_query_if_homepage_is_set(self) -> None:
saved_query = DiscoverSavedQuery.objects.create(
organization=self.org,
created_by_id=self.user.id,
name="Test query",
query=self.query,
is_homepage=True,
)
with self.feature(FEATURES):
response = self.client.get(self.url)
assert response.status_code == 200, response.content
assert response.data == serialize(saved_query)
def test_put_updates_existing_homepage_query_to_reflect_new_data(self) -> None:
saved_query = DiscoverSavedQuery.objects.create(
organization=self.org,
created_by_id=self.user.id,
name="Test query",
query=self.query,
dataset=DiscoverSavedQueryTypes.DISCOVER,
is_homepage=True,
)
with self.feature(FEATURES):
response = self.client.put(
self.url,
{
"name": "A new homepage query update",
"projects": self.project_ids,
"fields": ["field1", "field2"],
"queryDataset": DiscoverSavedQueryTypes.get_type_name(
DiscoverSavedQueryTypes.TRANSACTION_LIKE
),
},
)
assert response.status_code == 200, response.content
saved_query.refresh_from_db()
assert response.data == serialize(saved_query)
assert saved_query.query["fields"] == ["field1", "field2"]
assert saved_query.dataset == DiscoverSavedQueryTypes.TRANSACTION_LIKE
assert set(saved_query.projects.values_list("id", flat=True)) == set(self.project_ids)
def test_put_creates_new_discover_saved_query_if_none_exists(self) -> None:
homepage_query_payload = {
"version": 2,
"name": "New Homepage Query",
"projects": self.project_ids,
"environment": ["alpha"],
"fields": ["environment", "platform.name"],
"orderby": "-timestamp",
"range": None,
}
with self.feature(FEATURES):
response = self.client.put(self.url, data=homepage_query_payload)
assert response.status_code == 201, response.content
new_query = DiscoverSavedQuery.objects.get(
created_by_id=self.user.id, organization=self.org, is_homepage=True
)
assert response.data == serialize(new_query)
assert new_query.query["fields"] == homepage_query_payload["fields"]
assert new_query.query["environment"] == homepage_query_payload["environment"]
assert new_query.dataset == DiscoverSavedQueryTypes.get_id_for_type_name("error-events")
assert set(new_query.projects.values_list("id", flat=True)) == set(self.project_ids)
def test_put_responds_with_saved_empty_name_field(self) -> None:
homepage_query_payload = {
"version": 2,
"name": "New Homepage Query",
"projects": self.project_ids,
"environment": ["alpha"],
"fields": ["environment", "platform.name"],
"orderby": "-timestamp",
"range": None,
}
with self.feature(FEATURES):
response = self.client.put(self.url, data=homepage_query_payload)
assert response.status_code == 201, response.content
new_query = DiscoverSavedQuery.objects.get(
created_by_id=self.user.id, organization=self.org, is_homepage=True
)
assert new_query.name == ""
assert response.data["name"] == ""
def test_put_with_no_name(self) -> None:
homepage_query_payload = {
"version": 2,
"name": "",
"projects": self.project_ids,
"environment": ["alpha"],
"fields": ["environment", "platform.name"],
"orderby": "-timestamp",
"range": None,
}
with self.feature(FEATURES):
response = self.client.put(self.url, data=homepage_query_payload)
assert response.status_code == 201, response.content
new_query = DiscoverSavedQuery.objects.get(
created_by_id=self.user.id, organization=self.org, is_homepage=True
)
assert new_query.name == ""
assert response.data["name"] == ""
def test_post_not_allowed(self) -> None:
homepage_query_payload = {
"version": 2,
"name": "New Homepage Query",
"projects": ["-1"],
"environment": ["alpha"],
"fields": ["environment", "platform.name"],
"orderby": "-timestamp",
"range": None,
}
with self.feature(FEATURES):
response = self.client.post(self.url, data=homepage_query_payload)
assert response.status_code == 405, response.content
def test_delete_resets_saved_query(self) -> None:
DiscoverSavedQuery.objects.create(
organization=self.org,
created_by_id=self.user.id,
name="Test query",
query=self.query,
is_homepage=True,
)
with self.feature(FEATURES):
response = self.client.delete(self.url)
assert response.status_code == 204
assert not DiscoverSavedQuery.objects.filter(
created_by_id=self.user.id, organization=self.org, is_homepage=True
).exists()
def test_put_allows_custom_measurements_in_equations_with_query(self) -> None:
# Having a custom measurement stored implies that a transaction with this measurement has been stored
BaseMetricsTestCase.store_metric(
self.org.id,
self.project_ids[0],
"d:transactions/measurements.custom_duration@millisecond",
{},
int(before_now(days=1).timestamp()),
1,
)
homepage_query_payload = {
"version": 2,
"name": "New Homepage Query",
"projects": [self.project_ids[0]],
"environment": ["alpha"],
"fields": [
"transaction.duration",
"measurements.custom_duration",
"equation|measurements.custom_duration / transaction.duration",
],
"orderby": "-transaction.duration",
"query": "test",
"range": None,
"queryDataset": DiscoverSavedQueryTypes.get_type_name(
DiscoverSavedQueryTypes.TRANSACTION_LIKE
),
}
with self.feature(FEATURES):
response = self.client.put(self.url, data=homepage_query_payload)
assert response.status_code == 201, response.content
new_query = DiscoverSavedQuery.objects.get(
created_by_id=self.user.id, organization=self.org, is_homepage=True
)
assert response.data == serialize(new_query)
assert list(new_query.projects.values_list("id", flat=True)) == [self.project_ids[0]]
def test_put_success_is_filter(self) -> None:
with self.feature(FEATURES):
response = self.client.put(
self.url,
{
"name": "new query",
"projects": self.project_ids,
"fields": ["title"],
"query": "is:unresolved",
"range": "24h",
"yAxis": ["count(id)"],
"display": "releases",
"version": 2,
},
)
assert response.status_code == 201, response.content
data = response.data
assert data["fields"] == ["title"]
assert data["range"] == "24h"
assert data["query"] == "is:unresolved"
assert data["yAxis"] == ["count(id)"]
assert data["display"] == "releases"
assert data["version"] == 2
| DiscoverHomepageQueryTest |
python | jupyterlab__jupyterlab | jupyterlab/labapp.py | {
"start": 7511,
"end": 7679
} | class ____(AppOptions):
extensions = Bool(False)
settings = Bool(False)
staging = Bool(True)
static = Bool(False)
all = Bool(False)
| LabCleanAppOptions |
python | scrapy__scrapy | tests/test_pipeline_media.py | {
"start": 1341,
"end": 6689
} | class ____:
pipeline_class = UserDefinedPipeline
settings = None
def setup_method(self):
crawler = get_crawler(DefaultSpider, self.settings)
crawler.spider = crawler._create_spider()
self.pipe = self.pipeline_class.from_crawler(crawler)
self.pipe.download_func = _mocked_download_func
self.pipe.open_spider()
self.info = self.pipe.spiderinfo
self.fingerprint = crawler.request_fingerprinter.fingerprint
def teardown_method(self):
for name, signal in vars(signals).items():
if not name.startswith("_"):
disconnect_all(signal)
def test_modify_media_request(self):
request = Request("http://url")
self.pipe._modify_media_request(request)
assert request.meta == {"handle_httpstatus_all": True}
def test_should_remove_req_res_references_before_caching_the_results(self):
"""Regression test case to prevent a memory leak in the Media Pipeline.
The memory leak is triggered when an exception is raised when a Response
scheduled by the Media Pipeline is being returned. For example, when a
FileException('download-error') is raised because the Response status
code is not 200 OK.
It happens because we are keeping a reference to the Response object
inside the FileException context. This is caused by the way Twisted
return values from inline callbacks. It raises a custom exception
encapsulating the original return value.
The solution is to remove the exception context when this context is a
_DefGen_Return instance, the BaseException used by Twisted to pass the
returned value from those inline callbacks.
Maybe there's a better and more reliable way to test the case described
here, but it would be more complicated and involve running - or at least
mocking - some async steps from the Media Pipeline. The current test
case is simple and detects the problem very fast. On the other hand, it
would not detect another kind of leak happening due to old object
references being kept inside the Media Pipeline cache.
This problem does not occur in Python 2.7 since we don't have Exception
Chaining (https://www.python.org/dev/peps/pep-3134/).
"""
# Create sample pair of Request and Response objects
request = Request("http://url")
response = Response("http://url", body=b"", request=request)
# Simulate the Media Pipeline behavior to produce a Twisted Failure
try:
# Simulate a Twisted inline callback returning a Response
raise StopIteration(response)
except StopIteration as exc:
def_gen_return_exc = exc
try:
# Simulate the media_downloaded callback raising a FileException
# This usually happens when the status code is not 200 OK
raise FileException("download-error")
except Exception as exc:
file_exc = exc
# Simulate Twisted capturing the FileException
# It encapsulates the exception inside a Twisted Failure
failure = Failure(file_exc)
# The Failure should encapsulate a FileException ...
assert failure.value == file_exc
# ... and it should have the StopIteration exception set as its context
assert failure.value.__context__ == def_gen_return_exc
# Let's calculate the request fingerprint and fake some runtime data...
fp = self.fingerprint(request)
info = self.pipe.spiderinfo
info.downloading.add(fp)
info.waiting[fp] = []
# When calling the method that caches the Request's result ...
self.pipe._cache_result_and_execute_waiters(failure, fp, info)
# ... it should store the Twisted Failure ...
assert info.downloaded[fp] == failure
# ... encapsulating the original FileException ...
assert info.downloaded[fp].value == file_exc
# ... but it should not store the StopIteration exception on its context
context = getattr(info.downloaded[fp].value, "__context__", None)
assert context is None
def test_default_item_completed(self):
item = {"name": "name"}
assert self.pipe.item_completed([], item, self.info) is item
# Check that failures are logged by default
fail = Failure(Exception())
results = [(True, 1), (False, fail)]
with LogCapture() as log:
new_item = self.pipe.item_completed(results, item, self.info)
assert new_item is item
assert len(log.records) == 1
record = log.records[0]
assert record.levelname == "ERROR"
assert record.exc_info == failure_to_exc_info(fail)
# disable failure logging and check again
self.pipe.LOG_FAILED_RESULTS = False
with LogCapture() as log:
new_item = self.pipe.item_completed(results, item, self.info)
assert new_item is item
assert len(log.records) == 0
@inlineCallbacks
def test_default_process_item(self):
item = {"name": "name"}
new_item = yield self.pipe.process_item(item)
assert new_item is item
| TestBaseMediaPipeline |
python | huggingface__transformers | tests/models/metaclip_2/test_modeling_metaclip_2.py | {
"start": 18378,
"end": 20536
} | class ____:
def __init__(self, parent, text_kwargs=None, vision_kwargs=None, is_training=True):
if text_kwargs is None:
text_kwargs = {}
if vision_kwargs is None:
vision_kwargs = {}
self.parent = parent
self.text_model_tester = MetaClip2TextModelTester(parent, **text_kwargs)
self.vision_model_tester = MetaClip2VisionModelTester(parent, **vision_kwargs)
self.batch_size = self.text_model_tester.batch_size # need bs for batching_equivalence test
self.is_training = is_training
def prepare_config_and_inputs(self):
text_config, input_ids, attention_mask = self.text_model_tester.prepare_config_and_inputs()
vision_config, pixel_values = self.vision_model_tester.prepare_config_and_inputs()
config = self.get_config()
return config, input_ids, attention_mask, pixel_values
def get_config(self):
return MetaClip2Config(
text_config=self.text_model_tester.get_config().to_dict(),
vision_config=self.vision_model_tester.get_config().to_dict(),
projection_dim=64,
)
def create_and_check_model(self, config, input_ids, attention_mask, pixel_values):
model = MetaClip2Model(config).to(torch_device).eval()
with torch.no_grad():
result = model(input_ids, pixel_values, attention_mask)
self.parent.assertEqual(
result.logits_per_image.shape, (self.vision_model_tester.batch_size, self.text_model_tester.batch_size)
)
self.parent.assertEqual(
result.logits_per_text.shape, (self.text_model_tester.batch_size, self.vision_model_tester.batch_size)
)
def prepare_config_and_inputs_for_common(self):
config_and_inputs = self.prepare_config_and_inputs()
config, input_ids, attention_mask, pixel_values = config_and_inputs
inputs_dict = {
"input_ids": input_ids,
"attention_mask": attention_mask,
"pixel_values": pixel_values,
"return_loss": True,
}
return config, inputs_dict
@require_torch
| MetaClip2ModelTester |
python | coleifer__peewee | tests/keys.py | {
"start": 5894,
"end": 7676
} | class ____(ModelTestCase):
requires = [User, Relationship]
def test_multiple_fks(self):
a = User.create(username='a')
b = User.create(username='b')
c = User.create(username='c')
self.assertEqual(list(a.relationships), [])
self.assertEqual(list(a.related_to), [])
r_ab = Relationship.create(from_user=a, to_user=b)
self.assertEqual(list(a.relationships), [r_ab])
self.assertEqual(list(a.related_to), [])
self.assertEqual(list(b.relationships), [])
self.assertEqual(list(b.related_to), [r_ab])
r_bc = Relationship.create(from_user=b, to_user=c)
following = User.select().join(
Relationship, on=Relationship.to_user
).where(Relationship.from_user == a)
self.assertEqual(list(following), [b])
followers = User.select().join(
Relationship, on=Relationship.from_user
).where(Relationship.to_user == a.id)
self.assertEqual(list(followers), [])
following = User.select().join(
Relationship, on=Relationship.to_user
).where(Relationship.from_user == b.id)
self.assertEqual(list(following), [c])
followers = User.select().join(
Relationship, on=Relationship.from_user
).where(Relationship.to_user == b.id)
self.assertEqual(list(followers), [a])
following = User.select().join(
Relationship, on=Relationship.to_user
).where(Relationship.from_user == c.id)
self.assertEqual(list(following), [])
followers = User.select().join(
Relationship, on=Relationship.from_user
).where(Relationship.to_user == c.id)
self.assertEqual(list(followers), [b])
| TestMultipleForeignKeysJoining |
python | getsentry__sentry | src/sentry/notifications/apps.py | {
"start": 36,
"end": 562
} | class ____(AppConfig):
name = "sentry.notifications"
def ready(self) -> None:
# Register the providers and templates for the new platform
import sentry.notifications.platform.discord.provider # noqa: F401
import sentry.notifications.platform.email.provider # noqa: F401
import sentry.notifications.platform.msteams.provider # noqa: F401
import sentry.notifications.platform.slack.provider # noqa: F401
import sentry.notifications.platform.templates # noqa: F401
| Config |
python | pypa__hatch | tests/backend/builders/plugin/test_interface.py | {
"start": 3421,
"end": 3702
} | class ____:
def test_normalization(self, isolation):
config = {"project": {"name": "my-app", "version": "1.0.0-rc.1"}}
builder = MockBuilder(str(isolation), config=config)
assert builder.project_id == builder.project_id == "my_app-1.0.0rc1"
| TestProjectID |
python | huggingface__transformers | src/transformers/models/mamba/modeling_mamba.py | {
"start": 22345,
"end": 23414
} | class ____(GradientCheckpointingLayer):
def __init__(self, config, layer_idx):
super().__init__()
self.config = config
self.layer_idx = layer_idx
self.residual_in_fp32 = config.residual_in_fp32
self.norm = MambaRMSNorm(config.hidden_size, eps=config.layer_norm_epsilon)
self.mixer = MambaMixer(config, layer_idx=layer_idx)
def forward(
self,
hidden_states,
cache_params: Optional[MambaCache] = None,
cache_position: Optional[torch.LongTensor] = None,
attention_mask: Optional[torch.LongTensor] = None,
):
residual = hidden_states
hidden_states = self.norm(hidden_states.to(dtype=self.norm.weight.dtype))
if self.residual_in_fp32:
residual = residual.to(torch.float32)
hidden_states = self.mixer(
hidden_states, cache_params=cache_params, cache_position=cache_position, attention_mask=attention_mask
)
hidden_states = residual + hidden_states
return hidden_states
@auto_docstring
| MambaBlock |
python | huggingface__transformers | src/transformers/models/funnel/modeling_funnel.py | {
"start": 15563,
"end": 22520
} | class ____(nn.Module):
def __init__(self, config: FunnelConfig, block_index: int) -> None:
super().__init__()
self.config = config
self.block_index = block_index
d_model, n_head, d_head = config.d_model, config.n_head, config.d_head
self.hidden_dropout = nn.Dropout(config.hidden_dropout)
self.attention_dropout = nn.Dropout(config.attention_dropout)
self.q_head = nn.Linear(d_model, n_head * d_head, bias=False)
self.k_head = nn.Linear(d_model, n_head * d_head)
self.v_head = nn.Linear(d_model, n_head * d_head)
self.r_w_bias = nn.Parameter(torch.zeros([n_head, d_head]))
self.r_r_bias = nn.Parameter(torch.zeros([n_head, d_head]))
self.r_kernel = nn.Parameter(torch.zeros([d_model, n_head, d_head]))
self.r_s_bias = nn.Parameter(torch.zeros([n_head, d_head]))
self.seg_embed = nn.Parameter(torch.zeros([2, n_head, d_head]))
self.post_proj = nn.Linear(n_head * d_head, d_model)
self.layer_norm = nn.LayerNorm(d_model, eps=config.layer_norm_eps)
self.scale = 1.0 / (d_head**0.5)
def relative_positional_attention(self, position_embeds, q_head, context_len, cls_mask=None):
"""Relative attention score for the positional encodings"""
# q_head has shape batch_size x sea_len x n_head x d_head
if self.config.attention_type == "factorized":
# Notations from the paper, appending A.2.2, final formula (https://huggingface.co/papers/2006.03236)
# phi and pi have shape seq_len x d_model, psi and omega have shape context_len x d_model
phi, pi, psi, omega = position_embeds
# Shape n_head x d_head
u = self.r_r_bias * self.scale
# Shape d_model x n_head x d_head
w_r = self.r_kernel
# Shape batch_size x sea_len x n_head x d_model
q_r_attention = torch.einsum("binh,dnh->bind", q_head + u, w_r)
q_r_attention_1 = q_r_attention * phi[:, None]
q_r_attention_2 = q_r_attention * pi[:, None]
# Shape batch_size x n_head x seq_len x context_len
positional_attn = torch.einsum("bind,jd->bnij", q_r_attention_1, psi) + torch.einsum(
"bind,jd->bnij", q_r_attention_2, omega
)
else:
shift = 2 if q_head.shape[1] != context_len else 1
# Notations from the paper, appending A.2.1, final formula (https://huggingface.co/papers/2006.03236)
# Grab the proper positional encoding, shape max_rel_len x d_model
r = position_embeds[self.block_index][shift - 1]
# Shape n_head x d_head
v = self.r_r_bias * self.scale
# Shape d_model x n_head x d_head
w_r = self.r_kernel
# Shape max_rel_len x n_head x d_model
r_head = torch.einsum("td,dnh->tnh", r, w_r)
# Shape batch_size x n_head x seq_len x max_rel_len
positional_attn = torch.einsum("binh,tnh->bnit", q_head + v, r_head)
# Shape batch_size x n_head x seq_len x context_len
positional_attn = _relative_shift_gather(positional_attn, context_len, shift)
if cls_mask is not None:
positional_attn *= cls_mask
return positional_attn
def relative_token_type_attention(self, token_type_mat, q_head, cls_mask=None):
"""Relative attention score for the token_type_ids"""
if token_type_mat is None:
return 0
batch_size, seq_len, context_len = token_type_mat.shape
# q_head has shape batch_size x seq_len x n_head x d_head
# Shape n_head x d_head
r_s_bias = self.r_s_bias * self.scale
# Shape batch_size x n_head x seq_len x 2
token_type_bias = torch.einsum("bind,snd->bnis", q_head + r_s_bias, self.seg_embed)
# Shape batch_size x n_head x seq_len x context_len
token_type_mat = token_type_mat[:, None].expand([batch_size, q_head.shape[2], seq_len, context_len])
# Shapes batch_size x n_head x seq_len
diff_token_type, same_token_type = torch.split(token_type_bias, 1, dim=-1)
# Shape batch_size x n_head x seq_len x context_len
token_type_attn = torch.where(
token_type_mat, same_token_type.expand(token_type_mat.shape), diff_token_type.expand(token_type_mat.shape)
)
if cls_mask is not None:
token_type_attn *= cls_mask
return token_type_attn
def forward(
self,
query: torch.Tensor,
key: torch.Tensor,
value: torch.Tensor,
attention_inputs: tuple[torch.Tensor],
output_attentions: bool = False,
) -> tuple[torch.Tensor, ...]:
# query has shape batch_size x seq_len x d_model
# key and value have shapes batch_size x context_len x d_model
position_embeds, token_type_mat, attention_mask, cls_mask = attention_inputs
batch_size, seq_len, _ = query.shape
context_len = key.shape[1]
n_head, d_head = self.config.n_head, self.config.d_head
# Shape batch_size x seq_len x n_head x d_head
q_head = self.q_head(query).view(batch_size, seq_len, n_head, d_head)
# Shapes batch_size x context_len x n_head x d_head
k_head = self.k_head(key).view(batch_size, context_len, n_head, d_head)
v_head = self.v_head(value).view(batch_size, context_len, n_head, d_head)
q_head = q_head * self.scale
# Shape n_head x d_head
r_w_bias = self.r_w_bias * self.scale
# Shapes batch_size x n_head x seq_len x context_len
content_score = torch.einsum("bind,bjnd->bnij", q_head + r_w_bias, k_head)
positional_attn = self.relative_positional_attention(position_embeds, q_head, context_len, cls_mask)
token_type_attn = self.relative_token_type_attention(token_type_mat, q_head, cls_mask)
# merge attention scores
attn_score = content_score + positional_attn + token_type_attn
# precision safe in case of mixed precision training
dtype = attn_score.dtype
attn_score = attn_score.float()
# perform masking
if attention_mask is not None:
attn_score = attn_score - INF * (1 - attention_mask[:, None, None].float())
# attention probability
attn_prob = torch.softmax(attn_score, dim=-1, dtype=dtype)
attn_prob = self.attention_dropout(attn_prob)
# attention output, shape batch_size x seq_len x n_head x d_head
attn_vec = torch.einsum("bnij,bjnd->bind", attn_prob, v_head)
# Shape shape batch_size x seq_len x d_model
attn_out = self.post_proj(attn_vec.reshape(batch_size, seq_len, n_head * d_head))
attn_out = self.hidden_dropout(attn_out)
output = self.layer_norm(query + attn_out)
return (output, attn_prob) if output_attentions else (output,)
| FunnelRelMultiheadAttention |
python | django__django | tests/template_tests/filter_tests/test_force_escape.py | {
"start": 2650,
"end": 3145
} | class ____(SimpleTestCase):
def test_escape(self):
escaped = force_escape("<some html & special characters > here")
self.assertEqual(escaped, "<some html & special characters > here")
self.assertIsInstance(escaped, SafeData)
def test_unicode(self):
self.assertEqual(
force_escape("<some html & special characters > here ĐÅ€£"),
"<some html & special characters > here \u0110\xc5\u20ac\xa3",
)
| FunctionTests |
python | sympy__sympy | sympy/vector/dyadic.py | {
"start": 7167,
"end": 7698
} | class ____(BasisDependentMul, Dyadic):
""" Products of scalars and BaseDyadics """
def __new__(cls, *args, **options):
obj = BasisDependentMul.__new__(cls, *args, **options)
return obj
@property
def base_dyadic(self):
""" The BaseDyadic involved in the product. """
return self._base_instance
@property
def measure_number(self):
""" The scalar expression involved in the definition of
this DyadicMul.
"""
return self._measure_number
| DyadicMul |
python | huggingface__transformers | src/transformers/models/unispeech/modeling_unispeech.py | {
"start": 8595,
"end": 10083
} | class ____(nn.Module):
"""Construct the features from raw audio waveform"""
def __init__(self, config):
super().__init__()
if config.feat_extract_norm == "group":
conv_layers = [UniSpeechGroupNormConvLayer(config, layer_id=0)] + [
UniSpeechNoLayerNormConvLayer(config, layer_id=i + 1)
for i in range(config.num_feat_extract_layers - 1)
]
elif config.feat_extract_norm == "layer":
conv_layers = [
UniSpeechLayerNormConvLayer(config, layer_id=i) for i in range(config.num_feat_extract_layers)
]
else:
raise ValueError(
f"`config.feat_extract_norm` is {config.feat_extract_norm}, but has to be one of ['group', 'layer']"
)
self.conv_layers = nn.ModuleList(conv_layers)
self.gradient_checkpointing = False
self._requires_grad = True
def _freeze_parameters(self):
for param in self.parameters():
param.requires_grad = False
self._requires_grad = False
def forward(self, input_values):
hidden_states = input_values[:, None]
# make sure hidden_states require grad for gradient_checkpointing
if self._requires_grad and self.training:
hidden_states.requires_grad = True
for conv_layer in self.conv_layers:
hidden_states = conv_layer(hidden_states)
return hidden_states
| UniSpeechFeatureEncoder |
python | apache__airflow | providers/standard/tests/unit/standard/operators/test_branch_operator.py | {
"start": 2216,
"end": 13803
} | class ____:
def test_without_dag_run(self, dag_maker):
"""This checks the defensive against non-existent tasks in a dag run"""
dag_id = "branch_operator_test"
triggered_by_kwargs = {"triggered_by": DagRunTriggeredByType.TEST} if AIRFLOW_V_3_0_PLUS else {}
with dag_maker(
dag_id,
default_args={"owner": "airflow", "start_date": DEFAULT_DATE},
schedule=INTERVAL,
serialized=True,
):
branch_1 = EmptyOperator(task_id="branch_1")
branch_2 = EmptyOperator(task_id="branch_2")
branch_op = ChooseBranchOne(task_id="make_choice")
branch_1.set_upstream(branch_op)
branch_2.set_upstream(branch_op)
dr = dag_maker.create_dagrun(**triggered_by_kwargs)
if AIRFLOW_V_3_0_1:
with pytest.raises(DownstreamTasksSkipped) as exc_info:
dag_maker.run_ti("make_choice", dr)
assert exc_info.value.tasks == [("branch_2", -1)]
else:
dag_maker.run_ti("make_choice", dr)
ti_date = TI.logical_date if AIRFLOW_V_3_0_PLUS else TI.execution_date
for ti in dag_maker.session.query(TI).filter(TI.dag_id == dag_id, ti_date == DEFAULT_DATE):
if ti.task_id == "make_choice":
assert ti.state == State.SUCCESS
elif ti.task_id == "branch_1":
assert ti.state == State.NONE
elif ti.task_id == "branch_2":
assert ti.state == State.SKIPPED
else:
raise Exception
def test_branch_list_without_dag_run(self, dag_maker):
"""This checks if the BranchOperator supports branching off to a list of tasks."""
dag_id = "branch_operator_test"
triggered_by_kwargs = {"triggered_by": DagRunTriggeredByType.TEST} if AIRFLOW_V_3_0_PLUS else {}
with dag_maker(
dag_id,
default_args={"owner": "airflow", "start_date": DEFAULT_DATE},
schedule=INTERVAL,
serialized=True,
):
branch_1 = EmptyOperator(task_id="branch_1")
branch_2 = EmptyOperator(task_id="branch_2")
branch_3 = EmptyOperator(task_id="branch_3")
branch_op = ChooseBranchOneTwo(task_id="make_choice")
branch_1.set_upstream(branch_op)
branch_2.set_upstream(branch_op)
branch_3.set_upstream(branch_op)
dr = dag_maker.create_dagrun(**triggered_by_kwargs)
if AIRFLOW_V_3_0_1:
with pytest.raises(DownstreamTasksSkipped) as exc_info:
dag_maker.run_ti("make_choice", dr)
assert exc_info.value.tasks == [("branch_3", -1)]
else:
dag_maker.run_ti("make_choice", dr)
expected = {
"make_choice": State.SUCCESS,
"branch_1": State.NONE,
"branch_2": State.NONE,
"branch_3": State.SKIPPED,
}
ti_date = TI.logical_date if AIRFLOW_V_3_0_PLUS else TI.execution_date
for ti in dag_maker.session.query(TI).filter(TI.dag_id == dag_id, ti_date == DEFAULT_DATE):
if ti.task_id in expected:
assert ti.state == expected[ti.task_id]
else:
raise Exception
def test_with_dag_run(self, dag_maker):
dag_id = "branch_operator_test"
triggered_by_kwargs = {"triggered_by": DagRunTriggeredByType.TEST} if AIRFLOW_V_3_0_PLUS else {}
with dag_maker(
dag_id,
default_args={"owner": "airflow", "start_date": DEFAULT_DATE},
schedule=INTERVAL,
serialized=True,
):
branch_1 = EmptyOperator(task_id="branch_1")
branch_2 = EmptyOperator(task_id="branch_2")
branch_op = ChooseBranchOne(task_id="make_choice")
branch_1.set_upstream(branch_op)
branch_2.set_upstream(branch_op)
if AIRFLOW_V_3_0_1:
dr = dag_maker.create_dagrun(
run_type=DagRunType.MANUAL,
start_date=timezone.utcnow(),
logical_date=DEFAULT_DATE,
state=State.RUNNING,
data_interval=DataInterval(DEFAULT_DATE, DEFAULT_DATE),
**triggered_by_kwargs,
)
with pytest.raises(DownstreamTasksSkipped) as exc_info:
dag_maker.run_ti("make_choice", dr)
assert exc_info.value.tasks == [("branch_2", -1)]
else:
dr = dag_maker.create_dagrun(
run_type=DagRunType.MANUAL,
start_date=timezone.utcnow(),
execution_date=DEFAULT_DATE,
state=State.RUNNING,
data_interval=DataInterval(DEFAULT_DATE, DEFAULT_DATE),
**triggered_by_kwargs,
)
dag_maker.run_ti("make_choice", dr)
expected = {
"make_choice": State.SUCCESS,
"branch_1": State.NONE,
"branch_2": State.SKIPPED,
}
ti_date = TI.logical_date if AIRFLOW_V_3_0_PLUS else TI.execution_date
for ti in dag_maker.session.query(TI).filter(TI.dag_id == dag_id, ti_date == DEFAULT_DATE):
if ti.task_id in expected:
assert ti.state == expected[ti.task_id]
else:
raise Exception
def test_with_skip_in_branch_downstream_dependencies(self, dag_maker):
dag_id = "branch_operator_test"
triggered_by_kwargs = {"triggered_by": DagRunTriggeredByType.TEST} if AIRFLOW_V_3_0_PLUS else {}
with dag_maker(
dag_id,
default_args={"owner": "airflow", "start_date": DEFAULT_DATE},
schedule=INTERVAL,
serialized=True,
):
branch_1 = EmptyOperator(task_id="branch_1")
branch_2 = EmptyOperator(task_id="branch_2")
branch_op = ChooseBranchOne(task_id="make_choice")
branch_op >> branch_1 >> branch_2
branch_op >> branch_2
if AIRFLOW_V_3_0_PLUS:
dr = dag_maker.create_dagrun(
run_type=DagRunType.MANUAL,
start_date=timezone.utcnow(),
logical_date=DEFAULT_DATE,
state=State.RUNNING,
data_interval=DataInterval(DEFAULT_DATE, DEFAULT_DATE),
**triggered_by_kwargs,
)
else:
dr = dag_maker.create_dagrun(
run_type=DagRunType.MANUAL,
start_date=timezone.utcnow(),
execution_date=DEFAULT_DATE,
state=State.RUNNING,
data_interval=DataInterval(DEFAULT_DATE, DEFAULT_DATE),
**triggered_by_kwargs,
)
dag_maker.run_ti("make_choice", dr)
expected = {
"make_choice": State.SUCCESS,
"branch_1": State.NONE,
"branch_2": State.NONE,
}
ti_date = TI.logical_date if AIRFLOW_V_3_0_PLUS else TI.execution_date
for ti in dag_maker.session.query(TI).filter(TI.dag_id == dag_id, ti_date == DEFAULT_DATE):
if ti.task_id in expected:
assert ti.state == expected[ti.task_id]
else:
raise Exception
def test_xcom_push(self, dag_maker):
dag_id = "branch_operator_test"
triggered_by_kwargs = (
{
"triggered_by": DagRunTriggeredByType.TEST,
"logical_date": DEFAULT_DATE,
}
if AIRFLOW_V_3_0_PLUS
else {"execution_date": DEFAULT_DATE}
)
with dag_maker(
dag_id,
default_args={"owner": "airflow", "start_date": DEFAULT_DATE},
schedule=INTERVAL,
serialized=True,
):
branch_1 = EmptyOperator(task_id="branch_1")
branch_2 = EmptyOperator(task_id="branch_2")
branch_op = ChooseBranchOne(task_id="make_choice")
branch_1.set_upstream(branch_op)
branch_2.set_upstream(branch_op)
dr = dag_maker.create_dagrun(
run_type=DagRunType.MANUAL,
start_date=timezone.utcnow(),
state=State.RUNNING,
data_interval=DataInterval(DEFAULT_DATE, DEFAULT_DATE),
**triggered_by_kwargs,
)
if AIRFLOW_V_3_0_1:
with pytest.raises(DownstreamTasksSkipped) as exc_info:
dag_maker.run_ti("make_choice", dr)
assert exc_info.value.tasks == [("branch_2", -1)]
else:
dag_maker.run_ti("make_choice", dr)
branch_op_ti = dr.get_task_instance("make_choice")
assert branch_op_ti.xcom_pull(task_ids="make_choice", key=XCOM_SKIPMIXIN_KEY) == {
XCOM_SKIPMIXIN_FOLLOWED: ["branch_1"]
}
def test_with_dag_run_task_groups(self, dag_maker):
dag_id = "branch_operator_test"
triggered_by_kwargs = {"triggered_by": DagRunTriggeredByType.TEST} if AIRFLOW_V_3_0_PLUS else {}
with dag_maker(
dag_id,
default_args={"owner": "airflow", "start_date": DEFAULT_DATE},
schedule=INTERVAL,
serialized=True,
):
branch_1 = EmptyOperator(task_id="branch_1")
branch_2 = EmptyOperator(task_id="branch_2")
branch_3 = TaskGroup("branch_3")
EmptyOperator(task_id="task_1", task_group=branch_3)
EmptyOperator(task_id="task_2", task_group=branch_3)
branch_op = ChooseBranchThree(task_id="make_choice")
branch_1.set_upstream(branch_op)
branch_2.set_upstream(branch_op)
branch_3.set_upstream(branch_op)
if AIRFLOW_V_3_0_1:
dr = dag_maker.create_dagrun(
run_type=DagRunType.MANUAL,
start_date=timezone.utcnow(),
logical_date=DEFAULT_DATE,
state=State.RUNNING,
data_interval=DataInterval(DEFAULT_DATE, DEFAULT_DATE),
**triggered_by_kwargs,
)
with pytest.raises(DownstreamTasksSkipped) as exc_info:
dag_maker.run_ti("make_choice", dr)
assert set(exc_info.value.tasks) == {("branch_1", -1), ("branch_2", -1)}
else:
dr = dag_maker.create_dagrun(
run_type=DagRunType.MANUAL,
start_date=timezone.utcnow(),
execution_date=DEFAULT_DATE,
state=State.RUNNING,
data_interval=DataInterval(DEFAULT_DATE, DEFAULT_DATE),
**triggered_by_kwargs,
)
dag_maker.run_ti("make_choice", dr)
ti_date = TI.logical_date if AIRFLOW_V_3_0_PLUS else TI.execution_date
for ti in dag_maker.session.query(TI).filter(TI.dag_id == dag_id, ti_date == DEFAULT_DATE):
if ti.task_id == "make_choice":
assert ti.state == State.SUCCESS
elif ti.task_id == "branch_1":
assert ti.state == State.SKIPPED
elif ti.task_id == "branch_2":
assert ti.state == State.SKIPPED
elif ti.task_id == "branch_3.task_1":
assert ti.state == State.NONE
elif ti.task_id == "branch_3.task_2":
assert ti.state == State.NONE
else:
raise Exception
| TestBranchOperator |
python | mwaskom__seaborn | seaborn/_marks/line.py | {
"start": 7505,
"end": 8301
} | class ____(Paths):
"""
An oriented line mark drawn between min/max values.
Examples
--------
.. include:: ../docstrings/objects.Range.rst
"""
def _setup_segments(self, data, orient):
# TODO better checks on what variables we have
# TODO what if only one exist?
val = {"x": "y", "y": "x"}[orient]
if not set(data.columns) & {f"{val}min", f"{val}max"}:
agg = {f"{val}min": (val, "min"), f"{val}max": (val, "max")}
data = data.groupby(orient).agg(**agg).reset_index()
cols = [orient, f"{val}min", f"{val}max"]
data = data[cols].melt(orient, value_name=val)[["x", "y"]]
segments = [d.to_numpy() for _, d in data.groupby(orient)]
return segments
@document_properties
@dataclass
| Range |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 270920,
"end": 271327
} | class ____(sgqlc.types.Type):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("client_mutation_id", "pull_request_review")
client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
pull_request_review = sgqlc.types.Field(
"PullRequestReview", graphql_name="pullRequestReview"
)
| DeletePullRequestReviewPayload |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/del1.py | {
"start": 499,
"end": 885
} | class ____:
x: int
b = ClassB()
b.x = 3
reveal_type(b.x, expected_text="Literal[3]")
del b.x
reveal_type(b.x, expected_text="int")
x2: list[str | int] = ["a", 1, "b", 2]
reveal_type(x2[0], expected_text="str | int")
x2[0] = 0
reveal_type(x2[0], expected_text="Literal[0]")
reveal_type(x2[1], expected_text="str | int")
del x2[0]
reveal_type(x2[0], expected_text="str | int")
| ClassB |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/flake8_bugbear/B024.py | {
"start": 1784,
"end": 1930
} | class ____(abc.ABCMeta): # safe
def method(self):
foo()
# very invalid code, but that's up to mypy et al to check
| non_keyword_abcmeta_2 |
python | pallets__werkzeug | examples/couchy/models.py | {
"start": 253,
"end": 1356
} | class ____(Document):
target = TextField()
public = BooleanField()
added = DateTimeField(default=datetime.utcnow())
shorty_id = TextField(default=None)
db = None
@classmethod
def load(cls, id):
return super().load(URL.db, id)
@classmethod
def query(cls, code):
return URL.db.query(code)
def store(self):
if getattr(self._data, "id", None) is None:
new_id = self.shorty_id if self.shorty_id else None
while 1:
id = new_id if new_id else get_random_uid()
try:
docid = URL.db.resource.put(content=self._data, path=f"/{id}/")[
"id"
]
except Exception:
continue
if docid:
break
self._data = URL.db.get(docid)
else:
super().store(URL.db)
return self
@property
def short_url(self):
return url_for("link", uid=self.id, _external=True)
def __repr__(self):
return f"<URL {self.id!r}>"
| URL |
python | PyCQA__pylint | tests/functional/r/regression/regression_4723.py | {
"start": 271,
"end": 420
} | class ____(A):
def play(): # [no-method-argument]
pass
def func():
with B().get() as b:
b.play() # [too-many-function-args]
| B |
python | huggingface__transformers | src/transformers/data/processors/glue.py | {
"start": 17166,
"end": 18889
} | class ____(DataProcessor):
"""Processor for the RTE data set (GLUE version)."""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
warnings.warn(DEPRECATION_WARNING.format("processor"), FutureWarning)
def get_example_from_tensor_dict(self, tensor_dict):
"""See base class."""
return InputExample(
tensor_dict["idx"].numpy(),
tensor_dict["sentence1"].numpy().decode("utf-8"),
tensor_dict["sentence2"].numpy().decode("utf-8"),
str(tensor_dict["label"].numpy()),
)
def get_train_examples(self, data_dir):
"""See base class."""
return self._create_examples(self._read_tsv(os.path.join(data_dir, "train.tsv")), "train")
def get_dev_examples(self, data_dir):
"""See base class."""
return self._create_examples(self._read_tsv(os.path.join(data_dir, "dev.tsv")), "dev")
def get_test_examples(self, data_dir):
"""See base class."""
return self._create_examples(self._read_tsv(os.path.join(data_dir, "test.tsv")), "test")
def get_labels(self):
"""See base class."""
return ["entailment", "not_entailment"]
def _create_examples(self, lines, set_type):
"""Creates examples for the training, dev and test sets."""
examples = []
for i, line in enumerate(lines):
if i == 0:
continue
guid = f"{set_type}-{line[0]}"
text_a = line[1]
text_b = line[2]
label = None if set_type == "test" else line[-1]
examples.append(InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))
return examples
| RteProcessor |
python | weaviate__weaviate-python-client | weaviate/collections/classes/aggregate.py | {
"start": 7040,
"end": 7971
} | class ____(_MetricsBase):
maximum: bool
median: bool
minimum: bool
mode: bool
def to_gql(self) -> str:
body = " ".join(
[
"count" if self.count else "",
"maximum" if self.maximum else "",
"median" if self.median else "",
"minimum" if self.minimum else "",
"mode" if self.mode else "",
]
)
return f"{self.property_name} {{ {body} }}"
def to_grpc(self) -> aggregate_pb2.AggregateRequest.Aggregation:
return aggregate_pb2.AggregateRequest.Aggregation(
property=self.property_name,
date=aggregate_pb2.AggregateRequest.Aggregation.Date(
count=self.count,
maximum=self.maximum,
median=self.median,
minimum=self.minimum,
mode=self.mode,
),
)
| _MetricsDate |
python | ray-project__ray | python/ray/tests/test_concurrency_group.py | {
"start": 6325,
"end": 10581
} | class ____:
"""
This test verifies that synchronous tasks can access thread-local data that
was set by previous synchronous tasks when the concurrency group has only
one thread. For concurrency groups with multiple threads, it doesn't promise
access to the same thread-local data because Ray currently doesn't expose APIs
for users to specify which thread the task will be scheduled on in the same
concurrency group.
"""
def test_tasks_on_default_executor(self, ray_start_regular_shared):
a = Actor.remote()
tid_1 = ray.get(a.set_thread_local.remote("f1"))
value, tid_2 = ray.get(a.get_thread_local.remote())
assert tid_1 == tid_2
assert value == "f1"
def test_tasks_on_specific_executor(self, ray_start_regular_shared):
a = Actor.remote()
tid_1 = ray.get(a.set_thread_local.options(concurrency_group="io").remote("f1"))
value, tid_2 = ray.get(
a.get_thread_local.options(concurrency_group="io").remote()
)
assert tid_1 == tid_2
assert value == "f1"
def test_tasks_on_different_executors(self, ray_start_regular_shared):
a = Actor.remote()
tid_1 = ray.get(a.set_thread_local.options(concurrency_group="io").remote("f1"))
tid_3 = ray.get(
a.set_thread_local.options(concurrency_group="compute").remote("f2")
)
value, tid_2 = ray.get(
a.get_thread_local.options(concurrency_group="io").remote()
)
assert tid_1 == tid_2
assert value == "f1"
value, tid_4 = ray.get(
a.get_thread_local.options(concurrency_group="compute").remote()
)
assert tid_3 == tid_4
assert value == "f2"
def test_multiple_threads_in_same_group(ray_start_regular_shared):
"""
This test verifies that all threads in the same concurrency group are still
alive from the Python interpreter's perspective even if Ray tasks have finished, so that
thread-local data will not be garbage collected.
"""
@ray.remote
class Actor:
def __init__(self, signal: SignalActor, max_concurrency: int):
self._thread_local_data = threading.local()
self.signal = signal
self.thread_id_to_data = {}
self.max_concurrency = max_concurrency
def set_thread_local(self, value: int) -> int:
# If the thread-local data were garbage collected after the previous
# task on the same thread finished, `self.data` would be incremented
# more than once for the same thread.
assert not hasattr(self._thread_local_data, "value")
self._thread_local_data.value = value
self.thread_id_to_data[threading.current_thread().ident] = value
ray.get(self.signal.wait.remote())
def check_thread_local_data(self) -> bool:
assert len(self.thread_id_to_data) == self.max_concurrency
assert hasattr(self._thread_local_data, "value")
assert (
self._thread_local_data.value
== self.thread_id_to_data[threading.current_thread().ident]
)
ray.get(self.signal.wait.remote())
max_concurrency = 5
signal = SignalActor.remote()
a = Actor.options(max_concurrency=max_concurrency).remote(signal, max_concurrency)
refs = []
for i in range(max_concurrency):
refs.append(a.set_thread_local.remote(i))
ray.get(signal.send.remote())
ray.get(refs)
refs = []
for _ in range(max_concurrency):
refs.append(a.check_thread_local_data.remote())
ray.get(signal.send.remote())
ray.get(refs)
def test_invalid_concurrency_group():
"""Verify that when a concurrency group has max concurrency set to 0,
an error is raised when the actor is created. This test uses
`run_string_as_driver` and checks whether the error message appears in the
driver's stdout. Since the error in the core worker process does not raise
an exception in the driver process, we need to check the driver process's
stdout.
"""
script = """
import ray
ray.init()
@ray.remote(concurrency_groups={"io": 0, "compute": 0})
| TestThreadingLocalData |
python | huggingface__transformers | tests/models/siglip/test_modeling_siglip.py | {
"start": 23088,
"end": 25502
} | class ____(unittest.TestCase):
@slow
def test_inference(self):
model_name = "google/siglip-base-patch16-224"
model = SiglipModel.from_pretrained(model_name).to(torch_device)
processor = SiglipProcessor.from_pretrained(model_name)
image = prepare_img()
inputs = processor(
text=["a photo of 2 cats", "a photo of 2 dogs"], images=image, padding="max_length", return_tensors="pt"
).to(torch_device)
# forward pass
with torch.no_grad():
outputs = model(**inputs)
logits_per_image = outputs.logits_per_image
logits_per_text = outputs.logits_per_text
# verify the logits
self.assertEqual(
logits_per_image.shape,
torch.Size((inputs.pixel_values.shape[0], inputs.input_ids.shape[0])),
)
self.assertEqual(
logits_per_text.shape,
torch.Size((inputs.input_ids.shape[0], inputs.pixel_values.shape[0])),
)
expected_logits = torch.tensor([[-0.7567, -10.3354]], device=torch_device)
torch.testing.assert_close(outputs.logits_per_image, expected_logits, rtol=1e-3, atol=1e-3)
# verify the probs
probs = torch.sigmoid(logits_per_image) # these are the probabilities
expected_probs = torch.tensor([[3.1937e-01, 3.2463e-05]], device=torch_device)
torch.testing.assert_close(probs, expected_probs, rtol=1e-3, atol=1e-3)
@slow
def test_inference_interpolate_pos_encoding(self):
model_name = "google/siglip-base-patch16-224"
model = SiglipModel.from_pretrained(model_name).to(torch_device)
# 640 x 480 image
image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png")
processor = SiglipProcessor.from_pretrained(model_name, do_resize=False, size={"height": 480, "width": 640})
inputs = processor(text="what's in the image", images=image, return_tensors="pt").to(torch_device)
# forward pass
with torch.no_grad():
outputs = model(**inputs, interpolate_pos_encoding=True)
# verify the shape
# patch size = 16
# batch size 1, (640/16) * (480/16) = 1200 patches, 768 hidden size
expected_shape = torch.Size((1, 1200, 768))
self.assertEqual(outputs.vision_model_output.last_hidden_state.shape, expected_shape)
| SiglipModelIntegrationTest |
python | pytorch__pytorch | tools/experimental/torchfuzz/operators/nn_functional.py | {
"start": 7431,
"end": 8901
} | class ____(Operator):
"""Operator for torch.nn.functional.relu."""
def __init__(self):
super().__init__("torch.nn.functional.relu")
@property
def torch_op_name(self) -> str | None:
"""Return the torch operation name."""
return "torch.nn.functional.relu"
def can_produce(self, output_spec: Spec) -> bool:
"""ReLU can produce tensor outputs with floating point dtypes."""
if not isinstance(output_spec, TensorSpec):
return False
return is_float_dtype(output_spec.dtype)
def fuzz_inputs_specs(self, output_spec: Spec) -> list[Spec]:
"""Generate input specs for ReLU operation.
ReLU is element-wise, so input shape matches output shape.
"""
if not isinstance(output_spec, TensorSpec):
raise ValueError("ReLUOperator can only produce TensorSpec outputs")
# Input tensor has same shape and dtype as output
input_spec = TensorSpec(
size=output_spec.size, stride=output_spec.stride, dtype=output_spec.dtype
)
return [input_spec]
def codegen(
self, output_name: str, input_names: list[str], output_spec: Spec
) -> str:
"""Generate code for ReLU operation."""
if len(input_names) != 1:
raise ValueError("ReLU requires exactly 1 input")
input_name = input_names[0]
return f"{output_name} = torch.nn.functional.relu({input_name})"
| ReLUOperator |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/flake8_pyi/PYI036.py | {
"start": 4419,
"end": 4670
} | class ____:
def __exit__(self, typ, exc, tb, weird_extra_arg, extra_arg2 = None) -> None: ... # PYI036: Extra arg must have default
async def __aexit__(self, typ, exc, tb, *, weird_extra_arg) -> None: ... # PYI036: kwargs must have default
| BadSix |
python | pytorch__pytorch | test/test_sparse_csr.py | {
"start": 6945,
"end": 51832
} | class ____(TestCase):
"""Testing sparse compressed (CSR, CSC, BSR, BSC) tensor generic features.
"""
def genTensor(self, size, nnz, *, layout, device=None, dtype=torch.float, index_dtype=torch.int64):
if device is None:
device = self.device_type
return self.genSparseCompressedTensor(size, nnz, device=device, dtype=dtype, index_dtype=index_dtype, layout=layout)
@all_sparse_compressed_layouts()
@onlyCPU
def test_layout(self, layout):
self.assertIn(str(layout), {'torch.sparse_csr', 'torch.sparse_csc', 'torch.sparse_bsr', 'torch.sparse_bsc'})
self.assertEqual(type(layout), torch.layout)
@parametrize('shape_and_device_inference', [subtest(False, name='_'), subtest(True, name='shape_and_device_inference')])
@parametrize('use_factory_function', [subtest(False, name='_'), subtest(True, name='factory')])
@parametrize('input_kind', [subtest('tensor', name='from_tensor'), subtest('list', name='from_list')])
@all_sparse_compressed_layouts()
@dtypes(*all_types_and_complex_and(torch.half, torch.bool, torch.bfloat16))
def test_sparse_compressed_constructor(self, layout, device, dtype,
use_factory_function, shape_and_device_inference, input_kind):
if input_kind == 'list' and shape_and_device_inference:
if torch.device(device).type == 'cuda':
# list inputs to factory/constructor function without
# specifying device will result a sparse compressed tensor
# on CPU. So, skip testing against cuda device as unused.
self.skipTest("nothing to test")
if dtype not in {torch.float32, torch.complex64, torch.int64, torch.bool}:
self.skipTest("dtype not supported with list values")
expected_devices = [torch.device(device)]
if TEST_CUDA and torch.device(device).type == 'cuda' and torch.cuda.device_count() >= 2 and not shape_and_device_inference:
expected_devices.append(torch.device('cuda:1'))
factory_function = {
torch.sparse_csr: torch.sparse_csr_tensor,
torch.sparse_csc: torch.sparse_csc_tensor,
torch.sparse_bsr: torch.sparse_bsr_tensor,
torch.sparse_bsc: torch.sparse_bsc_tensor,
}[layout]
compressed_indices_mth, plain_indices_mth = sparse_compressed_indices_methods[layout]
if input_kind == 'list':
index_dtypes = [torch.int64]
else:
index_dtypes = [torch.int32, torch.int64]
if dtype.is_floating_point or dtype.is_complex:
requires_grad_lst = [False, True]
else:
requires_grad_lst = [False]
for index_dtype in index_dtypes:
for expected_device in expected_devices:
for (compressed_indices, plain_indices, values), kwargs in self.generate_simple_inputs(
layout, device=expected_device, dtype=dtype, index_dtype=index_dtype,
# skip zero-sized tensors for list inputs:
enable_zero_sized=input_kind != 'list',
output_tensor=False):
size = kwargs['size']
if shape_and_device_inference and 0 in size:
# skip shape inference for zero-sized tensor
# inputs because (i) the shape determined from
# an empty list is ambiguous, and (ii) the
# size of the plain dimension defined as
# max(plain_indices) is undefined if
# plain_indices has no values
continue
compressed_indices_expect = compressed_indices
plain_indices_expect = plain_indices
values_expect = values
if input_kind == 'list':
compressed_indices = compressed_indices.tolist()
plain_indices = plain_indices.tolist()
values = values.tolist()
for requires_grad in requires_grad_lst:
if use_factory_function:
if shape_and_device_inference:
sparse = factory_function(
compressed_indices, plain_indices, values, requires_grad=requires_grad)
else:
sparse = factory_function(
compressed_indices, plain_indices, values, size,
dtype=dtype, device=expected_device, requires_grad=requires_grad)
else:
if shape_and_device_inference:
sparse = torch.sparse_compressed_tensor(
compressed_indices, plain_indices, values,
layout=layout, requires_grad=requires_grad)
else:
sparse = torch.sparse_compressed_tensor(
compressed_indices, plain_indices, values, size,
dtype=dtype, layout=layout, device=expected_device, requires_grad=requires_grad)
self.assertEqual(layout, sparse.layout)
self.assertEqual(size, sparse.shape)
self.assertEqual(compressed_indices_expect, compressed_indices_mth(sparse))
self.assertEqual(plain_indices_expect, plain_indices_mth(sparse))
self.assertEqual(values_expect, sparse.values())
self.assertEqual(sparse.device, sparse.values().device)
self.assertEqual(sparse.device, expected_device)
self.assertEqual(sparse.values().requires_grad, requires_grad)
self.assertEqual(sparse.requires_grad, requires_grad)
self.assertFalse(compressed_indices_mth(sparse).requires_grad)
self.assertFalse(plain_indices_mth(sparse).requires_grad)
@skipMeta
@sparse_compressed_nonblock_layouts()
@dtypes(*all_types_and_complex_and(torch.bool, torch.bfloat16, torch.half))
def test_empty(self, layout, device, dtype):
ns = [5, 2, 0]
batch_shapes = [(), (2,), (2, 3)]
compressed_dim = {
torch.sparse_csr: -2,
torch.sparse_csc: -1,
}[layout]
compressed_indices_mth, plain_indices_mth = sparse_compressed_indices_methods[layout]
for m, n, b in itertools.product(ns, ns, batch_shapes):
shape = (*b, m, n)
with torch.sparse.check_sparse_tensor_invariants(enable=False):
# torch.empty may return invalid sparse compressed tensors
result = torch.empty(shape, dtype=dtype, device=device, layout=layout)
self.assertEqual(result.shape, shape)
self.assertEqual(result.dtype, dtype)
self.assertEqual(result.device, torch.device(device))
self.assertEqual(result.layout, layout)
self.assertEqual(compressed_indices_mth(result).shape, (*b, shape[compressed_dim] + 1,))
self.assertEqual(plain_indices_mth(result).shape, (*b, 0,))
self.assertEqual(result.values().shape, (*b, 0,))
self.assertEqual(result._nnz(), 0)
self.assertEqual(compressed_indices_mth(result).device, torch.device(device))
self.assertEqual(plain_indices_mth(result).device, torch.device(device))
self.assertEqual(result.values().device, torch.device(device))
self.assertEqual(compressed_indices_mth(result).dtype, torch.int64)
self.assertEqual(plain_indices_mth(result).dtype, torch.int64)
self.assertEqual(result.values().dtype, dtype)
@skipMeta
@sparse_compressed_nonblock_layouts()
@dtypes(*all_types_and_complex_and(torch.bool, torch.half, torch.bfloat16))
def test_empty_errors(self, layout, device, dtype):
with self.assertRaisesRegex(RuntimeError,
"torch.empty: Only batched sparse compressed \\(non-block\\) tensors are supported"
", but got size"):
torch.empty((5,), dtype=dtype, device=device, layout=layout)
@skipMeta
@all_sparse_compressed_layouts()
@dtypes(*all_types_and_complex_and(torch.bool, torch.bfloat16, torch.half))
def test_sparse_compressed_tensor_with_dims(self, layout, device, dtype):
def get_sparse_compressed_tensor_properties(s):
if layout in {torch.sparse_csr, torch.sparse_bsr}:
compressed_indices, plain_indices = s.crow_indices(), s.col_indices()
else:
compressed_indices, plain_indices = s.ccol_indices(), s.row_indices()
values = s.values()
return dict(shape=s.shape, dtype=s.dtype, device=s.device, nnz=s._nnz(), layout=s.layout,
compressed_indices_shape=compressed_indices.shape,
compressed_indices_dtype=compressed_indices.dtype,
compressed_indices_device=compressed_indices.device,
plain_indices_shape=plain_indices.shape,
plain_indices_dtype=plain_indices.dtype,
plain_indices_device=plain_indices.device,
values_shape=values.shape,
values_dtype=values.dtype,
values_device=values.device)
for index_dtype in [torch.int32, torch.int64]:
for t in self.generate_simple_inputs(layout, device=device, dtype=dtype, index_dtype=index_dtype):
dense_dim = t.dense_dim()
sparse_dim = t.sparse_dim()
batch_dim = t.ndim - sparse_dim - dense_dim
nnz = t.values().shape[batch_dim]
if layout in {torch.sparse_bsr, torch.sparse_bsc}:
blocksize = t.values().shape[batch_dim + 1: batch_dim + 1 + sparse_dim]
else:
blocksize = ()
e = torch.ops.aten._sparse_compressed_tensor_with_dims(nnz, dense_dim, t.shape, blocksize, index_dtype,
dtype=dtype, layout=layout, device=device)
e_prop, t_prop = get_sparse_compressed_tensor_properties(e), get_sparse_compressed_tensor_properties(t)
for k, v in e_prop.items():
self.assertEqual(v, t_prop[k], lambda msg: f'{msg} when comparing {k}, expected {t_prop[k]}, got {v}')
@skipMeta
@all_sparse_compressed_layouts()
@dtypes(*all_types_and_complex_and(torch.bool, torch.half, torch.bfloat16))
def test_clone(self, layout, device, dtype):
for sparse in self.generate_simple_inputs(
layout, device=device, dtype=dtype, index_dtype=torch.int32):
cloned_sparse = sparse.clone()
self.assertEqual(sparse, cloned_sparse)
@all_sparse_compressed_layouts()
def test_print(self, layout, device):
compressed_indices_mth, plain_indices_mth = sparse_compressed_indices_methods[layout]
printed = []
for enable_hybrid in [False, True]:
# using local patterns for test_print stability
patterns = [
# 2 x 3 batch of 3 x 2 tensors, trivial blocksize, non-hybrid/hybrid:
([[[[1, 2, 0],
[1, 0, 3]],
[[1, 2, 3],
[1, 0, 0]],
[[1, 0, 0],
[1, 2, 3]]],
[[[0, 2, 0],
[1, 2, 3]],
[[1, 0, 3],
[1, 2, 0]],
[[1, 2, 3],
[0, 2, 0]]]], [(2, 1)], [(), (4,)] if enable_hybrid else [()]),
# tensor with non-trivial blocksize, non-hybrid/hybrid:
([[0, 1, 0, 2, 0, 2],
[0, 1, 0, 0, 2, 0],
[3, 3, 3, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 5, 0, 6, 6, 6],
[5, 0, 5, 6, 6, 6],
[0, 0, 0, 0, 8, 8],
[7, 7, 7, 0, 8, 8]], [(2, 3)], [(), (4, 2)] if enable_hybrid else [()]),
]
for index_dtype in [torch.int32, torch.int64]:
for dtype in [torch.float32, torch.float64]:
for (compressed_indices, plain_indices, values), kwargs in self.generate_simple_inputs(
layout, device=device, dtype=dtype, index_dtype=index_dtype, enable_hybrid=enable_hybrid,
enable_non_contiguous_indices=False, enable_non_contiguous_values=False,
enable_zero_sized=False, output_tensor=False, patterns=patterns):
size = tuple(kwargs['size'])
block_ndim = 2 if layout in {torch.sparse_bsr, torch.sparse_bsc} else 0
base_ndim = 2
batch_ndim = compressed_indices.dim() - 1
dense_ndim = values.dim() - batch_ndim - block_ndim - 1
if enable_hybrid and dense_ndim == 0:
# non-hybrid cases are covered by the enable_hybrid==False loop
continue
batchsize = size[:batch_ndim]
basesize = size[batch_ndim:batch_ndim + base_ndim]
densesize = size[batch_ndim + base_ndim:]
assert len(densesize) == dense_ndim
printed.append(f"########## {dtype}/{index_dtype}/size={batchsize}+{basesize}+{densesize} ##########")
x = torch.sparse_compressed_tensor(compressed_indices,
plain_indices,
values, size, dtype=dtype, layout=layout, device=device)
printed.append("# sparse tensor")
printed.append(str(x))
printed.append(f"# _{compressed_indices_mth.__name__}")
printed.append(str(compressed_indices_mth(x)))
printed.append(f"# _{plain_indices_mth.__name__}")
printed.append(str(plain_indices_mth(x)))
printed.append("# _values")
printed.append(str(x.values()))
printed.append('')
printed.append('')
orig_maxDiff = self.maxDiff
self.maxDiff = None
try:
self.assertExpected('\n'.join(printed))
self.maxDiff = orig_maxDiff
except Exception:
self.maxDiff = orig_maxDiff
raise
@skipMeta
@all_sparse_compressed_layouts()
@dtypes(*all_types_and_complex_and(torch.half, torch.bool, torch.bfloat16))
def test_copy(self, layout, device, dtype):
def run_test(shape, blocksize, nnz, index_type):
a = self.genSparseCompressedTensor(shape, nnz, dtype=dtype, layout=layout, device=device,
index_dtype=index_dtype, blocksize=blocksize)
b = self.genSparseCompressedTensor(shape, nnz, dtype=dtype, layout=layout, device=device,
index_dtype=index_dtype, blocksize=blocksize)
a.copy_(b)
self.assertEqual(a, b)
ns = [(9, 3), (2, 1), (0, 0)] # (number of dimensions, the corresponding block size)
batch_shapes = [(), (2,), (2, 3)]
for ((m, bm), (n, bn), b), index_dtype in zip(itertools.product(ns, ns, batch_shapes), [torch.int32, torch.int64]):
blocksize = (bm, bn) if layout in {torch.sparse_bsr, torch.sparse_bsc} else ()
run_test((*b, m, n), blocksize, 0, index_dtype)
run_test((*b, m, n), blocksize, m * n, index_dtype)
@skipMeta
@all_sparse_compressed_layouts()
@dtypes(*all_types_and_complex_and(torch.half, torch.bool, torch.bfloat16))
def test_copy_errors(self, layout, device, dtype):
blocksize = (2, 3) if layout in {torch.sparse_bsr, torch.sparse_bsc} else ()
nnz = 6 if layout in {torch.sparse_bsr, torch.sparse_bsc} else 1
shape1 = (2 * 6, 3 * 6) if layout in {torch.sparse_bsr, torch.sparse_bsc} else (2, 3)
for index_dtype in [torch.int32, torch.int64]:
a = self.genSparseCompressedTensor(shape1, 0, dtype=dtype, layout=layout, device=device,
index_dtype=index_dtype, blocksize=blocksize)
with self.assertRaisesRegex(RuntimeError,
"copy of sparse compressed tensors having different layouts is not supported."):
a.copy_(torch.empty(a.shape, dtype=dtype, device=device))
b = self.genSparseCompressedTensor(shape1, nnz, dtype=dtype, layout=layout, device=device,
index_dtype=index_dtype, blocksize=blocksize)
assert a._nnz() != b._nnz(), (a._nnz(), b._nnz())
with self.assertRaisesRegex(RuntimeError,
"only sparse compressed tensors with the same number of specified elements are supported."):
a.copy_(b)
shape2 = tuple(reversed(shape1))
c = self.genSparseCompressedTensor(shape2, nnz, dtype=dtype, layout=layout, device=device,
index_dtype=index_dtype, blocksize=blocksize)
with self.assertRaisesRegex(
RuntimeError,
"expected shapes of self and src to match along dimension"):
b.copy_(c)
if blocksize:
blocksize1 = tuple(reversed(blocksize))
d = self.genSparseCompressedTensor(shape1, nnz, dtype=dtype, layout=layout, device=device,
index_dtype=index_dtype, blocksize=blocksize1)
with self.assertRaisesRegex(RuntimeError,
"copy of sparse compressed tensors having different block sizes is not supported"):
b.copy_(d)
def _smallest_divisor(self, n):
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
return i
return n
@skipIfTorchDynamo("Not a TorchDynamo suitable test")
@all_sparse_compressed_layouts()
@ops(_sparse_compressed_ops)
@precisionOverride({torch.bfloat16: 1e-2, torch.float16: 1e-2})
def test_consistency(self, layout, device, dtype, op):
"""Checks that the op on a strided and on a sparse tensors will
produce the same results.
"""
if not op.supports_sparse_layout(layout):
self.skipTest(f"{op.name} does not support input with {layout} layout")
# FIXME: remove in followup once integer support is landed for segment_reduce
if (layout == torch.sparse_csr and not dtype.is_floating_point
and op.name in ('masked.mean', 'masked.amax', 'masked.amin')):
self.skipTest(f"{op.name} does not support input with {layout} layout and {dtype} dtype")
require_mask = isinstance(op, ReductionOpInfo) and 'masked.' in op.name
samples = []
for sample in op.sample_inputs(device, dtype):
if sample.input.ndim < 2:
continue
dense_dim = sample.input.ndim - 2
blocksize = (tuple(map(self._smallest_divisor, sample.input.shape[:2]))
if layout in {torch.sparse_bsr, torch.sparse_bsc} else None)
def _to_sparse(x):
if isinstance(x, torch.Tensor):
if blocksize is None:
if x.ndim != sample.input.ndim:
return x
elif x.ndim != sample.input.ndim + 2 or x.shape[-3] % blocksize[0] or x.shape[-2] % blocksize[1]:
return x
return x.clone().to_sparse(layout=layout, blocksize=blocksize, dense_dim=dense_dim)
return x
sparse_sample = sample.transform(_to_sparse)
# Some strided samples (with inf, nan elements) appear to share
# storage, so we must clone:
sample = sample.transform(lambda x: (x.clone() if isinstance(x, torch.Tensor) else x))
if validate_sample_input_sparse(op, sparse_sample, check_validate=False) is not sparse_sample:
# that is, the validation returns the sparse sample
# wrapped within ErrorInput instance
continue
samples.append((sample, sparse_sample))
# Fail early to prevent silent success with this test
if len(samples) == 0:
raise ValueError("Expected at least one 2 or higher D tensor in samples.")
# Re-define atol and rtol for operations that result values
# are random (and hence, non-comparable) be we still want to
# check the shape, dtype, etc attributes of the results:
atol = rtol = None
if op.name == 'randn_like':
atol = 1e300
rtol = 1
for sample, sparse_sample in samples:
expected = op(sample.input, *sample.args, **sample.kwargs)
assert torch.is_tensor(expected)
output = op(sparse_sample.input, *sparse_sample.args, **sparse_sample.kwargs)
assert torch.is_tensor(output)
strided_output = output.to_dense()
if require_mask and sample.kwargs.get('mask') is not None:
output_mask = torch.masked._output_mask(op.op, sample.input, *sample.args, **sample.kwargs)
expected.masked_fill_(~output_mask, 0)
self.assertEqual(strided_output, expected, atol=atol, rtol=rtol)
@skipMeta
@all_sparse_compressed_layouts()
@all_sparse_compressed_layouts('layout2')
@dtypes(*all_types_and_complex_and(torch.bool, torch.half, torch.bfloat16))
def test_empty_like(self, layout, layout2, device, dtype):
for sparse in self.generate_simple_inputs(layout):
if layout == layout2:
result = torch.empty_like(sparse, layout=layout2)
compressed_indices_mth, plain_indices_mth = sparse_compressed_indices_methods[result.layout]
torch._validate_sparse_compressed_tensor_args(compressed_indices_mth(result),
plain_indices_mth(result),
result.values(),
result.shape,
result.layout)
self.assertEqual(sparse.shape, result.shape)
else:
self.assertRaisesRegex(
RuntimeError,
"empty_like with different sparse layout is not supported",
lambda: torch.empty_like(sparse, layout=layout2)
)
@skipMeta
@all_sparse_compressed_layouts()
@dtypes(*all_types_and_complex_and(torch.half, torch.bool, torch.bfloat16))
def test_validate(self, layout, device, dtype):
def make_zero_batched(t):
return torch.empty(*((0,) + t.shape), dtype=t.dtype, device=t.device)
for index_dtype in [torch.int32, torch.int64]:
for (compressed_indices, plain_indices, values), kwargs in self.generate_simple_inputs(
layout, device=device, dtype=dtype, index_dtype=index_dtype, output_tensor=False):
size = kwargs['size']
torch._validate_sparse_compressed_tensor_args(compressed_indices, plain_indices, values, size, layout)
# check empty batch
torch._validate_sparse_compressed_tensor_args(
*(make_zero_batched(t) for t in (compressed_indices, plain_indices, values)),
(0,) + size,
layout
)
compressed_indices = torch.tensor([0, 0], dtype=index_dtype)
plain_indices = torch.tensor([], dtype=index_dtype)
torch._validate_compressed_sparse_indices(layout in {torch.sparse_csr, torch.sparse_bsr},
compressed_indices, plain_indices, 1, 1, 0)
def _generate_invalid_input(self, layout, device):
from functools import partial
def shape(shape, basedim=0):
blocksize = (1, 1)
if layout is torch.sparse_csc:
shape = shape[:basedim] + (shape[basedim + 1], shape[basedim]) + shape[basedim + 2:]
elif layout is torch.sparse_bsc:
shape = shape[:basedim] + (shape[basedim + 1] * blocksize[1], shape[basedim] * blocksize[0]) + shape[basedim + 2:]
elif layout is torch.sparse_bsr:
shape = shape[:basedim] + (shape[basedim] * blocksize[0], shape[basedim + 1] * blocksize[1]) + shape[basedim + 2:]
return shape
def values(lst, device=device):
if layout in {torch.sparse_bsr, torch.sparse_bsc}:
lst = [[[item]] for item in lst]
return torch.tensor(lst, device=device)
tensor = partial(torch.tensor, device=device)
values = partial(values, device=device)
yield ('incontiguous compressed_indices',
tensor([0, -1, 2, -1, 4, -1])[::2],
tensor([0, 1, 0, 2]),
values([1, 2, 3, 4]),
shape((2, 3)),
'expected compressed_indices to be a contiguous tensor per batch')
yield ('incontiguous plain_indices',
tensor([0, 2, 4]),
tensor([0, -1, 1, -1, 0, -1, 2, -1])[::2],
values([1, 2, 3, 4]),
shape((2, 3)),
'expected plain_indices to be a contiguous tensor per batch')
yield ('0-D compressed_indices',
tensor(0),
tensor([0, 1, 0, 2]),
values([1, 2, 3, 4]),
shape((2, 3)),
'compressed_indices must have dimensionality >= 1 but got 0')
yield ('compressed/plain_indices mismatch of dimensionalities',
tensor([[0, 2, 4]]),
tensor([0, 1, 0, 2]),
values([1, 2, 3, 4]),
shape((2, 3)),
'compressed_indices and plain_indices dimensionalities must be equal but got 2 and 1, respectively')
if layout in {torch.sparse_csr, torch.sparse_csc}:
yield ('indices and values mismatch of dimensionalities',
tensor([[0, 2, 4]]),
tensor([[0, 1, 0, 2]]),
values([1, 2, 3, 4]),
shape((2, 3)),
r'values must have dimensionality > sum of batch and block dimensionalities \(=1 \+ 0\) but got 1')
else:
yield ('indices and values mismatch of dimensionalities',
tensor([[0, 2, 4]]),
tensor([[0, 1, 0, 2]]),
values([1, 2, 3, 4]),
shape((2, 3)),
r'values must have dimensionality > sum of batch and block dimensionalities \(=1 \+ 2\) but got 3')
yield ('invalid size',
tensor([0, 2, 4]),
tensor([0, 1, 0, 2]),
values([1, 2, 3, 4]),
(2,),
r'tensor dimensionality must be sum of batch, base, and dense dimensionalities \(=0 \+ 2 \+ 0\) but got 1')
yield ('invalid batchsize',
tensor([[0, 2, 4]]),
tensor([[0, 1, 0, 2]]),
values([[1, 2, 3, 4]]),
shape((2, 2, 3), 1),
r'all batch dimensions of compressed_indices \(=\[1\]\), plain_indices \(=\[1\]\), '
r'and values \(=\[1\]\) must be equal to tensor batch dimensions \(=\[2\]\)')
if layout is torch.sparse_bsr:
yield ('invalid blocksize',
tensor([0, 2, 4]),
tensor([0, 1, 0, 2]),
tensor([[[1, 11]], [[2, 22]], [[3, 33]], [[4, 33]]]),
shape((2, 3)),
r'tensor shape\[1\] \(=3\) must be divisible with blocksize\[1\] \(=2\) as defined by values shape')
if layout is torch.sparse_bsc:
yield ('invalid blocksize',
tensor([0, 2, 4]),
tensor([0, 1, 0, 2]),
tensor([[[1, 11]], [[2, 22]], [[3, 33]], [[4, 33]]]),
shape((3, 2)),
r'tensor shape\[1\] \(=3\) must be divisible with blocksize\[1\] \(=2\) as defined by values shape')
yield ('invalid compressed_indices shape',
tensor([0, 2, 3, 4]),
tensor([0, 1, 0, 2]),
values([1, 2, 3, 4]),
shape((2, 3)),
r'compressed_indices.shape\[-1\] must be equal to the number of compressed_indices_names \+ 1 \(=3\), but got 4')
yield ('invalid compressed_indices shape',
tensor([0, 2, 4]),
tensor([0, 1, 0, 1, 2]),
values([1, 2, 3, 4]),
shape((2, 3)),
r'plain_indices.shape\[-1\] must be equal to nnz \(=4\) as defined by values.shape\[0\], but got 5')
yield ('compressed/plain_indices mismatch of dtype',
tensor([0, 2, 4], dtype=torch.int32),
tensor([0, 1, 0, 2], dtype=torch.int64),
values([1, 2, 3, 4]),
shape((2, 3)),
r'compressed_indices and plain_indices must have the same dtype, bot got Int and Long, respectively')
yield ('invalid compressed/plain_indices dtype',
tensor([0, 2, 4], dtype=torch.int16),
tensor([0, 1, 0, 2], dtype=torch.int16),
values([1, 2, 3, 4]),
shape((2, 3)),
r'compressed_indices and plain_indices dtype must be Int or Long, but got Short')
# CUDA kernel asserts are not recoverable, so we skip these for now
if torch.device(device).type == 'cpu':
yield ('invalid compressed_indices[0]',
tensor([1, 2, 4]),
tensor([0, 1, 0, 2]),
values([1, 2, 3, 4]),
shape((2, 3)),
r'`compressed_indices\[..., 0\] == 0` is not satisfied.')
yield ('invalid compressed_indices[0] when nnz == 0',
tensor([1, 0], dtype=torch.int64),
tensor([], dtype=torch.int64),
values([1])[:0],
shape((1, 1)),
r'`compressed_indices\[..., 0\] == 0` is not satisfied.')
yield ('invalid compressed_indices[-1]',
tensor([0, 2, 5]),
tensor([0, 1, 0, 2]),
values([1, 2, 3, 4]),
shape((2, 3)),
r'`compressed_indices\[..., -1\] == nnz` is not satisfied.')
yield ('invalid compressed_indices[-1] when nnz == 0',
tensor([0, 1], dtype=torch.int64),
tensor([], dtype=torch.int64),
values([1])[:0],
shape((1, 1)),
r'`compressed_indices\[..., -1\] == nnz` is not satisfied.')
yield ('invalid compressed_indices.diff(dim=-1)',
tensor([0, 0, 4]),
tensor([0, 1, 0, 2]),
values([1, 2, 3, 4]),
shape((2, 3)),
r'0 <= compressed_indices\[..., 1:\] - compressed_indices\[..., :\-1\] <= plain_dim` is not satisfied.')
yield ('invalid compressed_indices.diff(dim=-1)',
tensor([0, 5, 4]),
tensor([0, 1, 0, 2]),
values([1, 2, 3, 4]),
shape((2, 3)),
r'0 <= compressed_indices\[..., 1:\] - compressed_indices\[..., :\-1\] <= plain_dim` is not satisfied.')
yield ('invalid min(plain_indices)',
tensor([0, 2, 4]),
tensor([0, -1, 0, 3]),
values([1, 2, 3, 4]),
shape((2, 3)),
r'`0 <= plain_indices < plain_dim` is not satisfied.')
yield ('invalid max(plain_indices)',
tensor([0, 2, 4]),
tensor([0, 1, 0, 3]),
values([1, 2, 3, 4]),
shape((2, 3)),
r'`0 <= plain_indices < plain_dim` is not satisfied.')
yield ('non-coalesced',
tensor([0, 2, 4]),
tensor([1, 0, 0, 2]),
values([1, 2, 3, 4]),
shape((2, 3)),
r'`plain_indices\[..., compressed_indices\[..., i - 1\]:compressed_indices\[..., i\]\] '
'for all i = 1, ..., compressed_dim '
'are sorted and distinct along the last dimension values` is not satisfied.')
if TEST_CUDA and torch.device(device).type == 'cpu':
yield ('indices and values mismatch of device',
torch.tensor([0, 2, 4]),
torch.tensor([0, 1, 0, 1]),
values([1, 2, 3, 4], device='cuda'),
shape((2, 3)),
r'device of compressed_indices \(=cpu\) must match device of values \(=cuda:0\)')
yield ('compressed_indices and values mismatch of device',
torch.tensor([0, 2, 4], device='cuda'),
torch.tensor([0, 1, 0, 1]),
values([1, 2, 3, 4]),
shape((2, 3)),
r'Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cpu!')
yield ('compressed/plain_indices mismatch of device',
torch.tensor([0, 2, 4], device='cuda'),
torch.tensor([0, 1, 0, 1]),
values([1, 2, 3, 4], device='cuda'),
shape((2, 3)),
r'Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cpu!')
if TEST_CUDA and torch.device(device).type == 'cuda' and torch.cuda.device_count() >= 2:
yield ('indices and values mismatch of device index',
torch.tensor([0, 2, 4], device='cuda:0'),
torch.tensor([0, 1, 0, 1], device='cuda:0'),
values([1, 2, 3, 4], device='cuda:1'),
shape((2, 3)),
r'device of compressed_indices \(=cuda:0\) must match device of values \(=cuda:1\)')
yield ('compressed_indices and values mismatch of device index',
torch.tensor([0, 2, 4], device='cuda:0'),
torch.tensor([0, 1, 0, 1], device='cuda:1'),
values([1, 2, 3, 4], device='cuda:0'),
shape((2, 3)),
r'Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cuda:1!')
@skipMeta
@all_sparse_compressed_layouts()
@parametrize('target', [subtest('validate_sparse_compressed_tensor_args'),
subtest('sparse_compressed_tensor'),
subtest('sparse_compressed_tensor_no_size')])
def test_invalid_input(self, layout, device, target):
for label, compressed_indices, plain_indices, values, size, errmsg in self._generate_invalid_input(layout, device):
if layout is torch.sparse_bsr:
errmsg = errmsg.replace('compressed_indices_name', 'row block').replace('plain_indices_name', 'column block')
elif layout is torch.sparse_bsc:
errmsg = errmsg.replace('compressed_indices_name', 'column block').replace('plain_indices_name', 'row block')
elif layout is torch.sparse_csr:
errmsg = errmsg.replace('compressed_indices_name', 'row').replace('plain_indices_name', 'column')
elif layout is torch.sparse_csc:
errmsg = errmsg.replace('compressed_indices_name', 'column').replace('plain_indices_name', 'row')
if layout in {torch.sparse_csr, torch.sparse_bsr}:
errmsg = errmsg.replace('compressed_indices', 'crow_indices') \
.replace('plain_indices', 'col_indices') \
.replace('plain_dim', 'ncols') \
.replace('compressed_dim', 'nrows')
else:
errmsg = errmsg.replace('compressed_indices', 'ccol_indices') \
.replace('plain_indices', 'row_indices') \
.replace('plain_dim', 'nrows') \
.replace('compressed_dim', 'ncols')
if target == 'sparse_compressed_tensor_no_size' and label in {
'invalid size', 'invalid batchsize', 'invalid compressed_indices shape', 'invalid max(plain_indices)',
'invalid blocksize'}:
# Skip invalid size input as a valid size is estimated for other inputs
continue
with self.assertRaisesRegex(RuntimeError, errmsg):
if target == 'validate_sparse_compressed_tensor_args':
torch._validate_sparse_compressed_tensor_args(compressed_indices, plain_indices, values, size, layout)
elif target == 'sparse_compressed_tensor':
torch.sparse_compressed_tensor(compressed_indices, plain_indices, values, size, layout=layout)
elif target == 'sparse_compressed_tensor_no_size':
torch.sparse_compressed_tensor(compressed_indices, plain_indices, values, layout=layout)
else:
raise NotImplementedError(target)
@skipMeta
@onlyCPU
@largeTensorTest("30GB", "cpu")
def test_invalid_input_csr_large(self):
rows = 2 ** 31
with self.assertRaisesRegex(RuntimeError, '32-bit integer overflow in row dimension'):
torch.sparse_csr_tensor(torch.arange(rows + 1, dtype=torch.int32) // rows,
torch.tensor([0], dtype=torch.int32),
torch.tensor([1]), (rows, 1))
torch.sparse_csr_tensor(torch.arange(rows + 1, dtype=torch.int64) // rows,
torch.tensor([0], dtype=torch.int64),
torch.tensor([1]), (rows, 1))
cols = 2 ** 31
with self.assertRaisesRegex(RuntimeError, '32-bit integer overflow in column dimension'):
torch.sparse_csr_tensor(torch.arange(2, dtype=torch.int32),
torch.tensor([0], dtype=torch.int32),
torch.tensor([1]), (1, cols))
torch.sparse_csr_tensor(torch.arange(2, dtype=torch.int64),
torch.tensor([0], dtype=torch.int64),
torch.tensor([1]), (1, cols))
nnz = 2 ** 31
with self.assertRaisesRegex(RuntimeError, '32-bit integer overflow in nnz'):
# nnz cannot be stored in int32 crow_indices
# but the `crow_indices[..., -1] == nnz`` check happens after the overflow validation
# So we can use `nnz - 1` here to avoid `value cannot be converted to type int32 without overflow`
# during construction of crow_indices
torch.sparse_csr_tensor(torch.tensor([0, nnz // 2, nnz - 1], dtype=torch.int32),
torch.arange(nnz // 2, dtype=torch.int32).repeat(2),
torch.ones(nnz, dtype=torch.int8), (2, nnz // 2))
torch.sparse_csr_tensor(torch.tensor([0, nnz // 2, nnz], dtype=torch.int64),
torch.arange(nnz // 2, dtype=torch.int64).repeat(2),
torch.ones(nnz, dtype=torch.int8), (2, nnz // 2))
@skipMeta
@onlyCPU
@all_sparse_compressed_layouts()
def test_dim(self, layout):
for (compressed_indices, plain_indices, values), kwargs in self.generate_simple_inputs(layout, output_tensor=False):
size = kwargs['size']
batch_dim = compressed_indices.dim() - 1
sparse_dim = 2
block_dim = 2 if layout in {torch.sparse_bsr, torch.sparse_bsc} else 0
dense_dim = values.dim() - batch_dim - block_dim - 1
sparse = torch.sparse_compressed_tensor(compressed_indices, plain_indices, values, size, layout=layout)
self.assertEqual(sparse.sparse_dim(), sparse_dim)
self.assertEqual(sparse.dense_dim(), dense_dim)
@skipMeta
@all_sparse_compressed_layouts()
@dtypes(*all_types_and_complex_and(torch.bool, torch.half, torch.bfloat16))
def test_to_dtype(self, layout, device, dtype):
# to_dense does not support hybrid inputs
for sparse in self.generate_simple_inputs(layout, dtype=dtype, device=device, enable_hybrid=False):
for to_dtype in all_types_and_complex_and(torch.bool, torch.half, torch.bfloat16):
sparse_to_dtype = sparse.to(to_dtype)
dense_to_dtype = sparse.to_dense().to(to_dtype)
self.assertEqual(sparse_to_dtype.to_dense(), dense_to_dtype)
@skipMeta
@all_sparse_compressed_layouts()
@dtypes(torch.double)
def test_pickle(self, layout, dtype, device):
import pickle
for sparse in self.generate_simple_inputs(layout, device=device, dtype=dtype):
serialized = pickle.dumps(sparse)
sparse_loaded = pickle.loads(serialized)
self.assertEqual(sparse, sparse_loaded)
@all_sparse_compressed_layouts()
@parametrize("index_dtype", [torch.int32, torch.int64])
@dtypes(*all_types_and_complex_and(torch.half, torch.bfloat16, torch.bool))
def test_select_copy(self, device, dtype, index_dtype, layout):
def is_view_of(base, other):
# a shameless copy of TestViewOps.is_view_of
if (
not other._is_view() or
other is base or
other._base is not base or
base.device != other.device
):
return False
if base.device.type in ('cpu', 'cuda'):
if base.untyped_storage().data_ptr() != other.untyped_storage().data_ptr():
return False
return True
kwargs = dict(device=device, dtype=dtype, index_dtype=index_dtype)
for sparse, dense in zip(self.generate_simple_inputs(layout, **kwargs),
self.generate_simple_inputs(torch.strided, **kwargs)):
if layout in {torch.sparse_csr, torch.sparse_bsr}:
n_batchdim = sparse.crow_indices().ndim - 1
elif layout in {torch.sparse_csc, torch.sparse_bsc}:
n_batchdim = sparse.ccol_indices().ndim - 1
else:
assert 0 # unreachable
self.assertEqual(sparse, dense)
for dim in range(sparse.ndim):
if sparse.shape[dim] == 0:
with self.assertRaisesRegex(IndexError, "index 0 out of range for tensor of size"):
torch.select_copy(sparse, dim, 0)
with self.assertRaisesRegex(IndexError, "index 0 out of range for tensor of size"):
torch.select_copy(dense, dim, 0)
elif n_batchdim and dim >= n_batchdim and dim < n_batchdim + 2:
with self.assertRaisesRegex(
RuntimeError,
"selecting sparse dimensions is not supported for batched sparse compressed tensors"):
torch.select_copy(sparse, dim, 0)
else:
for index in {0, sparse.shape[dim] // 2, sparse.shape[dim] - 1}:
dense_select = torch.select_copy(dense, dim, index)
sparse_select = torch.select_copy(sparse, dim, index)
self.assertEqual(sparse_select, dense_select)
self.assertFalse(is_view_of(sparse_select.values(), sparse.values()))
def _npref_block_addmm_addmv(c, a, b, alpha, beta):
return alpha * (a @ b) + beta * c
| TestSparseCompressed |
python | django__django | tests/admin_checks/models.py | {
"start": 1422,
"end": 1503
} | class ____(models.Model):
state = models.ForeignKey(State, models.CASCADE)
| City |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.