launchpy 0.5.3__tar.gz → 0.5.4.post1__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 (37) hide show
  1. {launchpy-0.5.3 → launchpy-0.5.4.post1}/PKG-INFO +1 -1
  2. {launchpy-0.5.3 → launchpy-0.5.4.post1}/docs/cli.md +170 -16
  3. {launchpy-0.5.3 → launchpy-0.5.4.post1}/docs/releases.md +9 -0
  4. {launchpy-0.5.3 → launchpy-0.5.4.post1}/docs/synchronizer.md +10 -0
  5. launchpy-0.5.4.post1/launchpy/__version__.py +1 -0
  6. {launchpy-0.5.3 → launchpy-0.5.4.post1}/launchpy/cli/__main__.py +5 -3
  7. {launchpy-0.5.3 → launchpy-0.5.4.post1}/launchpy/synchronizer.py +38 -29
  8. {launchpy-0.5.3 → launchpy-0.5.4.post1}/launchpy.egg-info/PKG-INFO +1 -1
  9. {launchpy-0.5.3 → launchpy-0.5.4.post1}/launchpy.egg-info/SOURCES.txt +2 -1
  10. launchpy-0.5.4.post1/tests/test_synchronizer.py +467 -0
  11. launchpy-0.5.3/launchpy/__version__.py +0 -1
  12. {launchpy-0.5.3 → launchpy-0.5.4.post1}/LICENSE +0 -0
  13. {launchpy-0.5.3 → launchpy-0.5.4.post1}/README.md +0 -0
  14. {launchpy-0.5.3 → launchpy-0.5.4.post1}/docs/admin.md +0 -0
  15. {launchpy-0.5.3 → launchpy-0.5.4.post1}/docs/getstarted.md +0 -0
  16. {launchpy-0.5.3 → launchpy-0.5.4.post1}/docs/library.md +0 -0
  17. {launchpy-0.5.3 → launchpy-0.5.4.post1}/docs/main.md +0 -0
  18. {launchpy-0.5.3 → launchpy-0.5.4.post1}/docs/property.md +0 -0
  19. {launchpy-0.5.3 → launchpy-0.5.4.post1}/docs/translator.md +0 -0
  20. {launchpy-0.5.3 → launchpy-0.5.4.post1}/launchpy/__init__.py +0 -0
  21. {launchpy-0.5.3 → launchpy-0.5.4.post1}/launchpy/admin.py +0 -0
  22. {launchpy-0.5.3 → launchpy-0.5.4.post1}/launchpy/cli/__init__.py +0 -0
  23. {launchpy-0.5.3 → launchpy-0.5.4.post1}/launchpy/config.py +0 -0
  24. {launchpy-0.5.3 → launchpy-0.5.4.post1}/launchpy/configs.py +0 -0
  25. {launchpy-0.5.3 → launchpy-0.5.4.post1}/launchpy/connector.py +0 -0
  26. {launchpy-0.5.3 → launchpy-0.5.4.post1}/launchpy/launchpy.py +0 -0
  27. {launchpy-0.5.3 → launchpy-0.5.4.post1}/launchpy/library.py +0 -0
  28. {launchpy-0.5.3 → launchpy-0.5.4.post1}/launchpy/property.py +0 -0
  29. {launchpy-0.5.3 → launchpy-0.5.4.post1}/launchpy.egg-info/dependency_links.txt +0 -0
  30. {launchpy-0.5.3 → launchpy-0.5.4.post1}/launchpy.egg-info/entry_points.txt +0 -0
  31. {launchpy-0.5.3 → launchpy-0.5.4.post1}/launchpy.egg-info/requires.txt +0 -0
  32. {launchpy-0.5.3 → launchpy-0.5.4.post1}/launchpy.egg-info/top_level.txt +0 -0
  33. {launchpy-0.5.3 → launchpy-0.5.4.post1}/pyproject.toml +0 -0
  34. {launchpy-0.5.3 → launchpy-0.5.4.post1}/requirements.txt +0 -0
  35. {launchpy-0.5.3 → launchpy-0.5.4.post1}/setup.cfg +0 -0
  36. {launchpy-0.5.3 → launchpy-0.5.4.post1}/tests/test_connector.py +0 -0
  37. {launchpy-0.5.3 → launchpy-0.5.4.post1}/tests/test_proxies.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: launchpy
3
- Version: 0.5.3
3
+ Version: 0.5.4.post1
4
4
  Summary: Adobe Launch API wrapper
5
5
  Author-email: Julien Piccini <piccini.julien@gmail.com>
6
6
  License: Apache License 2.0
@@ -50,6 +50,13 @@ This document provides an overview of the command line interface (CLI) for `laun
50
50
  - [sync\_from\_library](#sync_from_library)
51
51
  - [Behaviors for sync\_from\_library](#behaviors-for-sync_from_library)
52
52
  - [create\_libraries](#create_libraries)
53
+ - [Multi-Organization Synchronization](#multi-organization-synchronization)
54
+ - [1. Create and populate a multi-org config file](#1-create-and-populate-a-multi-org-config-file)
55
+ - [2. Connect the CLI with the multi-org config](#2-connect-the-cli-with-the-multi-org-config)
56
+ - [3. Load the synchronizer across organizations](#3-load-the-synchronizer-across-organizations)
57
+ - [4. End-to-end cross-org synchronization workflow](#4-end-to-end-cross-org-synchronization-workflow)
58
+ - [5. Dynamic component filtering across organizations](#5-dynamic-component-filtering-across-organizations)
59
+ - [6. Multi-org limitations and notes](#6-multi-org-limitations-and-notes)
53
60
 
54
61
 
55
62
 
@@ -343,29 +350,23 @@ synchronizer:Base_Property_Name>
343
350
  ```
344
351
 
345
352
  **Synchronizing across organizations**\
