Skip to content
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

⚡️ Speed up method Session.__getstate__ by 11% #10

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

codeflash-ai[bot]
Copy link

@codeflash-ai codeflash-ai bot commented Dec 22, 2024

📄 11% (0.11x) speedup for Session.__getstate__ in src/requests/sessions.py

⏱️ Runtime : 309 microseconds 279 microseconds (best of 218 runs)

📝 Explanation and details

Key Optimizations:

Correctness verification report:

Test Status
⚙️ Existing Unit Tests 🔘 None Found
🌀 Generated Regression Tests 27 Passed
⏪ Replay Tests 🔘 None Found
🔎 Concolic Coverage Tests 🔘 None Found
📊 Tests Coverage 100.0%
🌀 Generated Regression Tests Details
from collections import OrderedDict

# imports
import pytest  # used for our unit tests
from src.requests.adapters import HTTPAdapter
from src.requests.cookies import cookiejar_from_dict
from src.requests.hooks import default_hooks
from src.requests.models import DEFAULT_REDIRECT_LIMIT
from src.requests.sessions import Session
from src.requests.utils import default_headers


# function to test
class SessionRedirectMixin:
    pass
from src.requests.sessions import Session


# unit tests
def test_basic_functionality():
    # Test with default attributes
    session = Session()
    codeflash_output = session.__getstate__()


def test_non_existent_attributes():
    # Test with non-existent attributes in __attrs__
    session = Session()
    session.__attrs__.append('non_existent_attr')
    codeflash_output = session.__getstate__()

def test_complex_attribute_values():
    # Test with complex attribute values
    session = Session()
    session.headers['Custom-Header'] = 'Value'
    session.cookies.set('test_cookie', 'cookie_value')
    codeflash_output = session.__getstate__()

def test_edge_cases_with_attribute_values():
    # Test with None values
    session = Session()
    session.auth = None
    codeflash_output = session.__getstate__()

    # Test with empty collections
    session.proxies = {}
    codeflash_output = session.__getstate__()

    # Test with large data structures
    session.params = {f'key{i}': f'value{i}' for i in range(1000)}
    codeflash_output = session.__getstate__()

def test_large_scale():
    # Test with large number of attributes
    session = Session()
    session.params = {f'key{i}': f'value{i}' for i in range(1000)}
    codeflash_output = session.__getstate__()

def test_deterministic_output():
    # Test that output is consistent
    session = Session()
    codeflash_output = session.__getstate__()
    codeflash_output = session.__getstate__()

def test_attribute_mutability():
    # Test that attributes are not modified
    session = Session()
    original_headers = session.headers.copy()
    session.__getstate__()

def test_integration_with_pickle():
    import pickle

    # Test integration with pickle
    session = Session()
    serialized = pickle.dumps(session)
    deserialized = pickle.loads(serialized)
    codeflash_output = deserialized.__getstate__()

def test_custom_attributes():
    # Test with custom attributes
    session = Session()
    session.custom_attr = 'custom_value'
    session.__attrs__.append('custom_attr')
    codeflash_output = session.__getstate__()

def test_error_handling():
    # Test unexpected errors during attribute access
    session = Session()
    session.__attrs__.append('error_attr')

    def error_attr():
        raise Exception("Unexpected error")

    session.error_attr = property(error_attr)
    codeflash_output = session.__getstate__()
# codeflash_output is used to check that the output of the original code is the same as that of the optimized code.

from collections import OrderedDict

# imports
import pytest  # used for our unit tests
from src.requests.adapters import HTTPAdapter
from src.requests.cookies import cookiejar_from_dict
from src.requests.hooks import default_hooks
from src.requests.models import DEFAULT_REDIRECT_LIMIT
from src.requests.sessions import Session
from src.requests.utils import default_headers

# unit tests

def test_basic_functionality():
    # Test the function with default attributes
    session = Session()
    session.__attrs__ = ['headers', 'auth', 'proxies', 'hooks', 'params', 'stream', 'verify', 'cert', 'max_redirects', 'trust_env', 'cookies', 'adapters']
    codeflash_output = session.__getstate__()


def test_empty_attrs():
    # Test the function with an empty __attrs__ list
    session = Session()
    session.__attrs__ = []
    codeflash_output = session.__getstate__()

