graphcore-kernel 0.1.0__py3-none-any.whl

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 (343) hide show
  1. graphcore/__init__.py +5 -0
  2. graphcore/agent_frontend/__init__.py +8 -0
  3. graphcore/agent_frontend/api.py +69 -0
  4. graphcore/agent_frontend/base/__init__.py +11 -0
  5. graphcore/agent_frontend/base/views.py +167 -0
  6. graphcore/agent_frontend/client.py +31 -0
  7. graphcore/agent_frontend/context.py +157 -0
  8. graphcore/agent_frontend/errors.py +12 -0
  9. graphcore/agent_frontend/loading.py +54 -0
  10. graphcore/agent_frontend/registry.py +42 -0
  11. graphcore/agent_frontend/render.py +207 -0
  12. graphcore/agent_frontend/server.py +103 -0
  13. graphcore/agent_frontend/signatures.py +35 -0
  14. graphcore/agent_frontend/testing.py +45 -0
  15. graphcore/agent_frontend/tests/__init__.py +0 -0
  16. graphcore/agent_frontend/tests/fakes.py +114 -0
  17. graphcore/agent_frontend/tests/test_frontend.py +447 -0
  18. graphcore/agent_frontend/tests/test_loading.py +83 -0
  19. graphcore/agent_frontend/tests/test_server.py +109 -0
  20. graphcore/agent_frontend/tools.py +137 -0
  21. graphcore/api/__init__.py +4 -0
  22. graphcore/api/graph_api.py +378 -0
  23. graphcore/api/predicate_codec.py +81 -0
  24. graphcore/api/tests/__init__.py +0 -0
  25. graphcore/api/tests/test_changed_entities.py +109 -0
  26. graphcore/api/tests/test_graph_api.py +290 -0
  27. graphcore/api/tests/test_graph_api_access.py +94 -0
  28. graphcore/api/tests/test_graph_api_grants.py +90 -0
  29. graphcore/api/tests/test_predicate_codec.py +83 -0
  30. graphcore/api/tests/test_subtree_query.py +79 -0
  31. graphcore/apps.py +71 -0
  32. graphcore/auth/__init__.py +1 -0
  33. graphcore/auth/authn/README.md +178 -0
  34. graphcore/auth/authn/__init__.py +3 -0
  35. graphcore/auth/authn/authenticator.py +120 -0
  36. graphcore/auth/authn/onboarding.py +105 -0
  37. graphcore/auth/authn/principals.py +20 -0
  38. graphcore/auth/authn/resource_metadata.py +43 -0
  39. graphcore/auth/authn/service_accounts.py +96 -0
  40. graphcore/auth/authn/testing.py +96 -0
  41. graphcore/auth/authn/tests/__init__.py +0 -0
  42. graphcore/auth/authn/tests/test_authenticator.py +145 -0
  43. graphcore/auth/authn/tests/test_onboarding.py +145 -0
  44. graphcore/auth/authn/tests/test_service_accounts.py +180 -0
  45. graphcore/auth/authn/users.py +59 -0
  46. graphcore/auth/authz/__init__.py +0 -0
  47. graphcore/auth/authz/access_port.py +120 -0
  48. graphcore/auth/authz/adapter/__init__.py +0 -0
  49. graphcore/auth/authz/adapter/default_access_adapter.py +556 -0
  50. graphcore/auth/authz/adapter/tests/__init__.py +0 -0
  51. graphcore/auth/authz/adapter/tests/test_default_adapter.py +543 -0
  52. graphcore/auth/authz/adapter/tests/test_entity_write_hooks.py +207 -0
  53. graphcore/auth/authz/adapter/tests/test_group_types.py +70 -0
  54. graphcore/auth/authz/adapter/tests/test_sync_support.py +209 -0
  55. graphcore/auth/authz/defaults.py +26 -0
  56. graphcore/auth/authz/kernel_policy.py +191 -0
  57. graphcore/auth/authz/kernel_writes.py +31 -0
  58. graphcore/auth/authz/lookups.py +25 -0
  59. graphcore/auth/authz/policy.py +403 -0
  60. graphcore/auth/authz/tests/__init__.py +0 -0
  61. graphcore/auth/authz/tests/test_can_contain.py +150 -0
  62. graphcore/auth/authz/tests/test_contained_by.py +167 -0
  63. graphcore/auth/authz/tests/test_creation.py +391 -0
  64. graphcore/auth/authz/tests/test_delete_permission.py +82 -0
  65. graphcore/auth/authz/tests/test_granted_to_me.py +160 -0
  66. graphcore/auth/authz/tests/test_integration.py +637 -0
  67. graphcore/auth/authz/tests/test_invites.py +184 -0
  68. graphcore/auth/authz/tests/test_kernel_policy.py +140 -0
  69. graphcore/auth/authz/tests/test_lockout.py +132 -0
  70. graphcore/auth/authz/tests/test_policy.py +329 -0
  71. graphcore/auth/authz/tests/test_primitives.py +73 -0
  72. graphcore/auth/authz/tests/test_principal_creation.py +62 -0
  73. graphcore/bootstrap/__init__.py +0 -0
  74. graphcore/bootstrap/deployment.py +67 -0
  75. graphcore/bootstrap/signals.py +16 -0
  76. graphcore/bootstrap/tests/__init__.py +0 -0
  77. graphcore/bootstrap/tests/test_deployment_seed.py +154 -0
  78. graphcore/broadcast/__init__.py +4 -0
  79. graphcore/broadcast/broadcaster.py +201 -0
  80. graphcore/broadcast/channels.py +56 -0
  81. graphcore/broadcast/tests/__init__.py +0 -0
  82. graphcore/broadcast/tests/test_broadcaster.py +444 -0
  83. graphcore/celery.py +14 -0
  84. graphcore/docs/AGENT_FRONTEND_TDD.md +389 -0
  85. graphcore/docs/ARCHITECTURE_PRINCIPLES.md +152 -0
  86. graphcore/docs/AUTHORIZATION_TECHNICAL_TDD.md +1379 -0
  87. graphcore/docs/ENTITY_REFERENCE_TDD.md +561 -0
  88. graphcore/docs/GRAPHAPI_FRONT_DOOR.md +173 -0
  89. graphcore/docs/RUNTIME.md +90 -0
  90. graphcore/docs/SCHEDULING_TDD.md +244 -0
  91. graphcore/docs/STRATEGY_EXECUTION_TDD.md +1043 -0
  92. graphcore/docs/VIEW_ENTITY_TDD.md +522 -0
  93. graphcore/docs/VIEW_SYSTEM_TDD.md +307 -0
  94. graphcore/docs/__init__.py +0 -0
  95. graphcore/docs/doc_topics.py +97 -0
  96. graphcore/docs/docs_discovery.py +64 -0
  97. graphcore/docs/public_api.py +56 -0
  98. graphcore/domain/__init__.py +0 -0
  99. graphcore/domain/entity/Entity.py +204 -0
  100. graphcore/domain/entity/__init__.py +0 -0
  101. graphcore/domain/entity/deployment/Deployment.py +25 -0
  102. graphcore/domain/entity/deployment/__init__.py +0 -0
  103. graphcore/domain/entity/grant/Grant.py +31 -0
  104. graphcore/domain/entity/grant/__init__.py +0 -0
  105. graphcore/domain/entity/group/Group.py +48 -0
  106. graphcore/domain/entity/group/README.md +88 -0
  107. graphcore/domain/entity/group/__init__.py +0 -0
  108. graphcore/domain/entity/invite/Invite.py +31 -0
  109. graphcore/domain/entity/invite/__init__.py +0 -0
  110. graphcore/domain/entity/request_template/RequestTemplate.py +48 -0
  111. graphcore/domain/entity/request_template/__init__.py +0 -0
  112. graphcore/domain/entity/request_template/tests/__init__.py +0 -0
  113. graphcore/domain/entity/request_template/tests/test_request_template.py +52 -0
  114. graphcore/domain/entity/service_account/ServiceAccount.py +41 -0
  115. graphcore/domain/entity/service_account/__init__.py +0 -0
  116. graphcore/domain/entity/strategy_request/StrategyRequest.py +61 -0
  117. graphcore/domain/entity/strategy_request/__init__.py +0 -0
  118. graphcore/domain/entity/strategy_request/tests/__init__.py +0 -0
  119. graphcore/domain/entity/strategy_request/tests/test_strategy_request_entity.py +35 -0
  120. graphcore/domain/entity/tests/__init__.py +0 -0
  121. graphcore/domain/entity/tests/test_entity.py +227 -0
  122. graphcore/domain/entity/tests/test_grant_group_entities.py +36 -0
  123. graphcore/domain/entity/tests/test_write_once_fields.py +98 -0
  124. graphcore/domain/entity/user/User.py +39 -0
  125. graphcore/domain/entity/user/__init__.py +0 -0
  126. graphcore/domain/entity/user/tests/__init__.py +0 -0
  127. graphcore/domain/entity/user/tests/test_user_entity.py +33 -0
  128. graphcore/domain/entity/view/View.py +37 -0
  129. graphcore/domain/entity/view/__init__.py +0 -0
  130. graphcore/domain/entity/view/position.py +78 -0
  131. graphcore/domain/entity/view/tests/__init__.py +0 -0
  132. graphcore/domain/entity/view/tests/test_position.py +71 -0
  133. graphcore/domain/entity/view/tests/test_view_entity.py +134 -0
  134. graphcore/domain/strategy/BaseStrategy.py +759 -0
  135. graphcore/domain/strategy/DeploymentStrategies.py +55 -0
  136. graphcore/domain/strategy/GrantStrategies.py +189 -0
  137. graphcore/domain/strategy/GroupStrategies.py +193 -0
  138. graphcore/domain/strategy/InviteStrategies.py +84 -0
  139. graphcore/domain/strategy/RequestTemplateStrategies.py +126 -0
  140. graphcore/domain/strategy/ViewStrategies.py +219 -0
  141. graphcore/domain/strategy/__init__.py +0 -0
  142. graphcore/domain/strategy/runner.py +84 -0
  143. graphcore/domain/strategy/session.py +56 -0
  144. graphcore/domain/strategy/tests/BaseStrategyTest.py +167 -0
  145. graphcore/domain/strategy/tests/__init__.py +0 -0
  146. graphcore/domain/strategy/tests/test_BaseStrategies.py +870 -0
  147. graphcore/domain/strategy/tests/test_grant_strategies.py +245 -0
  148. graphcore/domain/strategy/tests/test_group_strategies.py +99 -0
  149. graphcore/domain/strategy/tests/test_runner.py +220 -0
  150. graphcore/domain/strategy/tests/test_strategy_locks.py +446 -0
  151. graphcore/domain/strategy/tests/test_utils.py +95 -0
  152. graphcore/domain/strategy/tests/test_view_strategies.py +436 -0
  153. graphcore/errors.py +145 -0
  154. graphcore/execution/README.md +97 -0
  155. graphcore/execution/StrategyExecutorService.py +333 -0
  156. graphcore/execution/__init__.py +0 -0
  157. graphcore/execution/dispatcher.py +19 -0
  158. graphcore/execution/environments/__init__.py +0 -0
  159. graphcore/execution/environments/celery.py +59 -0
  160. graphcore/execution/environments/in_process.py +55 -0
  161. graphcore/execution/local_session.py +117 -0
  162. graphcore/execution/redis_run_events.py +74 -0
  163. graphcore/execution/requests.py +22 -0
  164. graphcore/execution/run_events.py +85 -0
  165. graphcore/execution/strategy_context.py +54 -0
  166. graphcore/execution/tasks.py +34 -0
  167. graphcore/execution/tests/__init__.py +5 -0
  168. graphcore/execution/tests/contract.py +171 -0
  169. graphcore/execution/tests/support.py +310 -0
  170. graphcore/execution/tests/test_dispatchers.py +76 -0
  171. graphcore/execution/tests/test_executor.py +368 -0
  172. graphcore/execution/tests/test_local_session.py +95 -0
  173. graphcore/execution/tests/test_reconcile_runs.py +134 -0
  174. graphcore/execution/tests/test_run_events.py +106 -0
  175. graphcore/execution/tests/test_strategy_context.py +62 -0
  176. graphcore/gateway/__init__.py +1 -0
  177. graphcore/gateway/remote.py +35 -0
  178. graphcore/gateway/tests/__init__.py +0 -0
  179. graphcore/gateway/tests/test_remote.py +30 -0
  180. graphcore/graph/EntityService.py +710 -0
  181. graphcore/graph/__init__.py +0 -0
  182. graphcore/graph/entity_cache.py +152 -0
  183. graphcore/graph/tests/__init__.py +4 -0
  184. graphcore/graph/tests/test_EntityService.py +908 -0
  185. graphcore/graph/tests/test_EntityService_list.py +170 -0
  186. graphcore/graph/tests/test_EntityService_model_resolution.py +339 -0
  187. graphcore/graph/tests/test_EntityService_referrers.py +236 -0
  188. graphcore/graph/tests/test_EntityService_routing.py +119 -0
  189. graphcore/graph/tests/test_dependent_on.py +141 -0
  190. graphcore/graph/tests/test_engine_is_type_agnostic.py +25 -0
  191. graphcore/graph/tests/test_engine_resolves_read_permission.py +93 -0
  192. graphcore/graph/tests/test_entity_cache.py +159 -0
  193. graphcore/graph/tests/test_null_entity_cache.py +12 -0
  194. graphcore/management/__init__.py +0 -0
  195. graphcore/management/commands/__init__.py +0 -0
  196. graphcore/management/commands/dev_reset.py +18 -0
  197. graphcore/management/commands/graphcore_createadmin.py +65 -0
  198. graphcore/management/commands/graphcore_policy.py +59 -0
  199. graphcore/management/commands/graphcore_status.py +98 -0
  200. graphcore/management/tests/__init__.py +0 -0
  201. graphcore/management/tests/test_createadmin.py +78 -0
  202. graphcore/management/tests/test_policy_command.py +46 -0
  203. graphcore/management/tests/test_status_command.py +85 -0
  204. graphcore/migrations/0001_initial.py +186 -0
  205. graphcore/migrations/0002_invite.py +26 -0
  206. graphcore/migrations/__init__.py +0 -0
  207. graphcore/models.py +11 -0
  208. graphcore/persistence/ENTITY_REPOSITORY_TECHNICAL_TDD.md +396 -0
  209. graphcore/persistence/__init__.py +6 -0
  210. graphcore/persistence/django/__init__.py +0 -0
  211. graphcore/persistence/django/backends.py +43 -0
  212. graphcore/persistence/django/bindings.py +28 -0
  213. graphcore/persistence/django/cache.py +38 -0
  214. graphcore/persistence/django/compiler.py +214 -0
  215. graphcore/persistence/django/identity.py +18 -0
  216. graphcore/persistence/django/models.py +252 -0
  217. graphcore/persistence/django/repository.py +525 -0
  218. graphcore/persistence/django/tests/__init__.py +0 -0
  219. graphcore/persistence/django/tests/test_backends.py +68 -0
  220. graphcore/persistence/django/tests/test_compiler.py +269 -0
  221. graphcore/persistence/django/tests/test_repository.py +472 -0
  222. graphcore/persistence/django/tests/test_shared_column.py +120 -0
  223. graphcore/persistence/django/tests/test_threads.py +50 -0
  224. graphcore/persistence/django/tests/test_update_shape.py +175 -0
  225. graphcore/persistence/django/threads.py +38 -0
  226. graphcore/persistence/repository.py +172 -0
  227. graphcore/persistence/tests/__init__.py +0 -0
  228. graphcore/persistence/tests/contract.py +688 -0
  229. graphcore/persistence/tests/evaluate.py +51 -0
  230. graphcore/persistence/tests/fixtures.py +32 -0
  231. graphcore/persistence/tests/memory.py +263 -0
  232. graphcore/persistence/tests/test_memory_repository.py +10 -0
  233. graphcore/persistence/tests/test_query_types.py +127 -0
  234. graphcore/public/__init__.py +9 -0
  235. graphcore/public/api.py +9 -0
  236. graphcore/public/apps.py +10 -0
  237. graphcore/public/auth/__init__.py +1 -0
  238. graphcore/public/auth/grants.py +7 -0
  239. graphcore/public/auth/onboarding.py +8 -0
  240. graphcore/public/auth/perms.py +7 -0
  241. graphcore/public/auth/policy.py +10 -0
  242. graphcore/public/auth/roles.py +8 -0
  243. graphcore/public/auth/subjects.py +7 -0
  244. graphcore/public/entities/__init__.py +32 -0
  245. graphcore/public/errors.py +19 -0
  246. graphcore/public/persistence/__init__.py +44 -0
  247. graphcore/public/persistence/django.py +24 -0
  248. graphcore/public/scheduling.py +23 -0
  249. graphcore/public/strategies/__init__.py +85 -0
  250. graphcore/public/test_settings.py +16 -0
  251. graphcore/public/testing.py +47 -0
  252. graphcore/registry/EntityDirectory.py +246 -0
  253. graphcore/registry/README.md +147 -0
  254. graphcore/registry/StrategyDirectory.py +308 -0
  255. graphcore/registry/TYPE_METADATA_PLACEMENT.md +66 -0
  256. graphcore/registry/__init__.py +0 -0
  257. graphcore/registry/app_discovery.py +108 -0
  258. graphcore/registry/decorators.py +77 -0
  259. graphcore/registry/discovery.py +111 -0
  260. graphcore/registry/registry.py +79 -0
  261. graphcore/registry/tests/__init__.py +0 -0
  262. graphcore/registry/tests/test_agent_frontend_discovery.py +56 -0
  263. graphcore/registry/tests/test_app_config.py +36 -0
  264. graphcore/registry/tests/test_discovery.py +147 -0
  265. graphcore/registry/tests/test_entity_directory_storage.py +73 -0
  266. graphcore/registry/tests/test_import_package.py +87 -0
  267. graphcore/registry/tests/test_principal_flag.py +67 -0
  268. graphcore/registry/tests/test_strategy_directory.py +29 -0
  269. graphcore/routes/__init__.py +116 -0
  270. graphcore/routes/tests/__init__.py +0 -0
  271. graphcore/routes/tests/test_routes.py +90 -0
  272. graphcore/runtime.py +243 -0
  273. graphcore/scheduling/__init__.py +0 -0
  274. graphcore/scheduling/beat_scheduler.py +164 -0
  275. graphcore/scheduling/beat_tasks.py +63 -0
  276. graphcore/scheduling/scheduler.py +37 -0
  277. graphcore/scheduling/tests/__init__.py +0 -0
  278. graphcore/scheduling/tests/contract.py +136 -0
  279. graphcore/scheduling/tests/memory.py +42 -0
  280. graphcore/scheduling/tests/test_beat_scheduler.py +87 -0
  281. graphcore/scheduling/tests/test_memory_scheduler.py +15 -0
  282. graphcore/scheduling/tests/test_ticks.py +143 -0
  283. graphcore/tasks.py +9 -0
  284. graphcore/test_settings.py +78 -0
  285. graphcore/testing/__init__.py +0 -0
  286. graphcore/testing/case.py +112 -0
  287. graphcore/testing/runner.py +32 -0
  288. graphcore/testing/settings.py +26 -0
  289. graphcore/testing/tests/__init__.py +0 -0
  290. graphcore/testing/tests/agent_view_fixture.py +19 -0
  291. graphcore/testing/tests/test_case_and_runner.py +219 -0
  292. graphcore/testing/tests/test_settings_for_apps.py +50 -0
  293. graphcore/tests/__init__.py +0 -0
  294. graphcore/tests/ids.py +14 -0
  295. graphcore/tests/public_api_manifest.py +102 -0
  296. graphcore/tests/runs.py +7 -0
  297. graphcore/tests/test_app_discovery.py +90 -0
  298. graphcore/tests/test_composition_boundaries.py +231 -0
  299. graphcore/tests/test_docs_discovery.py +108 -0
  300. graphcore/tests/test_no_print.py +70 -0
  301. graphcore/tests/test_packaging.py +64 -0
  302. graphcore/tests/test_public_api_boundaries.py +229 -0
  303. graphcore/tests/test_public_api_contract.py +62 -0
  304. graphcore/tests/test_public_api_docs.py +28 -0
  305. graphcore/tests/test_runtime.py +42 -0
  306. graphcore/tests/test_shared_type_boundaries.py +128 -0
  307. graphcore/tests/test_shared_types.py +144 -0
  308. graphcore/tests/test_test_settings.py +45 -0
  309. graphcore/transport/__init__.py +0 -0
  310. graphcore/transport/agent_asgi.py +68 -0
  311. graphcore/transport/agent_client.py +85 -0
  312. graphcore/transport/channel_layer.py +68 -0
  313. graphcore/transport/consumers.py +507 -0
  314. graphcore/transport/routing.py +6 -0
  315. graphcore/transport/tests/__init__.py +0 -0
  316. graphcore/transport/tests/test_agent_client.py +31 -0
  317. graphcore/transport/tests/test_api_views.py +733 -0
  318. graphcore/transport/tests/test_channel_layer.py +96 -0
  319. graphcore/transport/tests/test_consumers.py +963 -0
  320. graphcore/transport/tests/test_resource_metadata.py +67 -0
  321. graphcore/transport/urls.py +29 -0
  322. graphcore/transport/views.py +358 -0
  323. graphcore/types/__init__.py +4 -0
  324. graphcore/types/access.py +114 -0
  325. graphcore/types/api.py +76 -0
  326. graphcore/types/entities.py +100 -0
  327. graphcore/types/entity_id.py +85 -0
  328. graphcore/types/execution.py +41 -0
  329. graphcore/types/identity.py +20 -0
  330. graphcore/types/onboarding.py +20 -0
  331. graphcore/types/query.py +116 -0
  332. graphcore/types/schedules.py +91 -0
  333. graphcore/types/strategy.py +73 -0
  334. graphcore/types/tests/__init__.py +0 -0
  335. graphcore/types/tests/test_entity_id.py +50 -0
  336. graphcore/urls.py +5 -0
  337. graphcore_kernel-0.1.0.dist-info/METADATA +94 -0
  338. graphcore_kernel-0.1.0.dist-info/RECORD +343 -0
  339. graphcore_kernel-0.1.0.dist-info/WHEEL +5 -0
  340. graphcore_kernel-0.1.0.dist-info/entry_points.txt +2 -0
  341. graphcore_kernel-0.1.0.dist-info/licenses/LICENSE +202 -0
  342. graphcore_kernel-0.1.0.dist-info/licenses/NOTICE +2 -0
  343. graphcore_kernel-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,35 @@
