We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Re-enable deps on 3.12 when ready
- [x] bpython (requires greenlet)
- [x] uvloop
- [x] pyftpdlib

Related: https://github.com/scrapy/scrapy/pull/6083

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `scrapy/contracts/__init__.py`
Content:
```
1 import re
2 import sys
3 from functools import wraps
4 from inspect import getmembers
5 from types import CoroutineType
6 from typing import AsyncGenerator, Dict
7 from unittest import TestCase
8 
9 from scrapy.http import Request
10 from scrapy.utils.python import get_spec
11 from scrapy.utils.spider import iterate_spider_output
12 
13 
14 class Contract:
15     """Abstract class for contracts"""
16 
17     request_cls = None
18 
19     def __init__(self, method, *args):
20         self.testcase_pre = _create_testcase(method, f"@{self.name} pre-hook")
21         self.testcase_post = _create_testcase(method, f"@{self.name} post-hook")
22         self.args = args
23 
24     def add_pre_hook(self, request, results):
25         if hasattr(self, "pre_process"):
26             cb = request.callback
27 
28             @wraps(cb)
29             def wrapper(response, **cb_kwargs):
30                 try:
31                     results.startTest(self.testcase_pre)
32                     self.pre_process(response)
33                     results.stopTest(self.testcase_pre)
34                 except AssertionError:
35                     results.addFailure(self.testcase_pre, sys.exc_info())
36                 except Exception:
37                     results.addError(self.testcase_pre, sys.exc_info())
38                 else:
39                     results.addSuccess(self.testcase_pre)
40                 finally:
41                     cb_result = cb(response, **cb_kwargs)
42                     if isinstance(cb_result, (AsyncGenerator, CoroutineType)):
43                         raise TypeError("Contracts don't support async callbacks")
44                     return list(iterate_spider_output(cb_result))
45 
46             request.callback = wrapper
47 
48         return request
49 
50     def add_post_hook(self, request, results):
51         if hasattr(self, "post_process"):
52             cb = request.callback
53 
54             @wraps(cb)
55             def wrapper(response, **cb_kwargs):
56                 cb_result = cb(response, **cb_kwargs)
57                 if isinstance(cb_result, (AsyncGenerator, CoroutineType)):
58                     raise TypeError("Contracts don't support async callbacks")
59                 output = list(iterate_spider_output(cb_result))
60                 try:
61                     results.startTest(self.testcase_post)
62                     self.post_process(output)
63                     results.stopTest(self.testcase_post)
64                 except AssertionError:
65                     results.addFailure(self.testcase_post, sys.exc_info())
66                 except Exception:
67                     results.addError(self.testcase_post, sys.exc_info())
68                 else:
69                     results.addSuccess(self.testcase_post)
70                 finally:
71                     return output
72 
73             request.callback = wrapper
74 
75         return request
76 
77     def adjust_request_args(self, args):
78         return args
79 
80 
81 class ContractsManager:
82     contracts: Dict[str, Contract] = {}
83 
84     def __init__(self, contracts):
85         for contract in contracts:
86             self.contracts[contract.name] = contract
87 
88     def tested_methods_from_spidercls(self, spidercls):
89         is_method = re.compile(r"^\s*@", re.MULTILINE).search
90         methods = []
91         for key, value in getmembers(spidercls):
92             if callable(value) and value.__doc__ and is_method(value.__doc__):
93                 methods.append(key)
94 
95         return methods
96 
97     def extract_contracts(self, method):
98         contracts = []
99         for line in method.__doc__.split("\n"):
100             line = line.strip()
101 
102             if line.startswith("@"):
103                 name, args = re.match(r"@(\w+)\s*(.*)", line).groups()
104                 args = re.split(r"\s+", args)
105 
106                 contracts.append(self.contracts[name](method, *args))
107 
108         return contracts
109 
110     def from_spider(self, spider, results):
111         requests = []
112         for method in self.tested_methods_from_spidercls(type(spider)):
113             bound_method = spider.__getattribute__(method)
114             try:
115                 requests.append(self.from_method(bound_method, results))
116             except Exception:
117                 case = _create_testcase(bound_method, "contract")
118                 results.addError(case, sys.exc_info())
119 
120         return requests
121 
122     def from_method(self, method, results):
123         contracts = self.extract_contracts(method)
124         if contracts:
125             request_cls = Request
126             for contract in contracts:
127                 if contract.request_cls is not None:
128                     request_cls = contract.request_cls
129 
130             # calculate request args
131             args, kwargs = get_spec(request_cls.__init__)
132 
133             # Don't filter requests to allow
134             # testing different callbacks on the same URL.
135             kwargs["dont_filter"] = True
136             kwargs["callback"] = method
137 
138             for contract in contracts:
139                 kwargs = contract.adjust_request_args(kwargs)
140 
141             args.remove("self")
142 
143             # check if all positional arguments are defined in kwargs
144             if set(args).issubset(set(kwargs)):
145                 request = request_cls(**kwargs)
146 
147                 # execute pre and post hooks in order
148                 for contract in reversed(contracts):
149                     request = contract.add_pre_hook(request, results)
150                 for contract in contracts:
151                     request = contract.add_post_hook(request, results)
152 
153                 self._clean_req(request, method, results)
154                 return request
155 
156     def _clean_req(self, request, method, results):
157         """stop the request from returning objects and records any errors"""
158 
159         cb = request.callback
160 
161         @wraps(cb)
162         def cb_wrapper(response, **cb_kwargs):
163             try:
164                 output = cb(response, **cb_kwargs)
165                 output = list(iterate_spider_output(output))
166             except Exception:
167                 case = _create_testcase(method, "callback")
168                 results.addError(case, sys.exc_info())
169 
170         def eb_wrapper(failure):
171             case = _create_testcase(method, "errback")
172             exc_info = failure.type, failure.value, failure.getTracebackObject()
173             results.addError(case, exc_info)
174 
175         request.callback = cb_wrapper
176         request.errback = eb_wrapper
177 
178 
179 def _create_testcase(method, desc):
180     spider = method.__self__.name
181 
182     class ContractTestCase(TestCase):
183         def __str__(_self):
184             return f"[{spider}] {method.__name__} ({desc})"
185 
186     name = f"{spider}_{method.__name__}"
187     setattr(ContractTestCase, name, lambda x: x)
188     return ContractTestCase(name)
189
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/scrapy/contracts/__init__.py b/scrapy/contracts/__init__.py
--- a/scrapy/contracts/__init__.py
+++ b/scrapy/contracts/__init__.py
@@ -41,7 +41,9 @@
                     cb_result = cb(response, **cb_kwargs)
                     if isinstance(cb_result, (AsyncGenerator, CoroutineType)):
                         raise TypeError("Contracts don't support async callbacks")
-                    return list(iterate_spider_output(cb_result))
+                    return list(  # pylint: disable=return-in-finally
+                        iterate_spider_output(cb_result)
+                    )
 
             request.callback = wrapper
 
@@ -68,7 +70,7 @@
                 else:
                     results.addSuccess(self.testcase_post)
                 finally:
-                    return output
+                    return output  # pylint: disable=return-in-finally
 
             request.callback = wrapper

{"golden_diff": "diff --git a/scrapy/contracts/__init__.py b/scrapy/contracts/__init__.py\n--- a/scrapy/contracts/__init__.py\n+++ b/scrapy/contracts/__init__.py\n@@ -41,7 +41,9 @@\n                     cb_result = cb(response, **cb_kwargs)\n                     if isinstance(cb_result, (AsyncGenerator, CoroutineType)):\n                         raise TypeError(\"Contracts don't support async callbacks\")\n-                    return list(iterate_spider_output(cb_result))\n+                    return list(  # pylint: disable=return-in-finally\n+                        iterate_spider_output(cb_result)\n+                    )\n \n             request.callback = wrapper\n \n@@ -68,7 +70,7 @@\n                 else:\n                     results.addSuccess(self.testcase_post)\n                 finally:\n-                    return output\n+                    return output  # pylint: disable=return-in-finally\n \n             request.callback = wrapper\n", "issue": "Re-enable deps on 3.12 when ready\n- [x] bpython (requires greenlet)\r\n- [x] uvloop\r\n- [x] pyftpdlib\r\n\r\nRelated: https://github.com/scrapy/scrapy/pull/6083\n", "before_files": [{"content": "import re\nimport sys\nfrom functools import wraps\nfrom inspect import getmembers\nfrom types import CoroutineType\nfrom typing import AsyncGenerator, Dict\nfrom unittest import TestCase\n\nfrom scrapy.http import Request\nfrom scrapy.utils.python import get_spec\nfrom scrapy.utils.spider import iterate_spider_output\n\n\nclass Contract:\n    \"\"\"Abstract class for contracts\"\"\"\n\n    request_cls = None\n\n    def __init__(self, method, *args):\n        self.testcase_pre = _create_testcase(method, f\"@{self.name} pre-hook\")\n        self.testcase_post = _create_testcase(method, f\"@{self.name} post-hook\")\n        self.args = args\n\n    def add_pre_hook(self, request, results):\n        if hasattr(self, \"pre_process\"):\n            cb = request.callback\n\n            @wraps(cb)\n            def wrapper(response, **cb_kwargs):\n                try:\n                    results.startTest(self.testcase_pre)\n                    self.pre_process(response)\n                    results.stopTest(self.testcase_pre)\n                except AssertionError:\n                    results.addFailure(self.testcase_pre, sys.exc_info())\n                except Exception:\n                    results.addError(self.testcase_pre, sys.exc_info())\n                else:\n                    results.addSuccess(self.testcase_pre)\n                finally:\n                    cb_result = cb(response, **cb_kwargs)\n                    if isinstance(cb_result, (AsyncGenerator, CoroutineType)):\n                        raise TypeError(\"Contracts don't support async callbacks\")\n                    return list(iterate_spider_output(cb_result))\n\n            request.callback = wrapper\n\n        return request\n\n    def add_post_hook(self, request, results):\n        if hasattr(self, \"post_process\"):\n            cb = request.callback\n\n            @wraps(cb)\n            def wrapper(response, **cb_kwargs):\n                cb_result = cb(response, **cb_kwargs)\n                if isinstance(cb_result, (AsyncGenerator, CoroutineType)):\n                    raise TypeError(\"Contracts don't support async callbacks\")\n                output = list(iterate_spider_output(cb_result))\n                try:\n                    results.startTest(self.testcase_post)\n                    self.post_process(output)\n                    results.stopTest(self.testcase_post)\n                except AssertionError:\n                    results.addFailure(self.testcase_post, sys.exc_info())\n                except Exception:\n                    results.addError(self.testcase_post, sys.exc_info())\n                else:\n                    results.addSuccess(self.testcase_post)\n                finally:\n                    return output\n\n            request.callback = wrapper\n\n        return request\n\n    def adjust_request_args(self, args):\n        return args\n\n\nclass ContractsManager:\n    contracts: Dict[str, Contract] = {}\n\n    def __init__(self, contracts):\n        for contract in contracts:\n            self.contracts[contract.name] = contract\n\n    def tested_methods_from_spidercls(self, spidercls):\n        is_method = re.compile(r\"^\\s*@\", re.MULTILINE).search\n        methods = []\n        for key, value in getmembers(spidercls):\n            if callable(value) and value.__doc__ and is_method(value.__doc__):\n                methods.append(key)\n\n        return methods\n\n    def extract_contracts(self, method):\n        contracts = []\n        for line in method.__doc__.split(\"\\n\"):\n            line = line.strip()\n\n            if line.startswith(\"@\"):\n                name, args = re.match(r\"@(\\w+)\\s*(.*)\", line).groups()\n                args = re.split(r\"\\s+\", args)\n\n                contracts.append(self.contracts[name](method, *args))\n\n        return contracts\n\n    def from_spider(self, spider, results):\n        requests = []\n        for method in self.tested_methods_from_spidercls(type(spider)):\n            bound_method = spider.__getattribute__(method)\n            try:\n                requests.append(self.from_method(bound_method, results))\n            except Exception:\n                case = _create_testcase(bound_method, \"contract\")\n                results.addError(case, sys.exc_info())\n\n        return requests\n\n    def from_method(self, method, results):\n        contracts = self.extract_contracts(method)\n        if contracts:\n            request_cls = Request\n            for contract in contracts:\n                if contract.request_cls is not None:\n                    request_cls = contract.request_cls\n\n            # calculate request args\n            args, kwargs = get_spec(request_cls.__init__)\n\n            # Don't filter requests to allow\n            # testing different callbacks on the same URL.\n            kwargs[\"dont_filter\"] = True\n            kwargs[\"callback\"] = method\n\n            for contract in contracts:\n                kwargs = contract.adjust_request_args(kwargs)\n\n            args.remove(\"self\")\n\n            # check if all positional arguments are defined in kwargs\n            if set(args).issubset(set(kwargs)):\n                request = request_cls(**kwargs)\n\n                # execute pre and post hooks in order\n                for contract in reversed(contracts):\n                    request = contract.add_pre_hook(request, results)\n                for contract in contracts:\n                    request = contract.add_post_hook(request, results)\n\n                self._clean_req(request, method, results)\n                return request\n\n    def _clean_req(self, request, method, results):\n        \"\"\"stop the request from returning objects and records any errors\"\"\"\n\n        cb = request.callback\n\n        @wraps(cb)\n        def cb_wrapper(response, **cb_kwargs):\n            try:\n                output = cb(response, **cb_kwargs)\n                output = list(iterate_spider_output(output))\n            except Exception:\n                case = _create_testcase(method, \"callback\")\n                results.addError(case, sys.exc_info())\n\n        def eb_wrapper(failure):\n            case = _create_testcase(method, \"errback\")\n            exc_info = failure.type, failure.value, failure.getTracebackObject()\n            results.addError(case, exc_info)\n\n        request.callback = cb_wrapper\n        request.errback = eb_wrapper\n\n\ndef _create_testcase(method, desc):\n    spider = method.__self__.name\n\n    class ContractTestCase(TestCase):\n        def __str__(_self):\n            return f\"[{spider}] {method.__name__} ({desc})\"\n\n    name = f\"{spider}_{method.__name__}\"\n    setattr(ContractTestCase, name, lambda x: x)\n    return ContractTestCase(name)\n", "path": "scrapy/contracts/__init__.py"}], "after_files": [{"content": "import re\nimport sys\nfrom functools import wraps\nfrom inspect import getmembers\nfrom types import CoroutineType\nfrom typing import AsyncGenerator, Dict\nfrom unittest import TestCase\n\nfrom scrapy.http import Request\nfrom scrapy.utils.python import get_spec\nfrom scrapy.utils.spider import iterate_spider_output\n\n\nclass Contract:\n    \"\"\"Abstract class for contracts\"\"\"\n\n    request_cls = None\n\n    def __init__(self, method, *args):\n        self.testcase_pre = _create_testcase(method, f\"@{self.name} pre-hook\")\n        self.testcase_post = _create_testcase(method, f\"@{self.name} post-hook\")\n        self.args = args\n\n    def add_pre_hook(self, request, results):\n        if hasattr(self, \"pre_process\"):\n            cb = request.callback\n\n            @wraps(cb)\n            def wrapper(response, **cb_kwargs):\n                try:\n                    results.startTest(self.testcase_pre)\n                    self.pre_process(response)\n                    results.stopTest(self.testcase_pre)\n                except AssertionError:\n                    results.addFailure(self.testcase_pre, sys.exc_info())\n                except Exception:\n                    results.addError(self.testcase_pre, sys.exc_info())\n                else:\n                    results.addSuccess(self.testcase_pre)\n                finally:\n                    cb_result = cb(response, **cb_kwargs)\n                    if isinstance(cb_result, (AsyncGenerator, CoroutineType)):\n                        raise TypeError(\"Contracts don't support async callbacks\")\n                    return list(  # pylint: disable=return-in-finally\n                        iterate_spider_output(cb_result)\n                    )\n\n            request.callback = wrapper\n\n        return request\n\n    def add_post_hook(self, request, results):\n        if hasattr(self, \"post_process\"):\n            cb = request.callback\n\n            @wraps(cb)\n            def wrapper(response, **cb_kwargs):\n                cb_result = cb(response, **cb_kwargs)\n                if isinstance(cb_result, (AsyncGenerator, CoroutineType)):\n                    raise TypeError(\"Contracts don't support async callbacks\")\n                output = list(iterate_spider_output(cb_result))\n                try:\n                    results.startTest(self.testcase_post)\n                    self.post_process(output)\n                    results.stopTest(self.testcase_post)\n                except AssertionError:\n                    results.addFailure(self.testcase_post, sys.exc_info())\n                except Exception:\n                    results.addError(self.testcase_post, sys.exc_info())\n                else:\n                    results.addSuccess(self.testcase_post)\n                finally:\n                    return output  # pylint: disable=return-in-finally\n\n            request.callback = wrapper\n\n        return request\n\n    def adjust_request_args(self, args):\n        return args\n\n\nclass ContractsManager:\n    contracts: Dict[str, Contract] = {}\n\n    def __init__(self, contracts):\n        for contract in contracts:\n            self.contracts[contract.name] = contract\n\n    def tested_methods_from_spidercls(self, spidercls):\n        is_method = re.compile(r\"^\\s*@\", re.MULTILINE).search\n        methods = []\n        for key, value in getmembers(spidercls):\n            if callable(value) and value.__doc__ and is_method(value.__doc__):\n                methods.append(key)\n\n        return methods\n\n    def extract_contracts(self, method):\n        contracts = []\n        for line in method.__doc__.split(\"\\n\"):\n            line = line.strip()\n\n            if line.startswith(\"@\"):\n                name, args = re.match(r\"@(\\w+)\\s*(.*)\", line).groups()\n                args = re.split(r\"\\s+\", args)\n\n                contracts.append(self.contracts[name](method, *args))\n\n        return contracts\n\n    def from_spider(self, spider, results):\n        requests = []\n        for method in self.tested_methods_from_spidercls(type(spider)):\n            bound_method = spider.__getattribute__(method)\n            try:\n                requests.append(self.from_method(bound_method, results))\n            except Exception:\n                case = _create_testcase(bound_method, \"contract\")\n                results.addError(case, sys.exc_info())\n\n        return requests\n\n    def from_method(self, method, results):\n        contracts = self.extract_contracts(method)\n        if contracts:\n            request_cls = Request\n            for contract in contracts:\n                if contract.request_cls is not None:\n                    request_cls = contract.request_cls\n\n            # calculate request args\n            args, kwargs = get_spec(request_cls.__init__)\n\n            # Don't filter requests to allow\n            # testing different callbacks on the same URL.\n            kwargs[\"dont_filter\"] = True\n            kwargs[\"callback\"] = method\n\n            for contract in contracts:\n                kwargs = contract.adjust_request_args(kwargs)\n\n            args.remove(\"self\")\n\n            # check if all positional arguments are defined in kwargs\n            if set(args).issubset(set(kwargs)):\n                request = request_cls(**kwargs)\n\n                # execute pre and post hooks in order\n                for contract in reversed(contracts):\n                    request = contract.add_pre_hook(request, results)\n                for contract in contracts:\n                    request = contract.add_post_hook(request, results)\n\n                self._clean_req(request, method, results)\n                return request\n\n    def _clean_req(self, request, method, results):\n        \"\"\"stop the request from returning objects and records any errors\"\"\"\n\n        cb = request.callback\n\n        @wraps(cb)\n        def cb_wrapper(response, **cb_kwargs):\n            try:\n                output = cb(response, **cb_kwargs)\n                output = list(iterate_spider_output(output))\n            except Exception:\n                case = _create_testcase(method, \"callback\")\n                results.addError(case, sys.exc_info())\n\n        def eb_wrapper(failure):\n            case = _create_testcase(method, \"errback\")\n            exc_info = failure.type, failure.value, failure.getTracebackObject()\n            results.addError(case, exc_info)\n\n        request.callback = cb_wrapper\n        request.errback = eb_wrapper\n\n\ndef _create_testcase(method, desc):\n    spider = method.__self__.name\n\n    class ContractTestCase(TestCase):\n        def __str__(_self):\n            return f\"[{spider}] {method.__name__} ({desc})\"\n\n    name = f\"{spider}_{method.__name__}\"\n    setattr(ContractTestCase, name, lambda x: x)\n    return ContractTestCase(name)\n", "path": "scrapy/contracts/__init__.py"}]}