prompt: We are currently solving the following issue within our repository. Here is the issue text:
  --- BEGIN ISSUE ---
  SCRAPY_CHECK is not set while running contract
  ### Description
  
  Hi, it seems that #3739 is not doing what the [documentation describe](https://docs.scrapy.org/en/latest/topics/contracts.html#detecting-check-runs):
  
  `os.environ.get('SCRAPY_CHECK')` is returning `None` in my contract check.
  
  ### Steps to Reproduce
  
  1. Create a project from scratch
  2. Add a random spider
  3. Contract code is as follow
  ```
      def parse(self, response):
          """
          @url http://www.amazon.com/s?field-keywords=selfish+gene
          @returns requests 1 1
          """
          print("test", os.environ.get('SCRAPY_CHECK'))
          if os.environ.get('SCRAPY_CHECK'):
              yield scrapy.Request(url="next_url")
  ```
  
  **Expected behavior:** Request should be yielded as per the documentation
  
  **Actual behavior:** Nothing happen
  
  **Reproduces how often:** In my local project and with fresh project
  
  ### Versions
  
  Windows
  ```
  (globenv) C:\Users\johnl>scrapy version --verbose
  Scrapy       : 1.8.0
  lxml         : 4.4.1.0
  libxml2      : 2.9.5
  cssselect    : 1.1.0
  parsel       : 1.5.2
  w3lib        : 1.21.0
  Twisted      : 19.10.0
  Python       : 3.7.4 (tags/v3.7.4:e09359112e, Jul  8 2019, 19:29:22) [MSC v.1916 32 bit (Intel)]
  pyOpenSSL    : 19.0.0 (OpenSSL 1.1.1c  28 May 2019)
  cryptography : 2.7
  Platform     : Windows-10-10.0.18362-SP0
  ```
  
  Linux
  ```
  scrapy version --verbose
  Scrapy       : 1.8.0
  lxml         : 4.4.1.0
  libxml2      : 2.9.9
  cssselect    : 1.1.0
  parsel       : 1.5.2
  w3lib        : 1.21.0
  Twisted      : 19.7.0
  Python       : 3.6.8 (default, Oct  7 2019, 12:59:55) - [GCC 8.3.0]
  pyOpenSSL    : 19.0.0 (OpenSSL 1.1.1d  10 Sep 2019)
  cryptography : 2.8
  Platform     : Linux-4.4.0-18362-Microsoft-x86_64-with-Ubuntu-18.04-bionic
  ```
  
  
  --- 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/commands/check.py`
  Content:
  ```
  1 import time
  2 from collections import defaultdict
  3 from unittest import TextTestRunner, TextTestResult as _TextTestResult
  4 
  5 from scrapy.commands import ScrapyCommand
  6 from scrapy.contracts import ContractsManager
  7 from scrapy.utils.misc import load_object, set_environ
  8 from scrapy.utils.conf import build_component_list
  9 
  10 
  11 class TextTestResult(_TextTestResult):
  12     def printSummary(self, start, stop):
  13         write = self.stream.write
  14         writeln = self.stream.writeln
  15 
  16         run = self.testsRun
  17         plural = "s" if run != 1 else ""
  18 
  19         writeln(self.separator2)
  20         writeln("Ran %d contract%s in %.3fs" % (run, plural, stop - start))
  21         writeln()
  22 
  23         infos = []
  24         if not self.wasSuccessful():
  25             write("FAILED")
  26             failed, errored = map(len, (self.failures, self.errors))
  27             if failed:
  28                 infos.append("failures=%d" % failed)
  29             if errored:
  30                 infos.append("errors=%d" % errored)
  31         else:
  32             write("OK")
  33 
  34         if infos:
  35             writeln(" (%s)" % (", ".join(infos),))
  36         else:
  37             write("\n")
  38 
  39 
  40 class Command(ScrapyCommand):
  41     requires_project = True
  42     default_settings = {'LOG_ENABLED': False}
  43 
  44     def syntax(self):
  45         return "[options] <spider>"
  46 
  47     def short_desc(self):
  48         return "Check spider contracts"
  49 
  50     def add_options(self, parser):
  51         ScrapyCommand.add_options(self, parser)
  52         parser.add_option("-l", "--list", dest="list", action="store_true",
  53                           help="only list contracts, without checking them")
  54         parser.add_option("-v", "--verbose", dest="verbose", default=False, action='store_true',
  55                           help="print contract tests for all spiders")
  56 
  57     def run(self, args, opts):
  58         # load contracts
  59         contracts = build_component_list(self.settings.getwithbase('SPIDER_CONTRACTS'))
  60         conman = ContractsManager(load_object(c) for c in contracts)
  61         runner = TextTestRunner(verbosity=2 if opts.verbose else 1)
  62         result = TextTestResult(runner.stream, runner.descriptions, runner.verbosity)
  63 
  64         # contract requests
  65         contract_reqs = defaultdict(list)
  66 
  67         spider_loader = self.crawler_process.spider_loader
  68 
  69         with set_environ(SCRAPY_CHECK='true'):
  70             for spidername in args or spider_loader.list():
  71                 spidercls = spider_loader.load(spidername)
  72                 spidercls.start_requests = lambda s: conman.from_spider(s, result)
  73 
  74                 tested_methods = conman.tested_methods_from_spidercls(spidercls)
  75                 if opts.list:
  76                     for method in tested_methods:
  77                         contract_reqs[spidercls.name].append(method)
  78                 elif tested_methods:
  79                     self.crawler_process.crawl(spidercls)
  80 
  81         # start checks
  82         if opts.list:
  83             for spider, methods in sorted(contract_reqs.items()):
  84                 if not methods and not opts.verbose:
  85                     continue
  86                 print(spider)
  87                 for method in sorted(methods):
  88                     print('  * %s' % method)
  89         else:
  90             start = time.time()
  91             self.crawler_process.start()
  92             stop = time.time()
  93 
  94             result.printErrors()
  95             result.printSummary(start, stop)
  96             self.exitcode = int(not result.wasSuccessful())
  97
  ```
  --- 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()
  
  ```
  