def test_non_existent_attrs():
    # Test the function with non-existent attributes in __attrs__
    session = Session()
    session.__attrs__ = ['non_existent_attr']
    codeflash_output = session.__getstate__()

def test_mixed_attribute_types():
    # Test the function with attributes of various types
    session = Session()
    session.some_list = [1, 2, 3]
    session.some_dict = {'key': 'value'}
    session.some_int = 42
    session.__attrs__ = ['some_list', 'some_dict', 'some_int']
    codeflash_output = session.__getstate__()

def test_large_number_of_attributes():
    # Test the function with a large number of attributes
    session = Session()
    session.__attrs__ = [f'attr_{i}' for i in range(1000)]
    for attr in session.__attrs__:
        setattr(session, attr, attr)
    codeflash_output = session.__getstate__()
    for attr in session.__attrs__:
        pass

def test_nested_attributes():
    # Test the function with nested attributes
    class Nested:
        def __init__(self):
            self.nested_attr = 'nested_value'
    session = Session()
    session.nested = Nested()
    session.__attrs__ = ['nested']
    codeflash_output = session.__getstate__()

def test_special_character_attributes():
    # Test the function with attributes that have special characters
    session = Session()
    session.__setattr__('attr with space', 'value')
    session.__attrs__ = ['attr with space']
    codeflash_output = session.__getstate__()

def test_attributes_with_default_values():
    # Test the function with attributes that have default values
    session = Session()
    session.__attrs__ = ['verify']
    codeflash_output = session.__getstate__()

def test_attributes_with_none_values():
    # Test the function with attributes that are explicitly set to None
    session = Session()
    session.some_attr = None
    session.__attrs__ = ['some_attr']
    codeflash_output = session.__getstate__()

def test_performance_and_scalability():
    # Test the function's performance with large data samples
    session = Session()
    session.large_list = list(range(1000))
    session.__attrs__ = ['large_list']
    codeflash_output = session.__getstate__()

def test_custom_objects_as_attributes():
    # Test the function with custom objects as attributes
    class CustomObject:
        def __init__(self, value):
            self.value = value
    session = Session()
    session.custom_obj = CustomObject('custom_value')
    session.__attrs__ = ['custom_obj']
    codeflash_output = session.__getstate__()

def test_attribute_name_collisions():
    # Test the function with potential attribute name collisions
    session = Session()
    session.__attrs__ = ['__class__']
    codeflash_output = session.__getstate__()

def test_immutable_attributes():
    # Test the function with immutable attributes
    session = Session()
    session.immutable_attr = (1, 2, 3)
    session.__attrs__ = ['immutable_attr']
    codeflash_output = session.__getstate__()

def test_attributes_with_side_effects():
    # Test the function with attributes that have side effects when accessed
    class SideEffect:
        def __init__(self):
            self.side_effect_triggered = False
        @property
        def side_effect_attr(self):
            self.side_effect_triggered = True
            return 'side_effect_value'
    session = Session()
    session.side_effect = SideEffect()
    session.__attrs__ = ['side_effect_attr']
    codeflash_output = session.__getstate__()
# codeflash_output is used to check that the output of the original code is the same as that of the optimized code.

from src.requests.sessions import Session

def test_Session___getstate__():
    assert Session.__getstate__(Session()) == {'headers': {'User-Agent': 'python-requests/2.32.3', 'Accept-Encoding': 'gzip, deflate, br', 'Accept': '*/*', 'Connection': 'keep-alive'}, 'cookies': <RequestsCookieJar[]>, 'auth': None, 'proxies': {}, 'hooks': {'response': []}, 'params': {}, 'verify': True, 'cert': None, 'adapters': OrderedDict({'https://': <src.requests.adapters.HTTPAdapter object at 0x74d1b72c09e0>, 'http://': <src.requests.adapters.HTTPAdapter object at 0x74d1b72c0b90>}), 'stream': False, 'trust_env': True, 'max_redirects': 30}

📢 Feedback on this optimization? Discord

@codeflash-ai codeflash-ai bot added the ⚡️ codeflash Optimization PR opened by Codeflash AI label Dec 22, 2024
@codeflash-ai codeflash-ai bot requested a review from alvin-r December 22, 2024 08:14
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
⚡️ codeflash Optimization PR opened by Codeflash AI
Projects
None yet
Development

Successfully merging this pull request may close these issues.

0 participants