DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
View Events Video Library
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Migrate, Modernize and Build Java Web Apps on Azure: This live workshop will cover methods to enhance Java application development workflow.

Modern Digital Website Security: Prepare to face any form of malicious web activity and enable your sites to optimally serve your customers.

Kubernetes in the Enterprise: The latest expert insights on scaling, serverless, Kubernetes-powered AI, cluster security, FinOps, and more.

E-Commerce Development Essentials: Considering starting or working on an e-commerce business? Learn how to create a backend that scales.

Related

  • Any Version of the Test Pyramid Is a Misconception – Don’t Use Anyone
  • That Can Not Be Tested!: Spring Cache and Retry
  • Improving Unit Test Maintainability
  • Selecting the Right Automated Tests

Trending

  • How to Submit a Post to DZone
  • What’s New Between Java 17 and Java 21?
  • API-Driven Integration
  • How To Use KubeDB and Postgres Sidecar for Database Integrations in Kubernetes
  1. DZone
  2. Testing, Deployment, and Maintenance
  3. Testing, Tools, and Frameworks
  4. Properly Unit Testing Scrapy Spiders

Properly Unit Testing Scrapy Spiders

Kelvin Tan user avatar by
Kelvin Tan
·
Dec. 04, 14 · Interview
Like (0)
Save
Tweet
Share
10.0K Views

Join the DZone community and get the full member experience.

Join For Free

Scrapy, being based on Twisted, introduces an incredible host of obstacles to easily and efficiently writing self-contained unit tests:

1. You can't call reactor.run() multiple times
2. You can't stop the reactor multiple times, so you can't blindly call "crawler.signals.connect(reactor.stop, signal=signals.spider_closed)"
3. Reactor runs in its own thread, so your failed assertions won't make it to the main unittest thread, so test failures will be thrown as assertion errors but unittest doesn't know about them

To get around these hurdles, I created a BaseScrapyTestCase class that uses tl.testing's ThreadAwareTestCase and the following workarounds.

class BaseScrapyTestCase(ThreadAwareTestCase):
    in_suite = False
    def setUp(self):
        self.last_crawler = None
        self.settings = get_project_settings()

    def run_reactor(self, called_from_suite=False):
        if not called_from_suite and BaseScrapyTestCase.in_suite:
            return
        log.start()
        self.last_crawler.signals.connect(reactor.stop, signal=signals.spider_closed)
        reactor.run()

    def queue_spider(self, spider, callback):
        crawler = Crawler(self.settings)
        self.last_crawler = crawler
        crawler.signals.connect(callback, signal=signals.spider_closed)
        crawler.configure()
        crawler.crawl(spider)
        crawler.start()
        return crawler

    def wrap_asserts(self, fn):
        with ThreadJoiner(1):
            self.run_in_thread(fn)

You'll use it like so:

class SimpleScrapyTestCase(BaseScrapyTestCase):
    def test_suite(self):
        BaseScrapyTestCase.in_suite = True
        self.do_test_simple()
        self.run_reactor(True)
    def do_test_simple(self):
        spider = Spider("site.com")
        def _fn():
            def __fn():
                self.assertTrue(False)
            self.wrap_asserts(__fn)
        self.queue_spider(spider, _fn)
        self.run_reactor()
 

1. Call run_reactor() at the end of test method.
2. You have to place your assertions in its own function which gets called in a ThreadJoiner so that unittest knows about assertion failures.
3. If you're testing multiple spiders, just call queue_spider() for each, and run_reactor() at the end.
4. BaseScrapyTestCase keeps track of the crawlers created, and makes sure to only attach a reactor.stop signal to the last one.

Let me know if you come up with a better/more elegant way of testing scrapy spiders!


unit test

Published at DZone with permission of Kelvin Tan. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Any Version of the Test Pyramid Is a Misconception – Don’t Use Anyone
  • That Can Not Be Tested!: Spring Cache and Retry
  • Improving Unit Test Maintainability
  • Selecting the Right Automated Tests

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: