- 
                Notifications
    You must be signed in to change notification settings 
- Fork 16
scrapy-loader-upkeep migration #12
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
          
     Open
      
      
            BurnzZ
  wants to merge
  7
  commits into
  master
  
    
      
        
          
  
    
      Choose a base branch
      
     
    
      
        
      
      
        
          
          
        
        
          
            
              
              
              
  
           
        
        
          
            
              
              
           
        
       
     
  
        
          
            
          
            
          
        
       
    
      
from
scrapy-loader-upkeep
  
      
      
   
  
    
  
  
  
 
  
      
    base: master
Could not load branches
            
              
  
    Branch not found: {{ refName }}
  
            
                
      Loading
              
            Could not load tags
            
            
              Nothing to show
            
              
  
            
                
      Loading
              
            Are you sure you want to change the base?
            Some commits from the old base branch may be removed from the timeline,
            and old review comments may become outdated.
          
          
  
     Open
                    Changes from all commits
      Commits
    
    
            Show all changes
          
          
            7 commits
          
        
        Select commit
          Hold shift + click to select a range
      
      05ddbc0
              
                initial migration of Burnzz/scrapy-loader-upkeep code
              
              
                BurnzZ 1df3891
              
                add __init__.py to tests/
              
              
                BurnzZ 42296f2
              
                fix failing tests by combining _get_xpathvalues() and _get_cssvalues()
              
              
                BurnzZ 57f5308
              
                streamline get_selector_values() and add tests to it
              
              
                BurnzZ d4d3671
              
                add tests to stat logging feature
              
              
                BurnzZ 1713944
              
                remove docstring in write_to_stats() causing sphinx build to fail
              
              
                BurnzZ dd96b7e
              
                rename field_tracker into field_position_tracker for more clarity
              
              
                BurnzZ File filter
Filter by extension
Conversations
          Failed to load comments.   
        
        
          
      Loading
        
  Jump to
        
          Jump to file
        
      
      
          Failed to load files.   
        
        
          
      Loading
        
  Diff view
