|
| 1 | +import os |
| 2 | + |
| 3 | +import pytest |
| 4 | +from strands import Agent |
| 5 | +from strands_tools import generate_image, image_reader |
| 6 | + |
| 7 | + |
| 8 | +@pytest.fixture |
| 9 | +def agent(): |
| 10 | + """Agent with image generation and reader tools.""" |
| 11 | + return Agent(tools=[generate_image, image_reader]) |
| 12 | + |
| 13 | + |
| 14 | +def test_generate_and_read_image(agent, tmp_path): |
| 15 | + # 1. Generate a lovely dog picture |
| 16 | + prompt = "A corgi riding a skateboard in Times Square" |
| 17 | + image_gen_result = agent.tool.generate_image( |
| 18 | + prompt=prompt, |
| 19 | + model_id="stability.stable-image-core-v1:1", |
| 20 | + aspect_ratio="1:1", |
| 21 | + output_format="png", |
| 22 | + negative_prompt="blurry, low quality", |
| 23 | + ) |
| 24 | + assert image_gen_result["status"] == "success", str(image_gen_result) |
| 25 | + content = image_gen_result["content"] |
| 26 | + |
| 27 | + # Extract and verify image bytes from result |
| 28 | + found_image = None |
| 29 | + for item in content: |
| 30 | + if "image" in item and "source" in item["image"]: |
| 31 | + found_image = item["image"]["source"]["bytes"] |
| 32 | + assert isinstance(found_image, bytes), "Returned image bytes are not 'bytes' type" |
| 33 | + assert len(found_image) > 1000, "Returned image is too small to be valid" |
| 34 | + break |
| 35 | + assert found_image is not None, "No image bytes found in result" |
| 36 | + |
| 37 | + # Save image to temp directory |
| 38 | + image_path = tmp_path / "generated.png" |
| 39 | + with open(image_path, "wb") as f: |
| 40 | + f.write(found_image) |
| 41 | + |
| 42 | + # 2. use image_reader tool to verify it's a real image |
| 43 | + assert os.path.exists(image_path), f"Image file not found at {image_path}" |
| 44 | + read_result = agent.tool.image_reader(image_path=str(image_path)) |
| 45 | + assert read_result["status"] == "success", str(read_result) |
| 46 | + image_content = read_result["content"][0]["image"] |
| 47 | + assert image_content["format"] == "png" |
| 48 | + assert isinstance(image_content["source"]["bytes"], bytes) |
| 49 | + assert len(image_content["source"]["bytes"]) > 1000 |
| 50 | + |
| 51 | + # 3. test semantic usage to check if it recognizes dog/corgi |
| 52 | + semantic_result = agent(f"What is the image at `{image_path}`") |
| 53 | + assert "dog" in str(semantic_result).lower() or "corgi" in str(semantic_result).lower() |
0 commit comments