Skip to content

Meta Ads (Facebook/Instagram) MCP server for Claude, ChatGPT, Perplexity & Cursor — the Meta node of Pipeboard’s 5-platform family (+ Google, TikTok, Snap, Reddit). Hosted remote MCP, badged Meta Business Partner, free plan — no self-hosting required.

7.1 KB
Raw Blame
"""Regression tests for get_ad_creatives function bug fix.

Tests for issue where get_ad_creatives would throw:
'TypeError: 'dict' object is not callable'

This was caused by trying to call ad_creative_images(creative), which was a
dictionary, not a function. That dictionary is gone (GHSA-25fp-988j-w29f).

The fix was to create extract_creative_image_urls() function and use that instead.
"""

import pytest
import json
from unittest.mock import AsyncMock, patch
from meta_ads_mcp.core.ads import get_ad_creatives


@pytest.mark.asyncio
class TestGetAdCreativesBugFix:
    """Regression test cases for the get_ad_creatives function bug fix."""
    
    async def test_get_ad_creatives_regression_fix(self):
        """Regression test: ensure get_ad_creatives works correctly and doesn't throw 'dict' object is not callable."""
        
        # Mock the make_api_request to return sample creative data
        sample_creative_data = {
            "data": [
                {
                    "id": "123456789",
                    "name": "Test Creative",
                    "status": "ACTIVE",
                    "thumbnail_url": "https://example.com/thumb.jpg",
                    "image_url": "https://example.com/image.jpg",
                    "image_hash": "abc123",
                    "object_story_spec": {
                        "page_id": "987654321",
                        "link_data": {
                            "image_hash": "abc123",
                            "link": "https://example.com",
                            "name": "Test Ad"
                        }
                    }
                }
            ]
        }
        
        with patch('meta_ads_mcp.core.ads.make_api_request', new_callable=AsyncMock) as mock_api:
            mock_api.return_value = sample_creative_data
            
            # This should NOT raise a TypeError anymore
            # Previously this would fail with: TypeError: 'dict' object is not callable
            result = await get_ad_creatives(access_token="test_token", ad_id="120228922933270272")
            
            # Parse the result
            result_data = json.loads(result)
            
            # Verify the structure is correct
            assert "data" in result_data
            assert len(result_data["data"]) == 1
            
            creative = result_data["data"][0]
            assert creative["id"] == "123456789"
            assert creative["name"] == "Test Creative"
            assert "image_urls_for_viewing" in creative
            assert isinstance(creative["image_urls_for_viewing"], list)
    
    async def test_extract_creative_image_urls_function(self):
        """Test the extract_creative_image_urls function works correctly."""
        from meta_ads_mcp.core.utils import extract_creative_image_urls
        
        # Test creative with various image URL fields
        test_creative = {
            "id": "123456789",
            "name": "Test Creative",
            "status": "ACTIVE",
            "thumbnail_url": "https://example.com/thumb.jpg",
            "image_url": "https://example.com/image.jpg",
            "image_hash": "abc123",
            "object_story_spec": {
                "page_id": "987654321",
                "link_data": {
                    "image_hash": "abc123",
                    "link": "https://example.com",
                    "name": "Test Ad",
                    "picture": "https://example.com/picture.jpg"
                }
            }
        }
        
        urls = extract_creative_image_urls(test_creative)
        
        # Should extract URLs in order: image_url, picture, thumbnail_url (new priority order)
        expected_urls = [
            "https://example.com/image.jpg",
            "https://example.com/picture.jpg",
            "https://example.com/thumb.jpg"
        ]
        
        assert urls == expected_urls
        
        # Test with empty creative
        empty_urls = extract_creative_image_urls({})
        assert empty_urls == []
        
        # Test with duplicates (should remove them)
        duplicate_creative = {
            "image_url": "https://example.com/same.jpg",
            "thumbnail_url": "https://example.com/same.jpg",  # Same URL
        }
        unique_urls = extract_creative_image_urls(duplicate_creative)
        assert unique_urls == ["https://example.com/same.jpg"]
    
    async def test_get_ad_creatives_no_ad_id(self):
        """Test get_ad_creatives with no ad_id provided."""
        
        result = await get_ad_creatives(access_token="test_token", ad_id=None)
        result_data = json.loads(result)
        
        # The @meta_api_tool decorator wraps the result in a data field
        assert "data" in result_data
        error_data = json.loads(result_data["data"])
        assert "error" in error_data
        assert error_data["error"] == "No ad ID provided"

    async def test_get_ad_creatives_empty_data(self):
        """Test get_ad_creatives when API returns empty data."""

        empty_data = {"data": []}

        with patch('meta_ads_mcp.core.ads.make_api_request', new_callable=AsyncMock) as mock_api:
            mock_api.return_value = empty_data

            result = await get_ad_creatives(access_token="test_token", ad_id="120228922933270272")
            result_data = json.loads(result)

            assert "data" in result_data
            assert len(result_data["data"]) == 0

    async def test_get_ad_creatives_strips_standard_enhancements(self):
        """The deprecated standard_enhancements key still surfaces on GET responses;
        strip it so LLMs do not echo it into a subsequent POST (error_subcode 3858504)."""

        creatives_with_se = {
            "data": [
                {
                    "id": "creative_1",
                    "name": "Has SE",
                    "status": "ACTIVE",
                    "creative_features_spec": {
                        "standard_enhancements": {"enroll_status": "OPT_IN"},
                        "image_touchups": {"enroll_status": "OPT_IN"},
                    },
                    "degrees_of_freedom_spec": {
                        "creative_features_spec": {
                            "standard_enhancements": {"enroll_status": "OPT_IN"},
                            "profile_card": {"enroll_status": "OPT_IN"},
                        }
                    },
                }
            ]
        }

        with patch('meta_ads_mcp.core.ads.make_api_request', new_callable=AsyncMock) as mock_api:
            mock_api.return_value = creatives_with_se

            result = await get_ad_creatives(access_token="test_token", ad_id="120228922933270272")
            result_data = json.loads(result)
            creative = result_data["data"][0]

            assert "standard_enhancements" not in creative["creative_features_spec"]
            assert creative["creative_features_spec"]["image_touchups"]["enroll_status"] == "OPT_IN"
            assert "standard_enhancements" not in creative["degrees_of_freedom_spec"]["creative_features_spec"]
            assert creative["degrees_of_freedom_spec"]["creative_features_spec"]["profile_card"]["enroll_status"] == "OPT_IN"