SyncMadeEasy/force-app/main/default/classes/ShopifyController_Test.cls

2726 lines
123 KiB
OpenEdge ABL

/*
*********************************************************
Apex Class Name : ShopifyController_Test
Created Date : 17/4/2024
@description : This test class cover the ShopifyController and some method of HIC_ShopifyUtility class
@author : SME Team
Modification Log:
Ver Date Author
1.0 06/06/2024 SME Team
*********************************************************
*/
@isTest
public with sharing class ShopifyController_Test {
public string siteguestid;
public string name;
public string id;
public static void requiredDate(){
List<HIC_ShopifySync__Configuration__c> confg = TestDataFactory.createConfigurationCustomSetting(1);
if(!confg.isempty() && confg != null){
insert confg;
}
List<Account> testAccounts = new List<Account>();
for (Integer i = 1; i <= 10; i++) {
testAccounts.add(new Account(Name = 'Test Account ' + i));
}
insert testAccounts;
List<HIC_ShopifySync__HIC_Configuration__c> configObj = TestDataFactory.createConfiguration(1);
if(!configObj.isempty() && configObj != null){
insert configObj;
}
}
@isTest
public static void testShopifyController(){
List<HIC_ShopifySync__HIC_Field_Mapping__c> fieldMapList = TestDataFactory.createFieldMapping(1);
insert fieldMapList;
List<HIC_ShopifySync__Configuration__c> configurationList = TestDataFactory.createConfigurationCustomSetting(1);
if(configurationList != null && !configurationList.isEmpty()){
upsert configurationList Name;
}
List<HIC_ShopifySync__HIC_Configuration__c> configurationCustomSetList = TestDataFactory.createConfiguration(1);
if(configurationCustomSetList != null && !configurationCustomSetList.isEmpty()){
upsert configurationCustomSetList Name;
}
List<HIC_ShopifySync__HIC_Configuration__c> configurationCustomSetListTwo = TestDataFactory.createConfiguration(1);
insert configurationCustomSetListTwo;
HIC_ShopifySync__HIC_Configuration__c hicCustomObj= [Select Id,Name,HIC_ShopifySync__Store__c From HIC_ShopifySync__HIC_Configuration__c WHERE Id=: configurationCustomSetListTwo[0].Id LIMIT 1];
hicCustomObj.HIC_ShopifySync__Store__c='default';
update hicCustomObj;
String hicConfigJson = JSON.serializePretty(hicCustomObj);
ShopifyController.removeStore('default');
//ShopifyController.checkDefaultStoreFieldMapping();
ShopifyController.saveDefaultOppStageName('default');
ShopifyController.saveConfigration(hicConfigJson,'True');
ShopifyController.saveConfigration(hicConfigJson,'false');
ShopifyController.saveConfigration(hicConfigJson,'Normal');
ShopifyController.saveConfigration(hicConfigJson,'True');
}
@isTest
public static void testShopifyControllerOpp(){
Id pricebookId = Test.getStandardPricebookId();
List<RecordType> accountRecordType = [SELECT Id FROM RecordType WHERE SObjectType = 'Account' Limit 1];
List<RecordType> personAccountRecordType = [SELECT Id FROM RecordType WHERE Name = 'isPersonAccount' and SObjectType = 'Account' Limit 1];
sObject newPersonAccount = Schema.getGlobalDescribe().get('Account').newSObject() ;
if(Schema.sObjectType.Account.fields.getMap().containsKey('isPersonAccount')){
newPersonAccount.put('Lastname','Fred');
}else{
newPersonAccount.put('name','Fred Smith');
}
if(!personAccountRecordType.isEmpty()){
newPersonAccount.put('RecordTypeid',personAccountRecordType[0].id);
}
else if(!accountRecordType.isEmpty()){
newPersonAccount.put('RecordTypeid',accountRecordType[0].id);
}
insert newPersonAccount;
opportunity newOpp1 = new Opportunity(name='newOppttt',Amount=2000.0, StageName= 'Closed Lost', CloseDate= System.today()); //----------------CREATING OPPORTUNITY
insert newOpp1;
HIC_ShopifySync__HIC_Webhook__c webhookObj= new HIC_ShopifySync__HIC_Webhook__c(Name='test',HIC_ShopifySync__Topic__c='test topic',HIC_ShopifySync__External_Id__c='test45');
insert webhookObj;
Product2 newProduct = new Product2(name='newProduct',ProductCode='00100',isActive = true);//----------------CREATING PRODUCT
insert newProduct;
PriceBookEntry stdPriceBookEntry = new PriceBookEntry();
stdPriceBookEntry.Product2Id=newProduct.Id;
stdPriceBookEntry.Pricebook2Id=pricebookId;
stdPriceBookEntry.UnitPrice=2000;
stdPriceBookEntry.IsActive=true;
insert stdPriceBookEntry;
Pricebook2 newPbook= new Pricebook2(name='PBook100', isActive=true);
insert newPbook;
PricebookEntry newPbookEntry= new PricebookEntry();
newPbookEntry.Pricebook2id=newPbook.id;
newPbookEntry.product2id=newProduct.id;
newPbookEntry.UnitPrice= 4500;
newPbookEntry.IsActive = true;
insert newPbookEntry;
OpportunityLineItem newObLineItem = new OpportunityLineItem();//----------------CREATING OpportunityLineItem
newObLineItem.OpportunityId=newOpp1.id;
newObLineItem.PriceBookEntryid=newPbookEntry.id;
newObLineItem.Quantity = 100;
newObLineItem.UnitPrice = 8000;
insert newObLineItem;
Order newOrder = new Order();
newOrder.AccountId = newPersonAccount.id;
newOrder.EffectiveDate =Date.newInstance(2020,06,22);
newOrder.status='Draft';
insert newOrder;
HIC_ShopifySync__Order_Fulfillment__c newOrderFul = new HIC_ShopifySync__Order_Fulfillment__c();
newOrderFul.Name='DemoFulfilment';
newOrderFul.Order__c= newOrder.id;
insert newOrderFul;
HIC_ShopifySync__Collection__c colleactionObj = new HIC_ShopifySync__Collection__c();
colleactionObj.name='TestCollection';
//colleactionObj.CurrencyIsoCode='USD';
insert colleactionObj;
HIC_ShopifySync__Collect__c colleactObj = new HIC_ShopifySync__Collect__c();
colleactObj.name='Test Collect';
colleactObj.HIC_ShopifySync__Collection__c= colleactionObj.id ;
insert colleactObj;
List<HIC_ShopifySync__HIC_Configuration__c>hicConfigOb1=TestDataFactory.createConfiguration(1);
List<HIC_ShopifySync__HIC_Field_Mapping__c> fieldMapList = TestDataFactory.createFieldMapping(1);
insert fieldMapList;
HIC_ShopifySync__HIC_Field_Mapping__c hicFieldObj=[Select Id,Name,HIC_ShopifySync__Store__c From HIC_ShopifySync__HIC_Field_Mapping__c Where Id=: fieldMapList[0].Id];
hicFieldObj.HIC_ShopifySync__Store__c='Default';
hicFieldObj.HIC_ShopifySync__SF_Field__c='Accountid';
hicFieldObj.HIC_ShopifySync__Object_Name__c='order';
hicFieldObj.HIC_ShopifySync__SF_Field__c='Pricebook2Id';
update hicFieldObj;
String hicConfigJson = JSON.serializePretty(hicConfigOb1);
ShopifyController.saveConfigration(hicConfigJson,'True');
String result = ShopifyController.getRecordTypes('testStore');
//system.assertNotEquals(null,result);
}
/**************************************fetchAccount*************************************************/
/**
* ─────────────────────────────────────────────────────────────────────────────────────────────┐
* Get list of Account base on search keyword
* ──────────────────────────────────────────────────────────────────────────────────────────────
* ─────────────────────────────────────────────────────────────────────────────────────────────┘
*/
@isTest
public static void accountFetch_Test(){
Account accObj=new Account(Name='Test');
insert accObj;
Test.StartTest();
List<Account> result = ShopifyController.fetchAccount('Test');
System.assertEquals(1, result.size(), 'Number of returned accounts should be 1');
for (Account acc : result) {
System.assert(acc.Name.startsWith('Test'), 'Account names should start with "Test"');
}
Test.StopTest();
}
/**************************************getConfigration Test *************************************************/
/**
* ─────────────────────────────────────────────────────────────────────────────────────────────┐
* Get saved Configuration to display in the page
* ──────────────────────────────────────────────────────────────────────────────────────────────
* ─────────────────────────────────────────────────────────────────────────────────────────────┘
*/
@isTest
public static void getConfigration_Test() {
List<HIC_ShopifySync__Configuration__c> mockDefaultConfig = TestDataFactory.createConfigurationCustomSetting(1);
if(!mockDefaultConfig.isempty() && mockDefaultConfig != null)
{
insert mockDefaultConfig;
}
System.assertNotEquals(null, mockDefaultConfig.size(), 'cyptokey has some records');
List<HIC_ShopifySync__HIC_Configuration__c> configer = TestDataFactory.createConfiguration(1);
if(!configer.isempty() && configer != null)
{
insert configer;
}
List<HIC_ShopifySync__HIC_Configuration__c> configerLst = TestDataFactory.createConfiguration(1);
if(!configerLst.isempty() && configerLst != null)
{
insert configerLst;
}
configer[0].Id = NULL;
String jsonString = JSON.serialize(configerLst[0]);
String configData = ShopifyController.getConfigration();
String configData1 = ShopifyController.getConfigrations();
System.assertNotEquals(null, configData);
delete mockDefaultConfig;
delete configerLst;
}
@isTest
public static void getConfigration_Test2() {
List<HIC_ShopifySync__Configuration__c> mockDefaultConfig = new List<HIC_ShopifySync__Configuration__c>{
new HIC_ShopifySync__Configuration__c(
Name = 'Default'
)
};
insert mockDefaultConfig;
List<HIC_ShopifySync__HIC_Configuration__c> defaultConfig = new List<HIC_ShopifySync__HIC_Configuration__c>{
new HIC_ShopifySync__HIC_Configuration__c(
Name = 'Test Config',
HIC_ShopifySync__Store__c = 'Default'
)
};
insert defaultConfig;
List<HIC_ShopifySync__Configuration__c> cyptokeyquery = new List<HIC_ShopifySync__Configuration__c>{
new HIC_ShopifySync__Configuration__c(
Name = 'Default'
)
};
insert cyptokeyquery;
Test.startTest();
String configData = ShopifyController.getConfigration();
Test.stopTest();
System.assertNotEquals(null, configData);
}
/**************************************getConfigrationForDynamicRow*************************************************/
/**
* ─────────────────────────────────────────────────────────────────────────────────────────────┐
* Get Configuration for check current User what select like Opportunity/draft Orerd
* If not selected then based on configuration will hide and show field mapping
* ──────────────────────────────────────────────────────────────────────────────────────────────
* ─────────────────────────────────────────────────────────────────────────────────────────────┘
*/
@isTest
public static void testGetConfigurationWithDefault() {
List<HIC_ShopifySync__Configuration__c> mockDefaultConfig = TestDataFactory.createConfigurationCustomSetting(1);
if(!mockDefaultConfig.isEmpty() && mockDefaultConfig != null)
{
insert mockDefaultConfig;
}
List<HIC_ShopifySync__HIC_Configuration__c> mockConfig = TestDataFactory.createConfiguration(1);
if(!mockConfig.isEmpty() && mockConfig != null)
{
insert mockConfig;
}
String configData = ShopifyController.getConfigrationForDynamicRow('Test Store');
delete mockConfig;
delete mockDefaultConfig;
}
@isTest
static void testGetConfigurationForDynamicRow() {
// Test with valid store name
List<HIC_ShopifySync__Configuration__c>config=TestDataFactory.createConfigurationCustomSetting(1);
if(!config.isEmpty() && config!=null){
insert config;
}
Test.startTest();
String result = ShopifyController.getConfigrationForDynamicRow('TestStore');
String result1 = ShopifyController.getConfigrationForDynamicRow('InvalidStore');
System.assertEquals(null, result1, 'Result should be null when an invalid store name is provided');
String result2 = ShopifyController.getConfigrationForDynamicRow('TestStore');
System.assertEquals(null, result2, 'Result should be null when Crypto Key is empty');
String result3 = ShopifyController.getConfigrationForDynamicRow('TestStore');
Test.stopTest();
}
/**************************************getBaseValue*************************************************/
/**
* ─────────────────────────────────────────────────────────────────────────────────────────────┐
* Get BASE 64 value OF password in Salesforce
* ──────────────────────────────────────────────────────────────────────────────────────────────
* ─────────────────────────────────────────────────────────────────────────────────────────────┘
*/
@isTest
public static void getBaseValue_Test() {
List<HIC_ShopifySync__Configuration__c> config = TestDataFactory.createConfigurationCustomSetting(1);
if(!config.isEmpty() && config != null)
{
insert config;
}
String encryptedPassword = ShopifyController.getBaseValue('MySecretPassword');
String cryptoKey = String.valueOf(config[0].HIC_ShopifySync__Cryptokey__c);
Blob decryptedData = Crypto.decryptWithManagedIV('AES128', Blob.valueOf(cryptoKey), EncodingUtil.base64Decode(encryptedPassword.removeEnd('True')));
String decryptedPassword = decryptedData.toString();
System.assertEquals('MySecretPassword', decryptedPassword, 'Password should match');
System.assertNotEquals('Error', encryptedPassword, 'Function should not return "Error"');
Test.startTest();
config[0].Name = 'SomeOtherName';
update config;
String result = ShopifyController.getBaseValue('MySecretPassword');
System.assertEquals(null, result, 'Function should return null if the Configuration record is not found');
Test.stopTest();
}
/**************************************getSiteURLs*************************************************/
/**
* ─────────────────────────────────────────────────────────────────────────────────────────────┐
* Get User Site URls in Salesforce
* ──────────────────────────────────────────────────────────────────────────────────────────────
* ─────────────────────────────────────────────────────────────────────────────────────────────┘
*/
@isTest
public static void testGetSiteURLs() {
Test.startTest();
String result = ShopifyController.getSiteURLs();
Test.stopTest();
//System.assertNotEquals(null, result, 'The result should not be null');
}
/**************************************getIsPerson*************************************************/
/**
* ─────────────────────────────────────────────────────────────────────────────────────────────┐
* Check Salesforce Org have PersonAccount Enabled or not
* What is Person Account in Salesforce ? https://help.salesforce.com/articleView?id=account_person.htm&type=5
* ──────────────────────────────────────────────────────────────────────────────────────────────
* ─────────────────────────────────────────────────────────────────────────────────────────────┘
*/
@isTest
public static void getIsPerson_Test() {
//System.assertEquals(true, ShopifyController.getIsPerson());
}
/**************************************getIsGeneral*************************************************/
/**
* ─────────────────────────────────────────────────────────────────────────────────────────────┐
* Check Salesforce Org have PersonAccount Enabled or not
* What is the Person Account ? https://help.salesforce.com/articleView?id=account_person.htm&type=5
* ──────────────────────────────────────────────────────────────────────────────────────────────
* ─────────────────────────────────────────────────────────────────────────────────────────────┘
*/
@isTest
public static void getIsGeneral_Test() {
List<HIC_ShopifySync__HIC_Configuration__c> mockConfig = TestDataFactory.createConfiguration(1);
if(!mockConfig.isEmpty() && mockConfig != null)
{
insert mockConfig;
}
HIC_ShopifySync__HIC_Configuration__c mockConfigObj=[SELECT id, Name, HIC_ShopifySync__Store__c, HIC_ShopifySync__Shopify_URL__c, HIC_ShopifySync__BatchRunOnce__c, HIC_ShopifySync__Order_Sync__c, HIC_ShopifySync__Draft_Order_Sync__c,HIC_ShopifySync__Inventory_Location_Sync__c,HIC_ShopifySync__Product_Sync__c,HIC_ShopifySync__Batch_Is_Processing__c, HIC_ShopifySync__Order__c, HIC_ShopifySync__Opportunity__c, HIC_ShopifySync__Opportunity_Line_Item__c, HIC_ShopifySync__Collection_Sync__c, HIC_ShopifySync__Order_Fulfillment__c, HIC_ShopifySync__Enable_Draft_Order__c, HIC_ShopifySync__Account_Contact__c, HIC_ShopifySync__Person_Account__c, HIC_ShopifySync__Inventory_Location__c, HIC_ShopifySync__Collection__c FROM
HIC_ShopifySync__HIC_Configuration__c LIMIT 1];
mockConfigObj.HIC_ShopifySync__Store__c='test';
update mockConfigObj;
String configData = ShopifyController.getGeneral('"https://test.myshopify.com"');
System.assertNotEquals(null, configData);
//System.assert(configData.contains('Mock Configuration'));
}
/**************************************getErrorMailList*************************************************/
/**
* ─────────────────────────────────────────────────────────────────────────────────────────────┐
* Get list of Email for send email notifications after Batch process complete
* ──────────────────────────────────────────────────────────────────────────────────────────────
* ─────────────────────────────────────────────────────────────────────────────────────────────┘
*/
@isTest
public static void testGetErrorMailListWithRecords() {
List<HIC_ShopifySync__Email_Addresses_to_send_error_CSV__c>errorMail=TestDataFactory.createErrorCsv(1);
insert errorMail;
List<HIC_ShopifySync__Email_Addresses_to_send_error_CSV__c>errorMail2=TestDataFactory.createErrorCsv(1);
insert errorMail2;
Test.startTest();
String result = ShopifyController.getErrorMailList();
String result2 = ShopifyController.getErrorMailList();
Test.stopTest();
System.assertNotEquals(null, result, 'The result should not be null');
System.assert(result2.contains('TestErrorMail'), 'The result should contain the test record name');
}
@isTest
public static void testGetErrorMailListWithoutRecords() {
delete [SELECT Id FROM HIC_ShopifySync__Email_Addresses_to_send_error_CSV__c];
Test.startTest();
String result = ShopifyController.getErrorMailList();
Test.stopTest();
System.assertNotEquals(null, result, 'The result should not be null');
System.assert(result.contains(UserInfo.getUserEmail()), 'The result should contain the user\'s email address');
}
/**************************************saveEmailSettings*************************************************/
/**
* ─────────────────────────────────────────────────────────────────────────────────────────────┐
* Save Emails into Salesforce for send email notifications
* ──────────────────────────────────────────────────────────────────────────────────────────────
* ─────────────────────────────────────────────────────────────────────────────────────────────┘
*/
@isTest
public static void testSaveEmailSettings() {
List<HIC_ShopifySync__Email_Addresses_to_send_error_CSV__c> emailListfrompage = new List<HIC_ShopifySync__Email_Addresses_to_send_error_CSV__c>();
emailListfrompage.add(new HIC_ShopifySync__Email_Addresses_to_send_error_CSV__c(Name = 'TestEmail1'));
emailListfrompage.add(new HIC_ShopifySync__Email_Addresses_to_send_error_CSV__c(Name = 'TestEmail2'));
emailListfrompage.add(new HIC_ShopifySync__Email_Addresses_to_send_error_CSV__c(Name = 'TestEmail3'));
// Test.setMock(HttpCalloutMock.class, new YourHttpMock());
Test.startTest();
ShopifyController.saveEmailSettings(JSON.serialize(emailListfrompage));
Test.stopTest();
List<HIC_ShopifySync__Email_Addresses_to_send_error_CSV__c> emailRecords = [
SELECT Name
FROM HIC_ShopifySync__Email_Addresses_to_send_error_CSV__c
];
System.assertEquals(3, emailRecords.size(), 'Email records not inserted');
for (HIC_ShopifySync__Email_Addresses_to_send_error_CSV__c email : emailRecords) {
System.assert(email.Name != null, 'Email Name is null');
}
}
/********************************************************************************************
* Created Date:- 23/10/2023
* Description:-This Method is used for deleting the field mapping into the Salesforce When every user delete the mapped data into the Salesforce.
*
*
**********************************************************************************************/
@IsTest
static void testSaveFieldMapping() {
String listofRecord = '[{"sobjectType":"TestObject","salesforcefields":"TestField","salesforceFieldType":"String","selectedfields":"test","shopifyFieldType":"string","HIC_ShopifySync__Store":"default","HIC_ShopifySync__Store_External_ID":"12345"}]';
Test.startTest();
// Test method invocation
String result = ShopifyController.saveFieldMapping(listofRecord);
Test.stopTest();
System.assertNotEquals(null, result);
}
@IsTest
static void testSaveFieldMappingWithInvalidInput() {
String listofRecord = null;
Test.startTest();
String result = ShopifyController.saveFieldMapping(listofRecord);
Test.stopTest();
System.assertEquals(null, result);
}
@IsTest
static void testSaveFieldMappingWithSelectedFields() {
// Prepare test data with specific conditions to trigger the mentioned code block
String listofRecord = '[{"sobjectType":"TestObject","salesforcefields":"TestField","salesforceFieldType":"String","selectedfields":"test.field1,test.field2","shopifyFieldType":"string","HIC_ShopifySync__Store":"default","HIC_ShopifySync__Store_External_ID":"12345"}]';
Test.startTest();
// Test method invocation
String result = ShopifyController.saveFieldMapping(listofRecord);
Test.stopTest();
// Assert that the result is not null
System.assertNotEquals(null, result);
// You can add further assertions if needed based on the behavior of the method
}
///////////////////////////////////////////////////////////////////////////////////////////////////
@isTest
static void testHandleDefaultFieldMapping() {
Account acc=new Account(name='test');
insert acc;
String accountId = 'Test1234';
String oppDefaultStage = 'TestStage';
String oppCloseDays = '2023-10-19';
String storeName = 'default';
List<HIC_ShopifySync__HIC_Field_Mapping__c> fieldMappings = TestDataFactory.createFieldMapping(1);
String fieldMappingcontain = ShopifyController.handleDefaultFieldMapping(accountId, oppDefaultStage, oppCloseDays, storeName);
System.assertNotEquals(null, fieldMappings);
System.assertNotEquals(5, fieldMappings.size());
for (HIC_ShopifySync__HIC_Field_Mapping__c fieldMapping : fieldMappings) {
System.assertNotEquals(false, fieldMapping.HIC_ShopifySync__Default_Value__c);
System.assertNotEquals('id', fieldMapping.HIC_ShopifySync__Shopify_Fields__c);
System.assertEquals(true, fieldMapping.HIC_ShopifySync__Default_Value__c);
System.assertNotEquals(oppCloseDays, fieldMapping.HIC_ShopifySync__Shopify_Fields__c);
// System.assertNEquals(oppCloseDays, fieldMapping.HIC_ShopifySync__Shopify_Fields__c);
}
System.assertNotEquals(null, fieldMappings);
System.assertNotEquals(5, fieldMappings.size());
}
@isTest
static void HandleDefaultValueFalse_Test() {
String accountId = null;
String oppDefaultStage = 'TestStage';
String oppCloseDays = '2023-10-19';
String storeName = 'TestStoreName';
String fieldMappingcontain = ShopifyController.handleDefaultFieldMapping(accountId, oppDefaultStage, oppCloseDays, storeName);
List<HIC_ShopifySync__HIC_Field_Mapping__c> fieldMappings=TestDataFactory.createFieldMapping(1);
System.assertNotEquals(null, fieldMappings);
System.assertNotEquals(5, fieldMappings.size());
for (HIC_ShopifySync__HIC_Field_Mapping__c fieldMapping : fieldMappings) {
System.assertEquals(true, fieldMapping.HIC_ShopifySync__Default_Value__c);
System.assertNotEquals('id', fieldMapping.HIC_ShopifySync__Shopify_Fields__c);
System.assertEquals(true, fieldMapping.HIC_ShopifySync__Default_Value__c);
System.assertNotEquals(oppCloseDays, fieldMapping.HIC_ShopifySync__Shopify_Fields__c);
}
}
/**************************************getWriteReviewURL*************************************************/
/**
* ─────────────────────────────────────────────────────────────────────────────────────────────┐
* Get URL For Shopify APP Review
* ──────────────────────────────────────────────────────────────────────────────────────────────
* ─────────────────────────────────────────────────────────────────────────────────────────────┘
*/
@isTest
static void testGetWriteReviewURL() {
Folder folderObj=[Select Id,Name From Folder Where Name='Hic Shopify made easy logo' LIMIT 1];
// Test when documents are available
List<Document> testDocuments = new List<Document>();
for (Integer i = 0; i < 5; i++) {
testDocuments.add(new Document(Name = 'Hic Shopify made easy logo' + i, Url = '/TestUrl' + i, FolderId = folderObj.Id));
}
insert testDocuments;
Test.startTest();
String result = ShopifyController.getWriteReviewURL();
Test.stopTest();
// Assertions
List<Map<String, Object>> expectedWrapperList = new List<Map<String, Object>>();
for (Document doc : testDocuments) {
Map<String, Object> docMap = new Map<String, Object>();
docMap.put('name', doc.Name);
docMap.put('Url', doc.Url);
expectedWrapperList.add(docMap);
}
//System.assertEquals(JSON.serialize(expectedWrapperList), result, 'Result should match expected JSON string');
}
@isTest
static void testGetWriteReviewURL_NoDocuments() {
// Test when no documents are available
Test.startTest();
String result = ShopifyController.getWriteReviewURL();
Test.stopTest();
// Assertions
System.assertEquals(null, result, 'Result should be null when no documents are available');
}
@isTest
static void createRemoteSiteSettings_Test() {
String name = 'name';
String validURL = 'https://example.com';
System.assertEquals('Error', ShopifyController.createRemoteSiteSettings(validURL));
String invalidURL = 'https://invalidurl.com';
System.assertNotEquals('Remote Site setting', ShopifyController.createRemoteSiteSettings(invalidURL));
String nullURL = null;
System.assertEquals('Remote Site setting', ShopifyController.createRemoteSiteSettings(nullURL));
String emptyURL = '';
System.assertEquals('Remote Site setting', ShopifyController.createRemoteSiteSettings(emptyURL));
Test.startTest();
Test.setMock(HttpCalloutMock.class, new MyHttpCalloutMock());
String result = ShopifyController.createRemoteSiteSettings(validURL);
//String result1 = ShopifyController.createRemoteSite(name,validURL);
ShopifyController.remoteSite();
System.assertNotEquals('Success', result);
//System.assertNotEquals('Success', result1);
Test.stopTest();
//Test.setMock(HttpCalloutMock.class, new MyHttpCalloutMock());
}
private class MyHttpCalloutMock implements HttpCalloutMock {
public HTTPResponse respond(HTTPRequest req) {
// Create a mock HTTP response
HTTPResponse res = new HTTPResponse();
res.setHeader('Content-Type', 'application/json');
res.setBody('{"example": "response"}');
res.setStatusCode(200);
return res;
}
}
@isTest
public static void testGetConfigurationWithException() {
Test.startTest();
Boolean throwException = true;
String RemoteSiteSetting = ShopifyController.createRemoteSiteSettings('https://example.com');
Test.stopTest();
System.assertEquals('Error', RemoteSiteSetting);
}
/**************************************checkCAccesscope*************************************************/
/**
* ─────────────────────────────────────────────────────────────────────────────────────────────┐
* check Shopify store access for the entity
* ──────────────────────────────────────────────────────────────────────────────────────────────
* ─────────────────────────────────────────────────────────────────────────────────────────────┘
*/
@isTest
static void CheckAccessScope_Test() {
List<HIC_ShopifySync__Configuration__c>config=TestDataFactory.createConfigurationCustomSetting(1);
if(!config.isEmpty() && config!=null){
insert config;
}
Test.setMock(HttpCalloutMock.class, new TestDataFactory.MockHttpResponseGeneratorTest());
Test.setMock(HttpCalloutMock.class, new TestDataFactory.oauthlogintest());
String result = ShopifyController.checkAccesScope('ShopifyURL', 'Password123True');
System.assertEquals(null, result);
System.assertNotEquals('', result);
System.assertNotEquals('ExpectedValue', result, 'Description of the assertion');
}
@isTest
static void testCheckAccessScope() {
// Create test data
List<HIC_ShopifySync__Configuration__c>config=TestDataFactory.createConfigurationCustomSetting(1);
if(!config.isEmpty() && config!=null){
insert config;
}
HttpRequest req = new HttpRequest();
req.setEndpoint('https://example.com');
req.setMethod('GET');
Test.setMock(HttpCalloutMock.class, new TestDataFactory.MockHttpResponseGeneratorTest());
Test.setMock(HttpCalloutMock.class, new TestDataFactory.oauthlogintest());
String result = ShopifyController.checkAccesScope('ShopifyURL', 'yourPassword');
System.assertNotEquals('ExpectedValue', result, 'Description of the assertion');
}
/********************************************************************************************
* Created Date:- 31/07/2023
* Description:- This method is used to count the records of the Shopify.
* We have to pass the store name and the object names to count the number of records
* at shopify side.
* Object name:- locations, products, customers(Account)variants, orders, collects,
* locations, draft_orders
*
*
*
************/
@isTest
static void getShopifyRecordCounts_Test()
{
List<HIC_ShopifySync__HIC_Configuration__c>testConfiguration=TestDataFactory.createConfiguration(1);
if(!testConfiguration.isEmpty() && testConfiguration!=null){
insert testConfiguration;
}
Test.setMock(HttpCalloutMock.class, new MockTestRecordsCount());
String storeName = 'Test Store';
String objectName = 'HIC_ShopifySync__HIC_Configuration__c'; // Set objectName
String result = ShopifyController.getShopifyRecordCounts(storeName, objectName);
System.assertNotEquals('Error!', result,'Result matched');
System.assertNotEquals('GET', result);
System.assertNotEquals('content-type', 'application/json');
// System.assertEquals(200, statuscode);
}
public class MockTestRecordsCount implements HttpCalloutMock {
public HTTPResponse respond(HTTPRequest req) {
HttpResponse res = new HttpResponse();
req.setHeader('X-Shopify-Access-Token', 'password@123');
res.setHeader('Content-Type', 'application/json');
res.setBody('{"status": "success"}');
res.setStatusCode(200);
return res;
}
}
/**************************************checkingBatchDetails*************************************************/
/**
* ─────────────────────────────────────────────────────────────────────────────────────────────┐
* Create RemoteSite Setting for Authentication URL
* @param String URL - URL for Create RemoteSite Setting
* ──────────────────────────────────────────────────────────────────────────────────────────────
* ─────────────────────────────────────────────────────────────────────────────────────────────┘
*/
@isTest
static void CheckingBatchDetails_Test() {
List<ApexClass> apList = new List<ApexClass>(
[SELECT Id, Name FROM ApexClass WHERE Name = :'FetchAccounts']
);
List<AsyncApexJob> listofAsyncApexJob = [SELECT ApexClassID, Status, ExtendedStatus FROM AsyncApexJob WHERE JobType = 'BatchApex'
AND (Status = 'Processing' OR Status = 'Holding' OR Status = 'Queued'
OR Status = 'Preparing' OR Status = 'Aborted' OR Status = 'Completed'
OR Status = 'Failed') AND ApexClassID = :apList[0].Id ORDER BY createddate DESC LIMIT 1];
List<HIC_ShopifySync__HIC_Configuration__c>testConfig=TestDataFactory.createConfiguration(1);
if(!testConfig.isEmpty() && testConfig!=null){
insert testConfig;
}
Test.startTest();
String result1 = ShopifyController.CheckingBatchDetails('Product2', 'BatchToCreateProducts', 'Test Store');
String result2 = ShopifyController.CheckingBatchDetails('HIC_ShopifySync__Variant__c', 'BatchToCreateProducts', 'Test Store');
String result3 = ShopifyController.CheckingBatchDetails('Account', 'FetchAccounts', 'Test Store');
String result4 = ShopifyController.CheckingBatchDetails('Contact', 'FetchAccounts', 'Test Store');
String result5 = ShopifyController.CheckingBatchDetails('Order', 'FetchAccounts', 'Test Store');
String result6 = ShopifyController.CheckingBatchDetails('Opportunity', 'FetchAccounts', 'Test Store');
String result7 = ShopifyController.CheckingBatchDetails('HIC_ShopifySync__Inventory__c', 'FetchInventoryItems', 'Test Store');
String result8 = ShopifyController.CheckingBatchDetails('Draftorder', 'FetchOrders', 'Test Store');
Test.stopTest();
System.assertEquals('Completed0', result1);
System.assertEquals('Completed0', result2);
System.assertEquals('Completed0', result3);
System.assertEquals('Completed0', result4);
System.assertEquals('Completed0', result5);
System.assertEquals('Completed0', result6);
System.assertEquals('Completed0', result7);
System.assertEquals('Completed0', result8);
}
@isTest
static void testCheckingBatchDetails_Completed() {
String objectName = 'Product2';
String apexClassName = 'HIC_ShopifyUtility';
String store = 'TestStore';
Test.startTest();
String result = ShopifyController.CheckingBatchDetails(objectName, apexClassName, store);
Test.stopTest();
}
@isTest
static void testCheckingBatchDetails_Aborted() {
String objectName = 'Product2';
String apexClassName = 'TestClass';
String store = 'TestStore';
Test.startTest();
String result = ShopifyController.CheckingBatchDetails(objectName, apexClassName, store);
Test.stopTest();
}
/**************************************CheckingBatchDetails*************************************************/
@isTest
public static void GetRealtimeData_Test(){
Test.startTest();
Integer result1 = ShopifyController.GetRealtimeData('Order','Gurgaonstore');
Integer result2 = ShopifyController.GetRealtimeData('DraftOrder','Gurgaonstore');
Integer result3 = ShopifyController.GetRealtimeData('Product2','Gurgaonstore');
Integer result4 = ShopifyController.GetRealtimeData('Account','Gurgaonstore');
Integer result5 = ShopifyController.GetRealtimeData('Contact','Gurgaonstore');
Integer result6 = ShopifyController.GetRealtimeData('HIC_ShopifySync__Variant__c','Gurgaonstore');
Integer result7 = ShopifyController.GetRealtimeData('Opportunity','Gurgaonstore');
Integer result8 = ShopifyController.GetRealtimeData('HIC_ShopifySync__Inventory__c','Gurgaonstore');
Test.stopTest();
System.assertEquals(result1, result1);
System.assertEquals(result2, result2);
System.assertEquals(result3, result3);
System.assertEquals(result4, result4);
System.assertEquals(result5, result5);
System.assertEquals(result8, result6);
System.assertEquals(result7, result7);
}
/****************************** Get Refresh Token to check remote site **************************************/
@isTest
static void refreshTokenCheck_Test()
{
List<HIC_ShopifySync__Configuration__c> hicShoList=TestDataFactory.createConfigurationCustomSetting(1);
insert hicShoList;
Organization orgRecord = [SELECT id, issandbox FROM Organization LIMIT 1];
String refreshToken= hicShoList[0].HIC_ShopifySync__Refresh_Token__c;
ShopifyController.refreshTokenCheck();
String accessToken = ShopifyController.oauthLogin(refreshToken);
//System.assertEquals('TestToken', accessToken, 'Refresh token should match');
}
/**************************************Check any batch is processing ********************************/
@isTest
static void testCheckBatchIsProcessing_ConfigurationFound() {
List<HIC_ShopifySync__Configuration__c>config=TestDataFactory.createConfigurationCustomSetting(1);
if(!config.isEmpty() && config!=null){
insert config;
}
List<HIC_ShopifySync__HIC_Configuration__c> configHicList=TestDataFactory.createConfiguration(1);
if(!configHicList.isEmpty() && configHicList!=null){
insert configHicList;
}
// Call the method to be tested
Test.startTest();
String result = ShopifyController.checkBatchIsProcessing();
Test.stopTest();
// Verify the result
System.assertNotEquals(null, result, 'Expected configuration record JSON was not returned');
// Add additional assertions based on the expected behavior when configuration is found
}
@isTest
static void testCheckBatchIsProcessing_NoConfigurationFound() {
List<HIC_ShopifySync__Configuration__c>config=TestDataFactory.createConfigurationCustomSetting(1);
if(!config.isEmpty() && config!=null){
insert config;
}
List<HIC_ShopifySync__HIC_Configuration__c> configHicList=TestDataFactory.createConfiguration(1);
if(!configHicList.isEmpty() && configHicList!=null){
insert configHicList;
}
HIC_ShopifySync__HIC_Configuration__c configHicObj=[Select Id,HIC_ShopifySync__Store__c From HIC_ShopifySync__HIC_Configuration__c WHERE Id=: configHicList[0].Id LIMIT 1];
configHicObj.HIC_ShopifySync__Store__c= 'Default';
update configHicObj;
Test.startTest();
String result = ShopifyController.checkBatchIsProcessing();
Test.stopTest();
// Verify the result
System.assertEquals(null, result, 'Expected null was not returned when no configuration with Batch_Is_Processing set to true was found');
// Add additional assertions based on the expected behavior when no configuration is found
}
public class oauthlogintest implements HttpCalloutMock {
String clientIdProduction='3MVG9G9pzCUSkzZv4NsQV0kOphjUwrs4pHcnEP.g4ejkZCmpEmiSkw9X.M3tdeT.6lSfM1Z6uCn85AdMduQ.H';
String clientSecretproduction= '8B4246BE2D9D89EF4B53D64E1687D9040A8273323429EA9E5C930BE6EC06F4E6';
String refreshToken = 'EwA4A61DBAAUm4Az4MbwzN0ziTM/2hwxwNoGHboAAdhOerUo/69NOyhLCeT3ezAWVIqBl3d9GY2fZRgf5Mw1ZJCzcc6BqU13NOHc3Aoaw5Iv0oIPTRkPHiOrsI0CSd4DPopoFyL7DYbUQovZw34TXrtb8tLVl/sc/0tHYhkbNohcQV+AKxS+NcXJMLQoXhiifl5lmaap957Tpc3PO4528RyBzWP4T+lekjRl0370wEAhIw1m57wW2e6tCDUcdWaVlmxBtRSysMPYFAa5lHCk5ApmAWIbzkHX2gP7LS8JiIP310KiNGaD0EfSNI+2yBCijw0nU5up9Mpy1er+BCRPFZ8N9k9yx0I1i6OPWeOorO7kELc5jp1yn6YJ0ZO69rwDZgAACAdz/Dmx9JBxCALuUGFpNhs9D1Ub86sv8jTobxj0I4Gs5t/EiEfCFqTqXe/zpR0BotwLQ/02FkxMTn2YpnTcDPe6mLmg6e+Jhp4NJfklFxhOt5VVI9NXfjVqZfhSRW3zVklwGJF8UArQ1KUL/8aG8t4IUa5T3//DwArJ0Klac3mQ/+Wz8qQZl1hXnsFFlPegUFF+tab06eNecOlliL3kuhymmT5xJuG6+kRn5C0waNt/TnOjxlrWYqwJieL/uMqhUiJYqaSOQmWnR7s3jMkER45h049N0T3RjaR8NaFl9tARKEW72nIQO9MN2TFW1anvueKXRkItGfL3OYkGE6Phft5qlHoPhXAsARFAzVyMGEWfcdg3/eLhgjBCZrIT4MIB8pcHzzn/QEhienDhvN708w3em/dQzPRTmbk99wvFeszEcWYK2xVz2PG7jgTGnxWXqFVDGRjgElQ0KW6YsXBog0jBrGLcQBQ3SST+OiAeniwtVxj8/4rkgL7XdMkzb/V6Si6HA+M7TrTXPy8/1E21m9pX5J0bnc7B/Db4e77FjeRR8zD51UeJSlGmtqass4cboMSccjAoXm4YTPlgnXgtH5bvQ+QXHS4M5ZI+GKu2FHrNvDO5ikuUMaY5QOMdQcVCAnmV1/iaCOBzZi0NWYWsMKWN43gF5iyN25Yzo+RZQu+jbFU8F6urs2wKKyjZi5F75/6kRQI=';
public HTTPResponse respond(HTTPRequest req) {
HttpResponse res = new HttpResponse();
res.setHeader('X-Shopify-Access-Token', 'password@123');
res.setHeader('Content-Type', 'application/json');
req.setMethod('POST');
req.setBody( 'grant_type=refresh_token' +
'&client_secret=' +
clientSecretproduction +
'&client_id=' +
clientIdProduction +
'&refresh_token=' +
refreshToken);
res.setStatusCode(200);
return res;
}
}
/**************************************CheckshopifycertificateandRemotesite*************************************************/
@isTest
static void CheckshopifycertificateandRemotesite_Test() {
Boolean result = ShopifyController.CheckshopifycertificateandRemotesite('certificate', 'TestAccessToken');
System.assertEquals(true, result);
}
@isTest
static void testRemoteSiteSettings() {
Boolean result = ShopifyController.CheckshopifycertificateandRemotesite('other', 'TestAccessToken');
System.assertEquals(true, result);
}
@isTest
static void testExceptionHandling() {
Boolean result = ShopifyController.CheckshopifycertificateandRemotesite('certificate', 'TestAccessToken');
System.assertEquals(true, result);
}
/**************************************checkCreds*************************************************/
/**
* ─────────────────────────────────────────────────────────────────────────────────────────────┐
* Verify Shopify Credetials via callout into the Shopify
* ──────────────────────────────────────────────────────────────────────────────────────────────
* ─────────────────────────────────────────────────────────────────────────────────────────────┘
*/
@isTest
static void checkCreds_Test1() {
List<HIC_ShopifySync__Configuration__c>config=TestDataFactory.createConfigurationCustomSetting(1);
if(!config.isEmpty() && config!=null){
insert config;
}
Boolean result = ShopifyController.checkCreds('https://example-shop.myshopify.com', 'TestCryptoKeyTrue');
System.assertEquals(false, result);
}
@isTest
static void CheckCredsFailure_Test() {
Boolean result = ShopifyController.checkCreds('https://invalid-shop.myshopify.com', 'InvalidPassword');
System.assertEquals(null, result);
}
@isTest
static void CheckCredsEmptyConfig_Test() {
Boolean result = ShopifyController.checkCreds('https://example-shop.myshopify.com', 'TestCryptoKeyTrue');
System.assertEquals(null, result);
}
@isTest
static void CheckCreds_Test2() {
List<HIC_ShopifySync__Configuration__c>config=TestDataFactory.createConfigurationCustomSetting(1);
if(!config.isEmpty() && config!=null){
insert config;
}
Boolean result = ShopifyController.checkCreds('https://example.com', 'passwordTest');
System.assertEquals(false, result);
}
/**************************************saveRecordTypeMapping*************************************************/
@isTest
static void saveRecordTypeMapping_Test(){
String personAccountRecordTypeId = 'PersonId1,Store1';
String accountRecordTypeId = 'AccountId1,Store2';
String contactRecordTypeId = 'ContactId1,Store3';
String orderRecordTypeId = 'OrderId1,Store4';
String opportunityRecordTypeId = 'OpportunityId1,Store5';
String draftOrderRecordTypeId = 'DraftOrderId1,Store6';
String productRecordTypeId = 'ProductId1,Store7';
String store = 'testStore';
Test.startTest();
boolean result = ShopifyController.saveRecordTypeMapping(
personAccountRecordTypeId,
accountRecordTypeId,
contactRecordTypeId,
orderRecordTypeId,
opportunityRecordTypeId,
draftOrderRecordTypeId,
productRecordTypeId,
store
);
Test.stopTest();
System.assertEquals(true, result);
}
/**************************************syncShopify*************************************************/
// Method for the first 'if else' condition
@isTest
static void syncShopify_Test1() {
Test.startTest();
List<HIC_ShopifySync__HIC_Configuration__c>configuration=TestDataFactory.createConfiguration(1);
insert configuration;
HIC_ShopifySync__HIC_Configuration__c updatedConfiguration = [SELECT Id, HIC_ShopifySync__BatchRunOnce__c, HIC_ShopifySync__Batch_Is_Processing__c, HIC_ShopifySync__BatchisAborted__c, HIC_ShopifySync__ProductVariantBatchCompleted__c, HIC_ShopifySync__AccountContactBatchCompleted__c, HIC_ShopifySync__OrderBatchCompleted__c, HIC_ShopifySync__CollectionsBatchCompleted__c, HIC_ShopifySync__InventoryBatchCompleted__c, HIC_ShopifySync__DraftOrderBatchCompleted__c,
HIC_ShopifySync__Store__c,HIC_ShopifySync__Order__c FROM HIC_ShopifySync__HIC_Configuration__c WHERE Id = :configuration[0].Id LIMIT 1];
updatedConfiguration.HIC_ShopifySync__AccountContactBatchCompleted__c = false;
updatedConfiguration.HIC_ShopifySync__OrderBatchCompleted__c= false;
updatedConfiguration.HIC_ShopifySync__Order__c=true;
updatedConfiguration.HIC_ShopifySync__CollectionsBatchCompleted__c= false;
update updatedConfiguration;
String objectName = 'products';
ShopifyController.syncShopify('Test Store');
System.assertEquals(false, updatedConfiguration.HIC_ShopifySync__AccountContactBatchCompleted__c);
List<sObject> result = ShopifyController.fetchLookupData('TestKey', 'Account');
sObject result1 = ShopifyController.fetchDefaultRecord('TestRecordId', 'Account');
System.assertNotEquals(null, result);
System.assertEquals(null, result1);
Test.stopTest();
}
@IsTest
static void testSyncShopify() {
// Test data
String store = 'Test Store';
HIC_ShopifySync__HIC_Configuration__c configuration = new HIC_ShopifySync__HIC_Configuration__c(
HIC_ShopifySync__Store__c = store,
HIC_ShopifySync__BatchRunOnce__c = false,
HIC_ShopifySync__Batch_Is_Processing__c = false,
HIC_ShopifySync__BatchisAborted__c = false,
HIC_ShopifySync__ProductVariantBatchCompleted__c = false,
HIC_ShopifySync__AccountContactBatchCompleted__c = false,
HIC_ShopifySync__OrderBatchCompleted__c = false,
HIC_ShopifySync__CollectionsBatchCompleted__c = false,
HIC_ShopifySync__InventoryBatchCompleted__c = false,
HIC_ShopifySync__DraftOrderBatchCompleted__c = false
);
insert configuration;
Test.startTest();
// Test method invocation
ShopifyController.syncShopify(store);
Test.stopTest();
// Query the configuration record to verify updates
configuration = [SELECT HIC_ShopifySync__BatchRunOnce__c, HIC_ShopifySync__Batch_Is_Processing__c,
HIC_ShopifySync__BatchisAborted__c, HIC_ShopifySync__ProductVariantBatchCompleted__c,
HIC_ShopifySync__AccountContactBatchCompleted__c, HIC_ShopifySync__OrderBatchCompleted__c,
HIC_ShopifySync__CollectionsBatchCompleted__c, HIC_ShopifySync__InventoryBatchCompleted__c,
HIC_ShopifySync__DraftOrderBatchCompleted__c
FROM HIC_ShopifySync__HIC_Configuration__c
WHERE HIC_ShopifySync__Store__c = :store];
// Verify that all relevant flags are updated
System.assertEquals(true, configuration.HIC_ShopifySync__BatchRunOnce__c);
System.assertEquals(true, configuration.HIC_ShopifySync__Batch_Is_Processing__c);
System.assertEquals(false, configuration.HIC_ShopifySync__BatchisAborted__c);
System.assertEquals(false, configuration.HIC_ShopifySync__ProductVariantBatchCompleted__c);
System.assertEquals(false, configuration.HIC_ShopifySync__AccountContactBatchCompleted__c);
System.assertEquals(false, configuration.HIC_ShopifySync__OrderBatchCompleted__c);
System.assertEquals(false, configuration.HIC_ShopifySync__CollectionsBatchCompleted__c);
System.assertEquals(false, configuration.HIC_ShopifySync__InventoryBatchCompleted__c);
System.assertEquals(false, configuration.HIC_ShopifySync__DraftOrderBatchCompleted__c);
// Add more assertions as needed to ensure the expected behavior of the method
}
/**************************************getActivePricebook*************************************************/
@isTest
static void getActivePricebook_Test(){
Test.startTest();
List<Pricebook2>testPricebook=TestDataFactory.createPriceBook2(1);
insert testPricebook;
String result = ShopifyController.getActivePricebook();
System.assertNotEquals(null, result);
//System.assertEquals(2, result.size());
System.assertEquals(true, testPricebook[0].IsActive,'Expected IsActive true');
Test.stopTest();
}
/**************************************saveCurrencyMappingList*************************************************/
// @isTest
// static void testSaveCurrencyMappingList() {
// Test.startTest();
// String testStore = 'TestStore';
// String testStoreSelectedCurrency = 'USD';
// String result = ShopifyController.saveCurrencyMappingList(testStore, testStoreSelectedCurrency);
// System.debug('Result from ShopifyController.saveCurrencyMappingList: ' + result);
// // Check if the result starts with 'Error' and assert accordingly
// if (result.startsWith('Error')) {
// System.assert(false, 'Error returned from ShopifyController.saveCurrencyMappingList: ' + result);
// } else {
// List<HIC_ShopifySync__HIC_Field_Mapping__c> currencyMappingList;
// try {
// currencyMappingList = (List<HIC_ShopifySync__HIC_Field_Mapping__c>)JSON.deserialize(result, List<HIC_ShopifySync__HIC_Field_Mapping__c>.class);
// } catch (System.JSONException e) {
// System.assert(false, 'JSON deserialization error: ' + e.getMessage());
// }
// System.assertNotEquals(null, currencyMappingList);
// System.assertEquals(4, currencyMappingList.size());
// HIC_ShopifySync__HIC_Field_Mapping__c firstMapping = currencyMappingList[0];
// System.assertEquals('Opportunity-CurrencyISOCODE', firstMapping.Name);
// System.assertEquals('Opportunity', firstMapping.HIC_ShopifySync__Object_Name__c);
// System.assertEquals('CurrencyISOCODE', firstMapping.HIC_ShopifySync__SF_Field__c);
// System.assertEquals(testStoreSelectedCurrency, firstMapping.HIC_ShopifySync__Shopify_Fields__c);
// }
// Test.stopTest();
// }
/**************************************getActiveCurrencies*************************************************/
@IsTest
static void testGetRecordTypes() {
// Create test data
List<HIC_ShopifySync__HIC_Configuration__c>config=TestDataFactory.createConfiguration(1);
if(!config.isEmpty() && config!=null){
insert config;
}
// Call the method being tested
Test.startTest();
String recordTypeJSON = ShopifyController.getRecordTypes('Test Store');
Test.stopTest();
// Verify the results
System.assertNotEquals(null, recordTypeJSON, 'Record type JSON should not be null');
Map<String, Object> recordTypeMap = (Map<String, Object>) JSON.deserializeUntyped(recordTypeJSON);
System.assertNotEquals(null, recordTypeMap, 'Deserialized record type map should not be null');
// Check if record types are retrieved properly
System.assert(recordTypeMap.containsKey('PersonAccount'), 'Person Account record type should be present');
System.assert(recordTypeMap.containsKey('Account'), 'Account record type should be present');
System.assert(recordTypeMap.containsKey('Contact'), 'Contact record type should be present');
System.assert(recordTypeMap.containsKey('Order'), 'Order record type should be present');
System.assert(recordTypeMap.containsKey('DraftOrder'), 'Draft Order record type should be present');
System.assert(recordTypeMap.containsKey('Opportunity'), 'Opportunity record type should be present');
System.assert(recordTypeMap.containsKey('Product2'), 'Product2 record type should be present');
}
/**************************************getEverythingForObjects*************************************************/
@isTest
static void testGetEverythingForObjects() {
List <HIC_ShopifySync__HIC_Configuration__c> config =TestDataFactory.createConfiguration(1);
if(!config.isEmpty() && config!=null){
insert config;
}
String accountResult = ShopifyController.getEverythingForObjects('TestStore','Account',config);
System.assertNotEquals(null, accountResult);
String contactResult = ShopifyController.getEverythingForObjects('TestStore','Contact',config);
System.assertNotEquals(null, contactResult);
String productResult = ShopifyController.getEverythingForObjects('TestStore', 'Product2',config);
System.assertNotEquals(null, productResult);
String opportunityResult = ShopifyController.getEverythingForObjects('TestStore', 'Opportunity',config);
System.assertNotEquals(null, opportunityResult);
String draftOrderResult = ShopifyController.getEverythingForObjects('TestStore', 'DraftOrder',config);
System.assertNotEquals(null, draftOrderResult);
String draftOrderItemResult = ShopifyController.getEverythingForObjects('TestStore', 'DraftOrderItem',config);
System.assertNotEquals(null, draftOrderItemResult);
// String invalidResult = ShopifyController.getEverythingForObjects('TestStore', 'Opportunity');
// System.assertEquals(null, invalidResult, 'Result should be null for invalid input parameters');
}
/**************************************CheckFieldMapping*************************************************/
@isTest
static void testCheckFieldMapping() {
Schema.DescribeFieldResult accountFieldResult = SObjectType.Account.fields.getMap().get('Name').getDescribe();
Boolean accountResult = ShopifyController.checkFieldMapping('Account', 'Name', accountFieldResult);
System.assertEquals(true, accountResult, 'Expected result is false for Account object and Name field');
Schema.DescribeFieldResult contactFieldResult = SObjectType.Contact.fields.getMap().get('LastName').getDescribe();
Boolean contactResult = ShopifyController.checkFieldMapping('Contact', 'LastName', contactFieldResult);
System.assertEquals(true, contactResult, 'Expected result is true for Contact object and LastName field');
Schema.DescribeFieldResult opportunityFieldResult = SObjectType.Opportunity.fields.getMap().get('StageName').getDescribe();
Boolean opportunityResult = ShopifyController.checkFieldMapping('Opportunity', 'StageName', opportunityFieldResult);
System.assertEquals(true, opportunityResult, 'Expected result is false for Opportunity object and StageName field');
Schema.DescribeFieldResult orderItemFieldResult = SObjectType.OrderItem.fields.getMap().get('Quantity').getDescribe();
Boolean orderItemResult = ShopifyController.checkFieldMapping('OrderItem', 'Quantity', orderItemFieldResult);
System.assertEquals(true, orderItemResult, 'Expected result is true for OrderItem object and Quantity field');
Schema.DescribeFieldResult productFieldResult = SObjectType.Product2.fields.getMap().get('IsActive').getDescribe();
Boolean productResult = ShopifyController.checkFieldMapping('Product2', 'IsActive', productFieldResult);
System.assertEquals(true, productResult, 'Expected result is true for Product2 object and IsActive field');
}
/**************************************************************************************** */
// ??? Uncomment this after currencyISO issue
@isTest
static void testGetListofCurrencyISOCode() {
Boolean multiCurrencyEnabled = Schema.getGlobalDescribe().containsKey('CurrencyType');
List<HIC_ShopifySync__HIC_Field_Mapping__c>fieldMapping=TestDataFactory.createFieldMapping(1);
if(!fieldMapping.isEmpty() && fieldMapping!=null){
insert fieldMapping;
}
List<String> result = ShopifyController.getlistofCurrencyISOCode('Opportunity-StageName');
result = ShopifyController.getlistofCurrencyISOCode('Opportunity-StageName');
}
/** CUSTOM ACCOUNT LOOK UP */
// Method to fetch lookup search result
@isTest
public static void fetchLookupData_Test(){
List<HIC_ShopifySync__HIC_Field_Mapping__c>fieldMapping=TestDataFactory.createFieldMapping(1);
if(!fieldMapping.isEmpty() && fieldMapping!=null){
insert fieldMapping;
}
Test.startTest();
List<sObject> result = ShopifyController.fetchLookupData('TestKey', 'Account');
Test.stopTest();
System.assertNotEquals(null, result);
}
@isTest
static void testFetchDefaultRecord() {
// Create test data
Account testAccount = new Account(Name = 'Test Account');
insert testAccount;
// Call the method being tested
Test.startTest();
sObject result = ShopifyController.fetchDefaultRecord(testAccount.Id, 'Account');
Test.stopTest();
// Debugging statements to understand the issue
System.debug('Result: ' + result);
// Assert the result
System.assertNotEquals(null, result, 'Result should not be null');
}
@isTest
static void testDeleteFieldMappings() {
String deletedCustomSetting = '["Order-name","Account-HIC_Shopify__TAG__c","Account-BillingStreet","Account-BillingCity"]';
String store = 'default'; // Replace with appropriate store name
List<HIC_ShopifySync__HIC_Field_Mapping__c> fieldObjList=TestDataFactory.createFieldMapping(1);
fieldObjList[0].HIC_ShopifySync__Store__c= 'default';
insert fieldObjList;
Test.startTest();
String result = ShopifyController.deleteFieldMappings(deletedCustomSetting, store);
Test.stopTest();
}
@isTest
static void testDeleteFieldMappings_NotBlank_CustomSetting() {
String deletedCustomSetting = '["Order-name","Account-HIC_Shopify__TAG__c","Account-BillingStreet","Account-BillingCity"]';
String store = 'StoreName';
Test.startTest();
String result = ShopifyController.deleteFieldMappings(deletedCustomSetting, store);
Test.stopTest();
}
@isTest
static void testGetAccessToken_AccessTokenFound() {
List<HIC_ShopifySync__Configuration__c>config=TestDataFactory.createConfigurationCustomSetting(1);
if(!config.isEmpty() && config!=null){
insert config;
}
Test.startTest();
String result = ShopifyController.getAccessToken();
Test.stopTest();
}
@isTest
static void testGetAccessToken_NoAccessTokenFound() {
Test.startTest();
String result = ShopifyController.getAccessToken();
Test.stopTest();
System.assertEquals('No refresh token found', result, 'Expected message for no access token was not returned');
}
@isTest
static void testSetupAccessCheck_Success() {
Test.startTest();
Map<String, Boolean> expectedResult = new Map<String, Boolean>{'classAndPageAccess' => false, 'remoteSite' => true, 'certificate' => true};
Map<String, Boolean> result = ShopifyController.setupAccessCheck('GuestUserId', 'AccessToken');
Test.stopTest();
// System.assertEquals(expectedResult, result, 'Result should be true for all keys');
}
@isTest
static void testSetupAccessCheck_SiteClassAndPageAccessFails() {
Test.startTest();
Map<String, Boolean> expectedResult = new Map<String, Boolean>{'classAndPageAccess' => false, 'remoteSite' => true, 'certificate' => true};
Map<String, Boolean> result = ShopifyController.setupAccessCheck('InvalidUserId', 'AccessToken');
Test.stopTest();
// Assertions
// System.assertEquals(expectedResult, result, 'Result should have classAndPageAccess as false');
}
@isTest
static void testSetupAccessCheck_RemoteSiteFails() {
Test.startTest();
Map<String, Boolean> expectedResult = new Map<String, Boolean>{'classAndPageAccess' => false, 'remoteSite' => true, 'certificate' => true};
Map<String, Boolean> result = ShopifyController.setupAccessCheck('GuestUserId', 'InvalidAccessToken');
Test.stopTest();
// Assertions
// System.assertEquals(expectedResult, result, 'Result should have remoteSite as false');
}
@isTest
static void testSetupAccessCheck_CertificateFails() {
Test.startTest();
Map<String, Boolean> expectedResult = new Map<String, Boolean>{'classAndPageAccess' => false, 'remoteSite' => true, 'certificate' => true};
Map<String, Boolean> result = ShopifyController.setupAccessCheck('GuestUserId', 'InvalidAccessToken');
Test.stopTest();
// System.assertEquals(expectedResult, result, 'Result should have certificate as false');
}
@isTest
static void testCheckSiteClassandPageAccess_ListOfApexClassEmpty() {
Profile profile = [SELECT Id FROM Profile WHERE Name = 'Standard User' LIMIT 1]; // Assuming you have a profile named 'Standard User'
User guestUser = new User(
Username = 'testuseralready@example.com',
LastName = 'Test',
Email = 'testuser1@example.com',
Alias = 'tuser',
TimeZoneSidKey = 'America/Los_Angeles',
LocaleSidKey = 'en_US',
EmailEncodingKey = 'UTF-8',
ProfileId = profile.Id,
LanguageLocaleKey = 'en_US'
);
insert guestUser;
User uesrObj=[Select Id,ProfileId,Email From User Where UserType='Guest' LIMIT 1];
Test.startTest();
Boolean result = ShopifyController.checkSiteClassandPageAccess(uesrObj.Id);
Test.stopTest();
System.assertEquals(true, result, 'Result should be true');
}
@isTest
static void testCheckSiteClassandPageAccess_Exception() {
Test.startTest();
Boolean result = ShopifyController.checkSiteClassandPageAccess('InvalidUserId');
Test.stopTest();
System.assertEquals(false, result, 'Result should be false when an exception occurs');
}
@isTest
static void testSyncShopify_EmptyConfigurationList() {
Test.startTest();
ShopifyController.syncShopify('TestStore');
Test.stopTest();
List<HIC_ShopifySync__HIC_Configuration__c> configurationList = [SELECT Id FROM HIC_ShopifySync__HIC_Configuration__c];
System.assertEquals(0, configurationList.size(), 'Configuration list should remain empty');
}
@isTest
static void testSyncShopify_ProductVariantBatchCompletedFalse() {
List<HIC_ShopifySync__HIC_Configuration__c>config=TestDataFactory.createConfiguration(1);
if(!config.isEmpty() && config!=null){
insert config;
}
// Call the method to be tested
Test.startTest();
ShopifyController.syncShopify('Test Store');
Test.stopTest();
// Verify the result
config = [SELECT HIC_ShopifySync__ProductVariantBatchCompleted__c FROM HIC_ShopifySync__HIC_Configuration__c WHERE Id = :config[0].Id];
System.assertEquals(true, config[0].HIC_ShopifySync__ProductVariantBatchCompleted__c, 'ProductVariantBatchCompleted should be true');
}
@isTest
static void testSyncShopify_AccountContactBatchCompletedFalse() {
List<HIC_ShopifySync__HIC_Configuration__c>config=TestDataFactory.createConfiguration(1);
insert config;
// Call the method to be tested
Test.startTest();
ShopifyController.syncShopify('Test Store');
Test.stopTest();
config = [SELECT HIC_ShopifySync__AccountContactBatchCompleted__c FROM HIC_ShopifySync__HIC_Configuration__c WHERE Id = :config[0].Id];
System.assertEquals(true, config[0].HIC_ShopifySync__AccountContactBatchCompleted__c, 'HIC_ShopifySync__AccountContactBatchCompleted__c should remain false');
}
@isTest
static void testSyncShopify_CollectionsBatchCompletedFalse() {
List<HIC_ShopifySync__HIC_Configuration__c>config=TestDataFactory.createConfiguration(1);
insert config;
// Set up test data
// Call the method to be tested
Test.startTest();
ShopifyController.syncShopify('TestStore');
Test.stopTest();
List<HIC_ShopifySync__HIC_Configuration__c>config2 = [SELECT HIC_ShopifySync__CollectionsBatchCompleted__c FROM HIC_ShopifySync__HIC_Configuration__c WHERE Id = :config[0].Id];
config2[0].HIC_ShopifySync__CollectionsBatchCompleted__c=false;
update config2;
config=[SELECT HIC_ShopifySync__CollectionsBatchCompleted__c FROM HIC_ShopifySync__HIC_Configuration__c WHERE Id = :config[0].Id];
System.assertEquals(false, config[0].HIC_ShopifySync__CollectionsBatchCompleted__c, 'HIC_ShopifySync__CollectionsBatchCompleted__c should remain false');
}
@isTest
static void testSyncShopify_InventoryBatchCompletedFalse() {
HIC_ShopifySync__HIC_Configuration__c config = new HIC_ShopifySync__HIC_Configuration__c();
// Set up configuration as required for this scenario
config.HIC_ShopifySync__InventoryBatchCompleted__c = false;
config.HIC_ShopifySync__Inventory_Location__c = true; // Assuming inventory location is enabled
insert config;
Test.startTest();
ShopifyController.syncShopify('TestStore');
Test.stopTest();
config = [SELECT HIC_ShopifySync__Inventory_Location__c FROM HIC_ShopifySync__HIC_Configuration__c WHERE Id = :config.Id];
System.assertEquals(true, config.HIC_ShopifySync__Inventory_Location__c, 'HIC_ShopifySync__Inventory_Location__c should remain true');
}
@isTest
static void testCheckEmailDeliverability_EmailsTurnedOn() {
Test.startTest();
Boolean emailsTurnedOn = ShopifyController.checkemaildeliverability();
Test.stopTest();
System.assertEquals(true, emailsTurnedOn, 'Email deliverability should be turned on');
}
@isTest
static void testSendingMailtoShopifySupport_Successful() {
Test.startTest();
boolean emailSent = ShopifyController.sendingMailtoShopifySupport('Test issue');
System.assertEquals(false, emailSent, 'Email should have been sent successfully');
Test.stopTest();
}
@isTest
static void testSendingMailtoShopifySupport_EmptyIssue() {
Test.startTest();
boolean emailSent = ShopifyController.sendingMailtoShopifySupport('');
System.assertEquals(false, emailSent, 'Email should have been sent with empty issue');
Test.stopTest();
}
// Test method to test the getUIThemeDescription() method
@isTest
static void testGetUIThemeDescription() {
String uiTheme = ShopifyController.getUIThemeDescription();
System.assertEquals(UserInfo.getUiThemeDisplayed(), uiTheme, 'UI theme should match the displayed UI theme');
}
// Test method to test the returnDomainUrl() method
@isTest
static void testReturnDomainUrl() {
Test.startTest();
String domainUrl = ShopifyController.returnDomainUrl();
Test.stopTest();
System.assertNotEquals(null, domainUrl, 'Domain URL should not be null');
System.assertNotEquals('', domainUrl, 'Domain URL should not be empty');
System.assert(domainUrl.startsWith('https://'), 'Domain URL should start with "https://"');
System.assert(domainUrl.endsWith('.salesforce.com'), 'Domain URL should end with ".salesforce.com"');
}
// Test method for when configuration record is found and site URL is not null
@isTest
static void checkSitefromConfiguration_when_config_is_found() {
HIC_ShopifySync__Configuration__c config = new HIC_ShopifySync__Configuration__c(
Name = 'Default',
HIC_ShopifySync__Salesforce_Site_URL__c = 'https://example.com'
);
insert config;
String result = ShopifyController.checkSitefromConfiguration();
ShopifyController.getMiddleWareUrl();
System.assertEquals('https://example.com', result, 'Expected site URL');
}
// Test method for when configuration record is found but site URL is null
@isTest
static void checkSitefromConfiguration_when_url_null() {
HIC_ShopifySync__Configuration__c config = new HIC_ShopifySync__Configuration__c(
Name = 'Default'
);
insert config;
// Call the method
String result = ShopifyController.checkSitefromConfiguration();
// Assertion
System.assertEquals('false', result, 'Expected false result');
}
// Test method for when configuration record is not found
@isTest
static void checkSitefromConfiguration_when_record_not_found() {
// Call the method
String result = ShopifyController.checkSitefromConfiguration();
// Assertion
System.assertEquals('false', result, 'Expected false result');
}
// Test method for when configuration record is not found
@isTest
static void getDefaultAccForConts_when_field_mappings_are_found() {
Account accObj= new Account();
accObj.Name= 'Test';
insert accObj;
String store = 'Default';
List<HIC_ShopifySync__HIC_Field_Mapping__c> mapping=TestDataFactory.createFieldMapping(1);
insert mapping;
HIC_ShopifySync__HIC_Field_Mapping__c hicShopObj= [Select Id,Name, HIC_ShopifySync__Default_Value__c, HIC_ShopifySync__Shopify_Fields__c,HIC_ShopifySync__External_ID__c,HIC_ShopifySync__Store__c FROM HIC_ShopifySync__HIC_Field_Mapping__c WHERE HIC_ShopifySync__Store__c ='Default' LIMIT 1];
hicShopObj.HIC_ShopifySync__External_ID__c= 'Contact-Accountid';
update hicShopObj;
Test.startTest();
ShopifyController.getDefaultAccForConts(store);
Test.stopTest();
//System.assertNotEquals(null, result, 'Expected field mapping value');
}
// Test method for when account is found
@isTest
static void getAccountDetails_Test() {
Account testAccount = new Account(Name = 'Test Account');
insert testAccount;
Test.startTest();
Account result = ShopifyController.getAccountDetails(testAccount.Id);
ShopifyController.getAccountDetails('testNull');
Test.stopTest();
System.assertNotEquals(null, result, 'Expected account object');
System.assertEquals(testAccount.Id, result.Id, 'Expected account Id');
}
// Test method for when field mappings are found
@isTest
static void getDefaultOppClosedate_Test() {
String store = 'Default';
List<HIC_ShopifySync__HIC_Field_Mapping__c>mapping=TestDataFactory.createFieldMapping(1);
insert mapping;
HIC_ShopifySync__HIC_Field_Mapping__c hicShopObj= [Select Id,Name, HIC_ShopifySync__Default_Value__c, HIC_ShopifySync__Shopify_Fields__c,HIC_ShopifySync__External_ID__c,HIC_ShopifySync__Store__c FROM HIC_ShopifySync__HIC_Field_Mapping__c WHERE HIC_ShopifySync__Store__c ='Default' LIMIT 1];
hicShopObj.HIC_ShopifySync__External_ID__c= 'Opportunity-CloseDate';
update hicShopObj;
Test.startTest();
HIC_ShopifySync__HIC_Field_Mapping__c result = ShopifyController.getDefaultOppClosedate(store);
Test.stopTest();
System.assertNotEquals(null, result, 'Expected field mapping value');
}
// Test method for when field mappings are not found and Salesforce Opportunity Stage values are returned
@isTest
static void getDefaultOppStage_when_field_mapping_not_found() {
String store = 'Test Store';
Test.startTest();
String result = ShopifyController.getDefaultOppStage(store);
Test.stopTest();
System.assertNotEquals(null, result, 'Expected Salesforce Opportunity Stage value');
}
// Test method for when all parameters are provided
@isTest
static void updatePriceBookCurrencyStage_when_all_parameters_are_provided() {
String storeName = 'Test Store';
String defaultStageName = 'Test Stage';
String priceBookId = 'Test Pricebook';
String currencyCode = 'USD';
String configObj = 'Test Config';
Test.startTest();
Map<String, Object> result = ShopifyController.updatePriceBookCurrencyStage(storeName, defaultStageName, priceBookId, currencyCode, configObj);
Test.stopTest();
}
@isTest
static void testGetSampleData() {
// Create test data
List<HIC_ShopifySync__HIC_Configuration__c>config=TestDataFactory.createConfiguration(1);
insert config;
Test.startTest();
// Call the method
List<String> sampleData = ShopifyController.getSampeledata('Test Store');
Test.stopTest();
// Assert
//System.assertNotEquals(null, sampleData);
//System.assertEquals(5, sampleData.size());
}
// Mock implementation of CheckAccessibility.isAccessible method
@TestVisible
static String isAccessible(String fields, String objectType) {
// Mock implementation here
// For simplicity, returning the fields as is
return fields;
}
// Mock data for HIC_ShopifySync__HIC_Configuration__c
static HIC_ShopifySync__HIC_Configuration__c createMockConfiguration(String storeName) {
HIC_ShopifySync__HIC_Configuration__c config = new HIC_ShopifySync__HIC_Configuration__c();
config.HIC_ShopifySync__Store__c = storeName;
// Populate other required fields
// ...
return config;
}
@isTest
static void testUpdateConfigurationPBatchProcessingField() {
// Mock configuration data
HIC_ShopifySync__HIC_Configuration__c config = createMockConfiguration('TestStore');
insert config;
Test.startTest();
boolean result = ShopifyController.updateconfigurationpbatchprocessingfield('TestStore', false);
boolean storeUrlResult = ShopifyController.checkStoreNameRemoteSite('TestStore');
Map<String, String> reportTest = ShopifyController.getReports();
Test.stopTest();
// Assertions
System.assertEquals(true, result, 'Result should be true when configuration is updated successfully');
System.assertEquals(false, config.HIC_ShopifySync__Batch_Is_Processing__c, 'Batch Is Processing field should be false');
System.assertEquals(false, config.HIC_ShopifySync__BatchisAborted__c, 'Batch Is Aborted field should be false');
System.assertEquals(false, config.HIC_ShopifySync__IsCurrencyChanged__c, 'Is Currency Changed field should be false');
}
@isTest
static void testUpdateConfigurationPBatchProcessingField_null() {
// Test with no configuration found
Test.startTest();
boolean result = ShopifyController.updateconfigurationpbatchprocessingfield('InvalidStore', false);
Test.stopTest();
// Assertions
System.assertEquals(false, result, 'Result should be false when no configuration is found');
}
// Mock implementation of CheckAccessibility.isAccessible method
@TestVisible
static String isAccessible1(String fields, String objectType) {
// Mock implementation here
// For simplicity, returning the fields as is
return fields;
}
// Mock data for HIC_ShopifySync__Configuration__c
static HIC_ShopifySync__Configuration__c createMockConfiguration1(String siteUrl) {
HIC_ShopifySync__Configuration__c config = new HIC_ShopifySync__Configuration__c();
config.Name = 'Default';
config.HIC_ShopifySync__Salesforce_Site_URL__c = siteUrl;
return config;
}
@isTest
static void testSaveSiteUrlConfig() {
// Mock configuration data
HIC_ShopifySync__Configuration__c config = createMockConfiguration1('https://example.com');
insert config;
Test.startTest();
boolean result = ShopifyController.savesiteurlconfig('https://newsite.com');
boolean result1 = ShopifyController.savesiteurlconfig('https://newsite.com');
boolean result2 = ShopifyController.savesiteurlconfig('https://newsite.com');
Test.stopTest();
System.assertEquals(true, result, 'Result should be true when site URL is updated successfully');
//System.assertEquals('https://newsite.com', config.HIC_ShopifySync__Salesforce_Site_URL__c, 'Site URL should be updated');
System.assertEquals(true, result2, 'Result should be true when exception occurs during update');
System.assertEquals(true, result1, 'Result should be false when no configuration is found');
}
@isTest
static void testUpdateFieldMappingAndConfiguration() {
List<HIC_ShopifySync__HIC_Field_Mapping__c>fieldMappings=TestDataFactory.createFieldMapping(1);
insert fieldMappings;
List<HIC_ShopifySync__HIC_Configuration__c>config=TestDataFactory.createConfiguration(1);
insert config;
Account accObj=new Account(Name='test');
insert accObj;
Test.startTest();
// Test method invocation with valid parameters
Map<String, Object> result1 = null;
try {
result1 = ShopifyController.updateFieldMappingAndConfigration(true, config[0].Id, null, accObj.Id, 'oppDefaultStage', 'oppCloseDays', 'storeName');
} catch (Exception e) {
System.debug('Exception1: ' + e.getMessage());
}
Map<String, Object> result2 = null;
try {
result2 = ShopifyController.updateFieldMappingAndConfigration(true, null, null, 'invalidAccountId', 'oppDefaultStage', 'oppCloseDays', 'storeName');
} catch (Exception e) {
System.debug('Exception2: ' + e.getMessage());
}
Test.stopTest();
}
@isTest
static void testGetFieldMappings() {
List<HIC_ShopifySync__HIC_Configuration__c>config=TestDataFactory.createConfiguration(1);
insert config;
Test.startTest();
String result = ShopifyController.getFieldMappings('Test Store');
Test.stopTest();
System.assertNotEquals('Error', result, 'Result should not be "Error"');
System.assertNotEquals(null, result, 'Result should not be null');
Map<String, Object> resultMap = (Map<String, Object>) JSON.deserializeUntyped(result);
System.assertEquals(true, resultMap.containsKey('Account'), 'Result should contain mapping for Account');
System.assertEquals(true, resultMap.containsKey('Contact'), 'Result should contain mapping for Contact');
System.assertEquals(true, resultMap.containsKey('Product2'), 'Result should contain mapping for Product2');
System.assertEquals(true, resultMap.containsKey('HIC_ShopifySync__Variant__c'), 'Result should contain mapping for HIC_ShopifySync__Variant__c');
System.assertEquals(true, resultMap.containsKey('Order'), 'Result should contain mapping for Order');
System.assertEquals(true, resultMap.containsKey('OrderItem'), 'Result should contain mapping for OrderItem');
System.assertEquals(true, resultMap.containsKey('DraftOrder'), 'Result should contain mapping for DraftOrder');
System.assertEquals(true, resultMap.containsKey('DraftOrderItem'), 'Result should contain mapping for DraftOrderItem');
System.assertEquals(true, resultMap.containsKey('Opportunity'), 'Result should contain mapping for Opportunity');
System.assertEquals(true, resultMap.containsKey('OpportunityLineItem'), 'Result should contain mapping for OpportunityLineItem');
}
@isTest
public static void getlistofobjecforsampleTest() {
String objectName = 'smart_collections.json';
List<HIC_ShopifySync__HIC_Field_Mapping__c> fieldMapList =TestDataFactory.createFieldMapping(1);
insert fieldMapList;
List<HIC_ShopifySync__HIC_Configuration__c>configList=TestDataFactory.createConfiguration(1);
insert configList;
list<string> listofallsampledata = new list<string>();
Test.setMock(HttpCalloutMock.class, new TestDataFactory.MockHttpResponseGeneratorTest());
Test.setMock(HttpCalloutMock.class, new TestDataFactory.oauthlogintest());
Test.startTest();
ShopifyController.getlistofobjecforsample(objectName,configList,listofallsampledata);
Test.stopTest();
}
public static List<String> getDataFromShopify(String endpoint, String accessToken) {
List<String> responseData = new List<String>();
HttpRequest req = new HttpRequest();
req.setMethod('GET');
req.setEndpoint(endpoint);
req.setHeader('Content-Type', 'application/json');
req.setHeader('X-Shopify-Access-Token', accessToken);
try {
HttpResponse res = new Http().send(req);
if (res.getStatusCode() == 200) { // Successful HTTP request
// Parse the response body to extract the data
Map<String, Object> jsonResponse = (Map<String, Object>)JSON.deserializeUntyped(res.getBody());
List<Object> accessScopes = (List<Object>)jsonResponse.get('access_scopes');
for (Object scope : accessScopes) {
Map<String, Object> scopeMap = (Map<String, Object>)scope;
String handle = (String)scopeMap.get('handle');
responseData.add(handle);
}
} else {
// Handle error response
System.debug('Error response from Shopify: ' + res.getBody());
// Optionally throw an exception or handle error response differently
}
} catch (Exception e) {
// Handle exception
System.debug('Exception occurred: ' + e.getMessage());
// Optionally throw an exception or handle exception differently
}
return responseData;
}
@isTest
static void testSaveConfiguration() {
// Test data setup
List<HIC_ShopifySync__Configuration__c>config=TestDataFactory.createConfigurationCustomSetting(1);
insert config;
Test.startTest();
Boolean result1 = ShopifyController.saveConfigration(JSON.serialize(config), 'True');
Boolean result2 = ShopifyController.saveConfigration(JSON.serialize(config), 'True');
Boolean result3 = ShopifyController.saveConfigration(JSON.serialize(config), 'False');
Boolean result4 = ShopifyController.saveConfigration(JSON.serialize(config), 'Normal');
Test.stopTest();
}
@isTest
static void testGetActiveCurrencies_MultiCurrencyDisabled() {
System.runAs(new User(Id = UserInfo.getUserId())) {
List<String> result = ShopifyController.getActiveCurrencies();
System.assertEquals('USD', result[0], 'Default currency should be USD');
}
}
private class MockCurrencyType implements HttpCalloutMock {
List<SObject> mockCurrencyData;
public MockCurrencyType(List<SObject> mockCurrencyData) {
this.mockCurrencyData = mockCurrencyData;
}
public HTTPResponse respond(HTTPRequest req) {
HTTPResponse res = new HTTPResponse();
res.setHeader('content-Type', 'application/json');
req.setHeader('X-Shopify-Access-Token', 'PASSWORD');
res.setBody(JSON.serialize(mockCurrencyData));
res.setStatusCode(200);
return res;
}
}
@isTest
static void testProcessFieldMappingSobjectWithAllFields() {
// Test data
String testObjectName = 'Opportunity';
String testSfField = 'CurrencyISOCODE';
String testShopifyField = 'shopifyCurrency';
String testNested = 'nestedValue';
boolean testIsDefault = true;
boolean testIsSfId = false;
String testSfFieldType = 'String';
String testShopifyType = 'String';
String testStore = 'TestStore';
String testGraphqlfield = 'graphqlFieldValue';
// Invoke the method
HIC_ShopifySync__HIC_Field_Mapping__c result = ShopifyController.processFieldMappingSobjectWithAllFields(
testObjectName,
testSfField,
testShopifyField,
testNested,
testIsDefault,
testIsSfId,
testSfFieldType,
testShopifyType,
testStore,
testGraphqlfield
);
// Verify the result is not null
System.assertNotEquals(null, result, 'The result should not be null');
// Verify the field values
String expectedName = 'Opportunity-CurrencyISOCODE'.length() > 38 ? 'Opportunity-CurrencyISOCODE'.substring(0, 38) : 'Opportunity-CurrencyISOCODE';
System.assertEquals(expectedName, result.Name);
System.assertEquals(testObjectName, result.HIC_ShopifySync__Object_Name__c);
System.assertEquals(testSfField, result.HIC_ShopifySync__SF_Field__c);
System.assertEquals(testShopifyField, result.HIC_ShopifySync__Shopify_Fields__c);
System.assertEquals(testGraphqlfield, result.HIC_ShopifySync__GQL_Field_API__c);
System.assertEquals(testNested, result.HIC_ShopifySync__Nested__c);
System.assertEquals(testIsDefault, result.HIC_ShopifySync__Default_Value__c);
System.assertEquals(testIsSfId, result.HIC_ShopifySync__IsSFID__c);
System.assertEquals(testObjectName + '-' + testSfField, result.HIC_ShopifySync__External_ID__c);
System.assertEquals(testStore + testObjectName + '-' + testSfField, result.HIC_ShopifySync__Store_External_ID__c);
System.assertEquals(testSfFieldType, result.HIC_ShopifySync__SF_Field_Type__c);
System.assertEquals(testShopifyType, result.HIC_ShopifySync__Shopify_Field_Type__c);
System.assertEquals(testStore, result.HIC_ShopifySync__Store__c);
}
@isTest
static void testSaveConfigration() {
String configObj = '{"HIC_ShopifySync__Shopify_URL__c":"https://example.myshopify.com","HIC_ShopifySync__Private_Key_Password__c":"yourpassword"}';
String checkTrue = 'True';
String checkFalse = 'False';
String checkNormal = 'Normal';
HIC_ShopifySync__HIC_Configuration__c config = new HIC_ShopifySync__HIC_Configuration__c();
config.HIC_ShopifySync__Shopify_URL__c = 'https://example.myshopify.com';
config.HIC_ShopifySync__Private_Key_Password__c = 'yourpassword';
Test.startTest();
Boolean resultTrue = ShopifyController.saveConfigration(configObj, checkTrue);
Boolean resultFalse = ShopifyController.saveConfigration(configObj, checkFalse);
Boolean resultNormal = ShopifyController.saveConfigration(configObj, checkNormal);
Test.stopTest();
}
/*
*
*
*
*Below method will cover the new added methods of HIC_ShopifyUtility class
*
*
*
*/
@isTest
static void getShopifyRecordCounts_Test2()
{
List<HIC_ShopifySync__HIC_Configuration__c>testConfiguration=TestDataFactory.createConfiguration(1);
if(!testConfiguration.isEmpty() && testConfiguration!=null){
insert testConfiguration;
}
String storeName = 'Test Store';
String objectName = 'HIC_ShopifySync__HIC_Configuration__c'; // Set objectName
String password='0000000000000000True';
Test.startTest();
String result = HIC_ShopifyUtility.getShopifyRecordCounts(storeName, objectName,password);
Test.stopTest();
System.assertNotEquals('Error!', result,'Result matched');
System.assertNotEquals('GET', result);
System.assertNotEquals('content-type', 'application/json');
}
@isTest
static void outhLoginTest()
{
List<HIC_ShopifySync__Configuration__c> hicShoList=TestDataFactory.createConfigurationCustomSetting(1);
insert hicShoList;
Organization orgRecord = [SELECT id, issandbox FROM Organization LIMIT 1];
String refreshToken= hicShoList[0].HIC_ShopifySync__Refresh_Token__c;
String clientIdProduction = hicShoList[0].HIC_ShopifySync__ClientId__c;
String clientSecretProduction = hicShoList[0].HIC_ShopifySync__ClientSecret__c;
Test.startTest();
Test.setMock(HttpCalloutMock.class, new MyHttpCalloutMock());
String accessToken = HIC_ShopifyUtility.oauthLogin(refreshToken,clientIdProduction,clientSecretProduction);
Test.stopTest();
}
@isTest
static void testCertificateQuery_Success() {
String accessToken = 'your_access_token';
String SFdomainUrl = 'https://yourdomain.salesforce.com';
Test.startTest();
Boolean result = HIC_ShopifyUtility.CheckshopifycertificateandRemotesite('certificate', accessToken, SFdomainUrl);
Boolean result2 = HIC_ShopifyUtility.CheckshopifycertificateandRemotesite('remotesite', accessToken, SFdomainUrl);
Test.stopTest();
System.assertEquals(true, result, 'Expected result not returned');
}
@isTest
static void testCheckCreds_Success() {
String shopifyUrl = 'https://myshopify.com';
String password = '000000R';
Test.startTest();
Test.setMock(HttpCalloutMock.class, new MyHttpCalloutMock());
Boolean result = HIC_ShopifyUtility.checkCreds(shopifyUrl, password);
Test.stopTest();
System.assertEquals(true, result, 'Expected result not returned');
}
@isTest
static void testRemotesiteExistence_Exception() {
String SFdomainUrl = 'https://yourdomain.salesforce.com';
String accessToken = 'your_access_token';
String OrgURl = 'https://yourorg.my.salesforce.com';
Test.startTest();
Test.setMock(HttpCalloutMock.class, new YourHttpMock(true, true));
Boolean result = HIC_ShopifyUtility.CheckingRemotesiteExistence(SFdomainUrl, accessToken, OrgURl);
Test.stopTest();
System.assertEquals(false, result, 'Expected result not returned');
}
private class YourHttpMock implements HttpCalloutMock {
Boolean success;
Boolean simulateException;
public YourHttpMock(Boolean success, Boolean simulateException) {
this.success = success;
this.simulateException = simulateException;
}
public HTTPResponse respond(HTTPRequest req) {
HttpResponse res = new HttpResponse();
if (success) {
res.setStatusCode(200);
res.setBody('{"size":1}');
} else {
if (simulateException) {
res.setStatusCode(500);
res.setBody('{"error":"Internal Server Error"}');
} else {
res.setStatusCode(400);
res.setBody('{}');
}
}
return res;
}
}
@isTest
static void testRemotesiteExists_Success() {
String remoteSiteUrl = 'https://example.com';
String domainUrl = 'https://yourdomain.salesforce.com';
Test.startTest();
Test.setMock(HttpCalloutMock.class, new MyHttpCalloutMock());
Boolean result = HIC_ShopifyUtility.checkRemotesiteExists(remoteSiteUrl, domainUrl);
Test.stopTest();
System.assertEquals(false, result, 'Expected result not returned');
}
@IsTest
static void testCheckAccesScopeTest2() {
String mockResponse = '{"access_scopes":[{"handle":"read_products"},{"handle":"write_orders"}]}';
Test.startTest();
Test.setMock(HttpCalloutMock.class, new MyHttpCalloutMock2(mockResponse));
String shopifyUrl = 'https://patchtesting.myshopify.com';
String password = '0000000000000000True';
String result = HIC_ShopifyUtility.checkAccesScope(shopifyUrl, password);
Test.stopTest();
}
private class MyHttpCalloutMock2 implements HttpCalloutMock {
String mockResponse;
public MyHttpCalloutMock2(String mockResponse) {
this.mockResponse = mockResponse;
}
public HTTPResponse respond(HTTPRequest req) {
HTTPResponse res = new HTTPResponse();
res.setHeader('Content-Type', 'application/json');
res.setBody(mockResponse);
res.setStatusCode(200);
return res;
}
}
@isTest
static void testDeleteCustomAppFromStore_Success() {
List<HIC_ShopifySync__HIC_Configuration__c> configurationList = new List<HIC_ShopifySync__HIC_Configuration__c>();
HIC_ShopifySync__HIC_Configuration__c config = new HIC_ShopifySync__HIC_Configuration__c();
config.HIC_ShopifySync__Shopify_URL__c = 'https://example.myshopify.com';
config.HIC_ShopifySync__Private_Key_Password__c = 'your_private_key_password';
configurationList.add(config);
Test.startTest();
Test.setMock(HttpCalloutMock.class, new MyHttpCalloutMock());
Boolean result = HIC_ShopifyUtility.deleteCustomAppFromStore(configurationList);
Test.stopTest();
System.assertEquals(true, result, 'Expected result not returned');
}
@isTest
static void testInitializeAccount_Success() {
Account accObj= new Account();
accObj.Name='test';
accObj.HIC_ShopifySync__Shopify_Id__c='ShopifyID1';
insert accObj;
Contact con=new Contact();
con.firstName='FirstName';
con.LastName='LastName';
con.HIC_ShopifySync__Shopify_Id__c='ShopifyID11';
insert con;
Contact conList= [Select Id,Name,HIC_ShopifySync__Shopify_Id__c From Contact Where Id=: con.Id LIMIT 1];
Map<String, String> shopifyIdvsAccountId = new Map<String, String>();
shopifyIdvsAccountId.put('ShopifyID1', conList.HIC_ShopifySync__Shopify_Id__c);
String objectName = 'Contact';
Boolean isPersonAccount = false;
List<HIC_ShopifySync__HIC_Configuration__c> configHicList = TestDataFactory.createConfiguration(1);
if (!configHicList.isEmpty() && configHicList != null) {
insert configHicList;
}
Test.startTest();
HIC_ShopifyUtility.InitializeAccount(shopifyIdvsAccountId, objectName, isPersonAccount, configHicList);
Test.stopTest();
Map<String, SObjectField> fieldMap = Contact.SObjectType.getDescribe().fields.getMap();
Schema.DescribeFieldResult nameField = fieldMap.get('Name').getDescribe();
System.assertEquals(true, nameField.isNameField());
System.assertEquals('Name', nameField.getName());
}
@isTest
static void testInitializeAccount_NullShopifyIdvsAccountId() {
String objectName = 'Account';
Boolean isPersonAccount = true;
List<HIC_ShopifySync__HIC_Configuration__c> configHicList=TestDataFactory.createConfiguration(1);
if(!configHicList.isEmpty() && configHicList!=null){
insert configHicList;
}
Test.startTest();
Test.setMock(HttpCalloutMock.class, new MyHttpCalloutMock());
HIC_ShopifyUtility.InitializeAccount(null, objectName, isPersonAccount, configHicList);
ShopifyController.getIsPerson();
ShopifyController.runPostInstallScript();
Test.stopTest();
List<Account> accounts = [SELECT Id FROM Account];
System.assertEquals(0, accounts.size(), 'No accounts should be initialized when the Shopify ID vs Account ID map is null');
}
@isTest
static void testUpdateCustomer_AccountContact_NoConfiguration() {
Account testAccount = new Account(Name = 'Test Account');
insert testAccount;
List<HIC_ShopifySync__HIC_Configuration__c>configHicList=TestDataFactory.createConfiguration(1);
configHicList[0].HIC_ShopifySync__Person_Account__c=false;
if(!configHicList.isEmpty()){
insert configHicList;
}
List<HIC_ShopifySync__HIC_Field_Mapping__c> shopifyHicList = TestDataFactory.createFieldMapping(1);
insert shopifyHicList;
HIC_ShopifySync__HIC_Field_Mapping__c shopifyHicObj = shopifyHicList[0];
shopifyHicObj.HIC_ShopifySync__Object_Name__c = 'Account';
shopifyHicObj.HIC_ShopifySync__Store__c = 'test_store';
shopifyHicObj.HIC_ShopifySync__SF_Field__c = 'Name';
update shopifyHicObj;
// Create test data for processing
Map<String, Object> testCustomerMap = new Map<String, Object>{
'id' => 'TestCustomerId',
'default_address' => new Map<String, Object>{
'first_name' => 'John',
'last_name' => 'Doe','company' => ''
}
};
List<Object> scope = new List<Object>{ testCustomerMap };
Test.startTest();
HIC_ShopifyUtility.updateCustomer(scope, configHicList, 'Test Store');
Test.stopTest();
Map<String, Object> updatedCustomerMap = (Map<String, Object>)scope[0];
System.assertEquals('Business TestCustomerId', (String)updatedCustomerMap.get('id'));
}
@isTest
static void testUpdateCustomer_for_else() {
Account testAccount = new Account(Name = 'Test Account');
insert testAccount;
List<HIC_ShopifySync__HIC_Configuration__c>configHicList=TestDataFactory.createConfiguration(1);
configHicList[0].HIC_ShopifySync__Default_Account__c=false;
if(!configHicList.isEmpty()){
insert configHicList;
}
List<HIC_ShopifySync__HIC_Field_Mapping__c> shopifyHicList = TestDataFactory.createFieldMapping(1);
insert shopifyHicList;
HIC_ShopifySync__HIC_Field_Mapping__c shopifyHicObj = shopifyHicList[0];
shopifyHicObj.HIC_ShopifySync__Object_Name__c = 'Account';
shopifyHicObj.HIC_ShopifySync__Store__c = 'test_store';
shopifyHicObj.HIC_ShopifySync__SF_Field__c = 'Name';
update shopifyHicObj;
Map<String, Object> testCustomerMap = new Map<String, Object>{
'id' => 'TestCustomerId',
'default_address' => new Map<String, Object>{
'first_name' => 'John',
'last_name' => 'Doe','company' => ''
}
};
List<Object> scope = new List<Object>{ testCustomerMap };
Test.startTest();
HIC_ShopifyUtility.updateCustomer(scope, configHicList, 'Test Store');
Test.stopTest();
Map<String, Object> updatedCustomerMap = (Map<String, Object>)scope[0];
System.assertEquals('TestCustomerId', (String)updatedCustomerMap.get('id'));
}
@isTest
static void testGetShopifyFields() {
String objectName = 'Account';
List<HIC_ShopifySync__HIC_Field_Mapping__c> shopifyHicList=TestDataFactory.createFieldMapping(1);
List<HIC_ShopifySync__Shopify_Fields__c> shopifyFields = new List<HIC_ShopifySync__Shopify_Fields__c>();
HIC_ShopifySync__Shopify_Fields__c shopifyObj= new HIC_ShopifySync__Shopify_Fields__c();
shopifyObj.Name='Test';
shopifyObj.HIC_ShopifySync__UI_Label_Name__c='Name';
shopifyObj.HIC_ShopifySync__Field_Name__c='Name';
shopifyObj.HIC_ShopifySync__Object_Name__c='Account';
shopifyObj.HIC_ShopifySync__Data_Type__c='Text';
shopifyObj.HIC_ShopifySync__Nested__c='test';
shopifyFields.add(shopifyObj);
insert shopifyFields;
Test.startTest();
String result = HIC_ShopifyUtility.getShopifyFields(objectName);
Test.stopTest();
System.assertNotEquals('Null', result, 'Result should not be "Null"');
List<Object> parsedResult = (List<Object>) JSON.deserializeUntyped(result);
System.assertNotEquals(0, parsedResult.size(), 'Shopify fields should not be empty');
}
@isTest
public static void processFieldTypeAndMappingTest() {
Opportunity opp = new Opportunity();
opp.Name = 'test_opp';
opp.CloseDate = system.today().addDays(10);
opp.StageName = 'Prospecting';
insert opp;
List<HIC_ShopifySync__HIC_Field_Mapping__c>fieldMappings=TestDataFactory.createFieldMapping(2);
fieldMappings[0].HIC_ShopifySync__SF_Field__c='CloseDate';
fieldMappings[0].HIC_ShopifySync__Shopify_Field_Type__c='Date';
fieldMappings[0].HIC_ShopifySync__Object_Name__c='Opportunity';
fieldMappings[0].HIC_ShopifySync__Shopify_Fields__c=string.valueOf(1);
fieldMappings[0].HIC_ShopifySync__Default_Value__c=true;
fieldMappings[1].HIC_ShopifySync__SF_Field__c='RecordTypeId';
fieldMappings[1].HIC_ShopifySync__Shopify_Field_Type__c='Id';
fieldMappings[1].HIC_ShopifySync__Object_Name__c='Order';
fieldMappings[1].HIC_ShopifySync__Shopify_Fields__c=Schema.SObjectType.Order.getRecordTypeInfosByName().get('Order').getRecordTypeId();
fieldMappings[1].HIC_ShopifySync__Default_Value__c=true;
insert fieldMappings;
String ObjectName = 'Opportunity';
Map<String, Object> objectMap = new Map<String, Object>();
objectMap.put('id', '12345');
objectMap.put('Person', 'TestName');
List<HIC_ShopifySync__HIC_Configuration__c> ConList =TestDataFactory.createConfiguration(1);
if(!ConList.isEmpty()){
insert ConList;
}
String companyTimeZone = 'GMT';
Test.startTest();
SObject result = HIC_ShopifyUtility.processFieldTypeAndMapping(fieldMappings, ObjectName, objectMap, ConList, companyTimeZone);
Test.stopTest();
System.assertEquals(ObjectName, result.getSObjectType().getDescribe().getName());
}
@isTest
static void testFetchAllDataWithLinkForNextPage_Error() {
List<HIC_ShopifySync__HIC_Configuration__c> configHicList=TestDataFactory.createConfiguration(1);
if(!configHicList.isEmpty() && configHicList!=null){
insert configHicList;
}
Test.startTest();
Test.setMock(HttpCalloutMock.class, new MyHttpCalloutMock());
String result = HIC_ShopifyUtility.fetchAllDataWithLinkForNextPage('shopifyUrlWithId', configHicList);
Test.stopTest();
}
@IsTest
static void testGetDefaultFieldMapping_StoreDefault() {
String objectName = 'Account';
Boolean isPersonAccount = false;
String store = 'Default';
SObjectType accountType = Account.sObjectType;
Map<String, SObjectField> fieldsMap = accountType.getDescribe().fields.getMap();
List<HIC_ShopifySync__HIC_Field_Mapping__c> fieldMappings = TestDataFactory.createFieldMapping(1);
fieldMappings[0].HIC_ShopifySync__Object_Name__c=objectName;
if(!fieldMappings.isEmpty() && fieldMappings!=null){
insert fieldMappings;
}
String objectName2='Reference';
Test.startTest();
String result = HIC_ShopifyUtility.getDefaultFieldMapping(objectName, isPersonAccount, store);
String result2 = HIC_ShopifyUtility.getDefaultFieldMapping(objectName2, true, store);
Test.stopTest();
}
@isTest
public static void testGetDefaultFieldMapping(){
String store = 'Default';
Boolean isPersonAccount = false;
String objectName='Reference';
String objectName2='DraftOrder';
String objectName3='DraftOrderItem';
Test.startTest();
String result = HIC_ShopifyUtility.getDefaultFieldMapping(objectName, isPersonAccount, store);
String result2 = HIC_ShopifyUtility.getDefaultFieldMapping(objectName, true, store);
String result3 = HIC_ShopifyUtility.getDefaultFieldMapping(objectName2, true, store);
String result4 = HIC_ShopifyUtility.getDefaultFieldMapping(objectName3, true, store);
Test.stopTest();
}
@isTest
public static void insertSmartCollectionRulesTest() {
Map<String, String> collectionIdVsRulesResponse = new Map<String, String>();
collectionIdVsRulesResponse.put('CollectionID', '[{"condition":"condition","relation":"relation","column":"column"}]');
Test.startTest();
Test.setMock(HttpCalloutMock.class, new MyHttpCalloutMock());
HIC_ShopifyUtility.insertSmartCollectionRules(CollectionIdVsRulesResponse);
Test.stopTest();
Integer expectedRecordsCount = 0;
Integer actualRecordsCount = [SELECT COUNT() FROM HIC_ShopifySync__Rules__c];
System.assertEquals(expectedRecordsCount, actualRecordsCount, 'Incorrect number of records inserted');
}
@isTest public static void TestfetchAllDataUsingId(){
String shopifyUrl = 'https://patchtesting.myshopify.com';
List<HIC_ShopifySync__HIC_Configuration__c> ConList =TestDataFactory.createConfiguration(1);
if(!ConList.isEmpty()){
insert ConList;
}
String shopifyUrlWithId = 'https://example.myshopify.com';
//String result = HIC_ShopifyUtility.fetchAllDataWithLinkForNextPage(shopifyUrlWithId, ConList);
Test.setMock(HttpCalloutMock.class, new TestDataFactory.MockHttpResponseGeneratorTest());
Test.setMock(HttpCalloutMock.class, new TestDataFactory.oauthlogintest());
Test.startTest();
HIC_ShopifyUtility.fetchAllDataUsingId(shopifyUrlWithId,ConList);
Test.stopTest();
//HttpResponse res = CalloutClassforHIC_ShopifyUtility.getInfoFromExternalService();
//system.assertEquals(200, res.getStatusCode());
}
@isTest static void testGetObjectFieldMapping(){
List<HIC_ShopifySync__HIC_Configuration__c> testConfiguration = TestDataFactory.createConfiguration(1);
if(!testConfiguration.isEmpty() && testConfiguration!=null){
insert testConfiguration;
}
testConfiguration[0].HIC_ShopifySync__Store__c = '123';
testConfiguration[0].HIC_ShopifySync__Account_Contact__c = true;
testConfiguration[0].HIC_ShopifySync__Product_Sync__c = true;
testConfiguration[0].HIC_ShopifySync__Order__c = true;
testConfiguration[0].HIC_ShopifySync__Enable_Draft_Order__c = true;
testConfiguration[0].HIC_ShopifySync__Opportunity__c = true;
testConfiguration[0].HIC_ShopifySync__Opportunity_Line_Item__c = true;
testConfiguration[0].HIC_ShopifySync__Enable_Opportunity_for_SDO__c = true;
update testConfiguration;
Test.startTest();
ShopifyController.getObjectFieldMapping('123','Account');
ShopifyController.getObjectFieldMapping('123','Contact');
ShopifyController.getObjectFieldMapping('123','Product2');
ShopifyController.getObjectFieldMapping('123','HIC_ShopifySync__Variant__c');
ShopifyController.getObjectFieldMapping('123','Order');
ShopifyController.getObjectFieldMapping('123','OrderItem');
ShopifyController.getObjectFieldMapping('123','DraftOrder');
ShopifyController.getObjectFieldMapping('123','DraftOrderItem');
ShopifyController.getObjectFieldMapping('123','Opportunity');
ShopifyController.getObjectFieldMapping('123','OpportunityLineItem');
Test.stopTest();
}
// ------- preAuthSetupCheck (tokenless RSS + certificate verification) -------
@isTest
static void preAuthSetupCheck_returnsAllKeys() {
try {
Test.startTest();
Map<String, Boolean> result = ShopifyController.preAuthSetupCheck();
Test.stopTest();
System.assert(result != null, 'Should return a non-null map');
System.assert(result.containsKey('domainRemoteSite'), 'domainRemoteSite key expected');
System.assert(result.containsKey('authRemoteSite'), 'authRemoteSite key expected');
System.assert(result.containsKey('certificate'), 'certificate key expected');
} catch (Exception e) {
System.debug('preAuthSetupCheck_returnsAllKeys: ' + e.getMessage());
}
System.assert(true);
}
// ------- getOpportunityStages (SOQL on OpportunityStage) -------
@isTest
static void getOpportunityStages_returnsActiveStagesSorted() {
Test.startTest();
List<Map<String, String>> options = ShopifyController.getOpportunityStages();
Test.stopTest();
System.assert(options != null, 'Should return a non-null list');
System.assert(!options.isEmpty(), 'Org should always have at least one active stage');
for (Map<String, String> opt : options) {
System.assert(opt.containsKey('label') && opt.containsKey('value'),
'Each option must carry label and value');
System.assert(String.isNotBlank(opt.get('value')), 'value (ApiName) populated');
}
}
// ------- isPackageInstalled / isPackageValid -------
@isTest
static void isPackageInstalled_unknownNamespace_returnsFalse() {
Test.startTest();
Boolean installed = ShopifyController.isPackageInstalled('NotARealNamespace_X');
Test.stopTest();
System.assertEquals(false, installed, 'Unknown namespace should not be installed');
}
@isTest
static void isPackageValid_coversSandboxBypassAndLicenseQuery() {
Test.startTest();
Boolean valid = ShopifyController.isPackageValid('NotARealNamespace_X');
Test.stopTest();
// In a sandbox the bypass returns true; in production/scratch the missing
// PackageLicense query throws → caught → false. Both are valid outcomes —
// assert the method completed and returned a Boolean either way.
Organization orgRecord = [SELECT IsSandbox FROM Organization LIMIT 1];
if (orgRecord.IsSandbox) {
System.assertEquals(true, valid, 'Sandbox must bypass expiry validation');
} else {
System.assertEquals(false, valid, 'Unknown namespace cannot be valid in production');
}
}
}