File size: 9,783 Bytes
ae3f25f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2db37fe
ae3f25f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2db37fe
ae3f25f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2db37fe
ae3f25f
 
 
 
 
 
 
 
 
 
 
 
 
 
2db37fe
ae3f25f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2db37fe
ae3f25f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2db37fe
ae3f25f
 
 
 
 
 
 
 
 
 
2db37fe
 
ae3f25f
 
 
2db37fe
 
ae3f25f
 
 
 
 
 
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
"""
Basic integration tests for OrKa core components.
Tests how the main components work together.
"""

from unittest.mock import MagicMock, patch

import pytest

from orka.loader import YAMLLoader
from orka.orchestrator import Orchestrator
from orka.registry import ResourceRegistry, init_registry


class TestBasicIntegration:
    """Test basic integration between core components."""

    def test_yaml_loader_and_orchestrator_integration(self, temp_yaml_config):
        """Test that YAMLLoader works with Orchestrator initialization."""
        # Load config using YAMLLoader
        loader = YAMLLoader(temp_yaml_config)
        config = loader.config

        # Verify config structure
        assert "orchestrator" in config
        assert "agents" in config

        # Test that config can be validated
        assert loader.validate() is True

    @pytest.mark.asyncio
    async def test_registry_initialization_with_config(self):
        """Test ResourceRegistry initialization with various resource types."""
        config = {
            "test_redis": {
                "type": "redis",
                "config": {"url": "redis://localhost:6380"},
            },
        }

        with patch("orka.registry.redis.from_url") as mock_redis:
            mock_redis.return_value = MagicMock()

            registry = init_registry(config)
            await registry.initialize()

            # Should have initialized successfully
            assert registry._initialized
            assert "test_redis" in registry._resources

    def test_config_validation_flow(self, tmp_path):
        """Test the complete config validation flow."""
        # Create a complete config
        config_content = """
orchestrator:
  id: integration_test
  strategy: sequential
  queue: orka:integration
  agents:
    - test_agent

agents:
  - id: test_agent
    type: openai-answer
    queue: orka:test_queue
    prompt: "Integration test: {{ input }}"
    config:
      model: "gpt-4"
      temperature: 0.7

memory:
  backend: redis
  url: redis://localhost:6380

nodes:
  - type: memory-writer
    id: memory_writer
    queue: orka:memory
"""
        config_file = tmp_path / "integration.yml"
        config_file.write_text(config_content)

        # Load and validate config
        loader = YAMLLoader(str(config_file))

        # Should validate successfully
        assert loader.validate() is True

        # Check structure
        config = loader.config
        assert config["orchestrator"]["id"] == "integration_test"
        assert len(config["agents"]) == 1
        assert config["agents"][0]["type"] == "openai-answer"
        assert "memory" in config
        assert "nodes" in config

    @pytest.mark.asyncio
    @patch.object(Orchestrator, "_init_agents")
    async def test_orchestrator_with_registry_integration(
        self,
        mock_init_agents,
        temp_yaml_config,
    ):
        """Test Orchestrator working with ResourceRegistry."""
        # Mock the orchestrator initialization
        mock_init_agents.return_value = {}

        # Create and initialize a registry
        registry_config = {
            "openai": {
                "type": "openai",
                "config": {"api_key": "test-key"},
            },
        }

        with patch("orka.registry.AsyncOpenAI") as mock_openai:
            mock_openai.return_value = MagicMock()

            registry = ResourceRegistry(registry_config)
            await registry.initialize()

            # Initialize orchestrator
            orchestrator = Orchestrator(temp_yaml_config)

            # Both should be properly initialized
            assert registry._initialized
            assert hasattr(orchestrator, "agents")

    def test_error_handling_integration(self, tmp_path):
        """Test error handling across components."""
        # Test invalid YAML
        invalid_config = tmp_path / "invalid.yml"
        invalid_config.write_text("invalid: yaml: [unclosed")

        with pytest.raises(Exception):  # Should raise YAML error
            YAMLLoader(str(invalid_config))

        # Test missing file
        with pytest.raises(FileNotFoundError):
            YAMLLoader("nonexistent.yml")

    def test_contract_usage_across_components(self):
        """Test that contracts work across different components."""

        # Create test data using contracts
        context = {
            "input": "test input",
            "previous_outputs": {},
            "metadata": {"test": True},
        }

        output = {
            "content": "test output",
            "success": True,
            "metadata": {"agent_id": "test_agent"},
        }

        resource_config = {
            "type": "redis",
            "config": {"url": "redis://localhost:6380"},
        }

        # All should work as regular dictionaries
        assert context["input"] == "test input"
        assert output["success"] is True
        assert resource_config["type"] == "redis"

    @pytest.mark.asyncio
    async def test_component_lifecycle_integration(self):
        """Test the complete lifecycle of components working together."""
        # 1. Create config
        config = {
            "test_resource": {
                "type": "redis",
                "config": {"url": "redis://localhost:6380"},
            },
        }

        # 2. Initialize registry
        with patch("orka.registry.redis.from_url") as mock_redis:
            mock_redis.return_value = MagicMock()

            registry = ResourceRegistry(config)
            await registry.initialize()

            # 3. Use resource
            resource = registry.get("test_resource")
            assert resource is not None

            # 4. Cleanup
            await registry.close()

    def test_configuration_completeness(self, tmp_path):
        """Test that a complete configuration works end-to-end."""
        # Create a comprehensive config
        config_content = """
orchestrator:
  id: complete_test
  strategy: parallel
  queue: orka:complete
  agents:
    - classifier
    - processor
    - responder
  max_parallel: 3
  timeout: 300

agents:
  - id: classifier
    type: openai-classification
    queue: orka:classifier
    prompt: "Classify this input: {{ input }}"
    config:
      model: "gpt-4"
      options:
        - technical
        - business
        - personal
        
  - id: processor
    type: openai-answer
    queue: orka:processor
    prompt: "Process this classified input: {{ input }}"
    depends_on:
      - classifier
    config:
      model: "gpt-4"
      temperature: 0.5
      
  - id: responder
    type: openai-answer
    queue: orka:responder
    prompt: "Generate final response: {{ previous_outputs.processor }}"
    depends_on:
      - processor
    config:
      model: "gpt-4"
      temperature: 0.3

memory:
  backend: redis
  url: redis://localhost:6380
  namespace: complete_test

nodes:
  - type: memory-writer
    id: mem_writer
    queue: orka:memory
    
  - type: memory-reader
    id: mem_reader
    queue: orka:memory_read
"""

        config_file = tmp_path / "complete.yml"
        config_file.write_text(config_content)

        # Load and validate
        loader = YAMLLoader(str(config_file))
        assert loader.validate() is True

        # Check all sections
        config = loader.config
        assert len(config["agents"]) == 3
        assert config["orchestrator"]["strategy"] == "parallel"
        assert config["orchestrator"]["max_parallel"] == 3
        assert "memory" in config
        assert len(config["nodes"]) == 2

        # Verify agent dependencies
        processor = next(a for a in config["agents"] if a["id"] == "processor")
        responder = next(a for a in config["agents"] if a["id"] == "responder")

        assert "depends_on" in processor
        assert "classifier" in processor["depends_on"]
        assert "depends_on" in responder
        assert "processor" in responder["depends_on"]

    def test_module_imports_integration(self):
        """Test that all core modules can be imported together."""
        try:
            from orka.contracts import Context, Output, ResourceConfig
            from orka.loader import YAMLLoader
            from orka.orchestrator import Orchestrator
            from orka.registry import ResourceRegistry, init_registry

            # All imports should succeed
            assert Orchestrator is not None
            assert YAMLLoader is not None
            assert ResourceRegistry is not None
            assert init_registry is not None
            assert Context is not None
            assert Output is not None
            assert ResourceConfig is not None

        except ImportError as e:
            pytest.fail(f"Failed to import core modules: {e}")

    def test_type_compatibility_integration(self):
        """Test that types work correctly across modules."""
        # Test that ResourceConfig from contracts works with registry
        from orka.contracts import ResourceConfig

        config: ResourceConfig = {
            "type": "redis",
            "config": {"url": "redis://localhost:6380"},
        }

        # Should work without type errors
        assert config["type"] == "redis"
        assert isinstance(config["config"], dict)

    def test_error_propagation_integration(self, tmp_path):
        """Test that errors propagate correctly between components."""
        # Create config with validation error
        bad_config = tmp_path / "bad.yml"
        bad_config.write_text(
            """
orchestrator:
  id: test
# Missing agents section
"""
        )

        loader = YAMLLoader(str(bad_config))

        # Should raise validation error
        with pytest.raises(ValueError, match="Missing 'agents' section"):
            loader.validate()