Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

keyword → query #112

Merged
merged 3 commits into from
Nov 8, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 21 additions & 21 deletions docs/usage/request-templates.rst
Original file line number Diff line number Diff line change
Expand Up @@ -32,13 +32,13 @@ specific parameters. For example:
def start_search(
self, response: DummyResponse, search_request_template: SearchRequestTemplate
):
yield search_request_template.request(keyword="foo bar").to_scrapy(
yield search_request_template.request(query="foo bar").to_scrapy(
callback=self.parse_result
)

def parse_result(self, response): ...

``search_request_template.request(keyword="foo bar")`` builds a
``search_request_template.request(query="foo bar")`` builds a
:class:`~zyte_common_items.Request` object, e.g. with URL
``https://example.com/search?q=foo+bar``.

Expand All @@ -62,10 +62,10 @@ For example:
class ExampleComSearchRequestTemplatePage(SearchRequestTemplatePage):
@field
def url(self):
return "https://example.com/search?q={{ keyword|quote_plus }}"
return "https://example.com/search?q={{ query|quote_plus }}"

Strings returned by request template page object fields are :doc:`Jinja
templates <jinja:templates>`, and may use the keyword arguments of the
templates <jinja:templates>`, and may use the query arguments of the
``request`` method of the corresponding :ref:`request template item class
<request-template-api>`.

Expand All @@ -77,8 +77,8 @@ on how spaces are encoded:
=================================== ===================================================
Example search URL for “foo bar” URL template
=================================== ===================================================
https://example.com/?q=foo%20bar ``https://example.com/?q={{ keyword|urlencode }}``
https://example.com/?q=foo+bar ``https://example.com/?q={{ keyword|quote_plus }}``
https://example.com/?q=foo%20bar ``https://example.com/?q={{ query|urlencode }}``
https://example.com/?q=foo+bar ``https://example.com/?q={{ query|quote_plus }}``
=================================== ===================================================

You can use any of :ref:`Jinja’s built-in filters <builtin-filters>`, plus
Expand All @@ -92,11 +92,11 @@ very complex scenarios:
def url(self):
return """
{%-
if keyword|length > 1
and keyword[0]|lower == 'p'
and keyword[1:]|int(-1) != -1
if query|length > 1
and query[0]|lower == 'p'
and query[1:]|int(-1) != -1
-%}
https://example.com/p/{{ keyword|upper }}
https://example.com/p/{{ query|upper }}
{%- else -%}
https://example.com/search
{%- endif -%}
Expand All @@ -106,9 +106,9 @@ very complex scenarios:
def method(self):
return """
{%-
if keyword|length > 1
and keyword[0]|lower == 'p'
and keyword[1:]|int(-1) != -1
if query|length > 1
and query[0]|lower == 'p'
and query[1:]|int(-1) != -1
-%}
GET
{%- else -%}
Expand All @@ -120,12 +120,12 @@ very complex scenarios:
def body(self):
return """
{%-
if keyword|length > 1
and keyword[0]|lower == 'p'
and keyword[1:]|int(-1) != -1
if query|length > 1
and query[0]|lower == 'p'
and query[1:]|int(-1) != -1
-%}
{%- else -%}
{"query": {{ keyword|tojson }}}
{"query": {{ query|tojson }}}
{%- endif -%}
"""

Expand All @@ -136,15 +136,15 @@ very complex scenarios:
name=(
"""
{%-
if keyword|length > 1
and keyword[0]|lower == 'p'
and keyword[1:]|int(-1) != -1
if query|length > 1
and query[0]|lower == 'p'
and query[1:]|int(-1) != -1
-%}
{%- else -%}
Query
{%- endif -%}
"""
),
value="{{ keyword }}",
value="{{ query }}",
),
]
130 changes: 98 additions & 32 deletions tests/test_request_templates.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,11 @@ class HolisticSearchRequestTemplatePage(SearchRequestTemplatePage):
def url(self):
return """
{%-
if keyword|length > 1
and keyword[0]|lower == 'p'
and keyword[1:]|int(-1) != -1
if query|length > 1
and query[0]|lower == 'p'
and query[1:]|int(-1) != -1
-%}
https://example.com/p/{{ keyword|upper }}
https://example.com/p/{{ query|upper }}
{%- else -%}
https://example.com/search
{%- endif -%}
Expand All @@ -38,9 +38,9 @@ def url(self):
def method(self):
return """
{%-
if keyword|length > 1
and keyword[0]|lower == 'p'
and keyword[1:]|int(-1) != -1
if query|length > 1
and query[0]|lower == 'p'
and query[1:]|int(-1) != -1
-%}
GET
{%- else -%}
Expand All @@ -52,12 +52,12 @@ def method(self):
def body(self):
return """
{%-
if keyword|length > 1
and keyword[0]|lower == 'p'
and keyword[1:]|int(-1) != -1
if query|length > 1
and query[0]|lower == 'p'
and query[1:]|int(-1) != -1
-%}
{%- else -%}
{"query": {{ keyword|tojson }}}
{"query": {{ query|tojson }}}
{%- endif -%}
"""

Expand All @@ -68,26 +68,26 @@ def headers(self):
name=(
"""
{%-
if keyword|length > 1
and keyword[0]|lower == 'p'
and keyword[1:]|int(-1) != -1
if query|length > 1
and query[0]|lower == 'p'
and query[1:]|int(-1) != -1
-%}
{%- else -%}
Query
{%- endif -%}
"""
),
value="{{ keyword }}",
value="{{ query }}",
),
]

search_request_template = await HolisticSearchRequestTemplatePage().to_item()

search_request = search_request_template.request(keyword="p250")
search_request = search_request_template.request(query="p250")
expected_request = Request("https://example.com/p/P250")
assert search_request == expected_request

search_request = search_request_template.request(keyword="foo bar")
search_request = search_request_template.request(query="foo bar")
expected_request = Request(
"https://example.com/search",
method="POST",
Expand All @@ -102,25 +102,25 @@ def headers(self):
class VerbatimSearchRequestTemplatePage(SearchRequestTemplatePage):
@field
def url(self):
return "https://example.com/?search={{ keyword }}"
return "https://example.com/?search={{ query }}"


class QuoteSearchRequestTemplatePage(SearchRequestTemplatePage):
@field
def url(self):
return "https://example.com/?search={{ keyword|urlencode }}"
return "https://example.com/?search={{ query|urlencode }}"


class QuotePlusSearchRequestTemplatePage(SearchRequestTemplatePage):
@field
def url(self):
return "https://example.com/?search={{ keyword|quote_plus }}"
return "https://example.com/?search={{ query|quote_plus }}"


class ReplaceSearchRequestTemplatePage(SearchRequestTemplatePage):
@field
def url(self):
return "https://example.com/search/{{ keyword|replace(' ', '/') }}"
return "https://example.com/search/{{ query|replace(' ', '/') }}"


@attrs.define
Expand All @@ -129,7 +129,7 @@ class UrlBasedSearchRequestTemplatePage(SearchRequestTemplatePage):

@field
def url(self):
return f"{self.request_url}?search={{{{ keyword|urlencode }}}}"
return f"{self.request_url}?search={{{{ query|urlencode }}}}"


# Defines way more of what the corresponding test scenario uses to give an idea
Expand All @@ -156,16 +156,16 @@ def edit_request_url(expression, page):
f"the parent page object class does not define any RequestUrl "
f"dependency."
)
url_safe_keyword_placeholder = "7dnKEYWORD2Ua"
url_safe_query_placeholder = "7dnQUERY2Ua"
if "add_query_params" in expression:
params = copy(expression["add_query_params"])
for k in list(params):
v = params.pop(k)
k = k.format(keyword=url_safe_keyword_placeholder)
v = v.format(keyword=url_safe_keyword_placeholder)
k = k.format(query=url_safe_query_placeholder)
v = v.format(query=url_safe_query_placeholder)
params[k] = v
url = add_or_replace_parameters(url, params)
url = url.replace(url_safe_keyword_placeholder, "{{ keyword|urlencode }}")
url = url.replace(url_safe_query_placeholder, "{{ query|urlencode }}")
return url


Expand All @@ -178,11 +178,11 @@ class Processors:

@field
def url(self):
return {"add_query_params": {"search": "{keyword}"}}
return {"add_query_params": {"search": "{query}"}}


@pytest.mark.parametrize(
("page", "inputs", "keyword", "url"),
("page", "inputs", "query", "url"),
(
(
VerbatimSearchRequestTemplatePage,
Expand Down Expand Up @@ -223,9 +223,9 @@ def url(self):
),
)
@pytest.mark.asyncio
async def test_url(page, inputs, keyword, url):
async def test_url(page, inputs, query, url):
search_request_template = await page(**inputs).to_item()
search_request = search_request_template.request(keyword=keyword)
search_request = search_request_template.request(query=query)
assert search_request.url == url


Expand All @@ -241,7 +241,7 @@ def body(self):
return " "

search_request_template = await BodySpaceSearchRequestTemplatePage().to_item()
search_request = search_request_template.request(keyword="foo bar")
search_request = search_request_template.request(query="foo bar")
assert search_request.body == b64encode(b" ").decode()


Expand All @@ -257,5 +257,71 @@ def headers(self):
return [Header(name="Foo", value="")]

search_request_template = await BodySpaceSearchRequestTemplatePage().to_item()
search_request = search_request_template.request(keyword="foo bar")
search_request = search_request_template.request(query="foo bar")
assert search_request.headers == [Header(name="Foo", value="")]


class KeywordSearchRequestTemplatePage(SearchRequestTemplatePage):
@field
def url(self):
return "https://example.com/?search={{ keyword }}"


@pytest.mark.asyncio
async def test_request_no_parameters():
search_request_template = await VerbatimSearchRequestTemplatePage().to_item()
with pytest.raises(TypeError):
search_request_template.request()


@pytest.mark.asyncio
async def test_request_template_keyword_call_keyword():
search_request_template = await KeywordSearchRequestTemplatePage().to_item()
with pytest.warns(
DeprecationWarning, match=r"Replace the 'keyword' variable with 'query'"
), pytest.warns(
DeprecationWarning,
match=r"The 'keyword' parameter of request\(\) is deprecated",
):
search_request = search_request_template.request(keyword="foo")
assert search_request.url == "https://example.com/?search=foo"


@pytest.mark.asyncio
async def test_request_template_keyword_call_query():
search_request_template = await KeywordSearchRequestTemplatePage().to_item()
with pytest.warns(
DeprecationWarning, match=r"Replace the 'keyword' variable with 'query'"
):
search_request = search_request_template.request(query="foo")
assert search_request.url == "https://example.com/?search=foo"


@pytest.mark.asyncio
async def test_request_template_query_call_keyword():
search_request_template = await VerbatimSearchRequestTemplatePage().to_item()
with pytest.warns(
DeprecationWarning,
match=r"The 'keyword' parameter of request\(\) is deprecated",
):
search_request = search_request_template.request(keyword="foo")
assert search_request.url == "https://example.com/?search=foo"


@pytest.mark.asyncio
async def test_request_keyword_and_query_same():
search_request_template = await VerbatimSearchRequestTemplatePage().to_item()
with pytest.warns(
DeprecationWarning,
match=r"The 'keyword' parameter of request\(\) is deprecated",
):
search_request = search_request_template.request(query="foo", keyword="foo")
assert search_request.url == "https://example.com/?search=foo"


@pytest.mark.asyncio
async def test_request_keyword_and_query_different():
search_request_template = await VerbatimSearchRequestTemplatePage().to_item()
with pytest.warns(DeprecationWarning, match=r"overrides the value of"):
search_request = search_request_template.request(query="foo", keyword="bar")
assert search_request.url == "https://example.com/?search=foo"
Loading
Loading