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 Group.create_video by 14% in facebook_business/adobjects/group.py #12

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 Nov 30, 2024

📄 Group.create_video() in facebook_business/adobjects/group.py

📈 Performance improved by 14% (0.14x faster)

⏱️ Runtime went down from 9.32 milliseconds to 8.18 milliseconds (best of 13 runs)

Explanation and details

  1. Unused else Simplification: In warning function, used direct raise or warnings.warn() based on condition without nested else.

Correctness verification

The new optimized code was tested for correctness. The results are listed below.

🔘 (none found) − ⚙️ Existing Unit Tests

✅ 11 Passed − 🌀 Generated Regression Tests

(click to show generated tests)
import warnings
from unittest.mock import MagicMock, patch

# imports
import pytest  # used for our unit tests
from facebook_business import apiconfig
# function to test
from facebook_business.adobjects.abstractcrudobject import AbstractCrudObject
from facebook_business.adobjects.group import Group
from facebook_business.adobjects.objectparser import ObjectParser
from facebook_business.api import FacebookRequest
from facebook_business.exceptions import FacebookBadObjectError
from facebook_business.typechecker import TypeChecker


# unit tests
@pytest.fixture
def mock_group():
    """Fixture to create a mock Group object with necessary attributes."""
    group = Group(fbid="123", parent_id="456", api="mock_api")
    group['id'] = "123"
    group._api = "mock_api"
    return group

def test_create_video_basic(mock_group):
    """Test creating a video with basic valid parameters."""
    fields = ["id", "title"]
    params = {"title": "Test Video", "description": "This is a test video"}
    with patch.object(FacebookRequest, 'execute', return_value="mock_response") as mock_execute:
        codeflash_output = mock_group.create_video(fields=fields, params=params)
        mock_execute.assert_called_once()

def test_create_video_empty_params(mock_group):
    """Test creating a video with empty parameters."""
    with patch.object(FacebookRequest, 'execute', return_value="mock_response") as mock_execute:
        codeflash_output = mock_group.create_video()
        mock_execute.assert_called_once()





def test_create_video_pending(mock_group):
    """Test creating a video with pending set to True."""
    fields = ["id", "title"]
    params = {"title": "Test Video", "description": "This is a test video"}
    codeflash_output = mock_group.create_video(fields=fields, params=params, pending=True)


def test_create_video_strict_mode():
    """Test creating a video with STRICT_MODE set to True."""
    apiconfig.ads_api_config['STRICT_MODE'] = True
    group = Group(fbid="123", parent_id="456", api="mock_api")
    with pytest.raises(FacebookBadObjectError):
        group.create_video(success=lambda x: x, failure=lambda x: x)
    apiconfig.ads_api_config['STRICT_MODE'] = False

def test_create_video_api_error(mock_group):
    """Test handling API error response."""
    fields = ["id", "title"]
    params = {"title": "Test Video", "description": "This is a test video"}
    with patch.object(FacebookRequest, 'execute', side_effect=Exception("API Error")):
        with pytest.raises(Exception):
            mock_group.create_video(fields=fields, params=params)

def test_create_video_large_data(mock_group):
    """Test creating a video with a large number of parameters."""
    fields = ["id", "title"]
    params = {f"param_{i}": f"value_{i}" for i in range(1000)}
    with patch.object(FacebookRequest, 'execute', return_value="mock_response") as mock_execute:
        codeflash_output = mock_group.create_video(fields=fields, params=params)
        mock_execute.assert_called_once()

def test_create_video_concurrent_calls(mock_group):
    """Test multiple concurrent calls to create_video."""
    fields = ["id", "title"]
    params = {"title": "Test Video", "description": "This is a test video"}
    with patch.object(FacebookRequest, 'execute', return_value="mock_response") as mock_execute:
        responses = [mock_group.create_video(fields=fields, params=params) for _ in range(10)]
# codeflash_output is used to check that the output of the original code is the same as that of the optimized code.
import warnings
from unittest.mock import MagicMock, patch

# imports
import pytest  # used for our unit tests
from facebook_business import apiconfig
# function to test
from facebook_business.adobjects.abstractcrudobject import AbstractCrudObject
from facebook_business.adobjects.group import Group
from facebook_business.adobjects.objectparser import ObjectParser
from facebook_business.api import FacebookRequest
from facebook_business.exceptions import FacebookBadObjectError
from facebook_business.typechecker import TypeChecker


# unit tests
class TestCreateVideo:
    @pytest.fixture
    def group(self):
        # Mock the Group object
        group = Group(fbid="123", parent_id="456", api=MagicMock())
        group['id'] = "123"
        return group

    

🔘 (none found) − ⏪ Replay Tests

4. **Unused `else` Simplification**: In `warning` function, used direct `raise` or `warnings.warn()` based on condition without nested `else`.
@codeflash-ai codeflash-ai bot added the ⚡️ codeflash Optimization PR opened by Codeflash AI label Nov 30, 2024
@codeflash-ai codeflash-ai bot requested a review from Saga4 November 30, 2024 01:57
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