346
- The synchronizer also supports a base property and/or target properties that live in a *different* Adobe organization than the one currently active in the CLI. This is useful when you manage several IMS orgs and want to push the same rules, data elements and extensions from a single base property to properties in other orgs.
353
+ The synchronizer supports a base property and/or target properties across multiple Adobe IMS organizations. Append `@<org_name>` to any property name to resolve it against that `org_name` entry from a multi-org config file (see [create_config_file](#create_config_file)).
347
354
 
348
- To reference a property in another organization, append `@<org_name>` to its name, where `<org_name>` matches an `org_name` entry from a multi-org config file (see [create_config_file](#create_config_file)). Any property name without `@<org_name>` is resolved against the organization that is currently active in the session (the one last set via [config](#config) or [change_org](#change_org)).
355
+ Any property name **without** `@<org_name>` defaults to the **first** organization defined in the multi-org config file (regardless of `--org_name` or `change_org`).
349
356
 
350
- First, load a multi-org config file so every organization you want to reference is available in the session:
351
- ```bash
352
- python -m launchpy.cli -cf <path_to_your_multi_org_config_file> --org_name client_a
353
- launchpy:client_a>
354
- ```
355
-
356
- Then load the synchronizer using `@org_name` on the base and/or the targets:
357
357
  ```bash
358
+ python -m launchpy.cli -cf <path_to_your_multi_org_config_file>
358
359
  launchpy:client_a> load_synchronizer "Base Property Name@client_a" -t "Target Property 1@client_b" "Target Property 2@client_c"
359
- synchronizer:Base_Property_Name>
360
+ synchronizer:Base Property Name>
360
361
  ```
361
362
 
362
- Organizations can be mixed freely; targets that omit `@org_name` resolve to the currently active organization (`client_a` below):
363
+ Organizations can be mixed freely; properties omitting `@org_name` resolve to the first organization in the config file (`client_a` below):
363
364
  ```bash
364
365
  launchpy:client_a> load_synchronizer "Base Property Name" -t "Target Property 1" "Target Property 2@client_b"
365
- synchronizer:Base_Property_Name>
366
+ synchronizer:Base Property Name>
366
367
  ```
367
368
 
368
- **Note**: if a private extension used by the base property is named differently in a target organization, the CLI cannot map the two names for you — this requires passing a `mapping_extensions` dictionary (`{"target-extension-name": "base-extension-name"}`) to `launchpy.Synchronizer` directly through the Python API, usually done via a Notebook, since that option is not exposed as a CLI flag.
369
+ See [Multi-Organization Synchronization](#multi-organization-synchronization) for the complete end-to-end workflow, dynamic filtering behavior, and cross-org limitations.
369
370
 
370
371
  ### Property Layer Commands
371
372
 
@@ -533,9 +534,12 @@ Arguments:
533
534
  `-r`, `--regex`: Regex pattern to filter rules by name (partial match, non-case sensitive). This is an optional parameter, if not provided, all rules are synced.
534
535
  `-c`, `--create` : Flag. Create rules that do not exist in the destination property. Default False.
535
536
  `-p`, `--published` : Flag. Sync the latest published version of the rules. Default False.
537
+ `-i`, `--ignore_disabled` : Optional boolean. Skip disabled source rules. Default False; a bare flag means True. With `-p`, checks the latest published source revision.
536
538
 
537
539
  ```bash
538
540
  synchronizer:Base_Property_Name> sync_rules -r "Rule Name" -c
541
+ synchronizer:Base_Property_Name> sync_rules -i
542
+ synchronizer:Base_Property_Name> sync_rules --ignore_disabled True -p
539
543
  ```
540
544
 
541
545
  #### sync_data_elements
@@ -544,9 +548,12 @@ Arguments:
544
548
  `-r`, `--regex`: Regex pattern to filter data elements by name (partial match, non-case sensitive). This is an optional parameter, if not provided, all data elements are synced.
545
549
  `-c`, `--create` : Flag. Create data elements that do not exist in the destination property. Default False.
546
550
  `-p`, `--published` : Flag. Sync the latest published version of the data elements. Default False.
551
+ `-i`, `--ignore_disabled` : Optional boolean. Skip disabled source data elements. Default False; a bare flag means True. With `-p`, checks the latest published source revision.
547
552
 
548
553
  ```bash
549
554
  synchronizer:Base_Property_Name> sync_data_elements -r "Data Element Name" -c
555
+ synchronizer:Base_Property_Name> sync_data_elements -i
556
+ synchronizer:Base_Property_Name> sync_data_elements --ignore_disabled False
550
557
  ```
551
558
 
552
559
  #### sync_extensions
@@ -669,11 +676,158 @@ Arguments:
669
676
  `-env`, `--environment`: String. If set to `True`, it will try to find a free environment and assign it to the library. If none is available, it will not assign any environment to the library. If the name of the environment is provided, it will try to assign it to that library. If the environment is already used in a Library, it will remove that association and assign it to the new library. Default False. Possible values: `True`, `False` or a `string` which is the (partial) name of the environment you want to assign to the library.
670
677
 
671
678
  ```bash
672
- synchronizer:Base_Property_Name> create_library "Library Name" -env True
679
+ synchronizer:Base_Property_Name> create_libraries "Library Name" -env True
680
+ ```
681
+
682
+ ```bash
683
+ synchronizer:Base_Property_Name> create_libraries "Library Name" -env "Environment Name"
684
+ ```
685
+
686
+ ### Multi-Organization Synchronization
687
+
688
+ The `launchpy` CLI can synchronize extensions, data elements, rules, and libraries from a base property in one Adobe IMS organization to target properties in one or more other IMS organizations within a single interactive session.
689
+
690
+ #### 1. Create and populate a multi-org config file
691
+
692
+ Generate a multi-org configuration template from the main CLI prompt:
693
+
694
+ ```bash
695
+ python -m launchpy.cli
696
+ (Cmd) create_config_file --multi_org -fn multi_org_config.json
697
+ ```
698
+
699
+ Add `--proxy` (`-p`) if you also want a `"proxy"` placeholder added to the template.
700
+
701
+ Unlike a single-org config file (a JSON object), a multi-org config file is a **JSON array** where each element represents one IMS organization and **must** include a unique `"org_name"` alias:
702
+
703
+ ```json
704
+ [
705
+ {
706
+ "org_id": "11111111111111110A495C00@AdobeOrg",
707
+ "client_id": "<client_id_source>",
708
+ "secret": "<secret_source>",
709
+ "scopes": "openid,AdobeID,read_organizations,additional_info.projectedProductContext,additional_info.job_function,https://ims-na1.adobelogin.com/s/ent_reactor_admin_sdk",
710
+ "org_name": "org_source"
711
+ },
712
+ {
713
+ "org_id": "22222222222222220A495C00@AdobeOrg",
714
+ "client_id": "<client_id_eu>",
715
+ "secret": "<secret_eu>",
716
+ "scopes": "openid,AdobeID,read_organizations,additional_info.projectedProductContext,additional_info.job_function,https://ims-na1.adobelogin.com/s/ent_reactor_admin_sdk",
717
+ "org_name": "org_eu",
718
+ "proxy": "http://proxy.example.com:8080"
719
+ },
720
+ {
721
+ "org_id": "33333333333333330A495C00@AdobeOrg",
722
+ "client_id": "<client_id_us>",
723
+ "secret": "<secret_us>",
724
+ "scopes": "openid,AdobeID,read_organizations,additional_info.projectedProductContext,additional_info.job_function,https://ims-na1.adobelogin.com/s/ent_reactor_admin_sdk",
725
+ "org_name": "org_us"
726
+ }
727
+ ]
673
728
  ```
674
729
 
730
+ * `org_name` is a short alias you choose (for example `org_source`, `client_a`), **not** the Adobe `org_id` (`...@AdobeOrg`). Do **not** include `@` in `org_name`.
731
+ * Each entry can use `client_id` (or legacy `api_key`) and an optional per-organization `proxy`.
732
+
733
+ #### 2. Connect the CLI with the multi-org config
734
+
735
+ Load the multi-org file either when launching the CLI (`launchpy` or `python -m launchpy.cli`) or interactively with `config`:
736
+
675
737
  ```bash
676
- synchronizer:Base_Property_Name> create_library "Library Name" -env "Environment Name
738
+ python -m launchpy.cli -cf multi_org_config.json
739
+ launchpy:org_source>
740
+ ```
677
741
 
742
+ Or interactively:
743
+
744
+ ```text
745
+ (Cmd) config -cf multi_org_config.json -on org_source
746
+ launchpy:org_source>
678
747
  ```
679
-
748
+
749
+ All organizations in the JSON array are registered in memory at once. Before starting the synchronizer, you can optionally verify property names in each organization using `change_org` and `get_properties`:
750
+
751
+ ```text
752
+ launchpy:org_source> get_properties
753
+ launchpy:org_source> change_org org_eu
754
+ launchpy:org_eu> get_properties
755
+ ```
756
+
757
+ #### 3. Load the synchronizer across organizations
758
+
759
+ Run `load_synchronizer` from the main shell (`launchpy:<org_name>>`) using `<Property Name>@<org_name>` for any base or target property:
760
+
761
+ ```text
762
+ launchpy:org_source> load_synchronizer "Global Template@org_source" -t "Brand Web@org_eu" "Brand Web@org_us"
763
+ synchronizer:Global Template>
764
+ ```
765
+
766
+ **Organization resolution rules:**
767
+ * **With `@<org_name>`** (`"Property Name@org_eu"`): `launchpy` creates a dedicated connector for `org_eu` and looks up `"Property Name"` in that organization.
768
+ * **Without `@<org_name>`** (`"Property Name"`): `launchpy` resolves the property against the **first organization** in the multi-org config file (`org_source` in the example above). Changing the active CLI prompt via `--org_name` or `change_org` does **not** change this default fallback.
769
+ * **Prompt and target identifiers**:
770
+ * The synchronizer prompt strips `@<org_name>` from the base property (`synchronizer:Global Template>`).
771
+ * Target identifiers keep their exact input string (`"Brand Web@org_eu"`, `"Brand Web@org_us"`), which you can inspect with `get_targets`. Because `@<org_name>` stays part of each target key, target properties in different organizations can safely share the exact same property name.
772
+
773
+ #### 4. End-to-end cross-org synchronization workflow
774
+
775
+ Once inside `synchronizer:<Base Property>>`, all synchronizer commands automatically route API calls and translate extension/rule IDs per target organization:
776
+
777
+ ```text
778
+ # 1. Verify configured targets
779
+ synchronizer:Global Template> get_targets
780
+
781
+ # 2. Install/align extensions in target orgs first (required before syncing dependent components)
782
+ synchronizer:Global Template> sync_extensions -c -v
783
+ synchronizer:Global Template> upgrade_extension "core" -v
784
+
785
+ # 3. Compare a component across target orgs before syncing
786
+ synchronizer:Global Template> check_component -n "DE - Page Name" -p
787
+
788
+ # 4a. Sync data elements and rules (skipping disabled source components)
789
+ synchronizer:Global Template> sync_data_elements -c -p -i -v
790
+ synchronizer:Global Template> sync_rules -c -p -i -v
791
+
792
+ # 4b. Or preview and sync everything from a specific library in the base property
793
+ synchronizer:Global Template> sync_from_library -n "Release 2026.11" -dr True
794
+ synchronizer:Global Template> sync_from_library -n "Release 2026.11" -c True -v True
795
+
796
+ # 5. Bundle all synced changes into a development library in each target org and build it
797
+ synchronizer:Global Template> create_libraries "Cross-Org Sync 2026.11" -env True
798
+
799
+ # 6. Return to the main CLI prompt
800
+ synchronizer:Global Template> exit
801
+ ```
802
+
803
+ #### 5. Dynamic component filtering across organizations
804
+
805
+ If you pass `-dy "<Data Element Name>"` to `load_synchronizer`, the JSON filter rules are read from that Data Element in the **base** property:
806
+
807
+ ```text
808
+ launchpy:org_source> load_synchronizer "Global Template@org_source" -t "Brand Web@org_eu" "Brand Web@org_us" -dy "DE - Sync Config"
809
+ ```
810
+
811
+ Each filter object's `"targetProperties"` regular expression is matched (`re.search`) against the **target key** stored in the synchronizer — including `@<org_name>` when `@<org_name>` was specified in `-t`. For example, you can exclude GDPR-specific rules for US organization targets:
812
+
813
+ ```json
814
+ [
815
+ {
816
+ "name": "US exclusions",
817
+ "targetProperties": "@org_us$",
818
+ "exclComponents": ["^RL - GDPR .*"],
819
+ "inclComponents": []
820
+ }
821
+ ]
822
+ ```
823
+
824
+ If you write a `"targetProperties"` regex with an end-of-string anchor (`$`), remember to include `@<org_name>` when targets are loaded with `@<org_name>`.
825
+
826
+ #### 6. Multi-org limitations and notes
827
+
828
+ * **First organization credentials are always queried on init**: `Synchronizer` initializes a default `Admin` connection against the first organization in the config file even when `base` and all `targets` include `@<org_name>`, so ensure the first entry in your multi-org config file has valid credentials.
829
+ * **No `@` in property names or `org_name`**: `@` is split using `split('@')`, so neither `org_name` nor property names passed with `@<org_name>` may contain `@`.
830
+ * **Unique component names & aligned extensions**: Rules and data elements are matched by exact name across organizations, and any extension referenced by synced rules or data elements must exist in the target property (use `sync_extensions -c` for catalog extensions).
831
+ * **Private extensions**:
832
+ * A private extension published only to one IMS organization cannot be auto-installed in another IMS organization unless its package is also available there.
833
+ * If equivalent private extensions have **different names** in two organizations, the CLI cannot map them; use `launchpy.Synchronizer(..., mapping_extensions={"target_ext_name": "base_ext_name"})` from Python instead.
@@ -3,6 +3,15 @@
3
3
  This page gathered the changes made between version of the launchpy module.\
4
4
  This has been started after the 0.3.0 release.\
5
5
 
6
+ ## 0.5.4
7
+ * Fixing enabled state handling for rules, data elements, and extensions during synchronization. Before release, state enablement was respected only during -published synchronization.
8
+ * Ensuring that the verbose flag correctly displays detailed information for all synchronized entities, including those with enabled state changes.
9
+ * Adding the `ignore_disabled` flag to the synchronization commands to allow skipping disabled source entities.
10
+ * Adding `-i` / `--ignore_disabled` flag to the CLI synchronization commands.\
11
+ Patch:
12
+ * Fixing the header used in multi-organization API requests.
13
+
14
+
6
15
  ## 0.5.3
7
16
  * Adding optional `proxy` support to `configure`, `importConfigFile`, `createConfigFile` and JSON configuration files. A single proxy URL is used for both HTTP and HTTPS, with separate settings per organization.
8
17
  * Applying proxy settings to OAuth token acquisition and refresh, all API requests and their retries, and asynchronous rule-component downloads during `extractProperty`.
@@ -150,6 +150,7 @@ synchronizor.syncComponent('my Component Name',publishedVersion=True)
150
150
  #### Data Elements
151
151
  The method will replace the existing configuration of a data element by the template configuration.\
152
152
  Completely overriding the existing element configuration in the target properties.
153
+ When a data element is created, its enabled state is updated if needed to match the selected source revision. The response from that update is retained in the target cache and library stack.
153
154
 
154
155
  #### Rules
155
156
  The method will delete all rule components existing in the Target property for that rule.\
@@ -198,6 +199,7 @@ Arguments:
198
199
  * regex : OPTIONAL : If you want to filter the data elements to sync based on a regex pattern. Default: None (sync all data elements)
199
200
  * forceCreation : OPTIONAL : If set to True, it will sync the data elements even if they do not exist in the target properties. If set to False, it will only sync the data elements that already exist in the target properties. Default: False.
200
201
  * publishedVersion : OPTIONAL : If set to True, it will sync the latest published version of the data elements. Default: False.
202
+ * ignoreDisabled : OPTIONAL : If set to True, skip data elements whose selected source revision has `enabled=False`. Default: False.
201
203
 
202
204
  ## SyncRules
203
205
  It will synchronize the rules in the base property to the target properties.
@@ -205,7 +207,14 @@ Arguments:
205
207
  * regex : OPTIONAL : If you want to filter the rules to sync based on a regex pattern. Default: None (sync all rules)
206
208
  * forceCreation : OPTIONAL : If set to True, it will sync the rules even if they do not exist in the target properties. If set to False, it will only sync the rules that already exist in the target properties. Default: False.
207
209
  * publishedVersion : OPTIONAL : If set to True, it will sync the latest published version of the rules. Default: False.
210
+ * ignoreDisabled : OPTIONAL : If set to True, skip rules whose selected source revision has `enabled=False`. Default: False.
208
211
 
212
+ For both methods, `ignoreDisabled=True` checks the source revision being synchronized, not the target's enabled state. With `publishedVersion=True`, it checks the latest published source revision rather than the current draft. Disabled components are not created or updated, even with `forceCreation=True`, and retain an empty per-target dictionary in the returned results.
213
+
214
+ ```python
215
+ synchronizor.syncRules(ignoreDisabled=True)
216
+ synchronizor.syncDataElements(ignoreDisabled=True, publishedVersion=True)
217
+ ```
209
218
 
210
219
  ## createTargetsLibrary
211
220
 
@@ -238,6 +247,7 @@ Check if the component,from the base property, is synced to the different target
238
247
  It can also check for the Extensions.\
239
248
  It will return a dictionary with the key being the target property and the value being the result of the evaluation, such as {targetProperty: 'similar'} when component have same settings or {targetPropery : '<difference>'} when component do not have same settings.\
240
249
  See below for differences.\
250
+ For rules and data elements, enabled-state differences are checked in both current and published modes. A matching configuration does not override an enabled-state difference with `"Similar"`. When a data element has multiple differences, they are returned together as a comma-separated message. Library dry runs use the same comparison logic.
241
251
  Arguments:
242
252
  * componentName : REQUIRED : the name of the component to compare
243
253
  * componentID : REQUIRED : the id of the component to compare
@@ -0,0 +1 @@
1
+ __version__ = "0.5.4-1"
@@ -595,10 +595,11 @@ class SynchronizerCLI(cmd.Cmd):
595
595
  parser.add_argument("-r", "--regex", help="Regex pattern to filter rules by name (partial match, non-case sensitive). Default None.", type=str, default=None)
596
596
  parser.add_argument("-c", "--create", help="Create rules that do not exist in the destination property. Default False.", action="store_true", default=False)
597
597
  parser.add_argument("-p", "--published", help="Sync the latest published version of the rules. Default False.", action="store_true", default=False)
598
+ parser.add_argument("-i", "--ignore_disabled", help="Skip disabled source rules. Default False. A bare flag means True.", type=str2bool, nargs="?", const=True, default=False)
598
599
  parser.add_argument("-v", "--verbose", help="Print detailed information about the sync process, including successes. Default False.", action="store_true", default=False)
599
600
  try:
600
601
  args = parser.parse_args(shlex.split(args))
601
- result = self.synchronizer.syncRules(regex=args.regex, forceCreation=args.create, publishedVersion=args.published)
602
+ result = self.synchronizer.syncRules(regex=args.regex, forceCreation=args.create, publishedVersion=args.published, ignoreDisabled=args.ignore_disabled)
602
603
  for ruleName, targetResults in result.items():
603
604
  for prop, message in (targetResults or {}).items():
604
605
  if "does not exist" in message:
@@ -617,10 +618,11 @@ class SynchronizerCLI(cmd.Cmd):
617
618
  parser.add_argument("-r", "--regex", help="Regex pattern to filter data elements by name (partial match, non-case sensitive). Default None.", type=str, default=None)
618
619
  parser.add_argument("-c", "--create", help="Create data elements that do not exist in the destination property. Default False.", action="store_true", default=False)
619
620
  parser.add_argument("-p", "--published", help="Sync the latest published version of the data elements. Default False.", action="store_true", default=False)
621
+ parser.add_argument("-i", "--ignore_disabled", help="Skip disabled source data elements. Default False. A bare flag means True.", type=str2bool, nargs="?", const=True, default=False)
620
622
  parser.add_argument("-v", "--verbose", help="Print detailed information about the sync process, including successes. Default False.", action="store_true", default=False)
621
623
  try:
622
624
  args = parser.parse_args(shlex.split(args))
623
- result = self.synchronizer.syncDataElements(regex=args.regex, forceCreation=args.create, publishedVersion=args.published)
625
+ result = self.synchronizer.syncDataElements(regex=args.regex, forceCreation=args.create, publishedVersion=args.published, ignoreDisabled=args.ignore_disabled)
624
626
  for deName, targetResults in result.items():
625
627
  for prop, message in (targetResults or {}).items():
626
628
  if "does not exist" in message:
@@ -1187,7 +1189,7 @@ class MainShell(cmd.Cmd):
1187
1189
  for org_name, config in config_objects.items():
1188
1190
  myheaders[org_name] = deepcopy(self.header_template)
1189
1191
  myheaders[org_name]["x-gw-ims-org-id"] = config['org_id']
1190
- myheaders[org_name]["x-gw-ims-org-id"] = config['org_id']
1192
+ myheaders[org_name]["x-api-key"] = config['client_id']
1191
1193
  headers.update(myheaders)
1192
1194
  config_key = args.org_name if args.org_name else config_key
1193
1195
  self._configure_connection(org_name=config_key)
@@ -263,6 +263,7 @@ class Synchronizer:
263
263
  timeout : OPTIONAL : The timeout to be used for the rule component. If not provided, the existing timeout will be used.
264
264
  libraryLinked : OPTIONAL : If you want to take a component ID that are associated to a specific library. Default: False. If set to True, the method will look for the component in the library and take the version linked to the library instead of the latest version in the property. Do not work for Extensions.
265
265
  verbose : OPTIONAL : If set to True, it will print the synchronization status of each property. Default: False.
266
+ ignoreDisabled : OPTIONAL : Skip disabled source rules and data elements, returning an empty dictionary. Uses the selected revision. Default: False.
266
267
  """
267
268
  timeout = kwargs.get('timeout',None)
268
269
  libraryLinked = kwargs.get('libraryLinked',False)
@@ -271,6 +272,10 @@ class Synchronizer:
271
272
  raise ValueError('Require a component Name of a component ID')
272
273
  response = {}
273
274
  cmp_baseDict = self.__prepareBaseComponent__(componentName=componentName,componentId=componentId,publishedVersion=publishedVersion,libraryLinked=libraryLinked)
275
+ if (kwargs.get('ignoreDisabled',False)
276
+ and cmp_baseDict['component']['type'] in ('rules','data_elements')
277
+ and not cmp_baseDict['component']['attributes']['enabled']):
278
+ return response
274
279
  ## handling the data element
275
280
  if cmp_baseDict['component']['type'] == 'data_elements':
276
281
  for target in list(self.targets.keys()):
@@ -288,6 +293,16 @@ class Synchronizer:
288
293
  if len(self.target_configs.get(target,{}).get('inclComponents',[]))==0 or flagAllowList:
289
294
  with self._target_locks[target]:
290
295
  translatedComponent = self.translator.translate(target,data_element=cmp_baseDict['copy'])
296
+ attributes = {
297
+ "name" : translatedComponent['name'],
298
+ "enabled" : translatedComponent["enabled"],
299
+ "delegate_descriptor_id" : translatedComponent["descriptor"],
300
+ "storage_duration" : translatedComponent["storage_duration"],
301
+ "force_lower_case" : translatedComponent["force_lower_case"],
302
+ "clean_text" : translatedComponent["clean_text"],
303
+ "settings" : translatedComponent["settings"],
304
+ "default_value": translatedComponent["default_value"]
305
+ }
291
306
  ## if it does not exist
292
307
  if cmp_baseDict['name'] not in [de.get('attributes',{}).get('name') for de in self.targets[target]['dataElements']]:
293
308
  if forceCreation:
@@ -304,9 +319,9 @@ class Synchronizer:
304
319
  default_value= translatedComponent["default_value"]
305
320
  )
306
321
  if cmp_baseDict['component']['attributes']['enabled'] != comp['attributes']['enabled']:
307
- updateDE = self.targets[target]['api'].updateDataElement(
322
+ comp = self.targets[target]['api'].updateDataElement(
308
323
  dataElement_id=comp['id'],
309
- attr_dict=translatedComponent)
324
+ attr_dict=attributes)
310
325
  self.targets[target]['libraryStack']['dataElements'].append(comp)
311
326
  self.targets[target]['dataElements'].append(comp)
312
327
  response[target] = f'Data element "{cmp_baseDict["name"]}" created in "{target}".'
@@ -316,16 +331,6 @@ class Synchronizer:
316
331
  response[target] = message
317
332
  else:
318
333
  index,old_component = [(index,de) for index,de in enumerate(self.targets[target]['dataElements']) if de.get('attributes',{}).get('name') == cmp_baseDict['name']][0]
319
- attributes = {
320
- "name" : translatedComponent['name'],
321
- "enabled" : translatedComponent["enabled"],
322
- "delegate_descriptor_id" : translatedComponent["descriptor"],
323
- "storage_duration" : translatedComponent["storage_duration"],
324
- "force_lower_case" : translatedComponent["force_lower_case"],
325
- "clean_text" : translatedComponent["clean_text"],
326
- "settings" : translatedComponent["settings"],
327
- "default_value": translatedComponent["default_value"]
328
- }
329
334
  comp = self.targets[target]['api'].updateDataElement(
330
335
  dataElement_id=old_component['id'],
331
336
  attr_dict=attributes,
@@ -513,7 +518,7 @@ class Synchronizer:
513
518
  results[component] = self.syncComponent(componentId=component,publishedVersion=publishedVersion,forceCreation=forceCreation)
514
519
  return results
515
520
 
516
- def syncRules(self,regex:str=None,forceCreation:bool=False,publishedVersion:bool=False)->dict:
521
+ def syncRules(self,regex:str=None,forceCreation:bool=False,publishedVersion:bool=False,ignoreDisabled:bool=False)->dict:
517
522
  """
518
523
  Synchronizing the rules in the base property to the target properties.
519
524
  Returns a dictionary keyed by rule name, with the per-target status (created, updated, or not synced because the rule does not exist and forceCreation is False).
@@ -521,18 +526,19 @@ class Synchronizer:
521
526
  regex : OPTIONAL : If you want to filter the rules to sync based on a regex pattern. Default: None (sync all rules)
522
527
  forceCreation : OPTIONAL : If set to True, it will sync the rules even if they do not exist in the target properties. If set to False, it will only sync the rules that already exist in the target properties. Default: False.
523
528
  publishedVersion : OPTIONAL : If set to True, it will sync the latest published version of the rules. Default: False.
529
+ ignoreDisabled : OPTIONAL : Skip rules whose selected source revision is disabled. Skipped rules have an empty per-target result. Default: False.
524
530
  """
525
531
  base_rule_names = [rule['attributes']['name'] for rule in self.base['rules']]
526
532
  if regex is not None:
527
533
  base_rule_names = [rule for rule in base_rule_names if re.search(regex,rule)]
528
534
  results = {}
529
535
  with ThreadPoolExecutor() as executor:
530
- future_to_name = {executor.submit(self.syncComponent, componentName=rule, forceCreation=forceCreation, publishedVersion=publishedVersion): rule for rule in base_rule_names}
536
+ future_to_name = {executor.submit(self.syncComponent, componentName=rule, forceCreation=forceCreation, publishedVersion=publishedVersion, ignoreDisabled=ignoreDisabled): rule for rule in base_rule_names}
531
537
  for future in future_to_name:
532
538
  results[future_to_name[future]] = future.result()
533
539
  return results
534
540
 
535
- def syncDataElements(self,regex:str=None,forceCreation:bool=False,publishedVersion:bool=False)->dict:
541
+ def syncDataElements(self,regex:str=None,forceCreation:bool=False,publishedVersion:bool=False,ignoreDisabled:bool=False)->dict:
536
542
  """
537
543
  Synchronizing the data elements in the base property to the target properties.
538
544
  Returns a dictionary keyed by data element name, with the per-target status (created, updated, or not synced because the data element does not exist and forceCreation is False).
@@ -540,13 +546,14 @@ class Synchronizer:
540
546
  regex : OPTIONAL : If you want to filter the data elements to sync based on a regex pattern. Default: None (sync all data elements)
541
547
  forceCreation : OPTIONAL : If set to True, it will sync the data elements even if they do not exist in the target properties. If set to False, it will only sync the data elements that already exist in the target properties. Default: False.
542
548
  publishedVersion : OPTIONAL : If set to True, it will sync the latest published version of the data elements. Default: False.
549
+ ignoreDisabled : OPTIONAL : Skip data elements whose selected source revision is disabled. Skipped data elements have an empty per-target result. Default: False.
543
550
  """
544
551
  base_de_names = [de['attributes']['name'] for de in self.base['dataElements']]
545
552
  if regex is not None:
546
553
  base_de_names = [de for de in base_de_names if re.search(regex,de)]
547
554
  results = {}
548
555
  with ThreadPoolExecutor() as executor:
549
- future_to_name = {executor.submit(self.syncComponent, componentName=de, forceCreation=forceCreation, publishedVersion=publishedVersion): de for de in base_de_names}
556
+ future_to_name = {executor.submit(self.syncComponent, componentName=de, forceCreation=forceCreation, publishedVersion=publishedVersion, ignoreDisabled=ignoreDisabled): de for de in base_de_names}
550
557
  for future in future_to_name:
551
558
  results[future_to_name[future]] = future.result()
552
559
  return results
@@ -793,21 +800,23 @@ class Synchronizer:
793
800
  else:
794
801
  index,target_de = [(index,de) for index,de in enumerate(self.targets[target]['dataElements']) if de['attributes']['name'] == cmp_baseDict['name']][0]
795
802
  issue_pub = ""
803
+ differences: list[str] = []
796
804
  if publishedVersion:
797
805
  try:
798
806
  revisions_dataElement = self.targets[target]["api"].getRevisions(target_de)
799
807
  target_de = self.targets[target]["api"].getLatestPublishedVersion(revisions_dataElement)
800
808
  except:
801
809
  issue_pub = " (draft)"
802
- if target_de['attributes']['enabled'] != cmp_baseDict['component']['attributes']['enabled']:
803
- dict_result[target] = "Data Element enabled status is different"+issue_pub
804
- if target_de['attributes']['published'] != cmp_baseDict['component']['attributes']['published']:
805
- dict_result[target] = "Data Element published status is different"+issue_pub
806
- if target_de['attributes']['settings'] == cmp_baseDict['component']['attributes']['settings']:
807
- if not excludeSimilar:
808
- dict_result[target] = "Similar"+issue_pub
809
- else:
810
- dict_result[target] = "Data Element settings are different"+issue_pub
810
+ if target_de['attributes']['enabled'] != cmp_baseDict['component']['attributes']['enabled']:
811
+ differences.append("Data Element enabled status is different")
812
+ if publishedVersion and target_de['attributes']['published'] != cmp_baseDict['component']['attributes']['published']:
813
+ differences.append("Data Element published status is different")
814
+ if target_de['attributes']['settings'] != cmp_baseDict['component']['attributes']['settings']:
815
+ differences.append("Data Element settings are different")
816
+ if differences:
817
+ dict_result[target] = ','.join(differences) + issue_pub
818
+ elif not excludeSimilar:
819
+ dict_result[target] = "Similar"+issue_pub
811
820
  if cmp_baseDict['component']['type'] == 'rules':
812
821
  rcsLink = cmp_baseDict['component'].get('relationships',{}).get('rule_components',{}).get('links',{}).get('related')
813
822
  resResource = self.base['api'].getRessource(rcsLink)
@@ -829,10 +838,10 @@ class Synchronizer:
829
838
  targetRule = self.targets[target]["api"].getLatestPublishedVersion(revisions_targetRule)
830
839
  except:
831
840
  issue_pub = " (not published)"
832
- if targetRule['attributes']['enabled'] != cmp_baseDict['component']['attributes']['enabled']:
833
- componentsDifferences.append("Rule enabled status is different")
834
- if targetRule['attributes']['published'] != cmp_baseDict['component']['attributes']['published']:
835
- componentsDifferences.append("Rule published status is different")
841
+ if targetRule['attributes']['enabled'] != cmp_baseDict['component']['attributes']['enabled']:
842
+ componentsDifferences.append("Rule enabled status is different")
843
+ if publishedVersion and targetRule['attributes']['published'] != cmp_baseDict['component']['attributes']['published']:
844
+ componentsDifferences.append("Rule published status is different")
836
845
  rcsLinkTarget = targetRule.get('relationships',{}).get('rule_components',{}).get('links',{}).get('related')
837
846
  resResource = self.targets[target]['api'].getRessource(rcsLinkTarget)
838
847
  target_rule_components:list = resResource['data']
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: launchpy
3
- Version: 0.5.3
3
+ Version: 0.5.4.post1
4
4
  Summary: Adobe Launch API wrapper
5
5
  Author-email: Julien Piccini <piccini.julien@gmail.com>
6
6
  License: Apache License 2.0
@@ -30,4 +30,5 @@ launchpy.egg-info/top_level.txt
30
30
  launchpy/cli/__init__.py
31
31
  launchpy/cli/__main__.py
32
32
  tests/test_connector.py
33
- tests/test_proxies.py
33
+ tests/test_proxies.py
34
+ tests/test_synchronizer.py
@@ -0,0 +1,467 @@
1
+ from copy import deepcopy
2
+ import json
3
+ from pathlib import Path
4
+ import tempfile
5
+ import threading
6
+ import unittest
7
+ from unittest.mock import Mock, patch
8
+
9
+ from launchpy.cli.__main__ import MainShell, SynchronizerCLI
10
+ from launchpy.config import config_objects, headers
11
+ from launchpy.launchpy import Translator
12
+ from launchpy.property import Property
13
+ from launchpy.synchronizer import Synchronizer
14
+
15
+
16
+ def component(kind: str, identifier: str, enabled: bool) -> dict:
17
+ data = {
18
+ "id": identifier,
19
+ "type": kind,
20
+ "attributes": {
21
+ "name": "Sample component",
22
+ "enabled": enabled,
23
+ "published": False,
24
+ "revision_number": 2,
25
+ },
26
+ "links": {
27
+ "self": "https://example.invalid/" + identifier,
28
+ "origin": "https://example.invalid/" + identifier,
29
+ },
30
+ "relationships": {
31
+ "rule_components": {"links": {"related": "mock:components"}},
32
+ },
33
+ }
34
+ if kind == "data_elements":
35
+ data["attributes"].update(
36
+ settings="{}",
37
+ delegate_descriptor_id="core::dataElements::custom-code",
38
+ storage_duration="pageview",
39
+ force_lower_case=False,
40
+ default_value="",
41
+ clean_text=False,
42
+ )
43
+ data["relationships"]["extension"] = {
44
+ "data": {"id": "EXbase", "type": "extensions"},
45
+ }
46
+ return data
47
+
48
+
49
+ class SynchronizerTests(unittest.TestCase):
50
+ def make_sync(
51
+ self, kind: str, source_enabled: bool = False, target_enabled: bool = True
52
+ ) -> tuple[Synchronizer, dict, dict]:
53
+ prefix = "RL" if kind == "rules" else "DE"
54
+ source = component(kind, prefix + "base", source_enabled)
55
+ target = component(kind, prefix + "target", target_enabled)
56
+ key = "rules" if kind == "rules" else "dataElements"
57
+ source_api = Mock(spec=Property)
58
+ source_api.connector = Mock()
59
+ target_api = Mock(spec=Property)
60
+ source_api.getRessource.return_value = {"data": []}
61
+ target_api.getRessource.return_value = {"data": []}
62
+ source_api.getRevisions.return_value = [source]
63
+ target_api.getRevisions.return_value = [target]
64
+ source_api.getLatestPublishedVersion.return_value = source
65
+ target_api.getLatestPublishedVersion.return_value = target
66
+ target_api.updateDataElement.side_effect = (
67
+ lambda dataElement_id, attr_dict: self.updated(target, attr_dict)
68
+ )
69
+ target_api.updateRule.side_effect = (
70
+ lambda rule_id, attr_dict: self.updated(target, attr_dict)
71
+ )
72
+ sync = Synchronizer.__new__(Synchronizer)
73
+ sync.base = {
74
+ "name": "Base",
75
+ "api": source_api,
76
+ "rules": [],
77
+ "dataElements": [],
78
+ "extensions": [],
79
+ }
80
+ sync.base[key] = [source]
81
+ sync.targets = {
82
+ "Target": {
83
+ "api": target_api,
84
+ "rules": [],
85
+ "dataElements": [],
86
+ "libraryStack": {"rules": [], "dataElements": [], "extensions": []},
87
+ },
88
+ }
89
+ sync.targets["Target"][key] = [target]
90
+ sync.target_configs = {}
91
+ sync._base_lock = threading.Lock()
92
+ sync._target_locks = {"Target": threading.Lock()}
93
+ sync.translator = Translator()
94
+ sync.translator.setBaseExtensions(
95
+ [{"id": "EXbase", "attributes": {"name": "core"}}], "Base"
96
+ )
97
+ sync.translator.extendExtensions(
98
+ [{"id": "EXtarget", "attributes": {"name": "core"}}], "Target"
99
+ )
100
+ sync.translator.setBaseRules(sync.base["rules"], "Base")
101
+ sync.translator.extendRules(sync.targets["Target"]["rules"], "Target")
102
+ return sync, source, target
103
+
104
+ @staticmethod
105
+ def updated(target: dict, attributes: dict) -> dict:
106
+ result = deepcopy(target)
107
+ result["attributes"].update(attributes)
108
+ return result
109
+
110
+ def test_created_data_element_update_uses_api_attributes_and_tracks_response(self):
111
+ for source_enabled in (False, True):
112
+ with self.subTest(source_enabled=source_enabled):
113
+ sync, source, created = self.make_sync(
114
+ "data_elements", source_enabled, not source_enabled
115
+ )
116
+ target = sync.targets["Target"]
117
+ target["dataElements"] = []
118
+ api = target["api"]
119
+ api.createDataElement.return_value = created
120
+ attributes = {
121
+ "name": source["attributes"]["name"],
122
+ "enabled": source_enabled,
123
+ "delegate_descriptor_id": source["attributes"]["delegate_descriptor_id"],
124
+ "storage_duration": source["attributes"]["storage_duration"],
125
+ "force_lower_case": source["attributes"]["force_lower_case"],
126
+ "clean_text": source["attributes"]["clean_text"],
127
+ "settings": source["attributes"]["settings"],
128
+ "default_value": source["attributes"]["default_value"],
129
+ }
130
+ updated = self.updated(created, attributes)
131
+ updated["attributes"]["revision_number"] += 1
132
+ api.updateDataElement.side_effect = None
133
+ api.updateDataElement.return_value = updated
134
+
135
+ result = sync.syncComponent(componentId=source["id"], forceCreation=True)
136
+
137
+ api.updateDataElement.assert_called_once_with(
138
+ dataElement_id=created["id"], attr_dict=attributes
139
+ )
140
+ self.assertEqual(
141
+ result,
142
+ {"Target": 'Data element "Sample component" created in "Target".'},
143
+ )
144
+ self.assertEqual(len(target["dataElements"]), 1)
145
+ self.assertEqual(len(target["libraryStack"]["dataElements"]), 1)
146
+ self.assertIs(target["dataElements"][0], updated)
147
+ self.assertIs(target["libraryStack"]["dataElements"][0], updated)
148
+ self.assertIs(created["attributes"]["enabled"], not source_enabled)
149
+ self.assertEqual(
150
+ sync.checkComponentSync(componentId=source["id"])["Target"], "Similar"
151
+ )
152
+
153
+ def test_created_data_element_needs_no_update_when_enabled_state_matches(self):
154
+ for enabled in (False, True):
155
+ with self.subTest(enabled=enabled):
156
+ sync, source, created = self.make_sync("data_elements", enabled, enabled)
157
+ target = sync.targets["Target"]
158
+ target["dataElements"] = []
159
+ api = target["api"]
160
+ api.createDataElement.return_value = created
161
+
162
+ sync.syncComponent(componentId=source["id"], forceCreation=True)
163
+
164
+ api.updateDataElement.assert_not_called()
165
+ self.assertEqual(target["dataElements"], [created])
166
+ self.assertEqual(target["libraryStack"]["dataElements"], [created])
167
+
168
+ def test_created_data_element_update_failure_is_not_cached_as_success(self):
169
+ sync, source, created = self.make_sync("data_elements")
170
+ target = sync.targets["Target"]
171
+ target["dataElements"] = []
172
+ api = target["api"]
173
+ api.createDataElement.return_value = created
174
+ api.updateDataElement.side_effect = RuntimeError("Data element update failed")
175
+
176
+ with self.assertRaisesRegex(RuntimeError, "Data element update failed"):
177
+ sync.syncComponent(componentId=source["id"], forceCreation=True)
178
+
179
+ self.assertEqual(target["dataElements"], [])
180
+ self.assertEqual(target["libraryStack"]["dataElements"], [])
181
+
182
+ def test_enabled_mismatches_are_reported_in_all_comparison_modes(self):
183
+ for kind, label in (("rules", "Rule"), ("data_elements", "Data Element")):
184
+ for enabled in (False, True):
185
+ for published in (False, True):
186
+ for exclude_similar in (False, True):
187
+ with self.subTest(
188
+ kind=kind, enabled=enabled, published=published,
189
+ exclude_similar=exclude_similar,
190
+ ):
191
+ sync, source, target = self.make_sync(
192
+ kind, enabled, not enabled
193
+ )
194
+ result = sync.checkComponentSync(
195
+ componentId=source["id"],
196
+ publishedVersion=published,
197
+ excludeSimilar=exclude_similar,
198
+ )
199
+ self.assertEqual(
200
+ result["Target"], f"{label} enabled status is different"
201
+ )
202
+
203
+ def test_matching_components_preserve_similar_and_exclude_similar_results(self):
204
+ for kind in ("rules", "data_elements"):
205
+ for published in (False, True):
206
+ for exclude_similar in (False, True):
207
+ with self.subTest(
208
+ kind=kind, published=published, exclude_similar=exclude_similar,
209
+ ):
210
+ sync, source, target = self.make_sync(kind, False, False)
211
+ result = sync.checkComponentSync(
212
+ componentId=source["id"],
213
+ publishedVersion=published,
214
+ excludeSimilar=exclude_similar,
215
+ )
216
+ self.assertEqual(result["Target"], "" if exclude_similar else "Similar")
217
+
218
+ def test_data_element_comparison_retains_all_differences(self):
219
+ sync, source, target = self.make_sync("data_elements")
220
+ source["attributes"]["published"] = True
221
+ target["attributes"]["settings"] = '{"different": true}'
222
+ result = sync.checkComponentSync(componentId=source["id"], publishedVersion=True)
223
+ self.assertEqual(
224
+ result["Target"],
225
+ "Data Element enabled status is different,"
226
+ "Data Element published status is different,"
227
+ "Data Element settings are different",
228
+ )
229
+
230
+ def test_data_element_published_difference_is_not_overwritten_by_similar_settings(self):
231
+ sync, source, target = self.make_sync("data_elements", False, False)
232
+ source["attributes"]["published"] = True
233
+ result = sync.checkComponentSync(componentId=source["id"], publishedVersion=True)
234
+ self.assertEqual(result["Target"], "Data Element published status is different")
235
+
236
+ def test_comparison_reports_enabled_difference_when_target_has_no_published_revision(self):
237
+ for kind, label, suffix in (
238
+ ("rules", "Rule", " (not published)"),
239
+ ("data_elements", "Data Element", " (draft)"),
240
+ ):
241
+ with self.subTest(kind=kind):
242
+ sync, source, target = self.make_sync(kind)
243
+ sync.targets["Target"]["api"].getLatestPublishedVersion.side_effect = (
244
+ IndexError("No published revision")
245
+ )
246
+ result = sync.checkComponentSync(
247
+ componentId=source["id"], publishedVersion=True
248
+ )
249
+ self.assertEqual(
250
+ result["Target"], f"{label} enabled status is different{suffix}"
251
+ )
252
+
253
+ def test_library_dry_run_reports_enabled_differences(self):
254
+ for kind, label in (("rules", "Rule"), ("data_elements", "Data Element")):
255
+ for published in (False, True):
256
+ with self.subTest(kind=kind, published=published):
257
+ sync, source, target = self.make_sync(kind)
258
+ api = sync.base["api"]
259
+ api.getLibraries.return_value = [
260
+ {"id": "LBbase", "attributes": {"name": "Base library"}},
261
+ ]
262
+ api.getRule.return_value = source
263
+ api.getDataElement.return_value = source
264
+ library = Mock()
265
+ library.getFullLibrary.return_value = {
266
+ "rules": [source] if kind == "rules" else [],
267
+ "data_elements": [source] if kind == "data_elements" else [],
268
+ "extensions": [],
269
+ }
270
+ with patch("launchpy.synchronizer.Library", return_value=library):
271
+ result = sync.syncFromLibrary(
272
+ library="LBbase", dryRun=True, publishedVersion=published
273
+ )
274
+ self.assertEqual(
275
+ result[source["attributes"]["name"]]["Target"],
276
+ f"{label} enabled status is different",
277
+ )
278
+ sync.targets["Target"]["api"].updateRule.assert_not_called()
279
+ sync.targets["Target"]["api"].updateDataElement.assert_not_called()
280
+
281
+ def test_bulk_sync_defaults_to_including_disabled_components(self):
282
+ for kind in ("rules", "data_elements"):
283
+ for options in ({}, {"ignoreDisabled": False}):
284
+ with self.subTest(kind=kind, options=options):
285
+ sync, source, target = self.make_sync(kind)
286
+ method = sync.syncRules if kind == "rules" else sync.syncDataElements
287
+ result = method(**options)
288
+ self.assertIn("Target", result[source["attributes"]["name"]])
289
+ update = (
290
+ sync.targets["Target"]["api"].updateRule
291
+ if kind == "rules"
292
+ else sync.targets["Target"]["api"].updateDataElement
293
+ )
294
+ self.assertIs(update.call_args.kwargs["attr_dict"]["enabled"], False)
295
+
296
+ def test_bulk_sync_ignores_disabled_components_without_touching_targets(self):
297
+ for kind in ("rules", "data_elements"):
298
+ for force_creation in (False, True):
299
+ for target_exists in (False, True):
300
+ with self.subTest(
301
+ kind=kind, force_creation=force_creation,
302
+ target_exists=target_exists,
303
+ ):
304
+ sync, source, target = self.make_sync(kind)
305
+ if not target_exists:
306
+ key = "rules" if kind == "rules" else "dataElements"
307
+ sync.targets["Target"][key] = []
308
+ method = sync.syncRules if kind == "rules" else sync.syncDataElements
309
+ result = method(ignoreDisabled=True, forceCreation=force_creation)
310
+ self.assertEqual(result, {source["attributes"]["name"]: {}})
311
+ self.assertEqual(sync.targets["Target"]["api"].mock_calls, [])
312
+ self.assertEqual(sync.base["api"].mock_calls, [])
313
+ self.assertEqual(
314
+ sync.targets["Target"]["libraryStack"],
315
+ {"rules": [], "dataElements": [], "extensions": []},
316
+ )
317
+
318
+ def test_bulk_sync_only_updates_enabled_components_in_a_mixed_batch(self):
319
+ for kind in ("rules", "data_elements"):
320
+ with self.subTest(kind=kind):
321
+ sync, source, target = self.make_sync(kind)
322
+ key = "rules" if kind == "rules" else "dataElements"
323
+ enabled_source = deepcopy(source)
324
+ enabled_source["id"] += "enabled"
325
+ enabled_source["attributes"].update(name="Enabled component", enabled=True)
326
+ enabled_target = deepcopy(target)
327
+ enabled_target["id"] += "enabled"
328
+ enabled_target["attributes"].update(name="Enabled component", enabled=False)
329
+ sync.base[key].append(enabled_source)
330
+ sync.targets["Target"][key].append(enabled_target)
331
+ api = sync.targets["Target"]["api"]
332
+ update = api.updateRule if kind == "rules" else api.updateDataElement
333
+ update.side_effect = lambda **kwargs: self.updated(
334
+ enabled_target, kwargs["attr_dict"]
335
+ )
336
+ method = sync.syncRules if kind == "rules" else sync.syncDataElements
337
+ result = method(ignoreDisabled=True)
338
+ self.assertEqual(result[source["attributes"]["name"]], {})
339
+ self.assertIn("Target", result["Enabled component"])
340
+ update.assert_called_once()
341
+ self.assertIs(update.call_args.kwargs["attr_dict"]["enabled"], True)
342
+
343
+ def test_bulk_sync_still_syncs_enabled_components_to_disabled_targets(self):
344
+ for kind in ("rules", "data_elements"):
345
+ with self.subTest(kind=kind):
346
+ sync, source, target = self.make_sync(kind, True, False)
347
+ method = sync.syncRules if kind == "rules" else sync.syncDataElements
348
+ result = method(ignoreDisabled=True)
349
+ self.assertIn("Target", result[source["attributes"]["name"]])
350
+ key = "rules" if kind == "rules" else "dataElements"
351
+ self.assertIs(
352
+ sync.targets["Target"][key][0]["attributes"]["enabled"], True
353
+ )
354
+
355
+ def test_bulk_sync_filters_the_selected_published_revision(self):
356
+ for kind in ("rules", "data_elements"):
357
+ for published_enabled in (False, True):
358
+ with self.subTest(kind=kind, published_enabled=published_enabled):
359
+ sync, source, target = self.make_sync(
360
+ kind, not published_enabled, not published_enabled
361
+ )
362
+ revision = deepcopy(source)
363
+ revision["id"] += "revision"
364
+ revision["attributes"]["enabled"] = published_enabled
365
+ revision["attributes"]["published"] = True
366
+ sync.base["api"].getLatestPublishedVersion.return_value = revision
367
+ method = sync.syncRules if kind == "rules" else sync.syncDataElements
368
+ result = method(ignoreDisabled=True, publishedVersion=True)
369
+ sync.base["api"].getRevisions.assert_called_once_with(source)
370
+ if published_enabled:
371
+ self.assertIn("Target", result[source["attributes"]["name"]])
372
+ else:
373
+ self.assertEqual(result[source["attributes"]["name"]], {})
374
+ self.assertEqual(sync.targets["Target"]["api"].mock_calls, [])
375
+
376
+ def test_bulk_sync_keeps_regex_filtering(self):
377
+ for kind in ("rules", "data_elements"):
378
+ with self.subTest(kind=kind):
379
+ sync, source, target = self.make_sync(kind, True, False)
380
+ method = sync.syncRules if kind == "rules" else sync.syncDataElements
381
+ self.assertEqual(method(regex="Does not match", ignoreDisabled=True), {})
382
+ self.assertEqual(sync.targets["Target"]["api"].mock_calls, [])
383
+
384
+
385
+ class SynchronizerCLITests(unittest.TestCase):
386
+ def test_ignore_disabled_accepts_optional_boolean_and_bare_flags(self):
387
+ options = (
388
+ ("", False),
389
+ ("-i", True),
390
+ ("--ignore_disabled", True),
391
+ ("-i True", True),
392
+ ("--ignore_disabled true", True),
393
+ ("-i False", False),
394
+ ("--ignore_disabled false", False),
395
+ ("--ignore_disabled=False", False),
396
+ )
397
+ for command, method_name in (
398
+ ("do_sync_rules", "syncRules"),
399
+ ("do_sync_data_elements", "syncDataElements"),
400
+ ):
401
+ for arguments, expected in options:
402
+ with self.subTest(command=command, arguments=arguments):
403
+ sync = Mock(spec=Synchronizer)
404
+ sync.base = {"name": "Base"}
405
+ method = getattr(sync, method_name)
406
+ method.return_value = {}
407
+ shell = SynchronizerCLI(sync)
408
+ with patch("launchpy.cli.__main__.console") as console:
409
+ getattr(shell, command)(arguments + " -r Sample -c -p")
410
+ method.assert_called_once_with(
411
+ regex="Sample", forceCreation=True, publishedVersion=True,
412
+ ignoreDisabled=expected,
413
+ )
414
+ console.print.assert_not_called()
415
+
416
+ def test_ignore_disabled_rejects_invalid_boolean_without_syncing(self):
417
+ for command, method_name in (
418
+ ("do_sync_rules", "syncRules"),
419
+ ("do_sync_data_elements", "syncDataElements"),
420
+ ):
421
+ with self.subTest(command=command):
422
+ sync = Mock(spec=Synchronizer)
423
+ sync.base = {"name": "Base"}
424
+ shell = SynchronizerCLI(sync)
425
+ with patch("sys.stderr") as stderr:
426
+ getattr(shell, command)("--ignore_disabled invalid")
427
+ getattr(sync, method_name).assert_not_called()
428
+ self.assertTrue(stderr.write.called)
429
+
430
+ def test_interactive_multi_org_config_sets_headers_for_all_organizations(self):
431
+ configs = [
432
+ {
433
+ "org_id": "orgA@AdobeOrg",
434
+ "client_id": "client-a",
435
+ "secret": "secret-a",
436
+ "scopes": "scope-a",
437
+ "org_name": "org_a",
438
+ },
439
+ {
440
+ "org_id": "orgB@AdobeOrg",
441
+ "api_key": "client-b",
442
+ "secret": "secret-b",
443
+ "scopes": "scope-b",
444
+ "org_name": "org_b",
445
+ },
446
+ ]
447
+ with (
448
+ tempfile.TemporaryDirectory() as tmp_dir,
449
+ patch.dict(config_objects, {}, clear=True),
450
+ patch.dict(headers, {}, clear=True),
451
+ patch("launchpy.cli.__main__.console"),
452
+ patch("launchpy.Admin"),
453
+ ):
454
+ config_path = Path(tmp_dir) / "multi_org.json"
455
+ config_path.write_text(json.dumps(configs), encoding="utf-8")
456
+ shell = MainShell()
457
+ shell.do_config(f'--config_file "{config_path}"')
458
+
459
+ self.assertEqual(shell.org_name, "org_a")
460
+ self.assertEqual(headers["org_a"]["x-gw-ims-org-id"], "orgA@AdobeOrg")
461
+ self.assertEqual(headers["org_a"]["x-api-key"], "client-a")
462
+ self.assertEqual(headers["org_b"]["x-gw-ims-org-id"], "orgB@AdobeOrg")
463
+ self.assertEqual(headers["org_b"]["x-api-key"], "client-b")
464
+
465
+
466
+ if __name__ == "__main__":
467
+ unittest.main()
@@ -1 +0,0 @@
1
- __version__ = "0.5.3"
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes