@purecore-br/one-proof-4-all
v0.1.2
Published
<p align="center"> <img src="https://i.imgur.com/2loqBUh.png" alt="one-proof-4-all" width="100%"/> </p>
Readme
Índice
- 🎯 Features
- 🚀 Installation
- ⚡ Quick Start
- 🧭 Which Dialect Is Right for You?
- 📐 Mathematical Dialect
- 📖 Narrative Dialect
- 🛡️ Imperative Dialect
- 🌐 API Testing Dialect
- 🎭 Polyglot Example: Shopping Cart
- 📚 Complete Documentation
- 🔄 Jest Compatibility
- 📊 Why Adopt in Your Team?
- 🏃 Running Tests
- 📦 Package Structure
- 🤝 Contributing
- 📄 License
- 🙏 Acknowledgments
🎯 Features
- Zero Risk Adoption: Your legacy code continues working unchanged
- Polyglot Approach: Multiple specialized dialects for different domains
- Jest Compatible: Runs alongside existing Jest tests in the same suite
- Four Specialized Dialects:
- 📐 Mathematical: For algorithms, calculations, and mathematical proofs
- 📖 Narrative: For business rules readable by product managers
- 🛡️ Imperative: For API contracts and integration testing
- 🌐 API Testing: For declarative API contract validation
🚀 Installation
npm install @purecore/one-proof-4-all⚡ Quick Start
Create a test file api.spec.ts:
import { ensure, check, that, stub } from "@purecore/one-proof-4-all";
ensure("My User API", () => {
const api = stub();
api.forceReturn({ status: 200, id: "user_123" });
check("User creation returns 200 OK", () => {
const response = api.createUser({ name: "John" });
that(response.status).is(200);
that(response.id).matches(/^user_\w+$/);
});
});Run your tests:
npx one-proof-4-all
# or aliases:
npx 1proof4all
npx 1spec
npx testall🧭 Which Dialect Is Right for You?
You don't need to learn all four. Choose what fits your domain:
┌─────────────────────────────────────────┐
│ What are you testing? │
└───────────────────┬─────────────────────┘
│
┌───────────────────────────────┼───────────────────────────────┐
│ │ │
▼ ▼ ▼
┌──────────────────────┐ ┌──────────────────────┐ ┌──────────────────────┐
│ Pure algorithms, │ │ User flows, business │ │ APIs, contracts, │
│ calculations, │ │ rules readable by │ │ integrations, │
│ mathematical rules? │ │ product managers? │ │ compliance? │
└──────────┬───────────┘ └──────────┬───────────┘ └──────────┬───────────┘
│ │ │
▼ ▼ ▼
┌──────────────────────┐ ┌──────────────────────┐ ┌──────────────────────┐
│ 📐 MATHEMATICAL │ │ 📖 NARRATIVE │ │ 🛡️ IMPERATIVE │
│ axiom, proof, implies│ │ intend, scenario, to │ │ ensure, check, that │
└──────────────────────┘ └──────────────────────┘ └──────────────────────┘
│
▼
┌──────────────────────────────┐
│ Backend services, QA teams? │
└─────────────┬────────────────┘
▼
┌──────────────────────────────┐
│ 🌐 API TESTING │
│ ApiSpec.define().post() │
└──────────────────────────────┘📐 Mathematical Dialect
Perfect for scientists and mathematicians proving pure functions.
Example
import { axiom, proof, implies } from "@purecore/one-proof-4-all";
axiom("SHA-256 Hash Theory", () => {
proof("Empty string hash converges to known constant", () => {
implies(sha256("")).is("e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855");
});
proof("Hash is deterministic", () => {
const input = "hello world";
implies(sha256(input)).is(sha256(input));
});
});Key Functions
axiom(name, fn)- Group of truthsproof(name, fn)- Individual proofimplies(val).is(x)- Logical implicationarbitrary()- Generic functionpostulate(fn)- Global premisesgiven(fn)- "Given that..."
📖 Narrative Dialect
Designed for teams with product managers who need to validate business rules.
Example
import { intend, scenario, to, standIn } from "@purecore/one-proof-4-all";
intend("User Permission Journey", () => {
const userService = standIn();
background(() => {
userService.setup({
permissions: ["read", "write"]
});
});
scenario("Unauthorized user tries to access admin panel", () => {
const response = userService.accessAdminPanel("guest_user");
to(response.status).be(403);
to(response.message).be("Access denied");
});
scenario("Authorized user accesses dashboard", () => {
const response = userService.accessDashboard("admin_user");
to(response.status).be(200);
to(response.data).toBeDefined();
});
});Key Functions
intend(name, fn)/story(name, fn)- Intent/storyscenario(name, fn)/detail(name, fn)- Scenarioto(val).be(x)- ExpectationstandIn()/dummy()- Stand-inbackground(fn)- Contextbefore(fn)- Before each scene
🛡️ Imperative Dialect
For backend developers testing API contracts and integrations.
Example
import { ensure, verify, that, stub, initAll, reset } from "@purecore/one-proof-4-all";
let api;
initAll(() => {
api = stub();
});
reset(() => {
api.reset();
});
ensure("PCI-DSS Gateway Compliance v4", () => {
verify("Sensitive data never travels in plain text", () => {
const payload = api.processPayment({ card: "1234" });
that(payload).matches(/^encrypted:/);
});
verify("All transactions are logged", () => {
api.processTransaction({ amount: 100 });
that(api.getTransactionLog()).toHaveLength(1);
});
});Key Functions
ensure(name, fn)- Ensure a requirementcheck(name, fn)/verify(name, fn)- Point checkthat(val).is(x)- Assertionstub()/mock()- Create mockinitAll(fn)- Initial setupreset(fn)- Reset per testspy()- Monitor callsdisposeAll(fn)- Cleanup
🌐 API Testing Dialect
Specialized for backend services and QA teams testing microservices.
Example
import { ApiSpec } from "@purecore/one-proof-4-all";
const userSchema = {
type: "object",
properties: {
id: { type: "string" },
name: { type: "string" },
email: { type: "string", format: "email" }
},
required: ["id", "name", "email"]
};
await ApiSpec.define("Create User")
.from("https://api.example.com")
.post("/users", {
name: "John Doe",
email: "[email protected]"
})
.shouldReturn(201)
.matchingSchema(userSchema)
.run();
await ApiSpec.define("Get User")
.from("https://api.example.com")
.get("/users/user_123")
.shouldReturn(200)
.matchingSchema(userSchema)
.run();Advanced Examples
Complete User Lifecycle Test
import { ApiSpec } from "@purecore/one-proof-4-all";
// Defining reusable schema
const userSchema = {
type: "object",
properties: {
id: { type: "string" },
name: { type: "string" },
email: { type: "string", format: "email" },
createdAt: { type: "string", format: "date-time" }
},
required: ["id", "name", "email", "createdAt"]
};
// Creating a user
await ApiSpec.define("Create User")
.from("https://api.example.com/v1")
.post("/users", {
name: "Jane Smith",
email: "[email protected]",
role: "admin"
})
.header("Content-Type", "application/json")
.header("X-API-Key", "test-key-123")
.shouldReturn(201)
.matchingSchema(userSchema)
.run();
// Retrieving the created user
await ApiSpec.define("Get User by ID")
.from("https://api.example.com/v1")
.get("/users/1")
.header("Authorization", "Bearer token-123")
.shouldReturn(200)
.matchingSchema(userSchema)
.run();
// Updating user information
await ApiSpec.define("Update User")
.from("https://api.example.com/v1")
.put("/users/1", {
name: "Jane Smith Updated",
email: "[email protected]"
})
.header("Authorization", "Bearer token-123")
.shouldReturn(200)
.matchingSchema(userSchema)
.run();
// Deleting the user
await ApiSpec.define("Delete User")
.from("https://api.example.com/v1")
.delete("/users/1")
.header("Authorization", "Bearer token-123")
.shouldReturn(204)
.run();API Testing with Authentication and Custom Headers
import { ApiSpec } from "@purecore/one-proof-4-all";
await ApiSpec.define("Protected Resource Access")
.from("https://api.example.com/v1")
.get("/protected/resource")
.withAuth("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...")
.header("X-Request-ID", "req-12345")
.header("X-Client-Version", "1.2.3")
.shouldReturn(200)
.matchingSchema({
data: { type: "array", items: { type: "object" } }
})
.run();Key Functions
ApiSpec.define(name)- Define the test.from(url)- Set base URL.get()/.post()/.put()/.delete()- HTTP actions.method(verb, path)- Arbitrary HTTP method.shouldReturn(code)- Status validation.matchingSchema(schema)- Contract validation.withHeaders(headers)- Set headers.withAuth(token)- Authentication (sets Authorization header).withBody(body)- Set request body.timeout(ms)- Set timeout.run()- Execute the request and validations
🏃 Running API Tests
- Create a file ending in
.spec.ts(e.g.,api.spec.ts) - Import the dialect:
import { ApiSpec } from "@purecore/one-proof-4-all"; - Define and run your test (supports Top-Level Await):
await ApiSpec.define("Health Check") .from("http://localhost:3000") .get("/health") .shouldReturn(200) .run(); - Execute using the CLI:
npx one-proof-4-all # or with bun bun run 1proof4all
🎭 Polyglot Example: Shopping Cart
Using multiple dialects in the same project:
// 📐 MATHEMATICAL: Price calculations (pure logic)
import { axiom, proof, implies } from "@purecore/one-proof-4-all";
axiom("Price Calculation Theory", () => {
proof("10% discount on $100 equals $90", () => {
implies(calcDiscount(100, 10)).is(90);
});
proof("Tax calculation is additive", () => {
const base = 100;
const discounted = calcDiscount(base, 10);
const withTax = addTax(discounted, 5);
implies(withTax).is(94.5);
});
});
// 📖 NARRATIVE: User journey (PM readable)
import { intend, scenario, to } from "@purecore/one-proof-4-all";
intend("User Shopping Journey", () => {
scenario("User adds product to cart", () => {
const cart = shoppingCart.addProduct(product);
to(cart.items).toHaveLength(1);
to(cart.total).be(29.99);
});
scenario("User applies coupon code", () => {
const cart = shoppingCart.applyCoupon("SAVE10");
to(cart.discount).be(10);
to(cart.finalTotal).be(26.99);
});
});
// 🛡️ IMPERATIVE: Payment gateway integration (strict contract)
import { ensure, check, that } from "@purecore/one-proof-4-all";
ensure("Payment Gateway v2.1 Compliance", () => {
check("Transaction returns status 200", () => {
const response = paymentGateway.process({
amount: 26.99,
card: "**** **** **** 1234"
});
that(response.status).is(200);
that(response.transactionId).matches(/^txn_[a-zA-Z0-9]+$/);
});
check("Failed transactions return proper error codes", () => {
const response = paymentGateway.process({
amount: 26.99,
card: "invalid_card"
});
that(response.status).is(400);
that(response.errorCode).is("INVALID_CARD");
});
});📚 Complete Documentation
Core Documentation
- 📚 Quick Start Guide - Comprehensive getting started guide
- 📄 Whitepaper - Detailed technical overview and philosophy
- 💡 4 Ideas Document - Original concept ideas
API References
Additional Resources
- 4 Ideas Document - Original concept ideas
- Quick Start Guide - Getting started with the framework
- Whitepaper - Technical overview and philosophy
Examples
- 📐 Mathematical Example
- 📖 Narrative Example
- 🛡️ Imperative Example
- 🎭 Polyglot Shopping Cart
- 🧪 Sanity Tests
- 🌐 API Testing Example
- 🚀 API Showcase (All features)
🔄 Jest Compatibility
Your existing Jest tests continue working unchanged:
// ✅ Your legacy Jest code - UNTOUCHED
describe("Login Module (Legacy)", () => {
it("should validate password", () => {
expect(validate("123")).toBe(true);
});
});
// ✅ New feature with new dialect - COMPLEMENTARY
import { axiom, implies } from "@purecore/one-proof-4-all";
axiom("New SHA-256 Cryptography", () => {
implies(hash("123")).matches(/^[a-f0-9]{64}$/);
});Single npm test command runs both. Same report. Same coverage. No rewrite needed.
⚡ Vitest Compatibility
Since one-proof-4-all maintains full Jest compatibility, it also works seamlessly with Vitest, the fast Vite-native testing framework. This means:
- ✅ Existing Vitest configurations work without changes
- ✅ Your current Vitest test files remain untouched
- ✅ Same reporters and coverage tools function identically
- ✅ All four specialized dialects work alongside your existing Vitest tests
Example with Vitest
// ✅ Your existing Vitest tests - UNTOUCHED
import { describe, it, expect } from 'vitest';
describe("Login Module (Vitest)", () => {
it("should validate password", () => {
expect(validate("123")).toBe(true);
});
});
// ✅ New feature with one-proof-4-all dialect - COMPLEMENTARY
import { axiom, implies } from "@purecore/one-proof-4-all";
axiom("New SHA-256 Cryptography", () => {
implies(hash("123")).matches(/^[a-f0-9]{64}$/);
});Run everything together with Vitest:
# If using Vitest as your primary runner
npx vitest
# Or with the one-proof-4-all runner
npx one-proof-4-allSame benefits: Single command runs both frameworks. Identical reports and coverage. Zero migration effort.
📊 Why Adopt in Your Team?
💰 Communication ROI
| Problem | Solution with one-proof-4-all | |---------|------------------------------| | PMs can't read tests | Narrative dialect produces readable specifications | | Meetings to validate rules | Tests become approvable documentation | | Ambiguity between product and engineering | Common language eliminates rework |
Result: Fewer meetings, shorter validation cycles, fewer bugs reaching production.
⚡ Team Efficiency
| Situation | Benefit |
|-----------|---------|
| Onboarding data scientists | Learn only MathDialect, not entire ecosystem |
| Backend devs focused | Use only ImperativeDialect for contracts |
| Domain specialization | Each member produces more, faster |
Result: Training in days, not weeks. Immediate contribution.
🛡️ Code Health (Zero Risk)
| Fear | Reality | |------|---------| | "I'll have to rewrite 5,000 tests" | ❌ False. Jest runs natively | | "Another dependency to maintain" | Incremental integration, not big-bang | | "What if it fails mid-project?" | Adopt in 1 new file. Evaluate. Expand if liked |
Result: Immediate improvement without technical debt. Trivial rollback if needed.
🏃 Running Tests
# Run all specs
npx one-proof-4-all
# Watch mode
npx one-proof-4-all --watch
# Specific file
npx one-proof-4-all src/**/*.spec.ts
# With coverage
npx one-proof-4-all --coverage⚡ Parallel Execution with Workers
For improved performance, tests can be executed in parallel using multiple workers. All tests run asynchronously with a default timeout of 60 seconds. The number of workers used is displayed at the start of execution, and individual worker durations are shown at the end of the test run.
Configuration
To enable parallel execution, use the --workers flag followed by the number of concurrent workers:
# Run tests with 4 parallel workers
npx one-proof-4-all --workers 4
# Run tests with maximum available CPU cores
npx one-proof-4-all --workers maxDefault Behavior
By default, all tests are:
- Asynchronous: Each test runs independently without blocking others
- Time-limited: 60-second timeout per test (configurable via
--timeoutflag) - Concurrent: Started simultaneously with results displayed as they arrive
- Isolated: Each worker operates in its own environment to prevent interference
- Visible Worker Count: Number of workers used is displayed at the start of execution
- Worker Duration Tracking: Individual worker durations are shown at the end of the test run
Timeout Configuration
Adjust the default 60-second timeout if needed:
# Set custom timeout (e.g., 120 seconds)
npx one-proof-4-all --timeout 120000
# Or when using with workers
npx one-proof-4-all --workers 4 --timeout 120000Example Output
When running tests with parallel workers, the output will show:
ONE-SPEC-4-ALL v0.1.0
Using 4 parallel workers for test execution
DEV Scanning for .spec.ts files...
Found 6 test files
─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─
✓ examples/imperative.spec.ts 4 passed (17ms)
✓ Test 1 1ms
✓ Test 2 5ms
✓ Test 3 7ms
✓ Test 4 9ms
...
─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─
Test Files 6 passed (6)
Tests 29 passed (29)
Duration 71ms
Worker Durations:
Worker 1: 42ms
Worker 2: 38ms
Worker 3: 51ms
Worker 4: 29ms
PASS All tests passed!Best Practices
- Async Tests: All tests are designed to be asynchronous by default
- Resource Management: Workers share system resources efficiently
- Real-time Results: View test results as they complete rather than waiting for all tests
- Scalability: Adjust worker count based on your system's CPU capacity
- Performance Monitoring: Use worker duration information to identify bottlenecks
📦 Package Structure
@purecore/one-proof-4-all/
├── src/
│ ├── index.ts # Main entry point
│ └── cli.ts # CLI runner
├── docs/ # Documentation
├── examples/ # Example specifications
├── packages/
│ ├── api-test-dialect/ # API testing package
│ └── reqify/ # HTTP utilities
└── types/
└── api-types.ts # TypeScript definitions🤝 Contributing
- Fork the repository
- Create your feature branch (
git checkout -b feature/AmazingFeature) - Commit your changes (
git commit -m 'Add some AmazingFeature') - Push to the branch (
git push origin feature/AmazingFeature) - Open a Pull Request
📄 License
Cogfulness Ethical License (CEL) v1.0
🙏 Acknowledgments
- Inspired by the need for domain-specific testing languages
- Built with ❤️ for diverse development teams
- Special thanks to all contributors and early adopters
