keycase-agent-sdk 0.2.0b1__tar.gz → 0.2.0b2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. {keycase_agent_sdk-0.2.0b1/keycase_agent_sdk.egg-info → keycase_agent_sdk-0.2.0b2}/PKG-INFO +17 -1
  2. {keycase_agent_sdk-0.2.0b1 → keycase_agent_sdk-0.2.0b2}/README.md +16 -0
  3. {keycase_agent_sdk-0.2.0b1 → keycase_agent_sdk-0.2.0b2}/keycase_agent/__init__.py +1 -1
  4. {keycase_agent_sdk-0.2.0b1 → keycase_agent_sdk-0.2.0b2}/keycase_agent/agent.py +35 -0
  5. {keycase_agent_sdk-0.2.0b1 → keycase_agent_sdk-0.2.0b2}/keycase_agent/execution_manager.py +31 -1
  6. {keycase_agent_sdk-0.2.0b1 → keycase_agent_sdk-0.2.0b2}/keycase_agent/models/execution_result.py +37 -3
  7. {keycase_agent_sdk-0.2.0b1 → keycase_agent_sdk-0.2.0b2/keycase_agent_sdk.egg-info}/PKG-INFO +17 -1
  8. {keycase_agent_sdk-0.2.0b1 → keycase_agent_sdk-0.2.0b2}/keycase_agent_sdk.egg-info/SOURCES.txt +1 -0
  9. {keycase_agent_sdk-0.2.0b1 → keycase_agent_sdk-0.2.0b2}/pyproject.toml +1 -1
  10. {keycase_agent_sdk-0.2.0b1 → keycase_agent_sdk-0.2.0b2}/setup.py +1 -1
  11. {keycase_agent_sdk-0.2.0b1 → keycase_agent_sdk-0.2.0b2}/tests/test_execution_manager.py +4 -0
  12. keycase_agent_sdk-0.2.0b2/tests/test_step_results.py +230 -0
  13. {keycase_agent_sdk-0.2.0b1 → keycase_agent_sdk-0.2.0b2}/LICENSE +0 -0
  14. {keycase_agent_sdk-0.2.0b1 → keycase_agent_sdk-0.2.0b2}/keycase_agent/attachments.py +0 -0
  15. {keycase_agent_sdk-0.2.0b1 → keycase_agent_sdk-0.2.0b2}/keycase_agent/auth.py +0 -0
  16. {keycase_agent_sdk-0.2.0b1 → keycase_agent_sdk-0.2.0b2}/keycase_agent/config.py +0 -0
  17. {keycase_agent_sdk-0.2.0b1 → keycase_agent_sdk-0.2.0b2}/keycase_agent/decorators.py +0 -0
  18. {keycase_agent_sdk-0.2.0b1 → keycase_agent_sdk-0.2.0b2}/keycase_agent/event_handler.py +0 -0
  19. {keycase_agent_sdk-0.2.0b1 → keycase_agent_sdk-0.2.0b2}/keycase_agent/exceptions/__init__.py +0 -0
  20. {keycase_agent_sdk-0.2.0b1 → keycase_agent_sdk-0.2.0b2}/keycase_agent/exceptions/auth_exceptions.py +0 -0
  21. {keycase_agent_sdk-0.2.0b1 → keycase_agent_sdk-0.2.0b2}/keycase_agent/exceptions/validation_exceptions.py +0 -0
  22. {keycase_agent_sdk-0.2.0b1 → keycase_agent_sdk-0.2.0b2}/keycase_agent/execution_context.py +0 -0
  23. {keycase_agent_sdk-0.2.0b1 → keycase_agent_sdk-0.2.0b2}/keycase_agent/loader.py +0 -0
  24. {keycase_agent_sdk-0.2.0b1 → keycase_agent_sdk-0.2.0b2}/keycase_agent/models/__init__.py +0 -0
  25. {keycase_agent_sdk-0.2.0b1 → keycase_agent_sdk-0.2.0b2}/keycase_agent/models/execute_plan.py +0 -0
  26. {keycase_agent_sdk-0.2.0b1 → keycase_agent_sdk-0.2.0b2}/keycase_agent/models/execution_run_mode_types.py +0 -0
  27. {keycase_agent_sdk-0.2.0b1 → keycase_agent_sdk-0.2.0b2}/keycase_agent/models/websocket_event_types.py +0 -0
  28. {keycase_agent_sdk-0.2.0b1 → keycase_agent_sdk-0.2.0b2}/keycase_agent/registry.py +0 -0
  29. {keycase_agent_sdk-0.2.0b1 → keycase_agent_sdk-0.2.0b2}/keycase_agent/state_tracker.py +0 -0
  30. {keycase_agent_sdk-0.2.0b1 → keycase_agent_sdk-0.2.0b2}/keycase_agent/utils/__init__.py +0 -0
  31. {keycase_agent_sdk-0.2.0b1 → keycase_agent_sdk-0.2.0b2}/keycase_agent/utils/auth_helper.py +0 -0
  32. {keycase_agent_sdk-0.2.0b1 → keycase_agent_sdk-0.2.0b2}/keycase_agent/utils/event_sender.py +0 -0
  33. {keycase_agent_sdk-0.2.0b1 → keycase_agent_sdk-0.2.0b2}/keycase_agent/websocket_client.py +0 -0
  34. {keycase_agent_sdk-0.2.0b1 → keycase_agent_sdk-0.2.0b2}/keycase_agent_sdk.egg-info/dependency_links.txt +0 -0
  35. {keycase_agent_sdk-0.2.0b1 → keycase_agent_sdk-0.2.0b2}/keycase_agent_sdk.egg-info/entry_points.txt +0 -0
  36. {keycase_agent_sdk-0.2.0b1 → keycase_agent_sdk-0.2.0b2}/keycase_agent_sdk.egg-info/requires.txt +0 -0
  37. {keycase_agent_sdk-0.2.0b1 → keycase_agent_sdk-0.2.0b2}/keycase_agent_sdk.egg-info/top_level.txt +0 -0
  38. {keycase_agent_sdk-0.2.0b1 → keycase_agent_sdk-0.2.0b2}/setup.cfg +0 -0
  39. {keycase_agent_sdk-0.2.0b1 → keycase_agent_sdk-0.2.0b2}/tests/test_agent_retry.py +0 -0
  40. {keycase_agent_sdk-0.2.0b1 → keycase_agent_sdk-0.2.0b2}/tests/test_attachments.py +0 -0
  41. {keycase_agent_sdk-0.2.0b1 → keycase_agent_sdk-0.2.0b2}/tests/test_config.py +0 -0
  42. {keycase_agent_sdk-0.2.0b1 → keycase_agent_sdk-0.2.0b2}/tests/test_websocket_client.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: keycase-agent-sdk
3
- Version: 0.2.0b1
3
+ Version: 0.2.0b2
4
4
  Summary: Python SDK for Keycase Agent execution and keyword integration
5
5
  Author: Apo
6
6
  Author-email: Keycase Team <support@keycase.io>
@@ -494,6 +494,22 @@ The hook may also take no argument. It only runs for errors raised by a keyword
494
494
  (not for plan problems such as a missing keyword), and an error inside the hook
495
495
  is logged without changing the step's result.
496
496
 
497
+ ## Step results
498
+
499
+ Every flow result includes the outcome and duration of each step, measured by
500
+ the agent, so Keycase can show how long each step took:
501
+
502
+ ```json
503
+ "stepResults": [
504
+ {"stepOrder": 0, "status": "PASSED", "durationMs": 405.2},
505
+ {"stepOrder": 1, "status": "FAILED", "durationMs": 30012.0},
506
+ {"stepOrder": 2, "status": "NOT_RUN", "durationMs": null}
507
+ ]
508
+ ```
509
+
510
+ No code is needed in your keywords. Older Keycase servers that do not accept
511
+ `stepResults` are handled automatically: the result is sent again without it.
512
+
497
513
  ## Architecture
498
514
 
499
515
  ```
@@ -447,6 +447,22 @@ The hook may also take no argument. It only runs for errors raised by a keyword
447
447
  (not for plan problems such as a missing keyword), and an error inside the hook
448
448
  is logged without changing the step's result.
449
449
 
450
+ ## Step results
451
+
452
+ Every flow result includes the outcome and duration of each step, measured by
453
+ the agent, so Keycase can show how long each step took:
454
+
455
+ ```json
456
+ "stepResults": [
457
+ {"stepOrder": 0, "status": "PASSED", "durationMs": 405.2},
458
+ {"stepOrder": 1, "status": "FAILED", "durationMs": 30012.0},
459
+ {"stepOrder": 2, "status": "NOT_RUN", "durationMs": null}
460
+ ]
461
+ ```
462
+
463
+ No code is needed in your keywords. Older Keycase servers that do not accept
464
+ `stepResults` are handled automatically: the result is sent again without it.
465
+
450
466
  ## Architecture
451
467
 
452
468
  ```
