Improve URL fragment handling in redirects #7058
                
     Open
            
            
          
      
        
          +64
        
        
          −1
        
        
          
        
      
    
  
  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.
  
    
  
    
Summary
This PR refactors the URL fragment handling logic in
SessionRedirectMixinto be more Pythonic and adds comprehensive test coverage for fragment preservation during HTTP redirects, as specified in RFC 7231 Section 7.1.2.Changes Made
Code Refactoring
src/requests/sessions.py: Simplified fragment check fromparsed.fragment == ""tonot parsed.fragmentfor more idiomatic Python codeTest Coverage Enhancement
Added 5 new test cases in
tests/test_requests.pyto ensure robust fragment handling:test_fragment_preserved_when_redirect_has_no_fragment: Verifies that the original URL fragment is preserved when redirecting to a URL without a fragmenttest_fragment_replaced_when_redirect_has_new_fragment: Confirms that fragments are properly maintained through redirect chainstest_fragment_with_no_initial_fragment: Ensures proper behavior when neither the original nor redirect URL contains a fragmenttest_fragment_multiple_redirects_preservation: Tests fragment preservation through multiple consecutive redirects (3+ hops)test_fragment_empty_string_handling: Validates correct handling of URLs ending with#(empty fragment string)Why These Changes Matter
Testing
All new tests pass and verify the correct behavior of fragment handling across various redirect scenarios.