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
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Testing Business Programs Without Constructing Domain Objects
  • Why Standard Test Automation Misses the Failures That Matter in AI Agent Systems
  • More Tests, More Confidence? Test Suites Are Investment Portfolios
  • One of Waterfall's Most Resilient Artifacts

Trending

  • Should Developers Switch From SQLite to DuckDB?
  • SSRF Prevention in C#: Securing File Imports From User-Supplied URLs
  • Searching Kafka Without an Index: Lessons From Building Message Search for Kafdrop
  • Delta Lake UniForm to Snowflake: Cross-Platform Table Access Without a Second Copy

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Testing, Deployment, and Maintenance
  3. Testing, Tools, and Frameworks
  4. Properly Unit Testing Scrapy Spiders

Properly Unit Testing Scrapy Spiders

By 
Kelvin Tan
·
Dec. 04, 14 · Interview
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
11.2K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

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

  • Testing Business Programs Without Constructing Domain Objects
  • Why Standard Test Automation Misses the Failures That Matter in AI Agent Systems
  • More Tests, More Confidence? Test Suites Are Investment Portfolios
  • One of Waterfall's Most Resilient Artifacts

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

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 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook