diff --git a/analytics/views.py b/analytics/views.py index 2d00dcb13e..1eba8f23e4 100644 --- a/analytics/views.py +++ b/analytics/views.py @@ -54,9 +54,9 @@ if settings.ZILENCER_ENABLED: RemoteZulipServer else: from mock import Mock - RemoteInstallationCount = Mock() # type: ignore # https://github.com/JukkaL/mypy/issues/1188 - RemoteZulipServer = Mock() # type: ignore # https://github.com/JukkaL/mypy/issues/1188 - RemoteRealmCount = Mock() # type: ignore # https://github.com/JukkaL/mypy/issues/1188 + RemoteInstallationCount = Mock() # type: ignore[misc] # https://github.com/JukkaL/mypy/issues/1188 + RemoteZulipServer = Mock() # type: ignore[misc] # https://github.com/JukkaL/mypy/issues/1188 + RemoteRealmCount = Mock() # type: ignore[misc] # https://github.com/JukkaL/mypy/issues/1188 MAX_TIME_FOR_FULL_ANALYTICS_GENERATION = timedelta(days=1, minutes=30) diff --git a/corporate/lib/stripe.py b/corporate/lib/stripe.py index 347b0b5dd3..fad152d328 100644 --- a/corporate/lib/stripe.py +++ b/corporate/lib/stripe.py @@ -164,7 +164,7 @@ def catch_stripe_errors(func: CallableT) -> CallableT: 'stripe connection error', _("Something went wrong. Please wait a few seconds and try again.")) raise BillingError('other stripe error', BillingError.CONTACT_SUPPORT) - return wrapped # type: ignore # https://github.com/python/mypy/issues/1927 + return wrapped # type: ignore[return-value] # https://github.com/python/mypy/issues/1927 @catch_stripe_errors def stripe_get_customer(stripe_customer_id: str) -> stripe.Customer: diff --git a/corporate/tests/test_stripe.py b/corporate/tests/test_stripe.py index cb747df490..16f3472132 100644 --- a/corporate/tests/test_stripe.py +++ b/corporate/tests/test_stripe.py @@ -919,8 +919,8 @@ class StripeTest(StripeTestCase): # Verify that we invoice them for the additional users from stripe import Invoice - Invoice.create = lambda **args: None # type: ignore # cleaner than mocking - Invoice.finalize_invoice = lambda *args: None # type: ignore # cleaner than mocking + Invoice.create = lambda **args: None # type: ignore[assignment] # cleaner than mocking + Invoice.finalize_invoice = lambda *args: None # type: ignore[assignment] # cleaner than mocking with patch("stripe.InvoiceItem.create") as mocked: invoice_plans_as_needed(self.next_month) mocked.assert_called_once() @@ -1204,7 +1204,7 @@ class BillingHelpersTest(ZulipTestCase): [(False, CustomerPlan.MONTHLY, 87.15), (anchor, month_later, month_later, 102)]] with patch('corporate.lib.stripe.timezone_now', return_value=anchor): for input_, output in test_cases: - output_ = compute_plan_parameters(*input_) # type: ignore # TODO + output_ = compute_plan_parameters(*input_) # type: ignore[arg-type] # TODO self.assertEqual(output_, output) def test_update_or_create_stripe_customer_logic(self) -> None: diff --git a/docs/testing/mypy.md b/docs/testing/mypy.md index be906daca3..90ca139d43 100644 --- a/docs/testing/mypy.md +++ b/docs/testing/mypy.md @@ -83,7 +83,7 @@ Possible explanations include: Each explanation has its own solution, but in every case the result should be solving the mypy warning in a way that makes the Zulip codebase better. If you're having trouble, silence the warning with -an `Any` or `# type: ignore` so you're not blocked waiting for help, +an `Any` or `# type: ignore[code]` so you're not blocked waiting for help, add a `# TODO: ` comment so it doesn't get forgotten in code review, and ask for help in chat.zulip.org. diff --git a/mypy.ini b/mypy.ini index b6d122e219..079f8b16e5 100644 --- a/mypy.ini +++ b/mypy.ini @@ -14,6 +14,9 @@ disallow_any_generics = True warn_no_return = True no_implicit_optional = True +# Display the codes needed for # type: ignore[code] annotations. +show_error_codes = True + # It's useful to try this occasionally, and keep it clean; but when # someone fixes a type error we don't want to add a burden for them. #warn_unused_ignores = True diff --git a/scripts/setup/flush-memcached b/scripts/setup/flush-memcached index 6bd873fd72..e8e7130a05 100755 --- a/scripts/setup/flush-memcached +++ b/scripts/setup/flush-memcached @@ -18,5 +18,5 @@ pylibmc.Client( binary=True, username=settings.MEMCACHED_USERNAME, password=settings.MEMCACHED_PASSWORD, - behaviors=settings.CACHES["default"]["OPTIONS"] # type: ignore # settings not typed properly + behaviors=settings.CACHES["default"]["OPTIONS"] # type: ignore[index] # settings not typed properly ).flush_all() diff --git a/tools/linter_lib/custom_check.py b/tools/linter_lib/custom_check.py index d16e68f74e..3fccdafebf 100644 --- a/tools/linter_lib/custom_check.py +++ b/tools/linter_lib/custom_check.py @@ -274,13 +274,15 @@ python_rules = RuleList( 'description': 'Missing whitespace after ":" in type annotation', 'good_lines': ['# type: (Any, Any)', 'colon:separated:string:containing:type:as:keyword'], 'bad_lines': ['# type:(Any, Any)']}, - {'pattern': "type: ignore$", + {'pattern': r"type: ignore(?!\[[^][]+\] +# +\S)", 'exclude': {'tools/tests', 'zerver/lib/test_runner.py', 'zerver/tests'}, - 'description': '"type: ignore" should always end with "# type: ignore # explanation for why"', - 'good_lines': ['foo = bar # type: ignore # explanation'], - 'bad_lines': ['foo = bar # type: ignore']}, + 'description': '"type: ignore" should always end with "# type: ignore[code] # explanation for why"', + 'good_lines': ['foo = bar # type: ignore[code] # explanation'], + 'bad_lines': ['foo = bar # type: ignore', + 'foo = bar # type: ignore[code]', + 'foo = bar # type: ignore # explanation']}, {'pattern': "# type [(]", 'description': 'Missing : after type in type annotation', 'good_lines': ['foo = 42 # type: int', '# type: (str, int) -> None'], diff --git a/zerver/decorator.py b/zerver/decorator.py index 5f08dacc99..5a45987a78 100644 --- a/zerver/decorator.py +++ b/zerver/decorator.py @@ -49,7 +49,7 @@ if settings.ZILENCER_ENABLED: else: # nocoverage # Hack here basically to make impossible code paths compile from mock import Mock get_remote_server_by_uuid = Mock() - RemoteZulipServer = Mock() # type: ignore # https://github.com/JukkaL/mypy/issues/1188 + RemoteZulipServer = Mock() # type: ignore[misc] # https://github.com/JukkaL/mypy/issues/1188 ReturnT = TypeVar('ReturnT') @@ -102,7 +102,7 @@ def require_post(func: ViewFuncT) -> ViewFuncT: extra={'status_code': 405, 'request': request}) return HttpResponseNotAllowed(["POST"]) return func(request, *args, **kwargs) - return wrapper # type: ignore # https://github.com/python/mypy/issues/1927 + return wrapper # type: ignore[return-value] # https://github.com/python/mypy/issues/1927 def require_realm_admin(func: ViewFuncT) -> ViewFuncT: @wraps(func) @@ -110,7 +110,7 @@ def require_realm_admin(func: ViewFuncT) -> ViewFuncT: if not user_profile.is_realm_admin: raise OrganizationAdministratorRequired() return func(request, user_profile, *args, **kwargs) - return wrapper # type: ignore # https://github.com/python/mypy/issues/1927 + return wrapper # type: ignore[return-value] # https://github.com/python/mypy/issues/1927 def require_billing_access(func: ViewFuncT) -> ViewFuncT: @wraps(func) @@ -118,7 +118,7 @@ def require_billing_access(func: ViewFuncT) -> ViewFuncT: if not user_profile.is_realm_admin and not user_profile.is_billing_admin: raise JsonableError(_("Must be a billing administrator or an organization administrator")) return func(request, user_profile, *args, **kwargs) - return wrapper # type: ignore # https://github.com/python/mypy/issues/1927 + return wrapper # type: ignore[return-value] # https://github.com/python/mypy/issues/1927 from zerver.lib.user_agent import parse_user_agent @@ -386,7 +386,7 @@ def user_passes_test(test_func: Callable[[HttpResponse], bool], login_url: Optio path = request.get_full_path() return redirect_to_login( path, resolved_login_url, redirect_field_name) - return _wrapped_view # type: ignore # https://github.com/python/mypy/issues/1927 + return _wrapped_view # type: ignore[return-value] # https://github.com/python/mypy/issues/1927 return decorator def logged_in_and_active(request: HttpRequest) -> bool: @@ -419,7 +419,7 @@ def log_view_func(view_func: ViewFuncT) -> ViewFuncT: def _wrapped_view_func(request: HttpRequest, *args: Any, **kwargs: Any) -> HttpResponse: request._query = view_func.__name__ return view_func(request, *args, **kwargs) - return _wrapped_view_func # type: ignore # https://github.com/python/mypy/issues/1927 + return _wrapped_view_func # type: ignore[return-value] # https://github.com/python/mypy/issues/1927 def add_logging_data(view_func: ViewFuncT) -> ViewFuncT: @wraps(view_func) @@ -427,7 +427,7 @@ def add_logging_data(view_func: ViewFuncT) -> ViewFuncT: process_client(request, request.user, is_browser_view=True, query=view_func.__name__) return rate_limit()(view_func)(request, *args, **kwargs) - return _wrapped_view_func # type: ignore # https://github.com/python/mypy/issues/1927 + return _wrapped_view_func # type: ignore[return-value] # https://github.com/python/mypy/issues/1927 def human_users_only(view_func: ViewFuncT) -> ViewFuncT: @wraps(view_func) @@ -435,7 +435,7 @@ def human_users_only(view_func: ViewFuncT) -> ViewFuncT: if request.user.is_bot: return json_error(_("This endpoint does not accept bot requests.")) return view_func(request, *args, **kwargs) - return _wrapped_view_func # type: ignore # https://github.com/python/mypy/issues/1927 + return _wrapped_view_func # type: ignore[return-value] # https://github.com/python/mypy/issues/1927 # Based on Django 1.8's @login_required def zulip_login_required( @@ -467,7 +467,7 @@ def require_server_admin(view_func: ViewFuncT) -> ViewFuncT: return HttpResponseRedirect(settings.HOME_NOT_LOGGED_IN) return add_logging_data(view_func)(request, *args, **kwargs) - return _wrapped_view_func # type: ignore # https://github.com/python/mypy/issues/1927 + return _wrapped_view_func # type: ignore[return-value] # https://github.com/python/mypy/issues/1927 def require_server_admin_api(view_func: ViewFuncT) -> ViewFuncT: @zulip_login_required @@ -477,7 +477,7 @@ def require_server_admin_api(view_func: ViewFuncT) -> ViewFuncT: if not user_profile.is_staff: raise JsonableError(_("Must be an server administrator")) return view_func(request, user_profile, *args, **kwargs) - return _wrapped_view_func # type: ignore # https://github.com/python/mypy/issues/1927 + return _wrapped_view_func # type: ignore[return-value] # https://github.com/python/mypy/issues/1927 def require_non_guest_user(view_func: ViewFuncT) -> ViewFuncT: @wraps(view_func) @@ -486,7 +486,7 @@ def require_non_guest_user(view_func: ViewFuncT) -> ViewFuncT: if user_profile.is_guest: raise JsonableError(_("Not allowed for guest users")) return view_func(request, user_profile, *args, **kwargs) - return _wrapped_view_func # type: ignore # https://github.com/python/mypy/issues/1927 + return _wrapped_view_func # type: ignore[return-value] # https://github.com/python/mypy/issues/1927 def require_member_or_admin(view_func: ViewFuncT) -> ViewFuncT: @wraps(view_func) @@ -497,7 +497,7 @@ def require_member_or_admin(view_func: ViewFuncT) -> ViewFuncT: if user_profile.is_bot: return json_error(_("This endpoint does not accept bot requests.")) return view_func(request, user_profile, *args, **kwargs) - return _wrapped_view_func # type: ignore # https://github.com/python/mypy/issues/1927 + return _wrapped_view_func # type: ignore[return-value] # https://github.com/python/mypy/issues/1927 def require_user_group_edit_permission(view_func: ViewFuncT) -> ViewFuncT: @require_member_or_admin @@ -509,7 +509,7 @@ def require_user_group_edit_permission(view_func: ViewFuncT) -> ViewFuncT: not user_profile.is_realm_admin: raise OrganizationAdministratorRequired() return view_func(request, user_profile, *args, **kwargs) - return _wrapped_view_func # type: ignore # https://github.com/python/mypy/issues/1927 + return _wrapped_view_func # type: ignore[return-value] # https://github.com/python/mypy/issues/1927 # This API endpoint is used only for the mobile apps. It is part of a # workaround for the fact that React Native doesn't support setting @@ -618,7 +618,7 @@ def process_as_post(view_func: ViewFuncT) -> ViewFuncT: return view_func(request, *args, **kwargs) - return _wrapped_view_func # type: ignore # https://github.com/python/mypy/issues/1927 + return _wrapped_view_func # type: ignore[return-value] # https://github.com/python/mypy/issues/1927 def authenticate_log_and_execute_json(request: HttpRequest, view_func: ViewFuncT, @@ -659,7 +659,7 @@ def authenticated_json_post_view(view_func: ViewFuncT) -> ViewFuncT: def _wrapped_view_func(request: HttpRequest, *args: Any, **kwargs: Any) -> HttpResponse: return authenticate_log_and_execute_json(request, view_func, *args, **kwargs) - return _wrapped_view_func # type: ignore # https://github.com/python/mypy/issues/1927 + return _wrapped_view_func # type: ignore[return-value] # https://github.com/python/mypy/issues/1927 def authenticated_json_view(view_func: ViewFuncT, skip_rate_limiting: bool=False, allow_unauthenticated: bool=False) -> ViewFuncT: @@ -669,7 +669,7 @@ def authenticated_json_view(view_func: ViewFuncT, skip_rate_limiting: bool=False kwargs["skip_rate_limiting"] = skip_rate_limiting kwargs["allow_unauthenticated"] = allow_unauthenticated return authenticate_log_and_execute_json(request, view_func, *args, **kwargs) - return _wrapped_view_func # type: ignore # https://github.com/python/mypy/issues/1927 + return _wrapped_view_func # type: ignore[return-value] # https://github.com/python/mypy/issues/1927 def is_local_addr(addr: str) -> bool: return addr in ('127.0.0.1', '::1') @@ -787,7 +787,7 @@ def rate_limit(domain: str='api_by_user') -> Callable[[ViewFuncT], ViewFuncT]: rate_limit_user(request, user, domain) return func(request, *args, **kwargs) - return wrapped_func # type: ignore # https://github.com/python/mypy/issues/1927 + return wrapped_func # type: ignore[return-value] # https://github.com/python/mypy/issues/1927 return wrapper def return_success_on_head_request(view_func: ViewFuncT) -> ViewFuncT: @@ -796,7 +796,7 @@ def return_success_on_head_request(view_func: ViewFuncT) -> ViewFuncT: if request.method == 'HEAD': return json_success() return view_func(request, *args, **kwargs) - return _wrapped_view_func # type: ignore # https://github.com/python/mypy/issues/1927 + return _wrapped_view_func # type: ignore[return-value] # https://github.com/python/mypy/issues/1927 def zulip_otp_required(view: Any=None, redirect_field_name: str='next', diff --git a/zerver/lib/actions.py b/zerver/lib/actions.py index 632468a7cd..ce6eb3a708 100644 --- a/zerver/lib/actions.py +++ b/zerver/lib/actions.py @@ -3322,7 +3322,7 @@ def do_change_plan_type(realm: Realm, plan_type: int) -> None: realm.message_visibility_limit = None realm.upload_quota_gb = Realm.UPLOAD_QUOTA_STANDARD elif plan_type == Realm.SELF_HOSTED: - realm.max_invites = None # type: ignore # Apparent mypy bug with Optional[int] setter. + realm.max_invites = None # type: ignore[assignment] # Apparent mypy bug with Optional[int] setter. realm.message_visibility_limit = None realm.upload_quota_gb = None elif plan_type == Realm.STANDARD_FREE: diff --git a/zerver/lib/cache.py b/zerver/lib/cache.py index 6bb0abb7e8..fa69214b02 100644 --- a/zerver/lib/cache.py +++ b/zerver/lib/cache.py @@ -339,16 +339,16 @@ CacheItemT = TypeVar('CacheItemT') CompressedItemT = TypeVar('CompressedItemT') def default_extractor(obj: CompressedItemT) -> ItemT: - return obj # type: ignore # Need a type assert that ItemT=CompressedItemT + return obj # type: ignore[return-value] # Need a type assert that ItemT=CompressedItemT def default_setter(obj: ItemT) -> CompressedItemT: - return obj # type: ignore # Need a type assert that ItemT=CompressedItemT + return obj # type: ignore[return-value] # Need a type assert that ItemT=CompressedItemT def default_id_fetcher(obj: ItemT) -> ObjKT: - return obj.id # type: ignore # Need ItemT/CompressedItemT typevars to be a Django protocol + return obj.id # type: ignore[attr-defined] # Need ItemT/CompressedItemT typevars to be a Django protocol def default_cache_transformer(obj: ItemT) -> CacheItemT: - return obj # type: ignore # Need a type assert that ItemT=CacheItemT + return obj # type: ignore[return-value] # Need a type assert that ItemT=CacheItemT # Required Arguments are as follows: # * object_ids: The list of object ids to look up diff --git a/zerver/lib/cache_helpers.py b/zerver/lib/cache_helpers.py index c30f161c08..ef3d2e4bad 100644 --- a/zerver/lib/cache_helpers.py +++ b/zerver/lib/cache_helpers.py @@ -73,7 +73,7 @@ def session_cache_items(items_for_remote_cache: Dict[str, str], # will be no store.cache_key attribute, and in any case we # don't need to fill the cache, since it won't exist. return - store = session_engine.SessionStore(session_key=session.session_key) # type: ignore # import_module + store = session_engine.SessionStore(session_key=session.session_key) # type: ignore[attr-defined] # import_module items_for_remote_cache[store.cache_key] = store.decode(session.session_data) def get_active_realm_ids() -> List[int]: diff --git a/zerver/lib/push_notifications.py b/zerver/lib/push_notifications.py index 9ae0df5bb2..868d4f0066 100644 --- a/zerver/lib/push_notifications.py +++ b/zerver/lib/push_notifications.py @@ -37,7 +37,7 @@ if settings.ZILENCER_ENABLED: from zilencer.models import RemotePushDeviceToken else: # nocoverage -- Not convenient to add test for this. from mock import Mock - RemotePushDeviceToken = Mock() # type: ignore # https://github.com/JukkaL/mypy/issues/1188 + RemotePushDeviceToken = Mock() # type: ignore[misc] # https://github.com/JukkaL/mypy/issues/1188 DeviceToken = Union[PushDeviceToken, RemotePushDeviceToken] diff --git a/zerver/lib/rest.py b/zerver/lib/rest.py index e34195d027..d567a51ec1 100644 --- a/zerver/lib/rest.py +++ b/zerver/lib/rest.py @@ -137,7 +137,7 @@ def rest_dispatch(request: HttpRequest, **kwargs: Any) -> HttpResponse: view_kwargs = {} if 'allow_incoming_webhooks' in view_flags: view_kwargs['is_webhook'] = True - target_function = authenticated_rest_api_view(**view_kwargs)(target_function) # type: ignore # likely mypy bug + target_function = authenticated_rest_api_view(**view_kwargs)(target_function) # type: ignore[arg-type] # likely mypy bug # Pick a way to tell user they're not authed based on how the request was made else: # If this looks like a request from a top-level page in a diff --git a/zerver/lib/sessions.py b/zerver/lib/sessions.py index 1c47973c17..e7043b2668 100644 --- a/zerver/lib/sessions.py +++ b/zerver/lib/sessions.py @@ -28,7 +28,7 @@ def user_sessions(user_profile: UserProfile) -> List[Session]: if get_session_user(s) == user_profile.id] def delete_session(session: Session) -> None: - session_engine.SessionStore(session.session_key).delete() # type: ignore # import_module + session_engine.SessionStore(session.session_key).delete() # type: ignore[attr-defined] # import_module def delete_user_sessions(user_profile: UserProfile) -> None: for session in Session.objects.all(): diff --git a/zerver/lib/test_helpers.py b/zerver/lib/test_helpers.py index 7f4c71c055..fb2dd65eaf 100644 --- a/zerver/lib/test_helpers.py +++ b/zerver/lib/test_helpers.py @@ -76,9 +76,9 @@ def stub_event_queue_user_events(event_queue_return: Any, user_events_return: An @contextmanager def simulated_queue_client(client: Callable[..., Any]) -> Iterator[None]: real_SimpleQueueClient = queue_processors.SimpleQueueClient - queue_processors.SimpleQueueClient = client # type: ignore # https://github.com/JukkaL/mypy/issues/1152 + queue_processors.SimpleQueueClient = client # type: ignore[assignment, misc] # https://github.com/JukkaL/mypy/issues/1152 yield - queue_processors.SimpleQueueClient = real_SimpleQueueClient # type: ignore # https://github.com/JukkaL/mypy/issues/1152 + queue_processors.SimpleQueueClient = real_SimpleQueueClient # type: ignore[misc] # https://github.com/JukkaL/mypy/issues/1152 @contextmanager def tornado_redirected_to_list(lst: List[Mapping[str, Any]]) -> Iterator[None]: @@ -169,17 +169,17 @@ def queries_captured(include_savepoints: Optional[bool]=False) -> Generator[ def cursor_execute(self: TimeTrackingCursor, sql: str, params: Iterable[Any]=()) -> None: return wrapper_execute(self, super(TimeTrackingCursor, self).execute, sql, params) - TimeTrackingCursor.execute = cursor_execute # type: ignore # https://github.com/JukkaL/mypy/issues/1167 + TimeTrackingCursor.execute = cursor_execute # type: ignore[assignment] # https://github.com/JukkaL/mypy/issues/1167 def cursor_executemany(self: TimeTrackingCursor, sql: str, params: Iterable[Any]=()) -> None: return wrapper_execute(self, super(TimeTrackingCursor, self).executemany, sql, params) # nocoverage -- doesn't actually get used in tests - TimeTrackingCursor.executemany = cursor_executemany # type: ignore # https://github.com/JukkaL/mypy/issues/1167 + TimeTrackingCursor.executemany = cursor_executemany # type: ignore[assignment] # https://github.com/JukkaL/mypy/issues/1167 yield queries - TimeTrackingCursor.execute = old_execute # type: ignore # https://github.com/JukkaL/mypy/issues/1167 - TimeTrackingCursor.executemany = old_executemany # type: ignore # https://github.com/JukkaL/mypy/issues/1167 + TimeTrackingCursor.execute = old_execute # type: ignore[assignment] # https://github.com/JukkaL/mypy/issues/1167 + TimeTrackingCursor.executemany = old_executemany # type: ignore[assignment] # https://github.com/JukkaL/mypy/issues/1167 @contextmanager def stdout_suppressed() -> Iterator[IO[str]]: @@ -252,7 +252,7 @@ def get_user_messages(user_profile: UserProfile) -> List[Message]: class DummyHandler: def __init__(self) -> None: - allocate_handler_id(self) # type: ignore # this is a testing mock + allocate_handler_id(self) # type: ignore[arg-type] # this is a testing mock class POSTRequestMock: method = "POST" diff --git a/zerver/lib/test_runner.py b/zerver/lib/test_runner.py index e9f8c77049..73b0d69662 100644 --- a/zerver/lib/test_runner.py +++ b/zerver/lib/test_runner.py @@ -157,16 +157,16 @@ class TextTestResult(runner.TextTestResult): self.failed_tests = [] # type: List[str] def addInfo(self, test: TestCase, msg: str) -> None: - self.stream.write(msg) # type: ignore # https://github.com/python/typeshed/issues/3139 - self.stream.flush() # type: ignore # https://github.com/python/typeshed/issues/3139 + self.stream.write(msg) # type: ignore[attr-defined] # https://github.com/python/typeshed/issues/3139 + self.stream.flush() # type: ignore[attr-defined] # https://github.com/python/typeshed/issues/3139 def addInstrumentation(self, test: TestCase, data: Dict[str, Any]) -> None: append_instrumentation_data(data) def startTest(self, test: TestCase) -> None: TestResult.startTest(self, test) - self.stream.writeln("Running {}".format(full_test_name(test))) # type: ignore # https://github.com/python/typeshed/issues/3139 - self.stream.flush() # type: ignore # https://github.com/python/typeshed/issues/3139 + self.stream.writeln("Running {}".format(full_test_name(test))) # type: ignore[attr-defined] # https://github.com/python/typeshed/issues/3139 + self.stream.flush() # type: ignore[attr-defined] # https://github.com/python/typeshed/issues/3139 def addSuccess(self, *args: Any, **kwargs: Any) -> None: TestResult.addSuccess(self, *args, **kwargs) @@ -183,10 +183,10 @@ class TextTestResult(runner.TextTestResult): def addSkip(self, test: TestCase, reason: str) -> None: TestResult.addSkip(self, test, reason) - self.stream.writeln("** Skipping {}: {}".format( # type: ignore # https://github.com/python/typeshed/issues/3139 + self.stream.writeln("** Skipping {}: {}".format( # type: ignore[attr-defined] # https://github.com/python/typeshed/issues/3139 full_test_name(test), reason)) - self.stream.flush() # type: ignore # https://github.com/python/typeshed/issues/3139 + self.stream.flush() # type: ignore[attr-defined] # https://github.com/python/typeshed/issues/3139 class RemoteTestResult(django_runner.RemoteTestResult): """ @@ -338,7 +338,7 @@ class TestSuite(unittest.TestSuite): """ topLevel = False if getattr(result, '_testRunEntered', False) is False: - result._testRunEntered = topLevel = True # type: ignore + result._testRunEntered = topLevel = True # type: ignore[attr-defined] for test in self: # but this is correct. Taken from unittest. @@ -348,10 +348,10 @@ class TestSuite(unittest.TestSuite): if isinstance(test, TestSuite): test.run(result, debug=debug) else: - self._tearDownPreviousClass(test, result) # type: ignore - self._handleModuleFixture(test, result) # type: ignore - self._handleClassSetUp(test, result) # type: ignore - result._previousTestClass = test.__class__ # type: ignore + self._tearDownPreviousClass(test, result) # type: ignore[attr-defined] + self._handleModuleFixture(test, result) # type: ignore[attr-defined] + self._handleClassSetUp(test, result) # type: ignore[attr-defined] + result._previousTestClass = test.__class__ # type: ignore[attr-defined] if (getattr(test.__class__, '_classSetupFailed', False) or getattr(result, '_moduleSetUpFailed', False)): continue @@ -362,9 +362,9 @@ class TestSuite(unittest.TestSuite): break if topLevel: - self._tearDownPreviousClass(None, result) # type: ignore - self._handleModuleTearDown(result) # type: ignore - result._testRunEntered = False # type: ignore + self._tearDownPreviousClass(None, result) # type: ignore[attr-defined] + self._handleModuleTearDown(result) # type: ignore[attr-defined] + result._testRunEntered = False # type: ignore[attr-defined] return result class TestLoader(loader.TestLoader): @@ -380,7 +380,7 @@ class ParallelTestSuite(django_runner.ParallelTestSuite): # the whole idea here is to monkey-patch that so we can use # most of django_runner.ParallelTestSuite with our own suite # definitions. - self.subsuites = SubSuiteList(self.subsuites) # type: ignore # Type of self.subsuites changes. + self.subsuites = SubSuiteList(self.subsuites) # type: ignore[has-type] # Type of self.subsuites changes. def check_import_error(test_name: str) -> None: try: diff --git a/zerver/lib/type_debug.py b/zerver/lib/type_debug.py index 3a225a1421..4aa6f571cd 100644 --- a/zerver/lib/type_debug.py +++ b/zerver/lib/type_debug.py @@ -77,7 +77,7 @@ def print_types_to(file_obj: IO[str]) -> Callable[[FuncT], FuncT]: get_type_str(ret_val)) print(output, file=file_obj) return ret_val - return wrapper # type: ignore # https://github.com/python/mypy/issues/1927 + return wrapper # type: ignore[return-value] # https://github.com/python/mypy/issues/1927 return decorator def print_types(func: FuncT) -> FuncT: diff --git a/zerver/lib/validator.py b/zerver/lib/validator.py index 24b16dd007..69a791ab09 100644 --- a/zerver/lib/validator.py +++ b/zerver/lib/validator.py @@ -49,7 +49,7 @@ TypeStructure = TypeVar("TypeStructure") def set_type_structure(type_structure: TypeStructure) -> Callable[[FuncT], Any]: def _set_type_structure(func: FuncT) -> FuncT: if settings.LOG_API_EVENT_TYPES: - func.type_structure = type_structure # type: ignore # monkey-patching + func.type_structure = type_structure # type: ignore[attr-defined] # monkey-patching return func return _set_type_structure @@ -166,7 +166,7 @@ def check_color(var_name: str, val: object) -> Optional[str]: def check_none_or(sub_validator: Validator) -> Validator: if settings.LOG_API_EVENT_TYPES: - type_structure = 'none_or_' + sub_validator.type_structure # type: ignore # monkey-patching + type_structure = 'none_or_' + sub_validator.type_structure # type: ignore[attr-defined] # monkey-patching else: type_structure = None @@ -181,11 +181,11 @@ def check_none_or(sub_validator: Validator) -> Validator: def check_list(sub_validator: Optional[Validator], length: Optional[int]=None) -> Validator: if settings.LOG_API_EVENT_TYPES: if sub_validator: - type_structure = [sub_validator.type_structure] # type: ignore # monkey-patching + type_structure = [sub_validator.type_structure] # type: ignore[attr-defined] # monkey-patching else: - type_structure = 'list' # type: ignore # monkey-patching + type_structure = 'list' # type: ignore[assignment] # monkey-patching else: - type_structure = None # type: ignore # monkey-patching + type_structure = None # type: ignore[assignment] # monkey-patching @set_type_structure(type_structure) def f(var_name: str, val: object) -> Optional[str]: @@ -226,7 +226,7 @@ def check_dict(required_keys: Iterable[Tuple[str, Validator]]=[], if error: return error if settings.LOG_API_EVENT_TYPES: - type_structure[k] = sub_validator.type_structure # type: ignore # monkey-patching + type_structure[k] = sub_validator.type_structure # type: ignore[attr-defined] # monkey-patching for k, sub_validator in optional_keys: if k in val: @@ -235,7 +235,7 @@ def check_dict(required_keys: Iterable[Tuple[str, Validator]]=[], if error: return error if settings.LOG_API_EVENT_TYPES: - type_structure[k] = sub_validator.type_structure # type: ignore # monkey-patching + type_structure[k] = sub_validator.type_structure # type: ignore[attr-defined] # monkey-patching if value_validator: for key in val: @@ -244,7 +244,7 @@ def check_dict(required_keys: Iterable[Tuple[str, Validator]]=[], if error: return error if settings.LOG_API_EVENT_TYPES: - type_structure['any'] = value_validator.type_structure # type: ignore # monkey-patching + type_structure['any'] = value_validator.type_structure # type: ignore[attr-defined] # monkey-patching if _allow_only_listed_keys: required_keys_set = {x[0] for x in required_keys} @@ -271,9 +271,9 @@ def check_variable_type(allowed_type_funcs: Iterable[Validator]) -> Validator: """ if settings.LOG_API_EVENT_TYPES: - type_structure = 'any("%s")' % ([x.type_structure for x in allowed_type_funcs],) # type: ignore # monkey-patching + type_structure = 'any("%s")' % ([x.type_structure for x in allowed_type_funcs],) # type: ignore[attr-defined] # monkey-patching else: - type_structure = None # type: ignore # monkey-patching + type_structure = None # type: ignore[assignment] # monkey-patching @set_type_structure(type_structure) def enumerated_type_check(var_name: str, val: object) -> Optional[str]: diff --git a/zerver/lib/webhooks/common.py b/zerver/lib/webhooks/common.py index c337f6d11d..aa83445251 100644 --- a/zerver/lib/webhooks/common.py +++ b/zerver/lib/webhooks/common.py @@ -141,7 +141,7 @@ def get_fixture_http_headers(integration_name: str, # TODO: We may want to migrate to a more explicit registration # strategy for this behavior rather than a try/except import. view_module = importlib.import_module(view_module_name) - fixture_to_headers = view_module.fixture_to_headers # type: ignore # we do extra exception handling in case it does not exist below. + fixture_to_headers = view_module.fixture_to_headers # type: ignore[attr-defined] # we do extra exception handling in case it does not exist below. except (ImportError, AttributeError): return {} return fixture_to_headers(fixture_name) diff --git a/zerver/logging_handlers.py b/zerver/logging_handlers.py index 87eef89dfc..95c92fb8b2 100644 --- a/zerver/logging_handlers.py +++ b/zerver/logging_handlers.py @@ -129,7 +129,7 @@ class AdminNotifyHandler(logging.Handler): report['log_lineno'] = record.lineno if hasattr(record, "request"): - add_request_metadata(report, record.request) # type: ignore # record.request is added dynamically + add_request_metadata(report, record.request) # type: ignore[attr-defined] # record.request is added dynamically except Exception: report['message'] = "Exception in preparing exception report!" diff --git a/zerver/tests/test_bugdown.py b/zerver/tests/test_bugdown.py index dbd48abaa9..f71c3bb84e 100644 --- a/zerver/tests/test_bugdown.py +++ b/zerver/tests/test_bugdown.py @@ -104,8 +104,8 @@ class FencedBlockPreprocessorTest(TestCase): processor = bugdown.fenced_code.FencedBlockPreprocessor(None) # Simulate code formatting. - processor.format_code = lambda lang, code: lang + ':' + code # type: ignore # mypy doesn't allow monkey-patching functions - processor.placeholder = lambda s: '**' + s.strip('\n') + '**' # type: ignore # https://github.com/python/mypy/issues/708 + processor.format_code = lambda lang, code: lang + ':' + code # type: ignore[assignment] # mypy doesn't allow monkey-patching functions + processor.placeholder = lambda s: '**' + s.strip('\n') + '**' # type: ignore[assignment] # https://github.com/python/mypy/issues/708 markdown = [ '``` .py', @@ -150,8 +150,8 @@ class FencedBlockPreprocessorTest(TestCase): processor = bugdown.fenced_code.FencedBlockPreprocessor(None) # Simulate code formatting. - processor.format_code = lambda lang, code: lang + ':' + code # type: ignore # mypy doesn't allow monkey-patching functions - processor.placeholder = lambda s: '**' + s.strip('\n') + '**' # type: ignore # https://github.com/python/mypy/issues/708 + processor.format_code = lambda lang, code: lang + ':' + code # type: ignore[assignment] # mypy doesn't allow monkey-patching functions + processor.placeholder = lambda s: '**' + s.strip('\n') + '**' # type: ignore[assignment] # https://github.com/python/mypy/issues/708 markdown = [ '~~~ quote', @@ -2045,8 +2045,8 @@ class BugdownErrorTests(ZulipTestCase): processor.run_content_validators = True # Simulate code formatting. - processor.format_code = lambda lang, code: lang + ':' + code # type: ignore # mypy doesn't allow monkey-patching functions - processor.placeholder = lambda s: '**' + s.strip('\n') + '**' # type: ignore # https://github.com/python/mypy/issues/708 + processor.format_code = lambda lang, code: lang + ':' + code # type: ignore[assignment] # mypy doesn't allow monkey-patching functions + processor.placeholder = lambda s: '**' + s.strip('\n') + '**' # type: ignore[assignment] # https://github.com/python/mypy/issues/708 markdown = [ '``` curl', @@ -2063,8 +2063,8 @@ class BugdownErrorTests(ZulipTestCase): processor = bugdown.fenced_code.FencedBlockPreprocessor(None) # Simulate code formatting. - processor.format_code = lambda lang, code: lang + ':' + code # type: ignore # mypy doesn't allow monkey-patching functions - processor.placeholder = lambda s: '**' + s.strip('\n') + '**' # type: ignore # https://github.com/python/mypy/issues/708 + processor.format_code = lambda lang, code: lang + ':' + code # type: ignore[assignment] # mypy doesn't allow monkey-patching functions + processor.placeholder = lambda s: '**' + s.strip('\n') + '**' # type: ignore[assignment] # https://github.com/python/mypy/issues/708 markdown = [ '``` curl', diff --git a/zerver/tests/test_decorators.py b/zerver/tests/test_decorators.py index 8245f85e1c..1e0cced6ce 100644 --- a/zerver/tests/test_decorators.py +++ b/zerver/tests/test_decorators.py @@ -158,7 +158,7 @@ class DecoratorTestCase(TestCase): with self.assertRaisesRegex(AssertionError, "converter and validator are mutually exclusive"): @has_request_variables def get_total(request: HttpRequest, - numbers: Iterable[int]=REQ(validator=check_list(check_int), # type: ignore # The condition being tested is in fact an error. + numbers: Iterable[int]=REQ(validator=check_list(check_int), # type: ignore[call-overload] # The condition being tested is in fact an error. converter=lambda x: [])) -> int: return sum(numbers) # nocoverage -- isn't intended to be run @@ -236,7 +236,7 @@ class DecoratorTestCase(TestCase): with self.assertRaises(Exception) as cm: @has_request_variables def test(request: HttpRequest, - payload: Any=REQ(argument_type="invalid")) -> None: # type: ignore # The condition being tested is in fact an error. + payload: Any=REQ(argument_type="invalid")) -> None: # type: ignore[call-overload] # The condition being tested is in fact an error. # Any is ok; exception should occur in decorator: pass # nocoverage # this function isn't meant to be called test(request) @@ -265,7 +265,7 @@ class DecoratorTestCase(TestCase): request.POST['api_key'] = 'X'*32 with self.assertRaisesRegex(JsonableError, "Invalid API key"): - my_webhook(request) # type: ignore # mypy doesn't seem to apply the decorator + my_webhook(request) # type: ignore[call-arg] # mypy doesn't seem to apply the decorator # Start a valid request here request.POST['api_key'] = webhook_bot_api_key @@ -273,7 +273,7 @@ class DecoratorTestCase(TestCase): with mock.patch('logging.warning') as mock_warning: with self.assertRaisesRegex(JsonableError, "Account is not associated with this subdomain"): - api_result = my_webhook(request) # type: ignore # mypy doesn't seem to apply the decorator + api_result = my_webhook(request) # type: ignore[call-arg] # mypy doesn't seem to apply the decorator mock_warning.assert_called_with( "User {} ({}) attempted to access API on wrong " @@ -283,7 +283,7 @@ class DecoratorTestCase(TestCase): with self.assertRaisesRegex(JsonableError, "Account is not associated with this subdomain"): request.host = "acme." + settings.EXTERNAL_HOST - api_result = my_webhook(request) # type: ignore # mypy doesn't seem to apply the decorator + api_result = my_webhook(request) # type: ignore[call-arg] # mypy doesn't seem to apply the decorator mock_warning.assert_called_with( "User {} ({}) attempted to access API on wrong " @@ -297,7 +297,7 @@ class DecoratorTestCase(TestCase): with self.assertRaisesRegex(Exception, "raised by webhook function"): request.body = "{}" request.content_type = 'application/json' - my_webhook_raises_exception(request) # type: ignore # mypy doesn't seem to apply the decorator + my_webhook_raises_exception(request) # type: ignore[call-arg] # mypy doesn't seem to apply the decorator # Test when content_type is not application/json; exception raised # in the webhook function should be re-raised @@ -305,7 +305,7 @@ class DecoratorTestCase(TestCase): with self.assertRaisesRegex(Exception, "raised by webhook function"): request.body = "notjson" request.content_type = 'text/plain' - my_webhook_raises_exception(request) # type: ignore # mypy doesn't seem to apply the decorator + my_webhook_raises_exception(request) # type: ignore[call-arg] # mypy doesn't seem to apply the decorator # Test when content_type is application/json but request.body # is not valid JSON; invalid JSON should be logged and the @@ -315,7 +315,7 @@ class DecoratorTestCase(TestCase): request.body = "invalidjson" request.content_type = 'application/json' request.META['HTTP_X_CUSTOM_HEADER'] = 'custom_value' - my_webhook_raises_exception(request) # type: ignore # mypy doesn't seem to apply the decorator + my_webhook_raises_exception(request) # type: ignore[call-arg] # mypy doesn't seem to apply the decorator message = """ user: {email} ({realm}) @@ -346,7 +346,7 @@ body: request.body = "invalidjson" request.content_type = 'application/json' request.META['HTTP_X_CUSTOM_HEADER'] = 'custom_value' - my_webhook_raises_exception_unexpected_event(request) # type: ignore # mypy doesn't seem to apply the decorator + my_webhook_raises_exception_unexpected_event(request) # type: ignore[call-arg] # mypy doesn't seem to apply the decorator message = """ user: {email} ({realm}) @@ -372,7 +372,7 @@ body: with self.settings(RATE_LIMITING=True): with mock.patch('zerver.decorator.rate_limit_user') as rate_limit_mock: - api_result = my_webhook(request) # type: ignore # mypy doesn't seem to apply the decorator + api_result = my_webhook(request) # type: ignore[call-arg] # mypy doesn't seem to apply the decorator # Verify rate limiting was attempted. self.assertTrue(rate_limit_mock.called) @@ -386,7 +386,7 @@ body: webhook_bot.is_active = False webhook_bot.save() with self.assertRaisesRegex(JsonableError, "Account is deactivated"): - my_webhook(request) # type: ignore # mypy doesn't seem to apply the decorator + my_webhook(request) # type: ignore[call-arg] # mypy doesn't seem to apply the decorator # Reactive the user, but deactivate their realm. webhook_bot.is_active = True @@ -394,7 +394,7 @@ body: webhook_bot.realm.deactivated = True webhook_bot.realm.save() with self.assertRaisesRegex(JsonableError, "This organization has been deactivated"): - my_webhook(request) # type: ignore # mypy doesn't seem to apply the decorator + my_webhook(request) # type: ignore[call-arg] # mypy doesn't seem to apply the decorator class SkipRateLimitingTest(ZulipTestCase): def test_authenticated_rest_api_view(self) -> None: @@ -411,12 +411,12 @@ class SkipRateLimitingTest(ZulipTestCase): request.method = 'POST' with mock.patch('zerver.decorator.rate_limit') as rate_limit_mock: - result = my_unlimited_view(request) # type: ignore # mypy doesn't seem to apply the decorator + result = my_unlimited_view(request) # type: ignore[call-arg] # mypy doesn't seem to apply the decorator self.assert_json_success(result) self.assertFalse(rate_limit_mock.called) with mock.patch('zerver.decorator.rate_limit') as rate_limit_mock: - result = my_rate_limited_view(request) # type: ignore # mypy doesn't seem to apply the decorator + result = my_rate_limited_view(request) # type: ignore[call-arg] # mypy doesn't seem to apply the decorator # Don't assert json_success, since it'll be the rate_limit mock object self.assertTrue(rate_limit_mock.called) @@ -434,12 +434,12 @@ class SkipRateLimitingTest(ZulipTestCase): request.POST['api_key'] = get_api_key(self.example_user("hamlet")) with mock.patch('zerver.decorator.rate_limit') as rate_limit_mock: - result = my_unlimited_view(request) # type: ignore # mypy doesn't seem to apply the decorator + result = my_unlimited_view(request) # type: ignore[call-arg] # mypy doesn't seem to apply the decorator self.assert_json_success(result) self.assertFalse(rate_limit_mock.called) with mock.patch('zerver.decorator.rate_limit') as rate_limit_mock: - result = my_rate_limited_view(request) # type: ignore # mypy doesn't seem to apply the decorator + result = my_rate_limited_view(request) # type: ignore[call-arg] # mypy doesn't seem to apply the decorator # Don't assert json_success, since it'll be the rate_limit mock object self.assertTrue(rate_limit_mock.called) @@ -452,16 +452,16 @@ class SkipRateLimitingTest(ZulipTestCase): request = HostRequestMock(host="zulip.testserver") request.method = 'POST' - request.is_authenticated = True # type: ignore # HostRequestMock doesn't have is_authenticated + request.is_authenticated = True # type: ignore[attr-defined] # HostRequestMock doesn't have is_authenticated request.user = self.example_user("hamlet") with mock.patch('zerver.decorator.rate_limit') as rate_limit_mock: - result = my_unlimited_view(request) # type: ignore # mypy doesn't seem to apply the decorator + result = my_unlimited_view(request) # type: ignore[call-arg] # mypy doesn't seem to apply the decorator self.assert_json_success(result) self.assertFalse(rate_limit_mock.called) with mock.patch('zerver.decorator.rate_limit') as rate_limit_mock: - result = my_rate_limited_view(request) # type: ignore # mypy doesn't seem to apply the decorator + result = my_rate_limited_view(request) # type: ignore[call-arg] # mypy doesn't seem to apply the decorator # Don't assert json_success, since it'll be the rate_limit mock object self.assertTrue(rate_limit_mock.called) @@ -485,7 +485,7 @@ class DecoratorLoggingTestCase(ZulipTestCase): with mock.patch('zerver.decorator.webhook_logger.exception') as mock_exception: with self.assertRaisesRegex(Exception, "raised by webhook function"): - my_webhook_raises_exception(request) # type: ignore # mypy doesn't seem to apply the decorator + my_webhook_raises_exception(request) # type: ignore[call-arg] # mypy doesn't seem to apply the decorator message = """ user: {email} ({realm}) @@ -529,7 +529,7 @@ body: with mock.patch('zerver.decorator.webhook_unexpected_events_logger.exception') as mock_exception: exception_msg = "The 'test_event' event isn't currently supported by the helloworld webhook" with self.assertRaisesRegex(UnexpectedWebhookEventType, exception_msg): - my_webhook_raises_exception(request) # type: ignore # mypy doesn't seem to apply the decorator + my_webhook_raises_exception(request) # type: ignore[call-arg] # mypy doesn't seem to apply the decorator message = """ user: {email} ({realm}) diff --git a/zerver/tests/test_embedded_bot_system.py b/zerver/tests/test_embedded_bot_system.py index e65dedbadd..ecfd2d2ea2 100644 --- a/zerver/tests/test_embedded_bot_system.py +++ b/zerver/tests/test_embedded_bot_system.py @@ -30,8 +30,8 @@ class TestEmbeddedBotMessaging(ZulipTestCase): # The next two lines error on mypy because the display_recipient is of type Union[str, List[Dict[str, Any]]]. # In this case, we know that display_recipient will be of type List[Dict[str, Any]]. # Otherwise this test will error, which is wanted behavior anyway. - self.assert_length(display_recipient, 1) # type: ignore - self.assertEqual(display_recipient[0]['email'], self.user_profile.email) # type: ignore + self.assert_length(display_recipient, 1) # type: ignore[arg-type] + self.assertEqual(display_recipient[0]['email'], self.user_profile.email) # type: ignore[index] def test_stream_message_to_embedded_bot(self) -> None: assert self.bot_profile is not None diff --git a/zerver/tests/test_hipchat_importer.py b/zerver/tests/test_hipchat_importer.py index d9de2e9d80..99ed998de3 100644 --- a/zerver/tests/test_hipchat_importer.py +++ b/zerver/tests/test_hipchat_importer.py @@ -20,7 +20,7 @@ class HipChatImporter(ZulipTestCase): user_handler = UserHandler() user_id_mapper = IdMapper() - user_id_mapper.has = lambda key: True # type: ignore # it's just a stub + user_id_mapper.has = lambda key: True # type: ignore[assignment] # it's just a stub # Simulate a "normal" user first. user_with_id = dict( diff --git a/zerver/tests/test_import_export.py b/zerver/tests/test_import_export.py index e3762c6090..b1b44efba4 100644 --- a/zerver/tests/test_import_export.py +++ b/zerver/tests/test_import_export.py @@ -211,7 +211,7 @@ class QueryUtilTest(ZulipTestCase): id_collector=all_msg_ids, chunk_size=10, # use a different size each time ) - first_chunk = next(chunker) # type: ignore + first_chunk = next(chunker) # type: ignore[call-overload] self.assertEqual(len(first_chunk), 10) self.assertEqual(len(all_msg_ids), 10) expected_msg = Message.objects.all()[0:10][5] diff --git a/zerver/tests/test_logging_handlers.py b/zerver/tests/test_logging_handlers.py index cc629cbe3b..4cb6c1d9a8 100644 --- a/zerver/tests/test_logging_handlers.py +++ b/zerver/tests/test_logging_handlers.py @@ -30,7 +30,7 @@ def capture_and_throw(domain: Optional[str]=None) -> Callable[[ViewFuncT], ViewF global captured_exc_info captured_exc_info = sys.exc_info() raise e - return wrapped_view # type: ignore # https://github.com/python/mypy/issues/1927 + return wrapped_view # type: ignore[return-value] # https://github.com/python/mypy/issues/1927 return wrapper class AdminNotifyHandlerTest(ZulipTestCase): @@ -81,7 +81,7 @@ class AdminNotifyHandlerTest(ZulipTestCase): record = self.logger.makeRecord('name', logging.ERROR, 'function', 15, 'message', {}, captured_exc_info) - record.request = captured_request # type: ignore # this field is dynamically added + record.request = captured_request # type: ignore[attr-defined] # this field is dynamically added return record def run_handler(self, record: logging.LogRecord) -> Dict[str, Any]: @@ -126,7 +126,7 @@ class AdminNotifyHandlerTest(ZulipTestCase): self.assertEqual(report["stack_trace"], "See /var/log/zulip/errors.log") # Check anonymous user is handled correctly - record.request.user = AnonymousUser() # type: ignore # this field is dynamically added + record.request.user = AnonymousUser() # type: ignore[attr-defined] # this field is dynamically added report = self.run_handler(record) self.assertIn("host", report) self.assertIn("user_email", report) @@ -136,10 +136,10 @@ class AdminNotifyHandlerTest(ZulipTestCase): # Now simulate a DisallowedHost exception def get_host_error() -> None: raise Exception("Get Host Failure!") - orig_get_host = record.request.get_host # type: ignore # this field is dynamically added - record.request.get_host = get_host_error # type: ignore # this field is dynamically added + orig_get_host = record.request.get_host # type: ignore[attr-defined] # this field is dynamically added + record.request.get_host = get_host_error # type: ignore[attr-defined] # this field is dynamically added report = self.run_handler(record) - record.request.get_host = orig_get_host # type: ignore # this field is dynamically added + record.request.get_host = orig_get_host # type: ignore[attr-defined] # this field is dynamically added self.assertIn("host", report) self.assertIn("user_email", report) self.assertIn("message", report) @@ -148,9 +148,9 @@ class AdminNotifyHandlerTest(ZulipTestCase): # Test an exception_filter exception with patch("zerver.logging_handlers.get_exception_reporter_filter", return_value=15): - record.request.method = "POST" # type: ignore # this field is dynamically added + record.request.method = "POST" # type: ignore[attr-defined] # this field is dynamically added report = self.run_handler(record) - record.request.method = "GET" # type: ignore # this field is dynamically added + record.request.method = "GET" # type: ignore[attr-defined] # this field is dynamically added self.assertIn("host", report) self.assertIn("user_email", report) self.assertIn("message", report) @@ -174,7 +174,7 @@ class AdminNotifyHandlerTest(ZulipTestCase): self.assertEqual(report["stack_trace"], 'No stack trace available') # Test arbitrary exceptions from request.user - record.request.user = None # type: ignore # this field is dynamically added + record.request.user = None # type: ignore[attr-defined] # this field is dynamically added with patch("zerver.logging_handlers.traceback.print_exc"): report = self.run_handler(record) self.assertIn("host", report) @@ -187,7 +187,7 @@ class LoggingConfigTest(TestCase): def all_loggers() -> Iterator[logging.Logger]: # There is no documented API for enumerating the loggers; but the # internals of `logging` haven't changed in ages, so just use them. - loggerDict = logging.Logger.manager.loggerDict # type: ignore + loggerDict = logging.Logger.manager.loggerDict # type: ignore[attr-defined] for logger in loggerDict.values(): if not isinstance(logger, logging.Logger): continue diff --git a/zerver/tests/test_messages.py b/zerver/tests/test_messages.py index bf4347f7ae..9a7ddf724a 100644 --- a/zerver/tests/test_messages.py +++ b/zerver/tests/test_messages.py @@ -2560,7 +2560,7 @@ class ScheduledMessageTest(ZulipTestCase): self.assertEqual(message.content, 'Test message 6') local_tz = get_timezone(tz_guess) # Since mypy is not able to recognize localize and normalize as attributes of tzinfo we use ignore. - utz_defer_until = local_tz.normalize(local_tz.localize(defer_until)) # type: ignore # Reason in comment on previous line. + utz_defer_until = local_tz.normalize(local_tz.localize(defer_until)) # type: ignore[attr-defined] # Reason in comment on previous line. self.assertEqual(message.scheduled_timestamp, convert_to_UTC(utz_defer_until)) self.assertEqual(message.delivery_type, ScheduledMessage.SEND_LATER) @@ -2577,7 +2577,7 @@ class ScheduledMessageTest(ZulipTestCase): self.assertEqual(message.content, 'Test message 7') local_tz = get_timezone(user.timezone) # Since mypy is not able to recognize localize and normalize as attributes of tzinfo we use ignore. - utz_defer_until = local_tz.normalize(local_tz.localize(defer_until)) # type: ignore # Reason in comment on previous line. + utz_defer_until = local_tz.normalize(local_tz.localize(defer_until)) # type: ignore[attr-defined] # Reason in comment on previous line. self.assertEqual(message.scheduled_timestamp, convert_to_UTC(utz_defer_until)) self.assertEqual(message.delivery_type, ScheduledMessage.SEND_LATER) diff --git a/zerver/tests/test_openapi.py b/zerver/tests/test_openapi.py index ce2397ada3..33e42c4e8e 100644 --- a/zerver/tests/test_openapi.py +++ b/zerver/tests/test_openapi.py @@ -494,7 +494,7 @@ do not match the types declared in the implementation of {}.\n""".format(functio # possible. vtype = self.get_standardized_argument_type(function.__annotations__[vname]) - vname = defval.post_var_name # type: ignore # See zerver/lib/request.py + vname = defval.post_var_name # type: ignore[attr-defined] # See zerver/lib/request.py function_params.add((vname, vtype)) diff = openapi_params - function_params diff --git a/zerver/tests/test_push_notifications.py b/zerver/tests/test_push_notifications.py index 5295af965f..9e32560f11 100644 --- a/zerver/tests/test_push_notifications.py +++ b/zerver/tests/test_push_notifications.py @@ -556,8 +556,8 @@ class AnalyticsBouncerTest(BouncerTestCase): event_time=self.TIME_ZERO, extra_data='data') def check_for_unwanted_data(*args: Any) -> Any: - if check_for_unwanted_data.first_call: # type: ignore - check_for_unwanted_data.first_call = False # type: ignore + if check_for_unwanted_data.first_call: # type: ignore[attr-defined] + check_for_unwanted_data.first_call = False # type: ignore[attr-defined] else: # Test that we're respecting SYNCED_BILLING_EVENTS self.assertIn('"event_type":{}'.format(RealmAuditLog.USER_REACTIVATED), str(args)) @@ -569,7 +569,7 @@ class AnalyticsBouncerTest(BouncerTestCase): # send_analytics_to_remote_server calls send_to_push_bouncer twice. # We need to distinguish the first and second calls. - check_for_unwanted_data.first_call = True # type: ignore + check_for_unwanted_data.first_call = True # type: ignore[attr-defined] with mock.patch('zerver.lib.remote_server.send_to_push_bouncer', side_effect=check_for_unwanted_data): send_analytics_to_remote_server() diff --git a/zerver/tests/test_service_bot_system.py b/zerver/tests/test_service_bot_system.py index 4c28670f9b..1bf4afc45b 100644 --- a/zerver/tests/test_service_bot_system.py +++ b/zerver/tests/test_service_bot_system.py @@ -207,7 +207,7 @@ class TestServiceBotStateHandler(ZulipTestCase): def test_marshaling(self) -> None: storage = StateHandler(self.bot_profile) serializable_obj = {'foo': 'bar', 'baz': [42, 'cux']} - storage.put('some key', serializable_obj) # type: ignore # Ignore for testing. + storage.put('some key', serializable_obj) # type: ignore[arg-type] # Ignore for testing. self.assertEqual(storage.get('some key'), serializable_obj) def test_invalid_calls(self) -> None: @@ -216,9 +216,9 @@ class TestServiceBotStateHandler(ZulipTestCase): storage.demarshal = lambda obj: obj serializable_obj = {'foo': 'bar', 'baz': [42, 'cux']} with self.assertRaisesMessage(StateError, "Value type is , but should be str."): - storage.put('some key', serializable_obj) # type: ignore # We intend to test an invalid type. + storage.put('some key', serializable_obj) # type: ignore[arg-type] # We intend to test an invalid type. with self.assertRaisesMessage(StateError, "Key type is , but should be str."): - storage.put(serializable_obj, 'some value') # type: ignore # We intend to test an invalid type. + storage.put(serializable_obj, 'some value') # type: ignore[arg-type] # We intend to test an invalid type. # Reduce maximal storage size for faster test string construction. @override_settings(USER_STATE_SIZE_LIMIT=100) @@ -293,7 +293,7 @@ class TestServiceBotStateHandler(ZulipTestCase): # Assert errors on invalid requests. params = { - 'keys': ["This is a list, but should be a serialized string."] # type: ignore # Ignore 'incompatible type "str": "List[str]"; expected "str": "str"' for testing + 'keys': ["This is a list, but should be a serialized string."] # type: ignore[dict-item] # Ignore 'incompatible type "str": "List[str]"; expected "str": "str"' for testing } result = self.client_get('/json/bot_storage', params) self.assert_json_error(result, 'Argument "keys" is not valid JSON.') diff --git a/zerver/tests/test_signup.py b/zerver/tests/test_signup.py index 04eaaf1ea0..22523a5ed2 100644 --- a/zerver/tests/test_signup.py +++ b/zerver/tests/test_signup.py @@ -2713,7 +2713,7 @@ class UserSignUpTest(InviteUserBase): do_set_realm_property(realm, 'emails_restricted_to_domains', True) request = HostRequestMock(host = realm.host) - request.session = {} # type: ignore + request.session = {} # type: ignore[attr-defined] email = 'user@acme.com' form = HomepageForm({'email': email}, realm=realm) self.assertIn("Your email address, {}, is not in one of the domains".format(email), @@ -2726,7 +2726,7 @@ class UserSignUpTest(InviteUserBase): realm.save() request = HostRequestMock(host = realm.host) - request.session = {} # type: ignore + request.session = {} # type: ignore[attr-defined] email = 'abc@mailnator.com' form = HomepageForm({'email': email}, realm=realm) self.assertIn("Please use your real email address", form.errors['email'][0]) @@ -2737,7 +2737,7 @@ class UserSignUpTest(InviteUserBase): realm.save() request = HostRequestMock(host = realm.host) - request.session = {} # type: ignore + request.session = {} # type: ignore[attr-defined] email = 'iago+label@zulip.com' form = HomepageForm({'email': email}, realm=realm) self.assertIn("Email addresses containing + are not allowed in this organization.", form.errors['email'][0]) @@ -2747,7 +2747,7 @@ class UserSignUpTest(InviteUserBase): realm.invite_required = True realm.save() request = HostRequestMock(host = realm.host) - request.session = {} # type: ignore + request.session = {} # type: ignore[attr-defined] email = 'user@zulip.com' form = HomepageForm({'email': email}, realm=realm) self.assertIn("Please request an invite for {} from".format(email), @@ -2755,7 +2755,7 @@ class UserSignUpTest(InviteUserBase): def test_failed_signup_due_to_nonexistent_realm(self) -> None: request = HostRequestMock(host = 'acme.' + settings.EXTERNAL_HOST) - request.session = {} # type: ignore + request.session = {} # type: ignore[attr-defined] email = 'user@acme.com' form = HomepageForm({'email': email}, realm=None) self.assertIn("organization you are trying to join using {} does " diff --git a/zerver/tests/test_webhooks_common.py b/zerver/tests/test_webhooks_common.py index b7b2b8f0bf..c003a37016 100644 --- a/zerver/tests/test_webhooks_common.py +++ b/zerver/tests/test_webhooks_common.py @@ -73,7 +73,7 @@ class WebhooksCommonTestCase(ZulipTestCase): last_message_id = self.get_last_message().id with self.assertRaisesRegex(JsonableError, "Malformed JSON"): - my_webhook_no_notify(request) # type: ignore # mypy doesn't seem to apply the decorator + my_webhook_no_notify(request) # type: ignore[call-arg] # mypy doesn't seem to apply the decorator # First verify that without the setting, it doesn't send a PM to bot owner. msg = self.get_last_message() @@ -82,7 +82,7 @@ class WebhooksCommonTestCase(ZulipTestCase): # Then verify that with the setting, it does send such a message. with self.assertRaisesRegex(JsonableError, "Malformed JSON"): - my_webhook_notify(request) # type: ignore # mypy doesn't seem to apply the decorator + my_webhook_notify(request) # type: ignore[call-arg] # mypy doesn't seem to apply the decorator msg = self.get_last_message() self.assertNotEqual(msg.id, last_message_id) self.assertEqual(msg.sender.email, self.notification_bot().email) diff --git a/zerver/tornado/ioloop_logging.py b/zerver/tornado/ioloop_logging.py index 20c0c05d55..2c4d8ab0bb 100644 --- a/zerver/tornado/ioloop_logging.py +++ b/zerver/tornado/ioloop_logging.py @@ -16,7 +16,7 @@ orig_poll_impl = select.epoll logging_data = {} # type: Dict[str, str] class InstrumentedPollIOLoop(PollIOLoop): - def initialize(self, **kwargs): # type: ignore # TODO investigate likely buggy monkey patching here + def initialize(self, **kwargs): # type: ignore[no-untyped-def] # TODO investigate likely buggy monkey patching here super().initialize(impl=InstrumentedPoll(), **kwargs) def instrument_tornado_ioloop() -> None: diff --git a/zerver/views/custom_profile_fields.py b/zerver/views/custom_profile_fields.py index fa416040ef..c32d11fd6f 100644 --- a/zerver/views/custom_profile_fields.py +++ b/zerver/views/custom_profile_fields.py @@ -93,7 +93,7 @@ def create_realm_custom_profile_field(request: HttpRequest, try: if is_default_external_field(field_type, field_data): field_subtype = '' # type: str - field_subtype = field_data['subtype'] # type: ignore # key for "Union[Dict[str, str], str]" can be str + field_subtype = field_data['subtype'] # type: ignore[assignment] # key for "Union[Dict[str, str], str]" can be str field = try_add_realm_default_custom_profile_field( realm=user_profile.realm, field_subtype=field_subtype, diff --git a/zerver/views/messages.py b/zerver/views/messages.py index d59401cd3f..150fa8944e 100644 --- a/zerver/views/messages.py +++ b/zerver/views/messages.py @@ -1300,7 +1300,7 @@ def handle_deferred_message(sender: UserProfile, client: Client, if deliver_at_usertz.tzinfo is None: user_tz = get_timezone(local_tz) # Since mypy is not able to recognize localize and normalize as attributes of tzinfo we use ignore. - deliver_at_usertz = user_tz.normalize(user_tz.localize(deliver_at)) # type: ignore # Reason in comment on previous line. + deliver_at_usertz = user_tz.normalize(user_tz.localize(deliver_at)) # type: ignore[attr-defined] # Reason in comment on previous line. deliver_at = convert_to_UTC(deliver_at_usertz) if deliver_at <= timezone_now(): diff --git a/zerver/webhooks/beanstalk/view.py b/zerver/webhooks/beanstalk/view.py index 9488fb40f6..d3e8803cbf 100644 --- a/zerver/webhooks/beanstalk/view.py +++ b/zerver/webhooks/beanstalk/view.py @@ -57,7 +57,7 @@ def beanstalk_decoder(view_func: ViewFuncT) -> ViewFuncT: return view_func(request, *args, **kwargs) - return _wrapped_view_func # type: ignore # https://github.com/python/mypy/issues/1927 + return _wrapped_view_func # type: ignore[return-value] # https://github.com/python/mypy/issues/1927 @beanstalk_decoder @authenticated_rest_api_view(webhook_client_name="Beanstalk") diff --git a/zproject/backends.py b/zproject/backends.py index 6ad4430a88..63f498b318 100644 --- a/zproject/backends.py +++ b/zproject/backends.py @@ -1251,7 +1251,7 @@ class SocialAuthMixin(ZulipAuthMixin, ExternalAuthMethod): """ try: # Call the auth_complete method of social_core.backends.oauth.BaseOAuth2 - return super().auth_complete(*args, **kwargs) # type: ignore # monkey-patching + return super().auth_complete(*args, **kwargs) # type: ignore[misc] # monkey-patching except AuthFailed as e: # When a user's social authentication fails (e.g. because # they did something funny with reloading in the middle of