Add tests for Entity get/set functions

main
copygirl 3 months ago
parent 01d5ed7e48
commit c092465fce
  1. 75
      src/entity.zig

@ -342,3 +342,78 @@ pub fn Entity(comptime ctx: anytype) type {
}
};
}
const expect = @import("./test/expect.zig");
test "Entity get and set" {
flecs.init(std.testing.allocator);
var world = try flecs.World(void).initMinimal();
defer world.deinit();
const Position = struct { x: f32, y: f32 };
const Velocity = struct { x: f32, y: f32 };
_ = try world.component(Position);
_ = try world.component(Velocity);
const entity = try world.entity(.{}, .{});
entity.set(Position, .{ .x = 10, .y = 20 });
entity.set(Velocity, .{ .x = 1, .y = 2 });
const pos = entity.get(Position).?;
const vel = entity.get(Velocity).?;
entity.set(Position, .{ .x = pos.x + vel.x, .y = pos.y + vel.y });
try expect.equal(.{ .x = 11, .y = 22 }, entity.get(Position).?);
}
test "Entity getMut" {
flecs.init(std.testing.allocator);
var world = try flecs.World(void).initMinimal();
defer world.deinit();
const Position = struct { x: f32, y: f32 };
const Velocity = struct { x: f32, y: f32 };
_ = try world.component(Position);
_ = try world.component(Velocity);
const entity = try world.entity(.{}, .{ Position, Velocity });
// Position and Velocity need to be present on the entity for component
// pointers to be stable. Otherwise, when `Velocity` is added, the entity
// would move tables and invalidate the `Position` pointer.
const pos = entity.getMut(Position);
const vel = entity.getMut(Velocity);
pos.* = .{ .x = 10, .y = 20 };
vel.* = .{ .x = 1, .y = 2 };
pos.* = .{ .x = pos.x + vel.x, .y = pos.y + vel.y };
try expect.equal(.{ .x = 11, .y = 22 }, pos.*);
}
test "Entity set and get with pair type" {
flecs.init(std.testing.allocator);
var world = try flecs.World(void).initMinimal();
defer world.deinit();
const Position = struct { x: f32, y: f32 };
const Rank = struct { value: i32 }; // Gives a component a certain "rank".
const Copy = struct {}; // Stores a "copy" of another component.
_ = try world.component(Position);
_ = try world.component(Rank);
_ = try world.tag(Copy);
const entity = try world.entity(.{}, .{});
entity.set(Position, .{ .x = 10, .y = 20 });
entity.set(.{ Rank, Position }, .{ .value = 9001 });
entity.set(.{ Copy, Position }, .{ .x = 60, .y = 80 });
try expect.equal(.{ .x = 10, .y = 20 }, entity.get(Position));
try expect.equal(.{ .value = 9001 }, entity.get(.{ Rank, Position }));
try expect.equal(.{ .x = 60, .y = 80 }, entity.get(.{ Copy, Position }));
}

Loading…
Cancel
Save