golden_diff: diff --git a/scrapy/commands/check.py b/scrapy/commands/check.py
  --- a/scrapy/commands/check.py
  +++ b/scrapy/commands/check.py
  @@ -78,19 +78,19 @@
                   elif tested_methods:
                       self.crawler_process.crawl(spidercls)
   
  -        # start checks
  -        if opts.list:
  -            for spider, methods in sorted(contract_reqs.items()):
  -                if not methods and not opts.verbose:
  -                    continue
  -                print(spider)
  -                for method in sorted(methods):
  -                    print('  * %s' % method)
  -        else:
  -            start = time.time()
  -            self.crawler_process.start()
  -            stop = time.time()
  -
  -            result.printErrors()
  -            result.printSummary(start, stop)
  -            self.exitcode = int(not result.wasSuccessful())
  +            # start checks
  +            if opts.list:
  +                for spider, methods in sorted(contract_reqs.items()):
  +                    if not methods and not opts.verbose:
  +                        continue
  +                    print(spider)
  +                    for method in sorted(methods):
  +                        print('  * %s' % method)
  +            else:
  +                start = time.time()
  +                self.crawler_process.start()
  +                stop = time.time()
  +
  +                result.printErrors()
  +                result.printSummary(start, stop)
  +                self.exitcode = int(not result.wasSuccessful())
  
