#!/usr/bin/env python3
"""Cross-language verification: Python writes SHM, C++ reads it.
This test creates shared memory with known values from Python,
then runs the C++ test binary which reads the same SHM region
and verifies the data matches.
"""
import importlib.util
import os
import subprocess
import sys
# Import shm_protocol directly
_proto_path = os.path.join(
os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
"blender_addon",
"shm_protocol.py",
)
_spec = importlib.util.spec_from_file_location("shm_protocol", _proto_path)
shm_protocol = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(shm_protocol)
ShmRegion = shm_protocol.ShmRegion
print("=== Cross-Language Tests (Python→C++) ===")
# Step 1: Python writes to SHM
shm = ShmRegion()
assert shm.create("/test_bb_xproc", 4096)
shm.write_header(
magic=b"BGOD",
version=1,
direction=1,
sequence=99,
object_count=1,
frame_number=0,
)
shm.write_object_entry(
index=0,
object_id=42,
object_type=shm_protocol.OBJ_CAMERA,
update_type=1, # UPDATE_VERTEX
data_offset=256,
data_size=48,
sequence=0,
)
print(" Python wrote header + entry to /test_bb_xproc")
# Step 2: Compile and run C++ reader that opens the same SHM
test_dir = os.path.dirname(os.path.abspath(__file__))
cpp_src = os.path.join(test_dir, "test_cross_read.cpp")
# Write a minimal C++ reader
with open(cpp_src, "w") as f:
f.write("""
#include "../src/shm_protocol.h"
#include <cassert>
#include <cstdio>
int main() {
ShmRegion reader;
assert(reader.open("/test_bb_xproc", 4096));
BridgeHeader hdr = read_header(reader.ptr());
assert(hdr.magic[0] == 'B' && hdr.magic[1] == 'G' && hdr.magic[2] == 'O' && hdr.magic[3] == 'D');
assert(hdr.version == 1);
assert(hdr.direction == 1);
assert(hdr.sequence == 99);
assert(hdr.object_count == 1);
ObjectEntry entry = read_object_entry(reader.ptr(), 0);
assert(entry.object_id == 42);
assert(entry.object_type == OBJ_CAMERA);
assert(entry.update_type == UPDATE_VERTEX);
assert(entry.data_offset == 256);
assert(entry.data_size == 48);
reader.destroy();
printf(" C++ verified Python-written SHM data...PASS\\n");
return 0;
}
""")
# Compile
bin_path = os.path.join(test_dir, "test_cross_read")
result = subprocess.run(
["g++", "-std=c++17", "-o", bin_path, cpp_src, "-lrt"],
capture_output=True,
text=True,
)
assert result.returncode == 0, f"Compile failed: {result.stderr}"
# Run
result = subprocess.run([bin_path], capture_output=True, text=True)
print(result.stdout, end="")
assert result.returncode == 0, f"C++ reader failed: {result.stderr}"
# Cleanup
shm.close()
os.unlink(cpp_src)
os.unlink(bin_path)
print("\nAll cross-language tests passed.")