从源码开始学习Scrapy系列04-check指令

前言

上一章我们学习了check指令以及指令的运行机制,这一章我们学习check指令,这个指令是用于执行 Spider 的Conract检查,Contract 的作用就是通过一系列的简单约定来替代单元测试

代码调试

打开check模块,直接定位到run方法

1.获取系统基础的contracts类路径

contracts = build_component_list(self.settings.getwithbase('SPIDER_CONTRACTS'))

2.使用ContractManager进行contract加载

conman = ContractsManager(load_object(c) for c in contracts)

3.实例化一个TextTestRunner对象

conman = ContractsManager(load_object(c) for c in contracts)

4.返回处理后的TextTestRunner对象

result = TextTestResult(runner.stream, runner.descriptions, runner.verbosity)

5.实例化爬虫加载器,并获取测试方法

spider_loader = self.crawler_process.spider_loader

for spidername in args or spider_loader.list():
    spidercls = spider_loader.load(spidername)
    spidercls.start_requests = lambda s: conman.from_spider(s, result)
    # 获取测试方法
    tested_methods = conman.tested_methods_from_spidercls(spidercls)
    if opts.list:
        for method in tested_methods:
            contract_reqs[spidercls.name].append(method)
    elif tested_methods:        #如果有测试方法,则进行crawl方法
        self.crawler_process.crawl(spidercls)

6.开始检验,并输出结果

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())
基本逻辑就是这样的,不是重点部分,先溜了。。。

猜你喜欢

转载自blog.csdn.net/wang1472jian1110/article/details/80352847