@@ -51,7 +51,7 @@ from .models.execution_result import ExecutionResultData, FlowResult, StatusEnum
51
51
  from .state_tracker import AgentStateTracker
52
52
  from .websocket_client import ConnectionState, WebSocketClient
53
53
 
54
- __version__ = "0.2.0b1"
54
+ __version__ = "0.2.0b2"
55
55
  __author__ = "Keycase Team"
56
56
 
57
57
  __all__ = [
@@ -190,6 +190,22 @@ class KeycaseAgent:
190
190
  logger.info(f"Successfully sent result on attempt {attempt}")
191
191
  return response.data
192
192
 
193
+ # Older servers reject the optional per-step results: send without
194
+ if response.error_code == SCHEMA_MISMATCH_CODE and _has_step_results(
195
+ result
196
+ ):
197
+ logger.warning(
198
+ "The server does not accept per-step results (upgrade the "
199
+ "server to see step durations); sending the result without them"
200
+ )
201
+ result = _without_step_results(result)
202
+ response = auth_request_with_details(
203
+ "POST", url, token, data=result
204
+ )
205
+ if response.success:
206
+ logger.info(f"Successfully sent result on attempt {attempt}")
207
+ return response.data
208
+
193
209
  # Check if this is an "already completed" error - treat as success
194
210
  if response.error_code in ALREADY_COMPLETED_CODES:
195
211
  logger.info(
@@ -362,3 +378,22 @@ class KeycaseAgent:
362
378
  self.auth_service.stop()
363
379
  if self.ws_client:
364
380
  self.ws_client.stop()
381
+
382
+
383
+ # Server error code for a request body that does not match its JSON schema
384
+ SCHEMA_MISMATCH_CODE = 4002
385
+
386
+
387
+ def _has_step_results(result: Dict[str, Any]) -> bool:
388
+ return any("stepResults" in f for f in result.get("flowResults", []))
389
+
390
+
391
+ def _without_step_results(result: Dict[str, Any]) -> Dict[str, Any]:
392
+ """A copy of the result in the shape older servers accept."""
393
+ return {
394
+ **result,
395
+ "flowResults": [
396
+ {k: v for k, v in f.items() if k != "stepResults"}
397
+ for f in result.get("flowResults", [])
398
+ ],
399
+ }
@@ -5,6 +5,7 @@ import json
5
5
  import logging
6
6
  import re
7
7
  import threading
8
+ import time
8
9
  import uuid
9
10
  from datetime import datetime, timezone
10
11
  from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Set, Tuple, Union
@@ -24,7 +25,12 @@ from .models.execute_plan import (
24
25
  KeywordInstance,
25
26
  execute_plan_from_json,
26
27
  )
27
- from .models.execution_result import ExecutionResultData, FlowResult, StatusEnum
28
+ from .models.execution_result import (
29
+ ExecutionResultData,
30
+ FlowResult,
31
+ StatusEnum,
32
+ StepStatus,
33
+ )
28
34
  from .models.execution_run_mode_types import ExecutionPlanRunMode
29
35
  from .models.websocket_event_types import WebSocketEventType
30
36
  from .utils.event_sender import completed_execution, progress_event
@@ -314,11 +320,15 @@ class ExecutionManager:
314
320
 
315
321
  flow_failed = False
316
322
  step_outputs: StepOutputs = {}
323
+ # stepOrder -> (status, duration in ms); steps missing here did not run
324
+ outcomes: Dict[int, Tuple[StepStatus, Optional[float]]] = {}
317
325
 
318
326
  for step in flow.steps:
319
327
  if self.stop_execution.is_set():
320
328
  break
321
329
 
330
+ # Monotonic clock: immune to system clock changes during the step
331
+ started = time.monotonic()
322
332
  executed_steps.add((flow.id, step.instanceId))
323
333
  # lets attach() know which flow / step it belongs to
324
334
  set_step(flow.id, step.sequenceOrder, step.id)
@@ -330,6 +340,7 @@ class ExecutionManager:
330
340
  flow_result.set_failed_on_step_id(step.sequenceOrder)
331
341
  flow_result.set_message("Keyword instance not found")
332
342
  flow_result.set_status(StatusEnum.FAILED)
343
+ outcomes[step.sequenceOrder] = (StepStatus.FAILED, _ms_since(started))
333
344
  flow_failed = True
334
345
  break
335
346
 
@@ -340,6 +351,7 @@ class ExecutionManager:
340
351
  f"Function for {instance.keywordName} not found"
341
352
  )
342
353
  flow_result.set_status(StatusEnum.FAILED)
354
+ outcomes[step.sequenceOrder] = (StepStatus.FAILED, _ms_since(started))
343
355
  flow_failed = True
344
356
  break
345
357
 
@@ -438,10 +450,12 @@ class ExecutionManager:
438
450
  self._process_output_params(
439
451
  step, instance, output_params, result, step_outputs
440
452
  )
453
+ outcomes[step.sequenceOrder] = (StepStatus.PASSED, _ms_since(started))
441
454
 
442
455
  except ParameterValidationError as e:
443
456
  # Strict validation failure - parameter mismatch
444
457
  logger.error(f"Parameter validation failed: {e.detailed_message}")
458
+ outcomes[step.sequenceOrder] = (StepStatus.FAILED, _ms_since(started))
445
459
  flow_result.set_failed_on_step_id(step.sequenceOrder)
446
460
  flow_result.set_message(e.detailed_message)
447
461
  flow_result.set_status(StatusEnum.FAILED)
@@ -449,6 +463,8 @@ class ExecutionManager:
449
463
  break
450
464
 
451
465
  except Exception as e:
466
+ # Measured before the failure hooks run: their time is not the step's
467
+ outcomes[step.sequenceOrder] = (StepStatus.FAILED, _ms_since(started))
452
468
  error_msg = self._enhance_error_message(str(e), func)
453
469
  flow_result.set_failed_on_step_id(step.sequenceOrder)
454
470
  flow_result.set_message(error_msg)
@@ -470,6 +486,13 @@ class ExecutionManager:
470
486
 
471
487
  set_step(None, None)
472
488
 
489
+ # One entry per step, in flow order; steps never reached are NOT_RUN
490
+ for step in flow.steps:
491
+ status, duration_ms = outcomes.get(
492
+ step.sequenceOrder, (StepStatus.NOT_RUN, None)
493
+ )
494
+ flow_result.add_step_result(step.sequenceOrder, status, duration_ms)
495
+
473
496
  if not flow_failed:
474
497
  flow_result.set_status(StatusEnum.PASSED)
475
498
 
@@ -674,6 +697,8 @@ class ExecutionManager:
674
697
  flow_result.started_execution()
675
698
  flow_result.set_status(StatusEnum.SKIPPED)
676
699
  flow_result.set_message("Flow skipped due to Skip run mode")
700
+ for step in flow.steps:
701
+ flow_result.add_step_result(step.sequenceOrder, StepStatus.SKIPPED)
677
702
  flow_result.completed_execution()
678
703
  return flow_result
679
704
 
@@ -863,6 +888,11 @@ class ExecutionManager:
863
888
  )
