Skip to content

Commit a80bab2

Browse files
authored
Assignment from no return (opensearch-project#658)
* added unnecessary-dunder-call to pylintrc files; disabled for certain lines in run_tests.py, exception thrown by 'git remote add origin' when the remote already exists will not exit Signed-off-by: Mark Cohen <[email protected]> * updates to adhere to assignment-from-no-return lint Signed-off-by: Mark Cohen <[email protected]> * simplified get_value_filter in Facet to return None added assert to test get_value_filter returning None Signed-off-by: Mark Cohen <[email protected]> * added option to output HTML test coverage locally from run_tests.py returning None from test_faceted_search.Facet.get_value_filter Signed-off-by: Mark Cohen <[email protected]> * added unused-variable lints; replaced unused variables with _ or referenced them Signed-off-by: Mark Cohen <[email protected]> * updated CHANGELOG to point to the right PR Signed-off-by: Mark Cohen <[email protected]> --------- Signed-off-by: Mark Cohen <[email protected]>
1 parent 900ea94 commit a80bab2

22 files changed

+70
-57
lines changed

.pylintrc

+3-1
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,9 @@ enable=line-too-long,
77
missing-function-docstring,
88
missing-param-doc,
99
differing-param-doc,
10-
unnecessary-dunder-call
10+
unnecessary-dunder-call,
11+
assignment-from-no-return,
12+
unused-variable
1113
max-line-length=240
1214
good-names-rgxs=^[_a-z][_a-z0-9]?$
1315

CHANGELOG.md

+3
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,9 @@ Inspired from [Keep a Changelog](https://keepachangelog.com/en/1.0.0/)
33

44
## [Unreleased]
55
### Added
6+
- Added pylint `assignment-from-no-return` and `unused-variable` (([#658](https://github.com/opensearch-project/opensearch-py/pull/658))
7+
- Added pylint `unnecessary-dunder-calls` (([#655](https://github.com/opensearch-project/opensearch-py/pull/655))
8+
- Changed to use .pylintrc files in root and any directory with override requirements (([#654](https://github.com/opensearch-project/opensearch-py/pull/654))
69
- Added pylint `unspecified-encoding` and `missing-function-docstring` and ignored opensearchpy for lints (([#643](https://github.com/opensearch-project/opensearch-py/pull/643)))
710
- Added pylint `line-too-long` and `invalid-name` ([#590](https://github.com/opensearch-project/opensearch-py/pull/590))
811
- Added pylint `pointless-statement` ([#611](https://github.com/opensearch-project/opensearch-py/pull/611))

benchmarks/bench_info_sync.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@
2323
def get_info(client: Any, request_count: int) -> float:
2424
"""get info from client"""
2525
total_time: float = 0
26-
for request in range(request_count):
26+
for _ in range(request_count):
2727
start = time.time() * 1000
2828
client.info()
2929
total_time += time.time() * 1000 - start
@@ -49,7 +49,7 @@ def test(thread_count: int = 1, request_count: int = 1, client_count: int = 1) -
4949
root.addHandler(handler)
5050

5151
clients = []
52-
for i in range(client_count):
52+
for _ in range(client_count):
5353
clients.append(
5454
OpenSearch(
5555
hosts=[{"host": host, "port": port}],

benchmarks/bench_sync.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@
2424
def index_records(client: Any, index_name: str, item_count: int) -> Any:
2525
"""bulk index item_count records into index_name"""
2626
total_time = 0
27-
for iteration in range(10):
27+
for _ in range(10):
2828
data: Any = []
2929
for item in range(item_count):
3030
data.append(
@@ -68,7 +68,7 @@ def test(thread_count: int = 1, item_count: int = 1, client_count: int = 1) -> N
6868
root.addHandler(handler)
6969

7070
clients = []
71-
for i in range(client_count):
71+
for _ in range(client_count):
7272
clients.append(
7373
OpenSearch(
7474
hosts=[{"host": host, "port": port}],

opensearchpy/.pylintrc

+3-1
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@ enable=line-too-long,
44
invalid-name,
55
pointless-statement,
66
unspecified-encoding,
7-
unnecessary-dunder-call
7+
unnecessary-dunder-call,
8+
assignment-from-no-return,
9+
unused-variable
810
max-line-length=240
911
good-names-rgxs=^[_a-z][_a-z0-9]?$

opensearchpy/helpers/faceted_search.py

+1-5
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,6 @@
2323
# KIND, either express or implied. See the License for the
2424
# specific language governing permissions and limitations
2525
# under the License.
26-
2726
from datetime import datetime, timedelta
2827
from typing import Any, Optional
2928

@@ -86,10 +85,7 @@ def add_filter(self, filter_values: Any) -> Any:
8685
return f
8786

8887
def get_value_filter(self, filter_value: Any) -> Any:
89-
"""
90-
Construct a filter for an individual value
91-
"""
92-
pass
88+
return None
9389

9490
def is_filtered(self, key: Any, filter_values: Any) -> bool:
9591
"""

samples/knn/knn_async_basics.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ async def main() -> None:
5656
vectors = []
5757
for i in range(10):
5858
vec = []
59-
for j in range(dimensions):
59+
for _ in range(dimensions):
6060
vec.append(round(random.uniform(0, 1), 2))
6161

6262
vectors.append(
@@ -74,7 +74,7 @@ async def main() -> None:
7474

7575
# search
7676
vec = []
77-
for j in range(dimensions):
77+
for _ in range(dimensions):
7878
vec.append(round(random.uniform(0, 1), 2))
7979
print(f"Searching for {vec} ...")
8080

samples/knn/knn_basics.py

+3-6
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ def main() -> None:
5555
vectors = []
5656
for i in range(10):
5757
vec = []
58-
for j in range(dimensions):
58+
for _ in range(dimensions):
5959
vec.append(round(random.uniform(0, 1), 2))
6060

6161
vectors.append(
@@ -72,15 +72,12 @@ def main() -> None:
7272
client.indices.refresh(index=index_name)
7373

7474
# search
75-
vec = []
76-
for j in range(dimensions):
77-
vec.append(round(random.uniform(0, 1), 2))
75+
vec = [round(random.uniform(0, 1), 2) for _ in range(dimensions)]
7876
print(f"Searching for {vec} ...")
7977

8078
search_query = {"query": {"knn": {"values": {"vector": vec, "k": 3}}}}
8179
results = client.search(index=index_name, body=search_query)
82-
for hit in results["hits"]["hits"]:
83-
print(hit)
80+
(print(hit) for hit in results["hits"]["hits"])
8481

8582
# delete index
8683
client.indices.delete(index=index_name)

samples/knn/knn_boolean_filter.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ def main() -> None:
5656
genres = ["fiction", "drama", "romance"]
5757
for i in range(3000):
5858
vec = []
59-
for j in range(dimensions):
59+
for _ in range(dimensions):
6060
vec.append(round(random.uniform(0, 1), 2))
6161

6262
vectors.append(
@@ -76,7 +76,7 @@ def main() -> None:
7676
# search
7777
genre = random.choice(genres)
7878
vec = []
79-
for j in range(dimensions):
79+
for _ in range(dimensions):
8080
vec.append(round(random.uniform(0, 1), 2))
8181
print(f"Searching for {vec} with the '{genre}' genre ...")
8282

test_opensearchpy/.pylintrc

+3-1
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@ enable=line-too-long,
66
unspecified-encoding,
77
missing-param-doc,
88
differing-param-doc,
9-
unnecessary-dunder-call
9+
unnecessary-dunder-call,
10+
assignment-from-no-return,
11+
unused-variable
1012
max-line-length=240
1113
good-names-rgxs=^[_a-z][_a-z0-9]?$

test_opensearchpy/run_tests.py

+14-3
Original file line numberDiff line numberDiff line change
@@ -94,9 +94,13 @@ def fetch_opensearch_repo() -> None:
9494
# if the run is interrupted from a previous run, it doesn't clean up, and the git add origin command
9595
# errors out; this allows the test to continue
9696
remote_origin_already_exists = 3
97-
print(e)
98-
if e.returncode != remote_origin_already_exists:
99-
sys.exit(1)
97+
if e.returncode == remote_origin_already_exists:
98+
print(
99+
"Consider setting TEST_OPENSEARCH_NOFETCH=true if you want to reuse the existing local OpenSearch repo"
100+
)
101+
else:
102+
print(e)
103+
sys.exit(1)
100104

101105
# fetch the sha commit, version from info()
102106
print("Fetching opensearch repo...")
@@ -128,6 +132,7 @@ def run_all(argv: Any = None) -> None:
128132
codecov_xml = join(
129133
abspath(dirname(dirname(__file__))), "junit", "opensearch-py-codecov.xml"
130134
)
135+
131136
argv = [
132137
"pytest",
133138
"--cov=opensearchpy",
@@ -137,6 +142,12 @@ def run_all(argv: Any = None) -> None:
137142
"-vv",
138143
"--cov-report=xml:%s" % codecov_xml,
139144
]
145+
if (
146+
"OPENSEARCHPY_GEN_HTML_COV" in environ
147+
and environ.get("OPENSEARCHPY_GEN_HTML_COV") == "true"
148+
):
149+
codecov_html = join(abspath(dirname(dirname(__file__))), "junit", "html")
150+
argv.append("--cov-report=html:%s" % codecov_html)
140151

141152
secured = False
142153
if environ.get("OPENSEARCH_URL", "").startswith("https://"):

test_opensearchpy/test_async/test_connection.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -341,7 +341,7 @@ async def test_failure_body_not_logged(self, logger: Any) -> None:
341341
async def test_surrogatepass_into_bytes(self) -> None:
342342
buf = b"\xe4\xbd\xa0\xe5\xa5\xbd\xed\xa9\xaa"
343343
con = await self._get_mock_connection(response_body=buf)
344-
status, headers, data = await con.perform_request("GET", "/")
344+
_, _, data = await con.perform_request("GET", "/")
345345
assert u"你好\uda6a" == data # fmt: skip
346346

347347
@pytest.mark.parametrize("exception_cls", reraise_exceptions) # type: ignore
@@ -394,7 +394,7 @@ def teardown_class(cls) -> None:
394394
cls.server.stop()
395395

396396
async def httpserver(self, conn: Any, **kwargs: Any) -> Any:
397-
status, headers, data = await conn.perform_request("GET", "/", **kwargs)
397+
status, _, data = await conn.perform_request("GET", "/", **kwargs)
398398
data = json.loads(data)
399399
return (status, data)
400400

test_opensearchpy/test_async/test_server/test_helpers/test_actions.py

+6-6
Original file line numberDiff line numberDiff line change
@@ -72,15 +72,15 @@ async def bulk(self, *args: Any, **kwargs: Any) -> Any:
7272
class TestStreamingBulk(object):
7373
async def test_actions_remain_unchanged(self, async_client: Any) -> None:
7474
actions1 = [{"_id": 1}, {"_id": 2}]
75-
async for ok, item in actions.async_streaming_bulk(
75+
async for ok, _ in actions.async_streaming_bulk(
7676
async_client, actions1, index="test-index"
7777
):
7878
assert ok
7979
assert [{"_id": 1}, {"_id": 2}] == actions1
8080

8181
async def test_all_documents_get_inserted(self, async_client: Any) -> None:
8282
docs = [{"answer": x, "_id": x} for x in range(100)]
83-
async for ok, item in actions.async_streaming_bulk(
83+
async for ok, _ in actions.async_streaming_bulk(
8484
async_client, docs, index="test-index", refresh=True
8585
):
8686
assert ok
@@ -100,7 +100,7 @@ def sync_gen() -> Any:
100100
for x in range(100):
101101
yield {"answer": x, "_id": x}
102102

103-
async for ok, item in actions.async_streaming_bulk(
103+
async for ok, _ in actions.async_streaming_bulk(
104104
async_client, async_gen(), index="test-index", refresh=True
105105
):
106106
assert ok
@@ -114,7 +114,7 @@ def sync_gen() -> Any:
114114
index="test-index", body={"query": {"match_all": {}}}
115115
)
116116

117-
async for ok, item in actions.async_streaming_bulk(
117+
async for ok, _ in actions.async_streaming_bulk(
118118
async_client, sync_gen(), index="test-index", refresh=True
119119
):
120120
assert ok
@@ -137,7 +137,7 @@ async def test_all_errors_from_chunk_are_raised_on_failure(
137137
await async_client.cluster.health(wait_for_status="yellow")
138138

139139
try:
140-
async for ok, item in actions.async_streaming_bulk(
140+
async for ok, _ in actions.async_streaming_bulk(
141141
async_client, [{"a": "b"}, {"a": "c"}], index="i", raise_on_error=True
142142
):
143143
assert ok
@@ -154,7 +154,7 @@ async def test_different_op_types(self, async_client: Any) -> None:
154154
{"_op_type": "delete", "_index": "i", "_id": 45},
155155
{"_op_type": "update", "_index": "i", "_id": 42, "doc": {"answer": 42}},
156156
]
157-
async for ok, item in actions.async_streaming_bulk(async_client, docs):
157+
async for ok, _ in actions.async_streaming_bulk(async_client, docs):
158158
assert ok
159159

160160
assert not await async_client.exists(index="i", id=45)

test_opensearchpy/test_async/test_server/test_helpers/test_faceted_search.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -170,7 +170,7 @@ async def test_boolean_facet(data_client: Any, repo_search_cls: Any) -> None:
170170

171171
assert r.hits.total.value == 1
172172
assert [(True, 1, False)] == r.facets.public
173-
value, count, selected = r.facets.public[0]
173+
value, _, _ = r.facets.public[0]
174174
assert value is True
175175

176176

test_opensearchpy/test_connection/test_requests_http_connection.py

+10-12
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,7 @@ def _get_request(self, connection: Any, *args: Any, **kwargs: Any) -> Any:
7373
if "body" in kwargs:
7474
kwargs["body"] = kwargs["body"].encode("utf-8")
7575

76-
status, headers, data = connection.perform_request(*args, **kwargs)
76+
status, _, data = connection.perform_request(*args, **kwargs)
7777
self.assertEqual(200, status)
7878
self.assertEqual("{}", data)
7979

@@ -278,7 +278,7 @@ def test_failed_request_logs_and_traces(self, logger: Any, tracer: Any) -> None:
278278
@patch("opensearchpy.connection.base.logger")
279279
def test_success_logs_and_traces(self, logger: Any, tracer: Any) -> None:
280280
con = self._get_mock_connection(response_body=b"""{"answer": "that's it!"}""")
281-
status, headers, data = con.perform_request(
281+
_, _, _ = con.perform_request(
282282
"GET",
283283
"/",
284284
{"param": 42},
@@ -430,7 +430,7 @@ def test_url_prefix(self, tracer: Any) -> None:
430430
def test_surrogatepass_into_bytes(self) -> None:
431431
buf = b"\xe4\xbd\xa0\xe5\xa5\xbd\xed\xa9\xaa"
432432
con = self._get_mock_connection(response_body=buf)
433-
status, headers, data = con.perform_request("GET", "/")
433+
_, _, data = con.perform_request("GET", "/")
434434
self.assertEqual(u"你好\uda6a", data) # fmt: skip
435435

436436
def test_recursion_error_reraised(self) -> None:
@@ -543,17 +543,15 @@ def test_redirect_failure_when_allow_redirect_false(self) -> None:
543543
def test_redirect_success_when_allow_redirect_true(self) -> None:
544544
conn = RequestsHttpConnection("localhost", port=8080, use_ssl=False, timeout=60)
545545
user_agent = conn._get_default_user_agent()
546-
status, headers, data = conn.perform_request("GET", "/redirect")
546+
status, _, data = conn.perform_request("GET", "/redirect")
547547
self.assertEqual(status, 200)
548548
data = json.loads(data)
549-
self.assertEqual(
550-
data["headers"],
551-
{
552-
"Host": "localhost:8090",
553-
"Accept-Encoding": "identity",
554-
"User-Agent": user_agent,
555-
},
556-
)
549+
expected_headers = {
550+
"Host": "localhost:8090",
551+
"Accept-Encoding": "identity",
552+
"User-Agent": user_agent,
553+
}
554+
self.assertEqual(data["headers"], expected_headers)
557555

558556

559557
class TestSignerWithFrozenCredentials(TestRequestsHttpConnection):

test_opensearchpy/test_connection/test_urllib3_http_connection.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -384,7 +384,7 @@ def test_failure_body_not_logged(self, logger: Any) -> None:
384384
def test_surrogatepass_into_bytes(self) -> None:
385385
buf = b"\xe4\xbd\xa0\xe5\xa5\xbd\xed\xa9\xaa"
386386
con = self._get_mock_connection(response_body=buf)
387-
status, headers, data = con.perform_request("GET", "/")
387+
_, _, data = con.perform_request("GET", "/")
388388
self.assertEqual(u"你好\uda6a", data) # fmt: skip
389389

390390
def test_recursion_error_reraised(self) -> None:

test_opensearchpy/test_helpers/test_actions.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -265,7 +265,7 @@ def test_chunks_are_chopped_by_byte_size_properly(self) -> None:
265265
)
266266
)
267267
self.assertEqual(25, len(chunks))
268-
for chunk_data, chunk_actions in chunks:
268+
for _, chunk_actions in chunks:
269269
chunk = u"".join(chunk_actions) # fmt: skip
270270
chunk = chunk if isinstance(chunk, str) else chunk.encode("utf-8")
271271
self.assertLessEqual(len(chunk), max_byte_size)

test_opensearchpy/test_helpers/test_faceted_search.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,7 @@ def test_query_is_created_properly_with_sort_tuple() -> None:
9494
"highlight": {"fields": {"body": {}, "title": {}}},
9595
"sort": ["category", {"title": {"order": "desc"}}],
9696
} == s.to_dict()
97+
assert bs.facets["category"].get_value_filter(None) is None
9798

9899

99100
def test_filter_is_applied_to_search_but_not_relevant_facet() -> None:
@@ -117,9 +118,10 @@ def test_filter_is_applied_to_search_but_not_relevant_facet() -> None:
117118
},
118119
"highlight": {"fields": {"body": {}, "title": {}}},
119120
} == s.to_dict()
121+
assert bs.facets["category"].get_value_filter(None) is None
120122

121123

122-
def test_filters_are_applied_to_search_ant_relevant_facets() -> None:
124+
def test_filters_are_applied_to_search_and_relevant_facets() -> None:
123125
bs = BlogSearch(
124126
"python search",
125127
filters={"category": "opensearch", "tags": ["python", "django"]},

0 commit comments

Comments
 (0)