verification_info: {"golden_diff": "diff --git a/scrapy/commands/check.py b/scrapy/commands/check.py\n--- a/scrapy/commands/check.py\n+++ b/scrapy/commands/check.py\n@@ -78,19 +78,19 @@\n                 elif tested_methods:\n                     self.crawler_process.crawl(spidercls)\n \n-        # start checks\n-        if opts.list:\n-            for spider, methods in sorted(contract_reqs.items()):\n-                if not methods and not opts.verbose:\n-                    continue\n-                print(spider)\n-                for method in sorted(methods):\n-                    print('  * %s' % method)\n-        else:\n-            start = time.time()\n-            self.crawler_process.start()\n-            stop = time.time()\n-\n-            result.printErrors()\n-            result.printSummary(start, stop)\n-            self.exitcode = int(not result.wasSuccessful())\n+            # start checks\n+            if opts.list:\n+                for spider, methods in sorted(contract_reqs.items()):\n+                    if not methods and not opts.verbose:\n+                        continue\n+                    print(spider)\n+                    for method in sorted(methods):\n+                        print('  * %s' % method)\n+            else:\n+                start = time.time()\n+                self.crawler_process.start()\n+                stop = time.time()\n+\n+                result.printErrors()\n+                result.printSummary(start, stop)\n+                self.exitcode = int(not result.wasSuccessful())\n", "issue": "SCRAPY_CHECK is not set while running contract\n### Description\r\n\r\nHi, it seems that #3739 is not doing what the [documentation describe](https://docs.scrapy.org/en/latest/topics/contracts.html#detecting-check-runs):\r\n\r\n`os.environ.get('SCRAPY_CHECK')` is returning `None` in my contract check.\r\n\r\n### Steps to Reproduce\r\n\r\n1. Create a project from scratch\r\n2. Add a random spider\r\n3. Contract code is as follow\r\n```\r\n    def parse(self, response):\r\n        \"\"\"\r\n        @url http://www.amazon.com/s?field-keywords=selfish+gene\r\n        @returns requests 1 1\r\n        \"\"\"\r\n        print(\"test\", os.environ.get('SCRAPY_CHECK'))\r\n        if os.environ.get('SCRAPY_CHECK'):\r\n            yield scrapy.Request(url=\"next_url\")\r\n```\r\n\r\n**Expected behavior:** Request should be yielded as per the documentation\r\n\r\n**Actual behavior:** Nothing happen\r\n\r\n**Reproduces how often:** In my local project and with fresh project\r\n\r\n### Versions\r\n\r\nWindows\r\n```\r\n(globenv) C:\\Users\\johnl>scrapy version --verbose\r\nScrapy       : 1.8.0\r\nlxml         : 4.4.1.0\r\nlibxml2      : 2.9.5\r\ncssselect    : 1.1.0\r\nparsel       : 1.5.2\r\nw3lib        : 1.21.0\r\nTwisted      : 19.10.0\r\nPython       : 3.7.4 (tags/v3.7.4:e09359112e, Jul  8 2019, 19:29:22) [MSC v.1916 32 bit (Intel)]\r\npyOpenSSL    : 19.0.0 (OpenSSL 1.1.1c  28 May 2019)\r\ncryptography : 2.7\r\nPlatform     : Windows-10-10.0.18362-SP0\r\n```\r\n\r\nLinux\r\n```\r\nscrapy version --verbose\r\nScrapy       : 1.8.0\r\nlxml         : 4.4.1.0\r\nlibxml2      : 2.9.9\r\ncssselect    : 1.1.0\r\nparsel       : 1.5.2\r\nw3lib        : 1.21.0\r\nTwisted      : 19.7.0\r\nPython       : 3.6.8 (default, Oct  7 2019, 12:59:55) - [GCC 8.3.0]\r\npyOpenSSL    : 19.0.0 (OpenSSL 1.1.1d  10 Sep 2019)\r\ncryptography : 2.8\r\nPlatform     : Linux-4.4.0-18362-Microsoft-x86_64-with-Ubuntu-18.04-bionic\r\n```\r\n\n", "before_files": [{"content": "import time\nfrom collections import defaultdict\nfrom unittest import TextTestRunner, TextTestResult as _TextTestResult\n\nfrom scrapy.commands import ScrapyCommand\nfrom scrapy.contracts import ContractsManager\nfrom scrapy.utils.misc import load_object, set_environ\nfrom scrapy.utils.conf import build_component_list\n\n\nclass TextTestResult(_TextTestResult):\n    def printSummary(self, start, stop):\n        write = self.stream.write\n        writeln = self.stream.writeln\n\n        run = self.testsRun\n        plural = \"s\" if run != 1 else \"\"\n\n        writeln(self.separator2)\n        writeln(\"Ran %d contract%s in %.3fs\" % (run, plural, stop - start))\n        writeln()\n\n        infos = []\n        if not self.wasSuccessful():\n            write(\"FAILED\")\n            failed, errored = map(len, (self.failures, self.errors))\n            if failed:\n                infos.append(\"failures=%d\" % failed)\n            if errored:\n                infos.append(\"errors=%d\" % errored)\n        else:\n            write(\"OK\")\n\n        if infos:\n            writeln(\" (%s)\" % (\", \".join(infos),))\n        else:\n            write(\"\\n\")\n\n\nclass Command(ScrapyCommand):\n    requires_project = True\n    default_settings = {'LOG_ENABLED': False}\n\n    def syntax(self):\n        return \"[options] <spider>\"\n\n    def short_desc(self):\n        return \"Check spider contracts\"\n\n    def add_options(self, parser):\n        ScrapyCommand.add_options(self, parser)\n        parser.add_option(\"-l\", \"--list\", dest=\"list\", action=\"store_true\",\n                          help=\"only list contracts, without checking them\")\n        parser.add_option(\"-v\", \"--verbose\", dest=\"verbose\", default=False, action='store_true',\n                          help=\"print contract tests for all spiders\")\n\n    def run(self, args, opts):\n        # load contracts\n        contracts = build_component_list(self.settings.getwithbase('SPIDER_CONTRACTS'))\n        conman = ContractsManager(load_object(c) for c in contracts)\n        runner = TextTestRunner(verbosity=2 if opts.verbose else 1)\n        result = TextTestResult(runner.stream, runner.descriptions, runner.verbosity)\n\n        # contract requests\n        contract_reqs = defaultdict(list)\n\n        spider_loader = self.crawler_process.spider_loader\n\n        with set_environ(SCRAPY_CHECK='true'):\n            for spidername in args or spider_loader.list():\n                spidercls = spider_loader.load(spidername)\n                spidercls.start_requests = lambda s: conman.from_spider(s, result)\n\n                tested_methods = conman.tested_methods_from_spidercls(spidercls)\n                if opts.list:\n                    for method in tested_methods:\n                        contract_reqs[spidercls.name].append(method)\n                elif tested_methods:\n                    self.crawler_process.crawl(spidercls)\n\n        # start checks\n        if opts.list:\n            for spider, methods in sorted(contract_reqs.items()):\n                if not methods and not opts.verbose:\n                    continue\n                print(spider)\n                for method in sorted(methods):\n                    print('  * %s' % method)\n        else:\n            start = time.time()\n            self.crawler_process.start()\n            stop = time.time()\n\n            result.printErrors()\n            result.printSummary(start, stop)\n            self.exitcode = int(not result.wasSuccessful())\n", "path": "scrapy/commands/check.py"}], "after_files": [{"content": "import time\nfrom collections import defaultdict\nfrom unittest import TextTestRunner, TextTestResult as _TextTestResult\n\nfrom scrapy.commands import ScrapyCommand\nfrom scrapy.contracts import ContractsManager\nfrom scrapy.utils.misc import load_object, set_environ\nfrom scrapy.utils.conf import build_component_list\n\n\nclass TextTestResult(_TextTestResult):\n    def printSummary(self, start, stop):\n        write = self.stream.write\n        writeln = self.stream.writeln\n\n        run = self.testsRun\n        plural = \"s\" if run != 1 else \"\"\n\n        writeln(self.separator2)\n        writeln(\"Ran %d contract%s in %.3fs\" % (run, plural, stop - start))\n        writeln()\n\n        infos = []\n        if not self.wasSuccessful():\n            write(\"FAILED\")\n            failed, errored = map(len, (self.failures, self.errors))\n            if failed:\n                infos.append(\"failures=%d\" % failed)\n            if errored:\n                infos.append(\"errors=%d\" % errored)\n        else:\n            write(\"OK\")\n\n        if infos:\n            writeln(\" (%s)\" % (\", \".join(infos),))\n        else:\n            write(\"\\n\")\n\n\nclass Command(ScrapyCommand):\n    requires_project = True\n    default_settings = {'LOG_ENABLED': False}\n\n    def syntax(self):\n        return \"[options] <spider>\"\n\n    def short_desc(self):\n        return \"Check spider contracts\"\n\n    def add_options(self, parser):\n        ScrapyCommand.add_options(self, parser)\n        parser.add_option(\"-l\", \"--list\", dest=\"list\", action=\"store_true\",\n                          help=\"only list contracts, without checking them\")\n        parser.add_option(\"-v\", \"--verbose\", dest=\"verbose\", default=False, action='store_true',\n                          help=\"print contract tests for all spiders\")\n\n    def run(self, args, opts):\n        # load contracts\n        contracts = build_component_list(self.settings.getwithbase('SPIDER_CONTRACTS'))\n        conman = ContractsManager(load_object(c) for c in contracts)\n        runner = TextTestRunner(verbosity=2 if opts.verbose else 1)\n        result = TextTestResult(runner.stream, runner.descriptions, runner.verbosity)\n\n        # contract requests\n        contract_reqs = defaultdict(list)\n\n        spider_loader = self.crawler_process.spider_loader\n\n        with set_environ(SCRAPY_CHECK='true'):\n            for spidername in args or spider_loader.list():\n                spidercls = spider_loader.load(spidername)\n                spidercls.start_requests = lambda s: conman.from_spider(s, result)\n\n                tested_methods = conman.tested_methods_from_spidercls(spidercls)\n                if opts.list:\n                    for method in tested_methods:\n                        contract_reqs[spidercls.name].append(method)\n                elif tested_methods:\n                    self.crawler_process.crawl(spidercls)\n\n            # start checks\n            if opts.list:\n                for spider, methods in sorted(contract_reqs.items()):\n                    if not methods and not opts.verbose:\n                        continue\n                    print(spider)\n                    for method in sorted(methods):\n                        print('  * %s' % method)\n            else:\n                start = time.time()\n                self.crawler_process.start()\n                stop = time.time()\n\n                result.printErrors()\n                result.printSummary(start, stop)\n                self.exitcode = int(not result.wasSuccessful())\n", "path": "scrapy/commands/check.py"}]}