864
889
 
865
890
 
891
+ def _ms_since(started: float) -> float:
892
+ """Milliseconds elapsed since a time.monotonic() reading."""
893
+ return (time.monotonic() - started) * 1000
894
+
895
+
866
896
  def _accepts_argument(func: Callable) -> bool:
867
897
  """True if func can be called with one positional argument."""
868
898
  try:
@@ -3,7 +3,7 @@
3
3
  import json
4
4
  from datetime import datetime, timezone
5
5
  from enum import Enum
6
- from typing import List, Optional
6
+ from typing import Any, Dict, List, Optional
7
7
 
8
8
 
9
9
  class StatusEnum(Enum):
@@ -22,6 +22,18 @@ class StatusEnum(Enum):
22
22
  return self.value
23
23
 
24
24
 
25
+ class StepStatus(Enum):
26
+ """Outcome of a single step, reported per flow in ``stepResults``."""
27
+
28
+ PASSED = "PASSED"
29
+ FAILED = "FAILED"
30
+ NOT_RUN = "NOT_RUN"
31
+ SKIPPED = "SKIPPED"
32
+
33
+ def __str__(self) -> str:
34
+ return self.value
35
+
36
+
25
37
  class FlowResult:
26
38
  """Result of a single flow execution."""
27
39
 
