Skip to content

Commit 7712112

Browse files
committed
Minor fixes/Fixed flake8
1 parent d1dd89f commit 7712112

File tree

15 files changed

+43
-98
lines changed

15 files changed

+43
-98
lines changed

azure_functions_worker/dispatcher.py

Lines changed: 3 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -14,12 +14,12 @@
1414
import sys
1515
import threading
1616
import uuid
17-
import grpc
18-
1917
from asyncio import BaseEventLoop
2018
from logging import LogRecord
2119
from typing import List, Optional
2220

21+
import grpc
22+
2323
from . import bindings, constants, functions, loader, protos
2424
from .bindings.shared_memory_data_transfer import SharedMemoryManager
2525
from .constants import (PYTHON_THREADPOOL_THREAD_COUNT,
@@ -38,7 +38,6 @@
3838
from .utils.wrappers import disable_feature_by
3939
from .version import VERSION
4040

41-
4241
_TRUE = "true"
4342

4443
"""In Python 3.6, the current_task method was in the Task class, but got moved
@@ -313,9 +312,7 @@ async def _handle__functions_metadata_request(self, request):
313312
function=indexed_function)
314313

315314
binding_protos = {}
316-
317315
for binding in indexed_function.get_bindings():
318-
319316
binding_protos[binding.name] = protos.BindingInfo(
320317
type=binding.type,
321318
data_type=binding.data_type,
@@ -795,12 +792,7 @@ def get_current_invocation_id() -> Optional[str]:
795792
if task_invocation_id is not None:
796793
return task_invocation_id
797794

798-
#return getattr(_invocation_id_local, 'v', None)
799-
800-
invocation_local_id = getattr(logging.getLogger(), 'invocation_local_id', None)
801-
return getattr(invocation_local_id, 'v', None)
802-
803-
795+
return getattr(_invocation_id_local, 'v', None)
804796

805797

806798
_invocation_id_local = threading.local()

azure_functions_worker/functions.py

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,6 @@ def get_function(self, function_id: str) -> FunctionInfo:
5050

5151
return None
5252

53-
5453
@staticmethod
5554
def validate_binding_direction(binding_name: str,
5655
binding_direction: str,
@@ -113,18 +112,18 @@ def validate_function_params(params, bound_params, annotations, func_name):
113112
param_anno_origin = typing_inspect.get_origin(param_anno)
114113
if param_anno_origin is not None:
115114
is_param_out = (
116-
isinstance(param_anno_origin, type)
117-
and param_anno_origin.__name__ == 'Out'
115+
isinstance(param_anno_origin, type)
116+
and param_anno_origin.__name__ == 'Out'
118117
)
119118
else:
120119
is_param_out = (
121-
isinstance(param_anno, type)
122-
and param_anno.__name__ == 'Out'
120+
isinstance(param_anno, type)
121+
and param_anno.__name__ == 'Out'
123122
)
124123
else:
125124
is_param_out = (
126-
isinstance(param_anno, type)
127-
and param_anno.__name__ == 'Out'
125+
isinstance(param_anno, type)
126+
and param_anno.__name__ == 'Out'
128127
)
129128
else:
130129
is_param_out = False
@@ -191,9 +190,9 @@ def validate_function_params(params, bound_params, annotations, func_name):
191190
raise FunctionLoadError(
192191
func_name,
193192
f'{param.name!r} binding type "{binding.type}" '
194-
f'and dataType "{binding.data_type}" in function.json'
195-
f' do not match the corresponding function '
196-
f'parameter\'s Python type '
193+
f'and dataType "{binding.data_type}" in '
194+
f'function.json do not match the corresponding '
195+
f'function parameter\'s Python type '
197196
f'annotation "{param_py_type.__name__}"')
198197
else:
199198
raise FunctionLoadError(
@@ -364,7 +363,8 @@ def add_indexed_function(self, function_id: str,
364363
directory=func_dir,
365364
requires_context=requires_context,
366365
is_async=inspect.iscoroutinefunction(func),
367-
has_return=has_explicit_return, # has_explicit_return or has_implicit_return,
366+
has_return=has_explicit_return,
367+
# has_explicit_return or has_implicit_return,
368368
input_types=input_types,
369369
output_types=output_types,
370370
return_type=return_type)

azure_functions_worker/loader.py

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
# Copyright (c) Microsoft Corporation. All rights reserved.
22
# Licensed under the MIT License.
33
"""Python functions loader."""
4-
import glob
54
import importlib
65
import importlib.machinery
76
import importlib.util
@@ -48,8 +47,8 @@ def uninstall() -> None:
4847

4948

5049
@attach_message_to_exception(
51-
expt_type=ImportError,
52-
message=f'Troubleshooting Guide: {MODULE_NOT_FOUND_TS_URL}'
50+
expt_type=ImportError,
51+
message=f'Troubleshooting Guide: {MODULE_NOT_FOUND_TS_URL}'
5352
)
5453
def load_function(name: str, directory: str, script_file: str,
5554
entry_point: typing.Optional[str]):
@@ -65,16 +64,16 @@ def load_function(name: str, directory: str, script_file: str,
6564
rel_script_path = script_path.relative_to(dir_path.parent)
6665
except ValueError:
6766
raise RuntimeError(
68-
f'script path {script_file} is not relative to the specified '
69-
f'directory {directory}'
67+
f'script path {script_file} is not relative to the specified '
68+
f'directory {directory}'
7069
)
7170

7271
last_part = rel_script_path.parts[-1]
7372
modname, ext = os.path.splitext(last_part)
7473
if ext != '.py':
7574
raise RuntimeError(
76-
f'cannot load function {name}: '
77-
f'invalid Python filename {script_file}')
75+
f'cannot load function {name}: '
76+
f'invalid Python filename {script_file}')
7877

7978
modname_parts = [_AZURE_NAMESPACE]
8079
modname_parts.extend(rel_script_path.parts[:-1])
@@ -90,15 +89,15 @@ def load_function(name: str, directory: str, script_file: str,
9089
func = getattr(mod, entry_point, None)
9190
if func is None or not callable(func):
9291
raise RuntimeError(
93-
f'cannot load function {name}: function {entry_point}() is not '
94-
f'present in {rel_script_path}')
92+
f'cannot load function {name}: function {entry_point}() is not '
93+
f'present in {rel_script_path}')
9594

9695
return func
9796

9897

9998
@attach_message_to_exception(
100-
expt_type=ImportError,
101-
message=f'Troubleshooting Guide: {MODULE_NOT_FOUND_TS_URL}'
99+
expt_type=ImportError,
100+
message=f'Troubleshooting Guide: {MODULE_NOT_FOUND_TS_URL}'
102101
)
103102
def index_function_app(directory: str) -> typing.List[Function]:
104103
function_path = os.path.join(directory, SCRIPT_FILE_NAME)

azure_functions_worker/logging.py

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -16,11 +16,6 @@
1616
error_logger: logging.Logger = (
1717
logging.getLogger('azure_functions_worker_errors'))
1818

19-
local_handler = logging.FileHandler('D://mylog.txt')
20-
logging.getLogger().addHandler(local_handler)
21-
22-
23-
2419
handler: Optional[logging.Handler] = None
2520
error_handler: Optional[logging.Handler] = None
2621

azure_functions_worker/testutils.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -915,7 +915,6 @@ def start_webhost(*, script_dir=None, stdout=None):
915915
health_check_endpoint = f'{addr}/api/ping'
916916
host_out = stdout.readlines(100)
917917
for _ in range(5):
918-
break
919918
try:
920919
r = requests.get(health_check_endpoint,
921920
params={'code': 'testFunctionKey'})

tests/endtoend/test_http_functions.py

Lines changed: 0 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -105,42 +105,3 @@ def test_worker_status_endpoint_should_return_ok_when_disabled(self):
105105
params={'checkHealth': '1'},
106106
timeout=REQUEST_TIMEOUT_SEC)
107107
self.assertTrue(r.ok)
108-
109-
110-
class TestHttpFunctionsNewProgrammingModel(testutils.WebHostTestCase):
111-
"""Test the native Http Trigger in the local webhost.
112-
113-
This test class will spawn a webhost from your <project_root>/build/webhost
114-
folder and replace the built-in Python with azure_functions_worker from
115-
your code base. Since the Http Trigger is a native suport from host, we
116-
don't need to setup any external resources.
117-
118-
Compared to the unittests/test_http_functions.py, this file is more focus
119-
on testing the E2E flow scenarios.
120-
"""
121-
122-
@classmethod
123-
def setUpClass(cls):
124-
os_environ = os.environ.copy()
125-
# Turn on feature flag
126-
os_environ['AzureWebJobsFeatureFlags'] = 'EnableWorkerIndexing'
127-
cls._patch_environ = patch.dict('os.environ', os_environ)
128-
cls._patch_environ.start()
129-
super().setUpClass()
130-
131-
@classmethod
132-
def tearDownClass(self):
133-
super().tearDownClass()
134-
self._patch_environ.stop()
135-
136-
@classmethod
137-
def get_script_dir(cls):
138-
return testutils.E2E_TESTS_FOLDER / 'http_functions'
139-
140-
# @testutils.retryable_test(3, 5)
141-
def test_default_http_template_should_return_ok(self):
142-
"""Test if the default template of Http trigger in Python Function app
143-
will return OK
144-
"""
145-
r = self.webhost.request('GET', 'default_template')
146-
self.assertEqual(r.status_code, 200)

tests/stein_tests/constants.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,4 +17,4 @@
1717
TIMER_FUNCS_PATH = UNIT_TESTS_ROOT / 'timer_functions'
1818
DISPATCHER_FUNCTIONS_DIR = UNIT_TESTS_ROOT / 'dispatcher_functions'
1919
E2E_TESTS_FOLDER = pathlib.Path('endtoendtests')
20-
E2E_TESTS_ROOT = STEIN_TESTS_ROOT / E2E_TESTS_FOLDER
20+
E2E_TESTS_ROOT = STEIN_TESTS_ROOT / E2E_TESTS_FOLDER

tests/stein_tests/endtoendtests/http_functions/function_app.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,9 +20,12 @@ def main(req: func.HttpRequest) -> func.HttpResponse:
2020

2121
if name:
2222
return func.HttpResponse(
23-
f"Hello, {name}. This HTTP triggered function executed successfully.")
23+
f"Hello, {name}. This HTTP triggered function executed "
24+
f"successfully.")
2425
else:
2526
return func.HttpResponse(
26-
"This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response.",
27+
"This HTTP triggered function executed successfully. Pass a name"
28+
" in the query string or in the request body for a personalized "
29+
"response.",
2730
status_code=200
2831
)

tests/stein_tests/testutils.py

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import argparse
22
import configparser
33
import functools
4+
import logging
45
import os
56
import pathlib
67
import platform
@@ -9,13 +10,11 @@
910
import socket
1011
import subprocess
1112
import sys
13+
import tempfile
1214
import time
1315
import unittest
14-
import tempfile
1516

1617
import requests
17-
18-
import logging
1918
from tests.stein_tests.constants import PYAZURE_WEBHOST_DEBUG, \
2019
PYAZURE_WORKER_DIR, \
2120
PYAZURE_INTEGRATION_TEST, PROJECT_ROOT, STEIN_TESTS_ROOT, WORKER_CONFIG, \
@@ -288,9 +287,9 @@ def popen_webhost(*, stdout, stderr, script_root=HTTP_FUNCS_PATH, port=None):
288287
stderr=stderr)
289288

290289

291-
292290
def start_webhost(*, script_dir=None, stdout=None):
293-
script_root = STEIN_TESTS_ROOT / script_dir if script_dir else HTTP_FUNCS_PATH
291+
script_root = STEIN_TESTS_ROOT / script_dir if script_dir else \
292+
HTTP_FUNCS_PATH
294293
if stdout is None:
295294
if is_env_var_true(PYAZURE_WEBHOST_DEBUG):
296295
stdout = sys.stdout
@@ -464,6 +463,6 @@ def _main():
464463
host.terminate()
465464
_teardown_func_app()
466465

466+
467467
if __name__ == '__main__':
468468
_main()
469-

tests/stein_tests/unittests/http_functions/function_app.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -221,7 +221,7 @@ def return_context(req: func.HttpRequest, context: func.Context):
221221
@app.route(route="return_http")
222222
def return_http(req: func.HttpRequest):
223223
return func.HttpResponse('<h1>Hello World™</h1>',
224-
mimetype='text/html')
224+
mimetype='text/html')
225225

226226

227227
@app.route(route="return_http_404")
@@ -232,7 +232,7 @@ def return_http_404(req: func.HttpRequest):
232232
@app.route(route="return_http_auth_admin", auth_level=func.AuthLevel.ADMIN)
233233
def return_http_auth_admin(req: func.HttpRequest):
234234
return func.HttpResponse('<h1>Hello World™</h1>',
235-
mimetype='text/html')
235+
mimetype='text/html')
236236

237237

238238
@app.route(route="return_http_no_body")
@@ -294,10 +294,12 @@ def unhandled_urllib_error(req: func.HttpRequest) -> str:
294294
image_url = req.params.get('img')
295295
urlopen(image_url).read()
296296

297+
297298
class UnserializableException(Exception):
298299
def __str__(self):
299300
raise RuntimeError('cannot serialize me')
300301

302+
301303
@app.route(route="unhandled_unserializable_error")
302304
def unhandled_unserializable_error(req: func.HttpRequest) -> str:
303305
raise UnserializableException('foo')
@@ -306,6 +308,7 @@ def unhandled_unserializable_error(req: func.HttpRequest) -> str:
306308
async def try_log():
307309
logger.info("try_log")
308310

311+
309312
@app.route(route="user_event_loop")
310313
def user_event_loop(req: func.HttpRequest) -> func.HttpResponse:
311314
loop = asyncio.SelectorEventLoop()
@@ -315,4 +318,3 @@ def user_event_loop(req: func.HttpRequest) -> func.HttpResponse:
315318
loop.run_until_complete(try_log())
316319
loop.close()
317320
return 'OK-user-event-loop'
318-

0 commit comments

Comments
 (0)