Diff view
There are no files selected for viewing
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
              Empty file.
          
    
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,175 @@ | ||
| import pytest | ||
| from unittest import mock | ||
|  | ||
| from itemloaders import ItemLoader | ||
| from parsel import Selector | ||
|  | ||
|  | ||
| def test_write_to_stats_with_uninjected_stat_dependency(): | ||
| """It should not call stats when the stat dependency isn't available.""" | ||
|  | ||
| loader = ItemLoader() | ||
| loader.stats = mock.MagicMock() | ||
| loader.stats.__bool__.return_value = False # don't pass the if-condition | ||
|  | ||
| assert loader.write_to_stats("field_name", "parsed_data", 0, "xpath") == None | ||
| assert not loader.stats.inc_value.called | ||
|  | ||
|  | ||
| def test_write_to_stats_with_no_parsed_data(): | ||
| """It should not call stats when parsing the data returned None.""" | ||
|  | ||
| loader = ItemLoader() | ||
| loader.stats = mock.Mock() | ||
|  | ||
| parsed_data = None | ||
| expected_stat_key = "parser/ItemLoader/field_name/css/0/missing" | ||
|  | ||
| assert loader.write_to_stats("field_name", parsed_data, 0, "css") == None | ||
| loader.stats.inc_value.assert_called_once_with(expected_stat_key) | ||
|  | ||
|  | ||
| def test_write_to_stats_with_no_field_name(): | ||
| """It should not call stats when the 'field_name' passed is None.""" | ||
|  | ||
| loader = ItemLoader() | ||
| loader.stats = mock.Mock() | ||
|  | ||
| assert loader.write_to_stats(None, "sample data", 0, "css") == None | ||
| loader.stats.inc_value.assert_not_called() | ||
|  | ||
|  | ||
| def test_write_to_stats(): | ||
| """It should incremenent the correct key in the stat.""" | ||
|  | ||
| loader = ItemLoader() | ||
| loader.stats = mock.MagicMock() | ||
|  | ||
| expected_stat_key = "parser/ItemLoader/field_name/css/0" | ||
|  | ||
| # Rules with values | ||
| assert loader.write_to_stats("field_name", "parsed_data", 123, "css") == None | ||
|  | ||
| # Rules that hasn't rendered any values | ||
| assert loader.write_to_stats("field_name", None, 456, "css") == None | ||
| assert loader.write_to_stats("field_name", [], 789, "css") == None | ||
|  | ||
| loader.stats.inc_value.assert_has_calls( | ||
| [ | ||
| mock.call("parser/ItemLoader/field_name/css/123"), | ||
| mock.call("parser/ItemLoader/field_name/css/456/missing"), | ||
| mock.call("parser/ItemLoader/field_name/css/789/missing"), | ||
| ] | ||
| ) | ||
|  | ||
|  | ||
| TEST_HTML_BODY = """ | ||
| <html> | ||
| <title>This is a title</title> | ||
| <body> | ||
| <article> | ||
| <h2>Product #1</h2> | ||
| <span class='price'>$1.23</span> | ||
| </article> | ||
|  | ||
| <article> | ||
| <div class='product-title'>Product #2</div> | ||
| <span class='price'>$9.99</span> | ||
| </article> | ||
| </body> | ||
| </html> | ||
| """ | ||
|  | ||
|  | ||
| class TestItemLoader(ItemLoader): | ||
| pass | ||
|  | ||
|  | ||
| @pytest.fixture() | ||
| def loader(): | ||
| mock_stats = mock.MagicMock() | ||
| selector = Selector(text=TEST_HTML_BODY) | ||
| loader = TestItemLoader(selector=selector, stats=mock_stats) | ||
| return loader | ||
|  | ||
|  | ||
| # NOTES: We'll be using the 'css' methods of ItemLoader below. The 'xpath' | ||
| # methods are also using the 'get_selector_values()' method underneath, the | ||
| # same with 'css'. So we'll assume that 'xpath' would also pass the test | ||
| # if 'css' passes. | ||
|  | ||
| # This assumption will hold true for now, since the current implementation of | ||
| # the 'css' and 'xpath' methods are just facades to the 'get_selector_values()'. | ||
|  | ||
|  | ||
| def test_add_css_1(loader): | ||
| loader.add_css("title", "article h2::text") | ||
| loader.stats.inc_value.assert_has_calls( | ||
| [mock.call("parser/TestItemLoader/title/css/1")] | ||
| ) | ||
| assert loader.stats.inc_value.call_count == 1 | ||
|  | ||
|  | ||
| def test_add_css_2(loader): | ||
| loader.add_css("title", ["article h2::text", "article .product-title::text"]) | ||
| loader.stats.inc_value.assert_has_calls( | ||
| [ | ||
| mock.call("parser/TestItemLoader/title/css/1"), | ||
| mock.call("parser/TestItemLoader/title/css/2"), | ||
| ] | ||
| ) | ||
| assert loader.stats.inc_value.call_count == 2 | ||
|  | ||
|  | ||
| def test_add_css_3_missing(loader): | ||
| loader.add_css("title", "h1::text") # The <h1> doesn't exist at all. | ||
| loader.stats.inc_value.assert_has_calls( | ||
| [mock.call("parser/TestItemLoader/title/css/1/missing")] | ||
| ) | ||
| assert loader.stats.inc_value.call_count == 1 | ||
|  | ||
|  | ||
| def test_multiple_1(loader): | ||
| loader.add_css("title", "h2::text") | ||
| loader.add_css("title", ["article h2::text", "article .product-title::text"]) | ||
| loader.stats.inc_value.assert_has_calls( | ||
| [ | ||
| mock.call("parser/TestItemLoader/title/css/1"), | ||
| mock.call("parser/TestItemLoader/title/css/2"), | ||
| mock.call("parser/TestItemLoader/title/css/3"), | ||
| ] | ||
| ) | ||
| assert loader.stats.inc_value.call_count == 3 | ||
|  | ||
|  | ||
| def test_multiple_1_with_name(loader): | ||
| loader.add_css("title", "h2::text", name="title from h2") | ||
| loader.add_css( | ||
| "title", | ||
| ["article h2::text", "article .product-title::text"], | ||
| name="title from article", | ||
| ) | ||
| loader.stats.inc_value.assert_has_calls( | ||
| [ | ||
| mock.call("parser/TestItemLoader/title/css/1/title from h2"), | ||
| mock.call("parser/TestItemLoader/title/css/2/title from article"), | ||
| mock.call("parser/TestItemLoader/title/css/3/title from article"), | ||
| ] | ||
| ) | ||
| assert loader.stats.inc_value.call_count == 3 | ||
|  | ||
|  | ||
| def test_multiple_2_with_name(loader): | ||
| loader.add_css("title", "h2::text", name="title from h2") | ||
| loader.add_xpath("title", "//article/h2/text()", name="title from article") | ||
| loader.add_css("title", "article .product-title::text") | ||
| loader.add_xpath("title", "//aside/h1/text()", name="title from aside") | ||
| loader.stats.inc_value.assert_has_calls( | ||
| [ | ||
| mock.call("parser/TestItemLoader/title/css/1/title from h2"), | ||
| mock.call("parser/TestItemLoader/title/xpath/1/title from article"), | ||
| mock.call("parser/TestItemLoader/title/css/2"), | ||
| mock.call("parser/TestItemLoader/title/xpath/2/title from aside/missing"), | ||
| ] | ||
| ) | ||
| assert loader.stats.inc_value.call_count == 4 | 
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
  Add this suggestion to a batch that can be applied as a single commit.
  This suggestion is invalid because no changes were made to the code.
  Suggestions cannot be applied while the pull request is closed.
  Suggestions cannot be applied while viewing a subset of changes.
  Only one suggestion per line can be applied in a batch.
  Add this suggestion to a batch that can be applied as a single commit.
  Applying suggestions on deleted lines is not supported.
  You must change the existing code in this line in order to create a valid suggestion.
  Outdated suggestions cannot be applied.
  This suggestion has been applied or marked resolved.
  Suggestions cannot be applied from pending reviews.
  Suggestions cannot be applied on multi-line comments.
  Suggestions cannot be applied while the pull request is queued to merge.
  Suggestion cannot be applied right now. Please check back later.
  
    
  
    
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This makes itemloaders depend on scrapy.stats, at least as far as interface is concerned. Do you think we can avoid it? I can see 2 main ways:
We can also start decoupling scrapy Stats from scrapy, but I'd rather not do this now.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Hi @kmike , the itemloaders accept Scrapy's stats instance via DI and could work without it, as per this.
Accepting the actual Scrapy stats instance is crucial for the loader's usage to be logged at the end of a job (and be logged in Scrapy Cloud's stats-tab), like this:
I'm all good for making it like a
defaultdict(int)to function like the stat'sinc_value, as long as we can pass it out to Scrapy's logging system.However, I might be missing something? 🤔Is there another way to circumvent injecting Scrapy's stats to the itemloaders and still log the parser's usage?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I guess @kmike 's point here is the implicit dependency.
Even though, scrapy is not a requirement, we require a direct dependency from scrapy..
So, maybe a solution would be to create some sort of adapter (another one).
Though, I somehow foresee a problem.
If we allow
ItemLoaderto be extended withupkeep, we'll need to makeupkeepthe default base class for scrapy, as scrapy users we'll keep using scrapy'sItemLoaderwhich is an extension to this one.So, if they import this extension instead of scrapy's, they'll be losing scrapy's behavior.