@@ -33,6 +45,21 @@ class FlowResult:
33
45
  self.message: Optional[str] = None
34
46
  self.run_at: Optional[datetime] = None
35
47
  self.completed_at: Optional[datetime] = None
48
+ self.step_results: List[Dict[str, Any]] = []
49
+
50
+ def add_step_result(
51
+ self, step_order: int, status: StepStatus, duration_ms: Optional[float] = None
52
+ ) -> None:
53
+ """Record how a step went and how long it took (milliseconds)."""
54
+ self.step_results.append(
55
+ {
56
+ "stepOrder": step_order,
57
+ "status": status.value,
58
+ "durationMs": (
59
+ round(duration_ms, 1) if duration_ms is not None else None
60
+ ),
61
+ }
62
+ )
36
63
 
37
64
  # Legacy property aliases for backward compatibility with API responses
38
65
  @property
@@ -68,8 +95,12 @@ class FlowResult:
68
95
  self.status = status
69
96
 
70
97
  def to_dict(self) -> dict:
71
- """Convert to dictionary for JSON serialization."""
72
- return {
98
+ """Convert to dictionary for JSON serialization.
99
+
100
+ ``stepResults`` is only included when steps were recorded, so flows without
101
+ it keep the original shape.
102
+ """
103
+ result: Dict[str, Any] = {
73
104
  "id": self.id,
74
105
  "failedOnStepId": self.failed_on_step_id,
75
106
  "status": str(self.status) if self.status else None,
@@ -78,6 +109,9 @@ class FlowResult:
78
109
  "completedAt": self.completed_at.isoformat() if self.completed_at else None,
79
110
  "name": self.name,
80
111
  }
112
+ if self.step_results:
113
+ result["stepResults"] = [dict(s) for s in self.step_results]
114
+ return result
81
115
 
82
116
 
83
117
  class ExecutionResultData:
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: keycase-agent-sdk
3
- Version: 0.2.0b1
3
+ Version: 0.2.0b2
4
4
  Summary: Python SDK for Keycase Agent execution and keyword integration
5
5
  Author: Apo
6
6
  Author-email: Keycase Team <support@keycase.io>
@@ -494,6 +494,22 @@ The hook may also take no argument. It only runs for errors raised by a keyword
494
494
  (not for plan problems such as a missing keyword), and an error inside the hook
495
495
  is logged without changing the step's result.
496
496
 
497
+ ## Step results
498
+
499
+ Every flow result includes the outcome and duration of each step, measured by
500
+ the agent, so Keycase can show how long each step took:
501
+
502
+ ```json
503
+ "stepResults": [
504
+ {"stepOrder": 0, "status": "PASSED", "durationMs": 405.2},
505
+ {"stepOrder": 1, "status": "FAILED", "durationMs": 30012.0},
506
+ {"stepOrder": 2, "status": "NOT_RUN", "durationMs": null}
507
+ ]
508
+ ```
509
+
510
+ No code is needed in your keywords. Older Keycase servers that do not accept
511
+ `stepResults` are handled automatically: the result is sent again without it.
512
+
497
513
  ## Architecture
498
514
 
499
515
  ```
@@ -37,4 +37,5 @@ tests/test_agent_retry.py
37
37
  tests/test_attachments.py
38
38
  tests/test_config.py
39
39
  tests/test_execution_manager.py
40
+ tests/test_step_results.py
40
41
  tests/test_websocket_client.py
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "keycase-agent-sdk"
7
- version = "0.2.0b1"
7
+ version = "0.2.0b2"
8
8
  description = "Python SDK for Keycase Agent execution and keyword integration"
9
9
  readme = "README.md"
10
10
  license = {text = "MIT"}
@@ -2,7 +2,7 @@ from setuptools import setup, find_packages
2
2
 
3
3
  setup(
4
4
  name="keycase-agent-sdk",
5
- version="0.2.0b1",
5
+ version="0.2.0b2",
6
6
  packages=find_packages(),
7
7
  include_package_data=True,
8
8
  install_requires=[
@@ -312,10 +312,14 @@ class TestExecutionManager:
312
312
  mock_flow = Mock()
313
313
  mock_flow.id = 1
314
314
  mock_flow.name = "test_flow"
315
+ mock_flow.steps = [Mock(sequenceOrder=0), Mock(sequenceOrder=1)]
315
316
 
316
317
  # Execute
317
318
  result = self.manager._create_skipped_flow_result(mock_flow)
318
319
 
320
+ # Every step is reported as skipped
321
+ assert [s["status"] for s in result.step_results] == ["SKIPPED", "SKIPPED"]
322
+
319
323
  # Verify result
320
324
  assert result.status == StatusEnum.SKIPPED
321
325
  assert result.id == 1
@@ -0,0 +1,230 @@
1
+ """Tests for per-step results (status + duration) and old-server compatibility."""
2
+
3
+ import json
4
+ import time
5
+ from datetime import datetime, timedelta
6
+ from unittest.mock import Mock, patch
7
+
8
+ import pytest
9
+
10
+ from keycase_agent.agent import KeycaseAgent
11
+ from keycase_agent.auth import AuthCredentials, AuthService
12
+ from keycase_agent.decorators import (
13
+ OnStepFailure,
14
+ keyword,
15
+ keyword_registry,
16
+ on_step_failure_hooks,
17
+ )
18
+ from keycase_agent.execution_manager import ExecutionManager
19
+ from keycase_agent.models.execution_result import FlowResult, StepStatus
20
+ from keycase_agent.utils.auth_helper import ApiResponse
21
+
22
+
23
+ @pytest.fixture
24
+ def registry():
25
+ """Register keywords / hooks for one test and remove them afterwards."""
26
+ names = []
27
+ hooks_before = list(on_step_failure_hooks)
28
+ yield names
29
+ for name in names:
30
+ keyword_registry.keywords.pop(name, None)
31
+ on_step_failure_hooks[:] = hooks_before
32
+
33
+
34
+ def _run(keyword_names, run_mode="CONTINUE_ON_FAILURE"):
35
+ """Run one flow whose steps call the given keywords; returns its flow result."""
36
+ instances = [
37
+ {
38
+ "id": i + 1,
39
+ "name": f"inst-{i}",
40
+ "keywordId": i + 1,
41
+ "keywordName": name,
42
+ "params": [],
43
+ }
44
+ for i, name in enumerate(keyword_names)
45
+ ]
46
+ steps = [
47
+ {
48
+ "id": i + 1,
49
+ "instanceId": i + 1,
50
+ "sequenceOrder": i * 10,
51
+ } # orders need not be 0..n
52
+ for i in range(len(keyword_names))
53
+ ]
54
+ plan = {
55
+ "keywordInstances": instances,
56
+ "flows": [
57
+ {
58
+ "id": 7,
59
+ "flowId": 7,
60
+ "name": "f",
61
+ "runMode": run_mode,
62
+ "steps": steps,
63
+ "connections": [],
64
+ }
65
+ ],
66
+ }
67
+ manager = ExecutionManager(mode="local", attachments_dir=None)
68
+ out = manager.execute_local(plan, run_id="r")
69
+ return out["result"]["flowResults"][0]
70
+
71
+
72
+ def test_passing_flow_reports_each_step(registry):
73
+ registry.extend(["SR Fast", "SR Slow"])
74
+
75
+ @keyword("SR Fast")
76
+ def fast():
77
+ return {}
78
+
79
+ @keyword("SR Slow")
80
+ def slow():
81
+ time.sleep(0.05)
82
+ return {}
83
+
84
+ flow = _run(["SR Fast", "SR Slow"])
85
+ steps = flow["stepResults"]
86
+ assert [(s["stepOrder"], s["status"]) for s in steps] == [
87
+ (0, "PASSED"),
88
+ (10, "PASSED"),
89
+ ]
90
+ assert steps[0]["durationMs"] >= 0
91
+ assert steps[1]["durationMs"] >= 50
92
+
93
+
94
+ def test_failure_marks_later_steps_not_run(registry):
95
+ registry.extend(["SR Ok", "SR Boom", "SR Never"])
96
+
97
+ @keyword("SR Ok")
98
+ def ok():
99
+ return {}
100
+
101
+ @keyword("SR Boom")
102
+ def boom():
103
+ raise AssertionError("nope")
104
+
105
+ @keyword("SR Never")
106
+ def never(): # pragma: no cover - must not run
107
+ raise RuntimeError("should not run")
108
+
109
+ # A slow failure hook must not be counted in the failed step's duration
110
+ OnStepFailure(lambda failure: time.sleep(0.2))
111
+
112
+ flow = _run(["SR Ok", "SR Boom", "SR Never"])
113
+ steps = flow["stepResults"]
114
+ assert [s["status"] for s in steps] == ["PASSED", "FAILED", "NOT_RUN"]
115
+ assert steps[1]["durationMs"] < 150
116
+ assert steps[2]["durationMs"] is None
117
+ assert flow["failedOnStepId"] == 10
118
+
119
+
120
+ def test_missing_keyword_is_a_failed_step(registry):
121
+ registry.append("SR First")
122
+
123
+ @keyword("SR First")
124
+ def first():
125
+ return {}
126
+
127
+ flow = _run(["SR First", "SR Not Registered", "SR First"])
128
+ assert [s["status"] for s in flow["stepResults"]] == ["PASSED", "FAILED", "NOT_RUN"]
129
+
130
+
131
+ def test_skipped_flow_reports_skipped_steps(registry):
132
+ registry.append("SR Any")
133
+
134
+ @keyword("SR Any")
135
+ def any_step(): # pragma: no cover - flow is skipped
136
+ return {}
137
+
138
+ flow = _run(["SR Any", "SR Any"], run_mode="skip")
139
+ assert flow["status"] == "SKIPPED"
140
+ assert [s["status"] for s in flow["stepResults"]] == ["SKIPPED", "SKIPPED"]
141
+ assert all(s["durationMs"] is None for s in flow["stepResults"])
142
+
143
+
144
+ def test_flow_without_step_results_keeps_original_shape():
145
+ result = FlowResult(1, "f").to_dict()
146
+ assert "stepResults" not in result
147
+
148
+ flow = FlowResult(1, "f")
149
+ flow.add_step_result(0, StepStatus.PASSED, 12.345)
150
+ assert flow.to_dict()["stepResults"] == [
151
+ {"stepOrder": 0, "status": "PASSED", "durationMs": 12.3}
152
+ ]
153
+
154
+
155
+ # ─── Sending results to older servers ────────────────────────────────────────
156
+
157
+
158
+ def _agent():
159
+ config = {
160
+ "HTTP_URL": "http://localhost:8080/api",
161
+ "AGENT_TOKEN": "agt_test_token_123456789",
162
+ "AGENT_NAME": "test-agent-01",
163
+ "AGENT_VERSION": "1.0.0",
164
+ "AGENT_CAPABILITIES": [],
165
+ "AGENT_TAGS": [],
166
+ }
167
+ with patch.object(AuthService, "__init__", lambda self, **kwargs: None):
168
+ agent = KeycaseAgent(config)
169
+ agent.auth_service = Mock(spec=AuthService)
170
+ agent.auth_service.get_token.return_value = "tok"
171
+ agent.auth_service.authenticate.return_value = AuthCredentials(
172
+ agent_id=1,
173
+ organization_id=1,
174
+ access_token="tok",
175
+ refresh_token="r",
176
+ session_id="s",
177
+ ws_url="ws://x",
178
+ token_expires_at=datetime.now() + timedelta(hours=1),
179
+ )
180
+ return agent
181
+
182
+
183
+ RESULT = {
184
+ "runId": 1,
185
+ "startDateTime": "a",
186
+ "endDateTime": "b",
187
+ "flowResults": [
188
+ {
189
+ "id": 7,
190
+ "name": "f",
191
+ "status": "PASSED",
192
+ "stepResults": [{"stepOrder": 0, "status": "PASSED"}],
193
+ }
194
+ ],
195
+ }
196
+ SCHEMA_MISMATCH = ApiResponse(
197
+ success=False,
198
+ status_code=400,
199
+ error_code=4002,
200
+ error_message="Request body does not match the schema must NOT have additional properties",
201
+ )
202
+
203
+
204
+ @patch("keycase_agent.agent.auth_request_with_details")
205
+ def test_old_server_gets_result_without_step_results(send):
206
+ send.side_effect = [SCHEMA_MISMATCH, ApiResponse(success=True, status_code=201)]
207
+
208
+ _agent()._send_result(1, 1, json.loads(json.dumps(RESULT)))
209
+
210
+ first, second = (c.kwargs["data"] for c in send.call_args_list)
211
+ assert "stepResults" in first["flowResults"][0]
212
+ assert "stepResults" not in second["flowResults"][0]
213
+ assert second["flowResults"][0]["status"] == "PASSED" # everything else kept
214
+ assert send.call_count == 2
215
+
216
+
217
+ @patch("keycase_agent.agent.time.sleep")
218
+ @patch("keycase_agent.agent.auth_request_with_details")
219
+ def test_schema_error_without_step_results_is_not_retried_specially(
220
+ send, _sleep, tmp_path, monkeypatch
221
+ ):
222
+ monkeypatch.chdir(tmp_path) # failed results are saved locally
223
+ send.return_value = SCHEMA_MISMATCH
224
+ plain = {**RESULT, "flowResults": [{"id": 7, "name": "f", "status": "PASSED"}]}
225
+
226
+ _agent()._send_result(1, 1, plain)
227
+
228
+ # only the normal retry loop: every attempt sends the same body
229
+ bodies = [c.kwargs["data"] for c in send.call_args_list]
230
+ assert all(b == plain for b in bodies)