CodeSampleX

Пример

openpyxl 3.0.7: styles.PatternFill

Проверенный пример — pypi openpyxl 3.0.7: styles.PatternFill. Контракт выполнен на python 3.12 · linux debian/x64 · docker и пройден.

sha256:eea22364b34a7e716df15879306a09f62f2a6138a06938e8e729bd0d3e843419

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. MIT-0

Свидетельства выполнения

Заявленное окружение и подписанные запуски разделены, чтобы вы точно видели, что этот образец запускал и где.

Основа свидетельства
Подписанный контракт пройден
Квитанции проверки
1
Ключи подписи, собравшие его
1
Заявленная среда linux 24 · ubuntu · glibc 2.39 x64 pip

Среды запусков проверки

Окружение Контракт Этапы Запуск
python 3.12 · linux debian/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · python@1python:3.12-slim@sha256:09f7da3bc104…
2026-10-14

Кейс

HOW
Цель
verify openpyxl.styles.PatternFill in pkg:pypi/openpyxl@3.0.7
Пакеты
Символы
  • openpyxl.styles.PatternFill
Создан
2026-10-14T09:28:34Z

Контракт

  1. openpyxl.styles.PatternFill configures fill_type/patternType and start_color/fgColor and end_color/bgColor aliases
  2. openpyxl.styles.PatternFill serializes to and from SpreadsheetML XML trees and supports value equality
  3. openpyxl.styles.PatternFill persists cell fill styling across Workbook save and load_workbook roundtrips

Файлы

  • PROMPT.md
  • csx.json
  • requirements.txt
  • sample.py
  • spec.json
  • test/contract.py

Скачать артефакт с исходным кодом (tar.gz)

Исходный код

PROMPT.md
Clean-room public code sample — generation instructions

Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.

A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.

Goal: verify openpyxl.styles.PatternFill in pkg:pypi/openpyxl@3.0.7
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:pypi/openpyxl@3.0.7
Demonstrate these symbols/APIs:
  - openpyxl.styles.PatternFill

Rules:
  - One focused purpose; the smallest project that proves the goal.
  - Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
  - Pin every dependency with a lockfile so resolution is reproducible.
  - No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
  - No personal names, emails, company names, or project identifiers of any kind.
  - No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
  - Keep it under 200 files and 256KB packed.