1
+ from django.test import SimpleTestCase
2
+
3
+ from graphcore.domain.entity.strategy_request.StrategyRequest import StrategyRequest
4
+ from graphcore.tests.ids import fixture_id
5
+
6
+
7
+ class StrategyRequestTests(SimpleTestCase):
8
+ """to_dict/from_dict hydration - storage conversion lives in
9
+ persistence/tests/contract.py."""
10
+
11
+ def test_from_dict_roundtrip_preserves_typed_fields(self):
12
+ entity = StrategyRequest(entity_id=fixture_id())
13
+ entity.strategy_name = "TestStrategy"
14
+ entity.param_config = {'param1': 'value1', 'param2': 42, 'param3': [1, 2, 3]}
15
+ entity.target_entity_id = fixture_id()
16
+ entity.ret_val = {'result': 'success', 'data': {'key': 'value'}}
17
+ entity.callbacks = [{'strategy_name': 'Next', 'param_config': {}, 'target_entity_id': fixture_id()}]
18
+ entity.callback_channel = 'specific.abc'
19
+ entity.client_request_id = 'client-1'
20
+ entity.status = 'running'
21
+ entity.attempt = 2
22
+ entity.attempt_deadline = 1_700_000_000.5
23
+ entity.error = None
24
+ entity.template_id = fixture_id()
25
+
26
+ record = entity.to_dict()
27
+ self.assertEqual(StrategyRequest.from_dict(record).to_dict(), record)
28
+
29
+ def test_a_new_request_is_pending_with_no_attempt(self):
30
+ entity = StrategyRequest(entity_id=fixture_id())
31
+
32
+ self.assertEqual((entity.status, entity.attempt), ('pending', 0))
33
+
34
+ def test_a_request_outlives_its_target(self):
35
+ self.assertEqual(StrategyRequest.dependent_on, ())
File without changes
@@ -0,0 +1,227 @@
1
+ from django.test import SimpleTestCase as TestCase
2
+
3
+ from graphcore.domain.entity.Entity import Entity
4
+ from graphcore.tests.ids import fixture_id
5
+ from graphcore.types.entity_id import ENTITY_ID_RE, backend_of, new_entity_id
6
+
7
+
8
+ class TestEntityIdentity(TestCase):
9
+ def test_entity_id_validation(self):
10
+ with self.assertRaises(ValueError):
11
+ Entity(entity_id="invalid-uuid-string")
12
+
13
+ def test_an_identifier_is_required(self):
14
+ """Minting belongs to `EntityService.create`; an entity has no
15
+ deployment identity to mint one from."""
16
+ with self.assertRaises(TypeError):
17
+ Entity()
18
+
19
+ def test_a_full_identifier_is_kept_verbatim(self):
20
+ entity_id = fixture_id()
21
+
22
+ self.assertIsNotNone(ENTITY_ID_RE.fullmatch(entity_id))
23
+ self.assertEqual(Entity(entity_id).entity_id, entity_id)
24
+
25
+ def test_a_bare_local_id_is_not_an_identifier(self):
26
+ with self.assertRaises(ValueError):
27
+ Entity(entity_id=fixture_id().rsplit('/', 1)[1])
28
+
29
+ def test_from_dict_round_trips_a_full_identifier(self):
30
+ entity_id = fixture_id()
31
+
32
+ self.assertEqual(Entity.from_dict({'entity_id': entity_id}).entity_id, entity_id)
33
+
34
+ def test_entity_type_id_comes_from_registration(self):
35
+ self.assertEqual(Entity(fixture_id()).entity_type_id, 'graphcore.Entity')
36
+
37
+
38
+ class TestDerivedProjections(TestCase):
39
+ """`children_ids` and `ancestor_ids` are read-only projections the
40
+ repository populates - a payload can never set either."""
41
+
42
+ def test_ancestor_ids_default_empty_and_are_read_only(self):
43
+ entity = Entity(fixture_id())
44
+ self.assertEqual(entity.ancestor_ids, ())
45
+ with self.assertRaises(AttributeError):
46
+ entity.ancestor_ids = ('scope',)
47
+
48
+ def test_to_dict_omits_ancestor_ids(self):
49
+ entity = Entity(fixture_id())
50
+ entity._ancestor_ids = ('scope-1', 'scope-2')
51
+ self.assertNotIn('ancestor_ids', entity.to_dict())
52
+
53
+ def test_to_client_includes_ancestor_ids(self):
54
+ entity = Entity(fixture_id())
55
+ entity._ancestor_ids = ('scope-1', 'scope-2')
56
+ self.assertEqual(entity.to_client()['ancestor_ids'], ['scope-1', 'scope-2'])
57
+
58
+ def test_from_dict_never_hydrates_ancestor_ids(self):
59
+ entity = Entity.from_dict({
60
+ 'entity_id': fixture_id(),
61
+ 'ancestor_ids': ['smuggled-scope'],
62
+ })
63
+ self.assertEqual(entity.ancestor_ids, ())
64
+ self.assertFalse(entity.has_attribute('ancestor_ids'))
65
+
66
+
67
+ class TestContainment(TestCase):
68
+ """`children_ids` is a read-only, derived projection; containment is
69
+ mutated only via `set_parent`, which writes the *child*'s
70
+ `parent_id` - never the parent. See docs/AUTHORIZATION_TECHNICAL_TDD.md
71
+ (Containment)."""
72
+
73
+ def setUp(self):
74
+ self.parent = Entity(fixture_id())
75
+ self.child = Entity(fixture_id())
76
+
77
+ def test_children_ids_append_raises(self):
78
+ with self.assertRaises(AttributeError):
79
+ self.parent.children_ids.append(self.child.entity_id)
80
+
81
+ def test_children_ids_assignment_raises(self):
82
+ with self.assertRaises(AttributeError):
83
+ self.parent.children_ids = [self.child.entity_id]
84
+
85
+ def test_parent_ids_assignment_raises(self):
86
+ with self.assertRaises(AttributeError):
87
+ self.child.parent_ids = [self.parent.entity_id]
88
+
89
+ def test_set_parent_sets_parent_id_and_position(self):
90
+ self.child.set_parent(self.parent.entity_id)
91
+ self.assertEqual(self.child.parent_id, self.parent.entity_id)
92
+ self.assertGreater(self.child.sibling_position, 0)
93
+ self.assertEqual(self.child.parent_ids, (self.parent.entity_id,))
94
+
95
+ def test_set_parent_does_not_touch_parent(self):
96
+ self.child.set_parent(self.parent.entity_id)
97
+ self.assertEqual(self.parent.children_ids, ())
98
+
99
+ def test_set_parent_none_detaches(self):
100
+ self.child.set_parent(self.parent.entity_id)
101
+ self.child.set_parent(None)
102
+ self.assertIsNone(self.child.parent_id)
103
+ self.assertEqual(self.child.parent_ids, ())
104
+
105
+
106
+ class TestMemberIds(TestCase):
107
+ """Tests for Group's member_ids roster - see
108
+ docs/AUTHORIZATION_TECHNICAL_TDD.md (Groups)."""
109
+
110
+ def setUp(self):
111
+ from graphcore.domain.entity.group.Group import Group
112
+ self.entity = Group(fixture_id())
113
+ self.user1 = fixture_id()
114
+ self.user2 = fixture_id()
115
+
116
+ # -- add_member / remove_member ----------------------------------------
117
+
118
+ def test_add_member_appends(self):
119
+ self.entity.add_member(self.user1)
120
+ self.assertIn(self.user1, self.entity.member_ids)
121
+
122
+ def test_add_member_is_idempotent(self):
123
+ self.entity.add_member(self.user1)
124
+ self.entity.add_member(self.user1)
125
+ self.assertEqual(self.entity.member_ids.count(self.user1), 1)
126
+
127
+ def test_remove_member(self):
128
+ self.entity.add_member(self.user1)
129
+ self.entity.remove_member(self.user1)
130
+ self.assertNotIn(self.user1, self.entity.member_ids)
131
+
132
+ def test_remove_member_absent_is_noop(self):
133
+ self.entity.remove_member(self.user1) # should not raise
134
+ self.assertEqual(self.entity.member_ids, [])
135
+
136
+ def test_remove_member_only_removes_target(self):
137
+ self.entity.add_member(self.user1)
138
+ self.entity.add_member(self.user2)
139
+ self.entity.remove_member(self.user1)
140
+ self.assertNotIn(self.user1, self.entity.member_ids)
141
+ self.assertIn(self.user2, self.entity.member_ids)
142
+
143
+ # -- round-trip via to_dict / from_dict ---------------------------------
144
+
145
+ def test_member_ids_in_to_dict(self):
146
+ self.entity.add_member(self.user1)
147
+ data = self.entity.to_dict()
148
+ self.assertIn('member_ids', data)
149
+ self.assertIn(self.user1, data['member_ids'])
150
+
151
+ def test_member_ids_round_trip_from_dict(self):
152
+ from graphcore.domain.entity.group.Group import Group
153
+ self.entity.add_member(self.user1)
154
+ data = self.entity.to_dict()
155
+ restored = Group.from_dict(data)
156
+ self.assertEqual(restored.member_ids, [self.user1])
157
+
158
+ def test_member_ids_defaults_to_empty_list_on_fresh_entity(self):
159
+ self.assertEqual(self.entity.member_ids, [])
160
+
161
+ def test_a_plain_entity_has_no_member_ids(self):
162
+ from graphcore.domain.entity.Entity import Entity
163
+ entity = Entity(fixture_id())
164
+ self.assertFalse(hasattr(entity, 'member_ids'))
165
+ self.assertNotIn('member_ids', entity.to_dict())
166
+
167
+
168
+
169
+ class TestEntityRecord(TestCase):
170
+ def test_all_concrete_entities_round_trip_nested_bags(self):
171
+ from graphcore.domain.entity.group.Group import Group
172
+ from graphcore.domain.entity.grant.Grant import Grant
173
+ from graphcore.domain.entity.user.User import User
174
+ from graphcore.domain.entity.view.View import View
175
+ from graphcore.domain.entity.deployment.Deployment import Deployment
176
+ from graphcore.domain.entity.strategy_request.StrategyRequest import StrategyRequest
177
+
178
+ for entity_class in (Entity, Group, Grant, User, View,
179
+ Deployment, StrategyRequest):
180
+ with self.subTest(entity_class=entity_class):
181
+ entity = entity_class(fixture_id())
182
+ bag = {'name': 'bag', 'owner': 'bag owner', 'parent_id': 'bag parent',
183
+ 'attributes': {'nested': [False, None, 3]}, 'entity_type': 'caller data',
184
+ 'strategy_name': 'bag strategy'}
185
+ for key, value in bag.items():
186
+ entity.set_attribute(key, value)
187
+ record = entity.to_dict()
188
+ self.assertEqual(record['attributes'], bag)
189
+ self.assertEqual(entity_class.from_dict(record).to_dict(), record)
190
+ client = entity.to_client()
191
+ for key in Entity._DERIVED_KEYS - {'entity_type_id'}:
192
+ self.assertNotIn(key, record)
193
+ self.assertIn(key, client)
194
+ restored = entity_class.from_dict(client)
195
+ self.assertEqual(restored.to_client(), client)
196
+
197
+ def test_rejects_non_fields(self):
198
+ for key in ('unknown', '_attributes', 'set_parent', 'to_dict', 'ownerless',
199
+ 'write_once_fields', 'dependent_on', 'entity_type'):
200
+ with self.subTest(key=key), self.assertRaises(ValueError):
201
+ Entity.from_dict({'entity_id': fixture_id(), key: 'invalid'})
202
+
203
+ def test_bag_requires_an_object(self):
204
+ for value in (False, 0, '', [], [['key', 'value']]):
205
+ with self.subTest(value=value), self.assertRaisesMessage(ValueError, 'attributes must'):
206
+ Entity.from_dict({'entity_id': fixture_id(), 'attributes': value})
207
+ for data in ({}, {'attributes': None}):
208
+ self.assertEqual(Entity.from_dict({'entity_id': fixture_id(), **data}).to_dict()['attributes'], {})
209
+
210
+ def test_derived_input_cannot_change_identity_or_projections(self):
211
+ entity = Entity.from_dict({
212
+ 'entity_id': fixture_id(), 'entity_type_id': 'other.Entity',
213
+ 'parent_ids': [fixture_id()], 'children_ids': [fixture_id()],
214
+ 'ancestor_ids': [fixture_id()], 'reference_ids': [fixture_id()],
215
+ })
216
+ self.assertEqual(entity.entity_type_id, 'graphcore.Entity')
217
+ self.assertIsNone(entity.parent_id)
218
+ for key in ('parent_ids', 'children_ids', 'ancestor_ids', 'reference_ids'):
219
+ self.assertEqual(getattr(entity, key), ())
220
+
221
+ def test_unserializable_bag_value_is_dropped(self):
222
+ entity = Entity(fixture_id())
223
+ entity.set_attribute('good', {'items': [1, False, None]})
224
+ entity.set_attribute('bad', object())
225
+ with self.assertLogs('graphcore.domain.entity.Entity', level='WARNING'):
226
+ data = entity.to_dict()
227
+ self.assertEqual(data['attributes'], {'good': {'items': [1, False, None]}})
@@ -0,0 +1,36 @@
1
+ from django.test import SimpleTestCase
2
+
3
+ from graphcore.domain.entity.grant.Grant import Grant
4
+ from graphcore.domain.entity.group.Group import Group
5
+ from graphcore.tests.ids import fixture_id
6
+ from graphcore.registry.registry import DEFAULT_REGISTRY
7
+
8
+
9
+ class RegisteredTypeFlagTests(SimpleTestCase):
10
+ def test_grant_is_not_shareable(self):
11
+ self.assertFalse(DEFAULT_REGISTRY.policy.is_shareable(Grant))
12
+
13
+ def test_group_is_shareable(self):
14
+ self.assertTrue(DEFAULT_REGISTRY.policy.is_shareable(Group))
15
+
16
+
17
+ class GrantSerializationTests(SimpleTestCase):
18
+ def test_to_dict_carries_typed_fields(self):
19
+ grant = Grant(fixture_id())
20
+ grant.subject_id = 'user-1'
21
+ grant.role_name = 'viewer'
22
+
23
+ data = grant.to_dict()
24
+ self.assertEqual(data['subject_id'], 'user-1')
25
+ self.assertEqual(data['role_name'], 'viewer')
26
+
27
+
28
+ class GroupSerializationTests(SimpleTestCase):
29
+ def test_to_dict_carries_name_and_roster(self):
30
+ group = Group(fixture_id())
31
+ group.name = 'Engineering'
32
+ group.add_member('user-1')
33
+
34
+ data = group.to_dict()
35
+ self.assertEqual(data['name'], 'Engineering')
36
+ self.assertEqual(data['member_ids'], ['user-1'])
@@ -0,0 +1,98 @@
1
+ """`write_once_fields`: a field that cannot change once it holds a value."""
2
+ from typing import ClassVar
3
+
4
+ from asgiref.sync import async_to_sync
5
+ from django.test import TestCase
6
+ from django.apps import apps
7
+ from django.db import connection, models
8
+ from graphcore.persistence.django.models import EntityModel
9
+
10
+ from graphcore.domain.entity.Entity import Entity
11
+ from graphcore.errors import InvalidRequest
12
+ from graphcore.execution.strategy_context import kernel_internal_context
13
+ from graphcore.registry.registry import DEFAULT_REGISTRY
14
+ from graphcore.runtime import django_runtime
15
+
16
+ TEST_REGISTRY = DEFAULT_REGISTRY.fork_open()
17
+
18
+
19
+ class _Ticket(Entity):
20
+ write_once_fields: ClassVar[tuple[str, ...]] = ('code',)
21
+
22
+ def __init__(self, entity_id: str):
23
+ super().__init__(entity_id)
24
+ self.code = None
25
+
26
+ def to_dict(self):
27
+ return {**super().to_dict(), 'code': self.code}
28
+
29
+
30
+ TEST_REGISTRY.entities.register_entity(_Ticket, app_label='graphcore')
31
+
32
+
33
+ class WriteOnceFieldTests(TestCase):
34
+ @classmethod
35
+ def setUpClass(cls):
36
+ cls.storage = type('TicketModel', (EntityModel,), {
37
+ '__module__': __name__,
38
+ 'code': models.CharField(max_length=50, null=True),
39
+ 'Meta': type('Meta', (), {'app_label': 'graphcore'}),
40
+ })
41
+ TEST_REGISTRY.entities.bind_storage(_Ticket, cls.storage)
42
+ with connection.schema_editor() as editor:
43
+ editor.create_model(cls.storage)
44
+ super().setUpClass()
45
+
46
+ @classmethod
47
+ def tearDownClass(cls):
48
+ super().tearDownClass()
49
+ with connection.schema_editor() as editor:
50
+ editor.delete_model(cls.storage)
51
+ del apps.all_models['graphcore'][cls.storage._meta.model_name]
52
+ delattr(EntityModel, cls.storage._meta.model_name)
53
+ apps.clear_cache()
54
+
55
+ def setUp(self):
56
+ self.service = django_runtime(TEST_REGISTRY).entity_service
57
+
58
+ def _save(self, entity):
59
+ with kernel_internal_context():
60
+ return async_to_sync(self.service.save_entity)(entity, None)
61
+
62
+ def _reload(self, entity_id):
63
+ return async_to_sync(self.service.load_from_db)(entity_id)
64
+
65
+ def test_an_unset_field_can_be_set(self):
66
+ ticket = self._save(self.service.create(_Ticket))
67
+ ticket = self._reload(ticket.entity_id)
68
+ ticket.code = 'T-1'
69
+ self._save(ticket)
70
+ self.assertEqual(self._reload(ticket.entity_id).code, 'T-1')
71
+
72
+ def test_a_set_field_cannot_change(self):
73
+ ticket = self.service.create(_Ticket)
74
+ ticket.code = 'T-1'
75
+ self._save(ticket)
76
+ ticket = self._reload(ticket.entity_id)
77
+ ticket.code = 'T-2'
78
+ with self.assertRaisesMessage(InvalidRequest, 'code of'):
79
+ self._save(ticket)
80
+
81
+ def test_other_fields_still_change(self):
82
+ ticket = self.service.create(_Ticket)
83
+ ticket.code = 'T-1'
84
+ self._save(ticket)
85
+ ticket = self._reload(ticket.entity_id)
86
+ ticket.set_attribute('note', 'x')
87
+ self._save(ticket)
88
+ self.assertEqual(self._reload(ticket.entity_id).get_attribute('note'), 'x')
89
+
90
+ def test_bag_code_does_not_change_the_write_once_field(self):
91
+ ticket = self.service.create(_Ticket)
92
+ ticket.code = 'T-1'
93
+ self._save(ticket)
94
+ ticket.set_attribute('code', 'bag value')
95
+ self._save(ticket)
96
+ loaded = self._reload(ticket.entity_id)
97
+ self.assertEqual(loaded.code, 'T-1')
98
+ self.assertEqual(loaded.get_attribute('code'), 'bag value')
@@ -0,0 +1,39 @@
1
+ from typing import Optional
2
+
3
+ from graphcore.domain.entity.Entity import Entity
4
+ from graphcore.registry.decorators import register_entity
5
+
6
+
7
+ @register_entity(principal=True)
8
+ class User(Entity):
9
+ """
10
+ Root entity for authenticated users, identified by ``(issuer, subject)``.
11
+ Contains nothing: what a user creates is owned by them, never stored
12
+ under them.
13
+ """
14
+
15
+ def __init__(self, entity_id: str, username: Optional[str] = None,
16
+ issuer: Optional[str] = None, subject: Optional[str] = None):
17
+ super().__init__(entity_id)
18
+ self.username = username
19
+ self.issuer = issuer
20
+ self.subject = subject
21
+
22
+ @property
23
+ def display_name(self) -> Optional[str]:
24
+ return self.username
25
+
26
+ def to_dict(self) -> dict:
27
+ data = super().to_dict()
28
+ data['username'] = self.username
29
+ data['issuer'] = self.issuer
30
+ data['subject'] = self.subject
31
+ return data
32
+
33
+ def to_client(self) -> dict:
34
+ """Drop issuer/subject: auth-layer correlation keys, not client data."""
35
+ data = super().to_client()
36
+ del data['issuer']
37
+ del data['subject']
38
+ return data
39
+
File without changes
File without changes
@@ -0,0 +1,33 @@
1
+
2
+ from django.test import SimpleTestCase
3
+
4
+ from graphcore.domain.entity.user.User import User
5
+ from graphcore.tests.ids import fixture_id
6
+ from graphcore.types.entity_id import new_entity_id
7
+
8
+
9
+ class UserEntitySerializationTests(SimpleTestCase):
10
+ def setUp(self):
11
+ self.entity_id = fixture_id()
12
+
13
+ def test_to_dict_has_no_django_user_link(self):
14
+ serialized = User(entity_id=self.entity_id, username='alice').to_dict()
15
+
16
+ self.assertNotIn('user_id', serialized)
17
+ self.assertEqual(serialized['username'], 'alice')
18
+ self.assertEqual(serialized['entity_type_id'], 'graphcore.User')
19
+
20
+ def test_to_dict_includes_issuer_and_subject(self):
21
+ """to_dict() is full-fidelity and includes auth correlation keys."""
22
+ serialized = User(entity_id=self.entity_id, issuer='local', subject='42').to_dict()
23
+
24
+ self.assertEqual(serialized['issuer'], 'local')
25
+ self.assertEqual(serialized['subject'], '42')
26
+
27
+ def test_to_client_omits_issuer_and_subject(self):
28
+ """to_client() drops auth correlation keys - not client data."""
29
+ client_data = User(entity_id=self.entity_id, issuer='local', subject='42').to_client()
30
+
31
+ self.assertNotIn('issuer', client_data)
32
+ self.assertNotIn('subject', client_data)
33
+ self.assertEqual(client_data['entity_id'], self.entity_id)
@@ -0,0 +1,37 @@
1
+ from typing import ClassVar, Optional
2
+
3
+ from graphcore.domain.entity.Entity import Entity
4
+ from graphcore.registry.decorators import register_entity
5
+
6
+
7
+ @register_entity()
8
+ class View(Entity):
9
+ """Stored view state (docs/VIEW_ENTITY_TDD.md). A view references what it
10
+ shows through `renders` and is never stored under it. `position_key` is
11
+ server-only: unique among siblings by client, slot, and `renders`."""
12
+
13
+ write_once_fields: ClassVar[tuple[str, ...]] = ('renders', 'client', 'slot', 'address', 'position_key')
14
+ dependent_on: ClassVar[tuple[str, ...]] = ('renders',)
15
+
16
+ def __init__(self, entity_id: str):
17
+ super().__init__(entity_id)
18
+ self.component: Optional[str] = None
19
+ self.renders: Optional[str] = None
20
+ self.client: Optional[str] = None
21
+ self.slot: Optional[str] = None
22
+ self.address: Optional[str] = None
23
+ self.position_key: Optional[str] = None
24
+ self.state: dict = {}
25
+
26
+ def to_dict(self) -> dict:
27
+ data = super().to_dict()
28
+ for field in ('component', 'renders', 'client', 'slot', 'address', 'position_key'):
29
+ data[field] = getattr(self, field)
30
+ data['state'] = dict(self.state)
31
+ return data
32
+
33
+ @classmethod
34
+ def from_dict(cls, data: dict) -> 'View':
35
+ view = super().from_dict(data)
36
+ view.state = dict(data.get('state') or {})
37
+ return view
File without changes
@@ -0,0 +1,78 @@
1
+ """Where a view sits, as `SetViewState` names it: a client, a start
2
+ (a page's address or a view's id), and a placement of steps below it
3
+ (docs/VIEW_ENTITY_TDD.md)."""
4
+ from __future__ import annotations
5
+
6
+ import hashlib
7
+ import json
8
+ from typing import NamedTuple, Optional
9
+
10
+ from graphcore.errors import InvalidRequest
11
+ from graphcore.types.entity_id import is_entity_id
12
+
13
+ MAX_STEPS = 64
14
+ MAX_NAME = 255
15
+
16
+
17
+ class Step(NamedTuple):
18
+ slot: str
19
+ renders: Optional[str] = None
20
+
21
+
22
+ class Position(NamedTuple):
23
+ client: str
24
+ address: Optional[str]
25
+ view: Optional[str]
26
+ steps: tuple[Step, ...]
27
+
28
+ @classmethod
29
+ def from_params(cls, config: dict) -> 'Position':
30
+ client = config.get('client')
31
+ if not _is_name(client):
32
+ raise InvalidRequest("client must be a non-empty string")
33
+ address, view = config.get('address'), config.get('view')
34
+ if (address is None) == (view is None):
35
+ raise InvalidRequest("give exactly one of address and view")
36
+ if address is not None:
37
+ check_address(address)
38
+ elif not is_entity_id(view):
39
+ raise InvalidRequest(f"view must be an entity identifier, got {view!r}")
40
+ steps = _steps(config.get('placement') or [])
41
+ if view is not None and not steps:
42
+ raise InvalidRequest("a placement starting at a view needs at least one step")
43
+ return cls(client, address, view, steps)
44
+
45
+
46
+ def check_address(address) -> None:
47
+ if not isinstance(address, str) or not address.startswith('/') or len(address) > MAX_NAME:
48
+ raise InvalidRequest(f"address must start with '/', got {address!r}")
49
+ if '?' in address or '#' in address:
50
+ raise InvalidRequest(f"address {address!r} has a query or fragment")
51
+ if address != '/' and address.endswith('/'):
52
+ raise InvalidRequest(f"address {address!r} has a trailing '/'")
53
+
54
+
55
+ def position_key(scope_id: str, client: str, slot: str, renders: Optional[str]) -> str:
56
+ """Unique among siblings: `scope_id` is the parent, or the owner of a top-level view."""
57
+ canonical = json.dumps([scope_id, client, slot, renders], separators=(',', ':'))
58
+ return hashlib.sha256(canonical.encode('utf-8')).hexdigest()
59
+
60
+
61
+ def _is_name(value) -> bool:
62
+ return isinstance(value, str) and 0 < len(value) <= MAX_NAME
63
+
64
+
65
+ def _steps(raw) -> tuple[Step, ...]:
66
+ if not isinstance(raw, list):
67
+ raise InvalidRequest("placement must be a list")
68
+ if len(raw) > MAX_STEPS:
69
+ raise InvalidRequest(f"placement has more than {MAX_STEPS} steps")
70
+ steps = []
71
+ for step in raw:
72
+ if not isinstance(step, dict) or not _is_name(step.get('slot')):
73
+ raise InvalidRequest(f"placement step {step!r} needs a non-empty slot")
74
+ renders = step.get('renders')
75
+ if renders is not None and not is_entity_id(renders):
76
+ raise InvalidRequest(f"placement step renders must be an entity identifier, got {renders!r}")
77
+ steps.append(Step(step['slot'], renders))
78
+ return tuple(steps)
File without changes
@@ -0,0 +1,71 @@
1
+ from unittest import TestCase
2
+
3
+ from graphcore.domain.entity.view.position import MAX_STEPS, Position, Step, position_key
4
+ from graphcore.errors import InvalidRequest
5
+
6
+ V = 'gc://0000000001/aaaaaaaaaaaa'
7
+ D = 'gc://0000000001/bbbbbbbbbbbb'
8
+ U = 'gc://0000000001/cccccccccccc'
9
+
10
+
11
+ class FromParamsTests(TestCase):
12
+ def test_an_address_start(self):
13
+ self.assertEqual(
14
+ Position.from_params({'client': 'web', 'address': '/e/b/l',
15
+ 'placement': [{'slot': 'outline', 'renders': D}]}),
16
+ Position('web', '/e/b/l', None, (Step('outline', D),)),
17
+ )
18
+
19
+ def test_an_address_start_may_have_an_empty_placement(self):
20
+ self.assertEqual(Position.from_params({'client': 'web', 'address': '/'}).steps, ())
21
+
22
+ def test_a_view_start(self):
23
+ position = Position.from_params({'client': 'web', 'view': V, 'placement': [{'slot': 'outline'}]})
24
+ self.assertEqual(position, Position('web', None, V, (Step('outline', None),)))
25
+
26
+ def test_exactly_one_start(self):
27
+ for config in ({'client': 'web'}, {'client': 'web', 'address': '/', 'view': V}):
28
+ with self.assertRaises(InvalidRequest):
29
+ Position.from_params(config)
30
+
31
+ def test_a_view_start_needs_a_step(self):
32
+ with self.assertRaises(InvalidRequest):
33
+ Position.from_params({'client': 'web', 'view': V, 'placement': []})
34
+
35
+ def test_a_view_must_be_an_entity_id(self):
36
+ with self.assertRaises(InvalidRequest):
37
+ Position.from_params({'client': 'web', 'view': 'nope', 'placement': [{'slot': 'a'}]})
38
+
39
+ def test_a_client_is_required(self):
40
+ for client in (None, '', 3):
41
+ with self.assertRaises(InvalidRequest):
42
+ Position.from_params({'client': client, 'address': '/'})
43
+
44
+ def test_non_normalized_addresses_are_refused(self):
45
+ for address in ('/a/', 'a', '/a?x=1', '/a#b', '', 5):
46
+ with self.assertRaises(InvalidRequest, msg=address):
47
+ Position.from_params({'client': 'web', 'address': address})
48
+
49
+ def test_bad_steps_are_refused(self):
50
+ for step in ({'slot': ''}, {'slot': 3}, {}, 'outline', {'slot': 'a', 'renders': 'nope'}):
51
+ with self.assertRaises(InvalidRequest, msg=step):
52
+ Position.from_params({'client': 'web', 'address': '/', 'placement': [step]})
53
+
54
+ def test_too_many_steps_are_refused(self):
55
+ steps = [{'slot': 'a'}] * (MAX_STEPS + 1)
56
+ with self.assertRaises(InvalidRequest):
57
+ Position.from_params({'client': 'web', 'address': '/', 'placement': steps})
58
+ Position.from_params({'client': 'web', 'address': '/', 'placement': steps[:MAX_STEPS]})
59
+
60
+
61
+ class PositionKeyTests(TestCase):
62
+ def test_equal_inputs_give_equal_keys(self):
63
+ self.assertEqual(position_key(U, 'web', '/', None), position_key(U, 'web', '/', None))
64
+
65
+ def test_each_input_changes_the_key(self):
66
+ base = (U, 'web', 'outline', D)
67
+ variants = [(V, 'web', 'outline', D), (U, 'agent', 'outline', D),
68
+ (U, 'web', 'other', D), (U, 'web', 'outline', None)]
69
+ keys = {position_key(*args) for args in [base, *variants]}
70
+ self.assertEqual(len(keys), 5)
71
+ self.assertRegex(position_key(*base), r'^[0-9a-f]{64}$')