-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_fluent_api.py
More file actions
380 lines (305 loc) · 10.3 KB
/
test_fluent_api.py
File metadata and controls
380 lines (305 loc) · 10.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
#!/usr/bin/env python3
"""
Comprehensive tests for the FuzzyInfer v2.0 Fluent API.
"""
import json
import pytest
from pathlib import Path
import tempfile
from fuzzy_infer.fluent import (
FluentKB,
FuzzySession,
Pipeline,
PatternMatcher,
FluentRule,
FluentQueryResult,
fuzzy,
when,
then,
)
from fuzzy_infer.models import Fact
class TestFluentKB:
"""Test FluentKB core functionality."""
def test_method_chaining(self):
"""Test method chaining returns self."""
kb = FluentKB()
result = kb.fact("is-bird", ["robin"], 0.9)
assert result is kb
result = kb.rule(when=("is-bird", "?x"), then=("can-fly", "?x", 0.9))
assert result is kb
result = kb.infer()
assert result is kb
def test_fact_addition(self):
"""Test various ways to add facts."""
kb = FluentKB()
# Single fact
kb.fact("is-mammal", ["dog"], 0.9)
assert len(kb.all_facts()) == 1
# Multiple facts with tuple notation
kb.facts(
("is-mammal", ["cat"], 1.0),
("is-bird", ["eagle"], 0.95)
)
assert len(kb.all_facts()) == 3
# Facts with varying argument structures
kb.facts(
("has-skill", ["alice", "python"], 0.9),
("temperature", ["room-1"], 0.75)
)
assert len(kb.all_facts()) == 5
def test_rule_creation(self):
"""Test rule creation methods."""
kb = FluentKB()
# Simple rule
kb.rule(
when=("is-bird", "?x"),
then=("can-fly", "?x", 0.9),
name="birds-fly"
)
assert len(kb._engine.rules) == 1
assert kb._engine.rules[0].name == "birds-fly"
# Rule with multiple conditions
kb.rule(
when=[("has-wings", "?x"), ("is-light", "?x")],
then=("can-fly", "?x", 0.95)
)
assert len(kb._engine.rules) == 2
def test_inference(self):
"""Test inference execution."""
kb = (
FluentKB()
.fact("is-bird", ["robin"], 1.0)
.rule(
when=("is-bird", "?x"),
then=("can-fly", "?x", 0.9)
)
.infer()
)
flying = kb.query("can-fly", ["robin"])
assert len(flying) == 1
assert flying.first.degree == 0.9
def test_clear_methods(self):
"""Test clearing facts and rules."""
kb = FluentKB()
kb.fact("test", ["a"], 1.0)
kb.rule(when=("test", "?x"), then=("result", "?x", 1.0))
kb.clear_facts()
assert len(kb.all_facts()) == 0
assert len(kb._engine.rules) == 1
kb.clear_rules()
assert len(kb._engine.rules) == 0
class TestFuzzySession:
"""Test FuzzySession context manager."""
def test_basic_session(self):
"""Test basic session functionality."""
with FuzzySession() as kb:
kb.fact("is-mammal", ["dog"], 1.0)
kb.rule(
when=("is-mammal", "?x"),
then=("warm-blooded", "?x", 0.99)
)
# Should auto-infer at exit
# Session completed without errors
assert True
def test_session_with_query(self):
"""Test querying within session."""
with FuzzySession() as kb:
kb.fact("is-bird", ["sparrow"], 0.9)
kb.rule(
when=("is-bird", "?x"),
then=("has-wings", "?x", 0.95)
)
kb.infer() # Explicit inference
results = kb.query("has-wings")
assert len(results) == 1
assert results.first.args[0] == "sparrow"
class TestFluentQueryResult:
"""Test query result operations."""
def test_query_operations(self):
"""Test various query operations."""
kb = FluentKB()
kb.facts(
("animal", ["dog"], 0.9),
("animal", ["cat"], 0.7),
("animal", ["bird"], 0.5)
)
results = kb.where("animal")
# Test properties
assert len(results) == 3
assert results.first is not None
assert results.max_degree == 0.9
assert results.min_degree == 0.5
assert results.degrees == [0.9, 0.7, 0.5]
def test_query_filtering(self):
"""Test filtering operations."""
kb = FluentKB()
kb.facts(
("score", ["alice"], 0.9),
("score", ["bob"], 0.7),
("score", ["charlie"], 0.5)
)
results = kb.where("score")
# Test degree filtering
high = results.having_degree('>', 0.6)
assert len(high) == 2
low = results.having_degree('<=', 0.5)
assert len(low) == 1
def test_query_mapping(self):
"""Test map operation."""
kb = FluentKB()
kb.facts(
("person", ["alice"], 1.0),
("person", ["bob"], 1.0)
)
names = kb.where("person").map(lambda f: f.args[0])
assert set(names) == {"alice", "bob"}
def test_query_export(self):
"""Test export operations."""
kb = FluentKB()
kb.fact("test", ["value"], 0.8)
results = kb.where("test")
# Test dict conversion
as_dict = results.to_dict()
assert isinstance(as_dict, list)
assert len(as_dict) == 1
assert as_dict[0]["pred"] == "test"
# Test JSON conversion
as_json = results.to_json()
assert isinstance(as_json, str)
parsed = json.loads(as_json)
assert parsed[0]["pred"] == "test"
class TestPatternMatcher:
"""Test pattern matching functionality."""
def test_pattern_creation(self):
"""Test creating patterns."""
kb = FluentKB()
# Subscript notation
pattern = kb["is-bird"]["?x"]
assert pattern.predicate == "is-bird"
assert pattern.args == ["?x"]
# Call notation
pattern = kb["has-skill"]("?person", "python")
assert pattern.predicate == "has-skill"
assert pattern.args == ["?person", "python"]
def test_pattern_constraints(self):
"""Test degree constraints on patterns."""
kb = FluentKB()
pattern = kb["temperature"]["?x"] > 0.7
assert pattern.predicate == "temperature"
assert len(pattern.constraints) == 1
pattern = kb["humidity"]["?x"] <= 0.5
assert len(pattern.constraints) == 1
def test_attribute_access(self):
"""Test attribute access for patterns."""
kb = FluentKB()
# Underscores to hyphens
pattern = kb.is_mammal["?x"]
assert pattern.predicate == "is-mammal"
pattern = kb.has_skill["?p", "?s"]
assert pattern.predicate == "has-skill"
assert pattern.args == ["?p", "?s"]
class TestPipeline:
"""Test Pipeline builder."""
def test_basic_pipeline(self):
"""Test basic pipeline operations."""
pipeline = (
Pipeline()
.facts_from([
("sensor", ["s1"], 0.8),
("sensor", ["s2"], 0.3)
])
.filter_facts(lambda f: f.degree > 0.5)
)
kb = pipeline.run()
facts = kb.all_facts()
assert len(facts) == 1
assert facts[0].args[0] == "s1"
def test_pipeline_with_inference(self):
"""Test pipeline with inference."""
pipeline = (
Pipeline()
.facts_from([("is-bird", ["robin"], 1.0)])
.transform(lambda kb: kb.rule(
when=("is-bird", "?x"),
then=("can-fly", "?x", 0.9)
))
.infer()
)
kb = pipeline.run()
flying = kb.where("can-fly")
assert len(flying) == 1
class TestHelperFunctions:
"""Test helper functions."""
def test_fuzzy_helper(self):
"""Test fuzzy() quick creation."""
kb = fuzzy(
("is-cat", ["fluffy"], 1.0),
("has-fur", ["fluffy"], 0.95)
)
assert len(kb.all_facts()) == 2
cats = kb.where("is-cat")
assert len(cats) == 1
def test_when_then_helpers(self):
"""Test when() and then() helpers."""
condition = when("is-mammal", "?x")
assert condition.predicate == "is-mammal"
assert condition.args == ["?x"]
action = then("warm-blooded", "?x", 0.99)
assert action == ("warm-blooded", ["?x"], 0.99)
class TestIntegration:
"""Integration tests for complex scenarios."""
def test_complex_inference_pipeline(self):
"""Test a complete inference pipeline."""
with FuzzySession() as kb:
# Add facts
kb.facts(
("is-bird", ["robin"], 0.9),
("is-bird", ["eagle"], 1.0),
("is-mammal", ["dog"], 1.0),
("has-wings", ["robin"], 1.0),
("has-wings", ["eagle"], 1.0),
("has-fur", ["dog"], 0.95)
)
# Add rules
kb.rule(
when=("is-bird", "?x"),
then=("can-fly", "?x", 0.9),
name="birds-fly"
).rule(
when=("is-mammal", "?x"),
then=("warm-blooded", "?x", 0.99),
name="mammals-warm"
).rule(
when=[("has-wings", "?x"), ("can-fly", "?x")],
then=("aerial-creature", "?x", 0.95),
name="aerial"
)
kb.infer()
# Check results
flying = kb.where("can-fly")
assert len(flying) == 2
warm = kb.where("warm-blooded")
assert len(warm) == 1
assert warm.first.args[0] == "dog"
aerial = kb.where("aerial-creature")
assert len(aerial) == 2
def test_save_load(self):
"""Test saving and loading."""
with tempfile.NamedTemporaryFile(suffix='.jsonl', delete=False) as f:
temp_path = Path(f.name)
try:
# Create and save KB
kb1 = FluentKB()
kb1.facts(
("test", ["a"], 0.8),
("test", ["b"], 0.6)
)
kb1.save(temp_path)
# Load into new KB
kb2 = FluentKB().load(temp_path)
facts = kb2.all_facts()
assert len(facts) == 2
finally:
temp_path.unlink()
if __name__ == "__main__":
pytest.main([__file__, "-v"])