csx.json
{"case":{"caseId":"case:sha256:ec6f1915b44699253568877851796655951a571db2fd50400aaad184249281d5","contract":["openpyxl.styles.PatternFill configures fill_type/patternType and start_color/fgColor and end_color/bgColor aliases","openpyxl.styles.PatternFill serializes to and from SpreadsheetML XML trees and supports value equality","openpyxl.styles.PatternFill persists cell fill styling across Workbook save and load_workbook roundtrips"],"goal":"verify openpyxl.styles.PatternFill in pkg:pypi/openpyxl@3.0.7","kind":"HOW","packages":["pkg:pypi/openpyxl@3.0.7"],"schemaVersion":1,"symbols":["openpyxl.styles.PatternFill"]},"contractCommand":["python","test/contract.py"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"pypi","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"pip","schemaVersion":1},"license":"MIT-0","packages":["pkg:pypi/openpyxl@3.0.7"],"schemaVersion":1,"subject":"pkg:pypi/openpyxl@3.0.7","symbols":["openpyxl.styles.PatternFill"],"verifierAdapter":"python@1"}
requirements.txt
et-xmlfile==2.0.0
openpyxl==3.0.7
sample.py
"""Demonstration of cell background pattern and color fill styling using openpyxl.styles.PatternFill."""

import io
from typing import Dict, Any, Optional
from openpyxl import Workbook, load_workbook
from openpyxl.styles import PatternFill, Color
from openpyxl.styles.fills import (
    FILL_SOLID,
    FILL_PATTERN_DARKDOWN,
    FILL_PATTERN_GRAY125,
)


def create_solid_fill(fg_color: str = "FFFF00") -> PatternFill:
    """Create a solid PatternFill with a specified foreground RGB hex color."""
    return PatternFill(fill_type=FILL_SOLID, start_color=fg_color, end_color=fg_color)


def create_patterned_fill(
    pattern_type: str = FILL_PATTERN_DARKDOWN,
    fg_color: str = "FF0000FF",
    bg_color: str = "FFFFFF00",
) -> PatternFill:
    """Create a patterned PatternFill using explicit Color objects for foreground and background."""
    return PatternFill(
        patternType=pattern_type,
        fgColor=Color(rgb=fg_color),
        bgColor=Color(rgb=bg_color),
    )


def apply_fills_and_roundtrip() -> Dict[str, Any]:
    """Apply PatternFill styles to workbook cells, serialize to bytes, and reload to verify persistence."""
    wb = Workbook()
    ws = wb.active
    ws.title = "Fills"

    solid = create_solid_fill("00FFCC00")
    patterned = create_patterned_fill(
        pattern_type=FILL_PATTERN_GRAY125,
        fg_color="00336699",
        bg_color="00EEEEEE",
    )

    ws["A1"] = "Solid Header"
    ws["A1"].fill = solid

    ws["B2"] = "Patterned Cell"
    ws["B2"].fill = patterned

    buffer = io.BytesIO()
    wb.save(buffer)
    buffer.seek(0)

    loaded_wb = load_workbook(buffer)
    loaded_ws = loaded_wb["Fills"]

    a1_fill = loaded_ws["A1"].fill
    b2_fill = loaded_ws["B2"].fill

    return {
        "a1_fill_type": a1_fill.fill_type,
        "a1_start_rgb": a1_fill.start_color.rgb,
        "a1_end_rgb": a1_fill.end_color.rgb,
        "b2_fill_type": b2_fill.fill_type,
        "b2_fg_rgb": b2_fill.fgColor.rgb,
        "b2_bg_rgb": b2_fill.bgColor.rgb,
    }
spec.json
{
  "schemaVersion": 1,
  "goal": "verify openpyxl.styles.PatternFill in pkg:pypi/openpyxl@3.0.7",
  "kind": "HOW",
  "packages": [
    "pkg:pypi/openpyxl@3.0.7"
  ],
  "symbols": [
    "openpyxl.styles.PatternFill"
  ]
}
test/contract.py
"""Contract verification test for openpyxl.styles.PatternFill."""

import os
import sys

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from openpyxl.styles import PatternFill, Color
from openpyxl.styles.fills import (
    FILL_NONE,
    FILL_SOLID,
    FILL_PATTERN_DARKDOWN,
    FILL_PATTERN_GRAY125,
)
import sample


def test_pattern_fill_construction_and_aliases() -> None:
    """Assertion 1: openpyxl.styles.PatternFill configures fill_type/patternType and start_color/fgColor and end_color/bgColor aliases."""
    default_fill = PatternFill()
    assert default_fill.fill_type is None
    assert default_fill.patternType is None

    solid = sample.create_solid_fill("AABBCC")
    assert isinstance(solid, PatternFill)
    assert solid.fill_type == FILL_SOLID
    assert solid.patternType == FILL_SOLID
    assert isinstance(solid.start_color, Color)
    assert solid.start_color.rgb == "00AABBCC"
    assert solid.fgColor.rgb == "00AABBCC"
    assert solid.end_color.rgb == "00AABBCC"
    assert solid.bgColor.rgb == "00AABBCC"

    patterned = sample.create_patterned_fill(
        pattern_type=FILL_PATTERN_DARKDOWN,
        fg_color="00112233",
        bg_color="00445566",
    )
    assert patterned.fill_type == FILL_PATTERN_DARKDOWN
    assert patterned.patternType == FILL_PATTERN_DARKDOWN
    assert patterned.fgColor.rgb == "00112233"
    assert patterned.start_color.rgb == "00112233"
    assert patterned.bgColor.rgb == "00445566"
    assert patterned.end_color.rgb == "00445566"


def test_pattern_fill_xml_serialization_and_equality() -> None:
    """Assertion 2: openpyxl.styles.PatternFill serializes to and from SpreadsheetML XML trees and supports value equality."""
    fill_a = PatternFill(fill_type=FILL_SOLID, start_color="00123456", end_color="00654321")
    fill_b = PatternFill(patternType=FILL_SOLID, fgColor="00123456", bgColor="00654321")
    fill_c = PatternFill(fill_type=FILL_NONE)

    assert fill_a == fill_b
    assert fill_a != fill_c

    xml_node = fill_a.to_tree()
    assert xml_node.tag == "fill"
    reconstructed = PatternFill.from_tree(xml_node)
    assert isinstance(reconstructed, PatternFill)
    assert reconstructed == fill_a
    assert reconstructed.fill_type == FILL_SOLID
    assert reconstructed.start_color.rgb == "00123456"
    assert reconstructed.end_color.rgb == "00654321"


def test_pattern_fill_workbook_roundtrip() -> None:
    """Assertion 3: openpyxl.styles.PatternFill persists cell fill styling across Workbook save and load_workbook roundtrips."""
    result = sample.apply_fills_and_roundtrip()

    assert result["a1_fill_type"] == FILL_SOLID
    assert result["a1_start_rgb"] == "00FFCC00"
    assert result["a1_end_rgb"] == "00FFCC00"

    assert result["b2_fill_type"] == FILL_PATTERN_GRAY125
    assert result["b2_fg_rgb"] == "00336699"
    assert result["b2_bg_rgb"] == "00EEEEEE"


def main() -> None:
    test_pattern_fill_construction_and_aliases()
    test_pattern_fill_xml_serialization_and_equality()
    test_pattern_fill_workbook_roundtrip()
    print("All openpyxl.styles.PatternFill contract assertions passed successfully.")


if __name__ == "__main__":
    main()

Исходный сидер

аноним