From 15093c9efc3c255741df012200ebafdc3bfd0303 Mon Sep 17 00:00:00 2001 From: Emiliano Sanchez Date: Thu, 25 Mar 2021 19:56:56 -0300 Subject: [PATCH 1/4] feedback --- src/evaluator/matchers/segment.ts | 4 ++-- src/logger/constants.ts | 8 +++----- src/logger/messages/debug.ts | 7 +++---- src/logger/messages/error.ts | 8 ++++---- src/logger/messages/info.ts | 5 +++-- src/logger/messages/warn.ts | 6 ++---- src/sdkFactory/index.ts | 7 +++---- src/sdkFactory/types.ts | 2 +- src/trackers/eventTracker.ts | 2 +- src/trackers/impressionsTracker.ts | 4 ++-- 10 files changed, 24 insertions(+), 29 deletions(-) diff --git a/src/evaluator/matchers/segment.ts b/src/evaluator/matchers/segment.ts index 7b6f6d4f..3e9db7d5 100644 --- a/src/evaluator/matchers/segment.ts +++ b/src/evaluator/matchers/segment.ts @@ -2,7 +2,7 @@ import { MaybeThenable } from '../../dtos/types'; import { ISegmentsCacheBase } from '../../storages/types'; import { ILogger } from '../../logger/types'; import thenable from '../../utils/promise/thenable'; -import { ENGINE_MATCHER_SEGMENT_ASYNC, ENGINE_MATCHER_SEGMENT } from '../../logger/constants'; +import { ENGINE_MATCHER_SEGMENT } from '../../logger/constants'; export default function matcherSegmentContext(log: ILogger, segmentName: string, storage: { segments: ISegmentsCacheBase }) { @@ -11,7 +11,7 @@ export default function matcherSegmentContext(log: ILogger, segmentName: string, if (thenable(isInSegment)) { isInSegment.then(result => { - log.debug(ENGINE_MATCHER_SEGMENT_ASYNC, [segmentName, key, isInSegment]); + log.debug(ENGINE_MATCHER_SEGMENT, [segmentName, key, isInSegment]); return result; }); diff --git a/src/logger/constants.ts b/src/logger/constants.ts index 8b0c9397..75e18f7e 100644 --- a/src/logger/constants.ts +++ b/src/logger/constants.ts @@ -23,7 +23,6 @@ export const ENGINE_MATCHER_ENDS_WITH = 14; export const ENGINE_MATCHER_GREATER = 15; export const ENGINE_MATCHER_LESS = 16; export const ENGINE_MATCHER_PART_OF = 17; -export const ENGINE_MATCHER_SEGMENT_ASYNC = 18; export const ENGINE_MATCHER_SEGMENT = 19; export const ENGINE_MATCHER_STRING = 20; export const ENGINE_MATCHER_STRING_INVALID = 21; @@ -35,6 +34,7 @@ export const CLEANUP_REGISTERING = 26; export const CLEANUP_DEREGISTERING = 27; export const RETRIEVE_CLIENT_DEFAULT = 32; export const RETRIEVE_CLIENT_EXISTING = 33; +export const RETRIEVE_MANAGER = 34; export const SYNC_OFFLINE_DATA = 36; export const SYNC_SPLITS_FETCH = 42; export const SYNC_SPLITS_NEW = 43; @@ -44,7 +44,6 @@ export const STREAMING_NEW_MESSAGE = 46; export const SYNC_TASK_START = 47; export const SYNC_TASK_EXECUTE = 48; export const SYNC_TASK_STOP = 49; -export const IMPRESSIONS_TRACKER_SUCCESS = 50; export const SETTINGS_SPLITS_FILTER = 51; export const CLIENT_READY_FROM_CACHE = 100; @@ -53,7 +52,6 @@ export const IMPRESSION = 102; export const IMPRESSION_QUEUEING = 103; export const NEW_SHARED_CLIENT = 104; export const NEW_FACTORY = 105; -export const RETRIEVE_MANAGER = 106; export const POLLING_SMART_PAUSING = 107; export const POLLING_START = 108; export const POLLING_STOP = 109; @@ -69,6 +67,7 @@ export const SYNC_START_POLLING = 118; export const SYNC_CONTINUE_POLLING = 119; export const SYNC_STOP_POLLING = 120; export const EVENTS_TRACKER_SUCCESS = 121; +export const IMPRESSIONS_TRACKER_SUCCESS = 122; export const ENGINE_VALUE_INVALID = 200; export const ENGINE_VALUE_NO_ATTRIBUTES = 201; @@ -94,18 +93,17 @@ export const WARN_SPLITS_FILTER_INVALID = 223; export const WARN_SPLITS_FILTER_EMPTY = 224; export const WARN_STORAGE_INVALID = 225; export const WARN_API_KEY = 226; -export const ERROR_EVENTS_TRACKER = 211; export const ERROR_ENGINE_COMBINER_IFELSEIF = 300; export const ERROR_LOGLEVEL_INVALID = 302; export const ERROR_CLIENT_LISTENER = 303; -export const ERROR_MANAGER_NOT_AVAILABLE = 304; export const ERROR_CLIENT_CANNOT_GET_READY = 305; export const ERROR_SYNC_OFFLINE_LOADING = 307; export const ERROR_STREAMING_SSE = 309; export const ERROR_STREAMING_AUTH = 310; export const ERROR_IMPRESSIONS_TRACKER = 311; export const ERROR_IMPRESSIONS_LISTENER = 312; +export const ERROR_EVENTS_TRACKER = 313; export const ERROR_EVENT_TYPE_FORMAT = 314; export const ERROR_NOT_PLAIN_OBJECT = 318; export const ERROR_SIZE_EXCEEDED = 319; diff --git a/src/logger/messages/debug.ts b/src/logger/messages/debug.ts index af0098c8..9b4468ae 100644 --- a/src/logger/messages/debug.ts +++ b/src/logger/messages/debug.ts @@ -1,4 +1,4 @@ -import { ENGINE_COMBINER_AND, ENGINE_COMBINER_IFELSEIF, ENGINE_COMBINER_IFELSEIF_NO_TREATMENT, ENGINE_BUCKET, ENGINE_MATCHER_ALL, ENGINE_MATCHER_BETWEEN, ENGINE_MATCHER_BOOLEAN, ENGINE_MATCHER_CONTAINS_ALL, ENGINE_MATCHER_CONTAINS_ANY, ENGINE_MATCHER_CONTAINS_STRING, ENGINE_MATCHER_DEPENDENCY, ENGINE_MATCHER_DEPENDENCY_PRE, ENGINE_MATCHER_EQUAL, ENGINE_MATCHER_EQUAL_TO_SET, ENGINE_MATCHER_ENDS_WITH, ENGINE_MATCHER_GREATER, ENGINE_MATCHER_LESS, ENGINE_MATCHER_PART_OF, ENGINE_MATCHER_SEGMENT_ASYNC, ENGINE_MATCHER_SEGMENT, ENGINE_MATCHER_STRING, ENGINE_MATCHER_STRING_INVALID, ENGINE_MATCHER_STARTS_WITH, ENGINE_MATCHER_WHITELIST, ENGINE_VALUE, ENGINE_SANITIZE, RETRIEVE_CLIENT_DEFAULT, RETRIEVE_CLIENT_EXISTING, SYNC_OFFLINE_DATA, SYNC_SPLITS_FETCH, SYNC_SPLITS_NEW, SYNC_SPLITS_REMOVED, SYNC_SPLITS_SEGMENTS, STREAMING_NEW_MESSAGE, SYNC_TASK_START, SYNC_TASK_EXECUTE, SYNC_TASK_STOP, IMPRESSIONS_TRACKER_SUCCESS, SETTINGS_SPLITS_FILTER, logPrefixSettings, logPrefixEngine, logPrefixEngineCombiner, logPrefixEngineMatcher, logPrefixEngineValue, logPrefixSyncOffline, logPrefixImpressionsTracker, logPrefixSync, logPrefixSyncSplits, logPrefixSyncStreaming, logPrefixCleanup, CLEANUP_REGISTERING, CLEANUP_DEREGISTERING } from '../constants'; +import { ENGINE_COMBINER_AND, ENGINE_COMBINER_IFELSEIF, ENGINE_COMBINER_IFELSEIF_NO_TREATMENT, ENGINE_BUCKET, ENGINE_MATCHER_ALL, ENGINE_MATCHER_BETWEEN, ENGINE_MATCHER_BOOLEAN, ENGINE_MATCHER_CONTAINS_ALL, ENGINE_MATCHER_CONTAINS_ANY, ENGINE_MATCHER_CONTAINS_STRING, ENGINE_MATCHER_DEPENDENCY, ENGINE_MATCHER_DEPENDENCY_PRE, ENGINE_MATCHER_EQUAL, ENGINE_MATCHER_EQUAL_TO_SET, ENGINE_MATCHER_ENDS_WITH, ENGINE_MATCHER_GREATER, ENGINE_MATCHER_LESS, ENGINE_MATCHER_PART_OF, ENGINE_MATCHER_SEGMENT, ENGINE_MATCHER_STRING, ENGINE_MATCHER_STRING_INVALID, ENGINE_MATCHER_STARTS_WITH, ENGINE_MATCHER_WHITELIST, ENGINE_VALUE, ENGINE_SANITIZE, RETRIEVE_CLIENT_DEFAULT, RETRIEVE_CLIENT_EXISTING, RETRIEVE_MANAGER, SYNC_OFFLINE_DATA, SYNC_SPLITS_FETCH, SYNC_SPLITS_NEW, SYNC_SPLITS_REMOVED, SYNC_SPLITS_SEGMENTS, STREAMING_NEW_MESSAGE, SYNC_TASK_START, SYNC_TASK_EXECUTE, SYNC_TASK_STOP, SETTINGS_SPLITS_FILTER, logPrefixSettings, logPrefixEngine, logPrefixEngineCombiner, logPrefixEngineMatcher, logPrefixEngineValue, logPrefixSyncOffline, logPrefixSync, logPrefixSyncSplits, logPrefixSyncStreaming, logPrefixCleanup, CLEANUP_REGISTERING, CLEANUP_DEREGISTERING } from '../constants'; import { codesInfo } from './info'; export const codesDebug: [number, string][] = codesInfo.concat([ @@ -13,7 +13,7 @@ export const codesDebug: [number, string][] = codesInfo.concat([ [ENGINE_MATCHER_CONTAINS_ALL, logPrefixEngineMatcher + '[containsAllMatcher] %s contains all elements of %s? %s'], [ENGINE_MATCHER_CONTAINS_ANY, logPrefixEngineMatcher + '[containsAnyMatcher] %s contains at least an element of %s? %s'], [ENGINE_MATCHER_CONTAINS_STRING, logPrefixEngineMatcher + '[containsStringMatcher] %s contains %s? %s'], - [ENGINE_MATCHER_DEPENDENCY, logPrefixEngineMatcher + '[dependencyMatcher] Parent split "%s" evaluated to "%s" with label "%s". %s evaluated treatment is part of [%s] ? %s.'], + [ENGINE_MATCHER_DEPENDENCY, logPrefixEngineMatcher + '[dependencyMatcher] parent split "%s" evaluated to "%s" with label "%s". %s evaluated treatment is part of [%s] ? %s.'], [ENGINE_MATCHER_DEPENDENCY_PRE, logPrefixEngineMatcher + '[dependencyMatcher] will evaluate parent split: "%s" with key: %s %s'], [ENGINE_MATCHER_EQUAL, logPrefixEngineMatcher + '[equalToMatcher] is %s equal to %s? %s'], [ENGINE_MATCHER_EQUAL_TO_SET, logPrefixEngineMatcher + '[equalToSetMatcher] is %s equal to set %s? %s'], @@ -21,7 +21,6 @@ export const codesDebug: [number, string][] = codesInfo.concat([ [ENGINE_MATCHER_GREATER, logPrefixEngineMatcher + '[greaterThanEqualMatcher] is %s greater than %s? %s'], [ENGINE_MATCHER_LESS, logPrefixEngineMatcher + '[lessThanEqualMatcher] is %s less than %s? %s'], [ENGINE_MATCHER_PART_OF, logPrefixEngineMatcher + '[partOfMatcher] %s is part of %s? %s'], - [ENGINE_MATCHER_SEGMENT_ASYNC, logPrefixEngineMatcher + '[asyncSegmentMatcher] evaluated %s / %s => %s'], [ENGINE_MATCHER_SEGMENT, logPrefixEngineMatcher + '[segmentMatcher] evaluated %s / %s => %s'], [ENGINE_MATCHER_STRING, logPrefixEngineMatcher + '[stringMatcher] does %s matches with %s? %s'], [ENGINE_MATCHER_STRING_INVALID, logPrefixEngineMatcher + '[stringMatcher] %s is an invalid regex'], @@ -34,6 +33,7 @@ export const codesDebug: [number, string][] = codesInfo.concat([ [CLEANUP_DEREGISTERING, logPrefixCleanup + 'Deregistering cleanup handler %s'], [RETRIEVE_CLIENT_DEFAULT, ' Retrieving default SDK client.'], [RETRIEVE_CLIENT_EXISTING, ' Retrieving existing SDK client.'], + [RETRIEVE_MANAGER, ' Retrieving manager instance.'], // synchronizer [SYNC_OFFLINE_DATA, logPrefixSyncOffline + 'Splits data: \n%s'], [SYNC_SPLITS_FETCH, logPrefixSyncSplits + 'Spin up split update using since = %s'], @@ -44,7 +44,6 @@ export const codesDebug: [number, string][] = codesInfo.concat([ [SYNC_TASK_START, logPrefixSync + ': Starting %s. Running each %s millis'], [SYNC_TASK_EXECUTE, logPrefixSync + ': Running %s'], [SYNC_TASK_STOP, logPrefixSync + ': Stopping %s'], - [IMPRESSIONS_TRACKER_SUCCESS, logPrefixImpressionsTracker + 'Successfully stored %s impression%s.'], // initialization / settings validation [SETTINGS_SPLITS_FILTER, logPrefixSettings + ': splits filtering criteria is "%s".'] ]); diff --git a/src/logger/messages/error.ts b/src/logger/messages/error.ts index 54e0c188..2e4eb9c7 100644 --- a/src/logger/messages/error.ts +++ b/src/logger/messages/error.ts @@ -1,18 +1,18 @@ -import { ERROR_ENGINE_COMBINER_IFELSEIF, ERROR_LOGLEVEL_INVALID, ERROR_CLIENT_LISTENER, ERROR_MANAGER_NOT_AVAILABLE, ERROR_CLIENT_CANNOT_GET_READY, ERROR_SYNC_OFFLINE_LOADING, ERROR_STREAMING_SSE, ERROR_STREAMING_AUTH, ERROR_IMPRESSIONS_TRACKER, ERROR_IMPRESSIONS_LISTENER, ERROR_EVENT_TYPE_FORMAT, ERROR_NOT_PLAIN_OBJECT, ERROR_SIZE_EXCEEDED, ERROR_NOT_FINITE, ERROR_CLIENT_DESTROYED, ERROR_NULL, ERROR_TOO_LONG, ERROR_INVALID_KEY_OBJECT, ERROR_INVALID, ERROR_EMPTY, ERROR_EMPTY_ARRAY, ERROR_INVALID_IMPRESSIONS_MODE, ERROR_HTTP, logPrefixSettings, logPrefixEngineCombiner, logPrefixSyncOffline, logPrefixSyncStreaming, logPrefixImpressionsTracker } from '../constants'; +import { ERROR_ENGINE_COMBINER_IFELSEIF, ERROR_LOGLEVEL_INVALID, ERROR_CLIENT_LISTENER, ERROR_CLIENT_CANNOT_GET_READY, ERROR_SYNC_OFFLINE_LOADING, ERROR_STREAMING_SSE, ERROR_STREAMING_AUTH, ERROR_IMPRESSIONS_TRACKER, ERROR_IMPRESSIONS_LISTENER, ERROR_EVENT_TYPE_FORMAT, ERROR_NOT_PLAIN_OBJECT, ERROR_SIZE_EXCEEDED, ERROR_NOT_FINITE, ERROR_CLIENT_DESTROYED, ERROR_NULL, ERROR_TOO_LONG, ERROR_INVALID_KEY_OBJECT, ERROR_INVALID, ERROR_EMPTY, ERROR_EMPTY_ARRAY, ERROR_INVALID_IMPRESSIONS_MODE, ERROR_HTTP, logPrefixSettings, logPrefixEngineCombiner, logPrefixSyncOffline, logPrefixSyncStreaming, logPrefixImpressionsTracker, ERROR_EVENTS_TRACKER, logPrefixEventsTracker } from '../constants'; export const codesError: [number, string][] = [ // evaluator [ERROR_ENGINE_COMBINER_IFELSEIF, logPrefixEngineCombiner + 'Invalid Split, no valid rules found'], // SDK [ERROR_LOGLEVEL_INVALID, 'logger: Invalid Log Level - No changes to the logs will be applied.'], - [ERROR_MANAGER_NOT_AVAILABLE, ' Manager instance is not available.'], // @TODO remove if the manager is not pluggable [ERROR_CLIENT_CANNOT_GET_READY, ' The SDK will not get ready. Reason: %s'], + [ERROR_IMPRESSIONS_TRACKER, logPrefixImpressionsTracker + 'Could not store impressions bulk with %s impression(s). Error: %s'], + [ERROR_IMPRESSIONS_LISTENER, logPrefixImpressionsTracker + 'Impression listener logImpression method threw: %s.'], + [ERROR_EVENTS_TRACKER, logPrefixEventsTracker + 'Failed to queue %s'], // synchronizer [ERROR_SYNC_OFFLINE_LOADING, logPrefixSyncOffline + 'There was an issue loading the mock Splits data, no changes will be applied to the current cache. %s'], [ERROR_STREAMING_SSE, logPrefixSyncStreaming + 'Fail to connect to streaming, with error message: %s'], [ERROR_STREAMING_AUTH, logPrefixSyncStreaming + 'Failed to authenticate for streaming. Error: "%s".'], - [ERROR_IMPRESSIONS_TRACKER, logPrefixImpressionsTracker + 'Could not store impressions bulk with %s impression%s. Error: %s'], - [ERROR_IMPRESSIONS_LISTENER, logPrefixImpressionsTracker + 'Impression listener logImpression method threw: %s.'], [ERROR_HTTP, ' Response status is not OK. Status: %s. URL: %s. Message: %s'], // client status [ERROR_CLIENT_LISTENER, 'A listener was added for %s on the SDK, which has already fired and won\'t be emitted again. The callback won\'t be executed.'], diff --git a/src/logger/messages/info.ts b/src/logger/messages/info.ts index 9a9c237e..6c00a5ff 100644 --- a/src/logger/messages/info.ts +++ b/src/logger/messages/info.ts @@ -1,4 +1,4 @@ -import { CLIENT_READY_FROM_CACHE, CLIENT_READY, IMPRESSION, IMPRESSION_QUEUEING, NEW_SHARED_CLIENT, NEW_FACTORY, RETRIEVE_MANAGER, POLLING_SMART_PAUSING, POLLING_START, POLLING_STOP, SYNC_SPLITS_FETCH_RETRY, STREAMING_REFRESH_TOKEN, STREAMING_RECONNECT, STREAMING_CONNECTING, STREAMING_DISABLED, STREAMING_DISCONNECTING, SUBMITTERS_PUSH_FULL_EVENTS_QUEUE, SUBMITTERS_PUSH, SYNC_START_POLLING, SYNC_CONTINUE_POLLING, SYNC_STOP_POLLING, EVENTS_TRACKER_SUCCESS, logPrefixEventsTracker, logPrefixSyncManager, logPrefixSyncPolling, logPrefixSyncSplits, logPrefixSyncStreaming, logPrefixSyncSubmitters, logPrefixImpressionsTracker } from '../constants'; +import { CLIENT_READY_FROM_CACHE, CLIENT_READY, IMPRESSION, IMPRESSION_QUEUEING, NEW_SHARED_CLIENT, NEW_FACTORY, POLLING_SMART_PAUSING, POLLING_START, POLLING_STOP, SYNC_SPLITS_FETCH_RETRY, STREAMING_REFRESH_TOKEN, STREAMING_RECONNECT, STREAMING_CONNECTING, STREAMING_DISABLED, STREAMING_DISCONNECTING, SUBMITTERS_PUSH_FULL_EVENTS_QUEUE, SUBMITTERS_PUSH, SYNC_START_POLLING, SYNC_CONTINUE_POLLING, SYNC_STOP_POLLING, EVENTS_TRACKER_SUCCESS, logPrefixEventsTracker, logPrefixSyncManager, logPrefixSyncPolling, logPrefixSyncSplits, logPrefixSyncStreaming, logPrefixSyncSubmitters, logPrefixImpressionsTracker, IMPRESSIONS_TRACKER_SUCCESS } from '../constants'; import { codesWarn } from './warn'; const READY_MSG = 'Split SDK is ready'; @@ -12,8 +12,9 @@ export const codesInfo: [number, string][] = codesWarn.concat([ [IMPRESSION_QUEUEING, logPrefixImpressionsTracker +'Queueing corresponding impression.'], [NEW_SHARED_CLIENT, ' New shared client instance created.'], [NEW_FACTORY, ' New Split SDK instance created.'], - [RETRIEVE_MANAGER, ' Manager instance retrieved.'], [EVENTS_TRACKER_SUCCESS, logPrefixEventsTracker + 'Successfully qeued %s'], + [IMPRESSIONS_TRACKER_SUCCESS, logPrefixImpressionsTracker + 'Successfully stored %s impression(s).'], + // synchronizer [POLLING_SMART_PAUSING, logPrefixSyncPolling + 'Turning segments data polling %s.'], [POLLING_START, logPrefixSyncPolling + 'Starting polling'], diff --git a/src/logger/messages/warn.ts b/src/logger/messages/warn.ts index 96d36127..b246e0fb 100644 --- a/src/logger/messages/warn.ts +++ b/src/logger/messages/warn.ts @@ -1,4 +1,4 @@ -import { ENGINE_VALUE_INVALID, ENGINE_VALUE_NO_ATTRIBUTES, CLIENT_NO_LISTENER, SYNC_MYSEGMENTS_FETCH_RETRY, SYNC_SPLITS_FETCH_FAILS, STREAMING_PARSING_ERROR_FAILS, STREAMING_PARSING_MESSAGE_FAILS, STREAMING_FALLBACK, SUBMITTERS_PUSH_FAILS, SUBMITTERS_PUSH_RETRY, ERROR_EVENTS_TRACKER, WARN_SETTING_NULL, WARN_TRIMMING_PROPERTIES, CLIENT_NOT_READY, WARN_CONVERTING, WARN_TRIMMING, WARN_NOT_EXISTENT_SPLIT, WARN_LOWERCASE_TRAFFIC_TYPE, WARN_NOT_EXISTENT_TT, WARN_INTEGRATION_INVALID, WARN_SPLITS_FILTER_IGNORED, WARN_SPLITS_FILTER_INVALID, WARN_SPLITS_FILTER_EMPTY, WARN_STORAGE_INVALID, WARN_API_KEY, logPrefixSettings, logPrefixEngineValue, logPrefixEventsTracker, logPrefixSyncMysegments, logPrefixSyncSplits, logPrefixSyncStreaming, logPrefixSyncSubmitters } from '../constants'; +import { ENGINE_VALUE_INVALID, ENGINE_VALUE_NO_ATTRIBUTES, CLIENT_NO_LISTENER, SYNC_MYSEGMENTS_FETCH_RETRY, SYNC_SPLITS_FETCH_FAILS, STREAMING_PARSING_ERROR_FAILS, STREAMING_PARSING_MESSAGE_FAILS, STREAMING_FALLBACK, SUBMITTERS_PUSH_FAILS, SUBMITTERS_PUSH_RETRY, WARN_SETTING_NULL, WARN_TRIMMING_PROPERTIES, CLIENT_NOT_READY, WARN_CONVERTING, WARN_TRIMMING, WARN_NOT_EXISTENT_SPLIT, WARN_LOWERCASE_TRAFFIC_TYPE, WARN_NOT_EXISTENT_TT, WARN_INTEGRATION_INVALID, WARN_SPLITS_FILTER_IGNORED, WARN_SPLITS_FILTER_INVALID, WARN_SPLITS_FILTER_EMPTY, WARN_STORAGE_INVALID, WARN_API_KEY, logPrefixSettings, logPrefixEngineValue, logPrefixSyncMysegments, logPrefixSyncSplits, logPrefixSyncStreaming, logPrefixSyncSubmitters } from '../constants'; import { codesError } from './error'; export const codesWarn: [number, string][] = codesError.concat([ @@ -9,12 +9,10 @@ export const codesWarn: [number, string][] = codesError.concat([ [SYNC_MYSEGMENTS_FETCH_RETRY, logPrefixSyncMysegments + 'Retrying download of segments #%s. Reason: %s'], [SYNC_SPLITS_FETCH_FAILS, logPrefixSyncSplits + 'Error while doing fetch of Splits. %s'], [STREAMING_PARSING_ERROR_FAILS, logPrefixSyncStreaming + 'Error parsing SSE error notification: %s'], - [STREAMING_PARSING_MESSAGE_FAILS, logPrefixSyncStreaming + 'Error parsing new SSE message notification: %s'], + [STREAMING_PARSING_MESSAGE_FAILS, logPrefixSyncStreaming + 'Error parsing SSE message notification: %s'], [STREAMING_FALLBACK, logPrefixSyncStreaming + 'Falling back to polling mode. Reason: %s'], [SUBMITTERS_PUSH_FAILS, logPrefixSyncSubmitters + 'Droping %s %s after retry. Reason: %s.'], [SUBMITTERS_PUSH_RETRY, logPrefixSyncSubmitters + 'Failed to push %s %s, keeping data to retry on next iteration. Reason: %s.'], - // SDK - [ERROR_EVENTS_TRACKER, logPrefixEventsTracker + 'Failed to queue %s'], // client status [CLIENT_NOT_READY, '%s: the SDK is not ready, results may be incorrect. Make sure to wait for SDK readiness before using this method.'], [CLIENT_NO_LISTENER, 'No listeners for SDK Readiness detected. Incorrect control treatments could have been logged if you called getTreatment/s while the SDK was not yet ready.'], diff --git a/src/sdkFactory/index.ts b/src/sdkFactory/index.ts index 0b08ad5a..2fd3e67c 100644 --- a/src/sdkFactory/index.ts +++ b/src/sdkFactory/index.ts @@ -10,7 +10,7 @@ import { getMatching } from '../utils/key'; import { shouldBeOptimized } from '../trackers/impressionObserver/utils'; import { validateAndTrackApiKey } from '../utils/inputValidation/apiKey'; import { createLoggerAPI } from '../logger/sdkLogger'; -import { NEW_FACTORY, RETRIEVE_MANAGER, ERROR_MANAGER_NOT_AVAILABLE } from '../logger/constants'; +import { NEW_FACTORY, RETRIEVE_MANAGER } from '../logger/constants'; /** * Modular SDK factory @@ -73,7 +73,7 @@ export function sdkFactory(params: ISdkFactoryParams): SplitIO.ICsSDK | SplitIO. // Sdk client and manager const clientMethod = sdkClientMethodFactory({ eventTracker, impressionsTracker, sdkReadinessManager, settings, storage, syncManager, signalListener }); - const managerInstance = sdkManagerFactory && sdkManagerFactory(log, storage.splits, sdkReadinessManager); + const managerInstance = sdkManagerFactory(log, storage.splits, sdkReadinessManager); syncManager && syncManager.start(); signalListener && signalListener.start(); @@ -87,8 +87,7 @@ export function sdkFactory(params: ISdkFactoryParams): SplitIO.ICsSDK | SplitIO. // Manager API to explore available information // @ts-ignore manager() { - if (managerInstance) log.info(RETRIEVE_MANAGER); - else log.error(ERROR_MANAGER_NOT_AVAILABLE); + log.debug(RETRIEVE_MANAGER); return managerInstance; }, diff --git a/src/sdkFactory/types.ts b/src/sdkFactory/types.ts index 95355d82..dcd6c0d2 100644 --- a/src/sdkFactory/types.ts +++ b/src/sdkFactory/types.ts @@ -46,7 +46,7 @@ export interface ISdkFactoryParams { syncManagerFactory?: (params: ISyncManagerFactoryParams) => ISyncManager, // Sdk manager factory - sdkManagerFactory?: ( + sdkManagerFactory: ( log: ILogger, splits: ISplitsCacheSync | ISplitsCacheAsync, sdkReadinessManager: ISdkReadinessManager diff --git a/src/trackers/eventTracker.ts b/src/trackers/eventTracker.ts index 343e737f..b18c0546 100644 --- a/src/trackers/eventTracker.ts +++ b/src/trackers/eventTracker.ts @@ -36,7 +36,7 @@ export default function eventTrackerFactory( }, 0); } } else { - log.warn(ERROR_EVENTS_TRACKER, [msg]); + log.error(ERROR_EVENTS_TRACKER, [msg]); } return tracked; diff --git a/src/trackers/impressionsTracker.ts b/src/trackers/impressionsTracker.ts index 00e7c25f..5d227892 100644 --- a/src/trackers/impressionsTracker.ts +++ b/src/trackers/impressionsTracker.ts @@ -63,9 +63,9 @@ export default function impressionsTrackerFactory( // If we're on an async storage, handle error and log it. if (thenable(res)) { res.then(() => { - log.debug(IMPRESSIONS_TRACKER_SUCCESS, [impressionsCount, impressionsCount === 1 ? '' : 's']); + log.info(IMPRESSIONS_TRACKER_SUCCESS, [impressionsCount]); }).catch(err => { - log.error(ERROR_IMPRESSIONS_TRACKER, [impressionsCount, impressionsCount === 1 ? '' : 's', err]); + log.error(ERROR_IMPRESSIONS_TRACKER, [impressionsCount, err]); }); } From 3426f1dd561d17f9012632f57c669e42e690006c Mon Sep 17 00:00:00 2001 From: Emiliano Sanchez Date: Fri, 26 Mar 2021 12:44:31 -0300 Subject: [PATCH 2/4] cleanup imports --- src/logger/messages/debug.ts | 82 ++++++++++++++++++------------------ src/logger/messages/error.ts | 48 ++++++++++----------- src/logger/messages/info.ts | 46 ++++++++++---------- src/logger/messages/warn.ts | 50 +++++++++++----------- 4 files changed, 113 insertions(+), 113 deletions(-) diff --git a/src/logger/messages/debug.ts b/src/logger/messages/debug.ts index 9b4468ae..4f1444bc 100644 --- a/src/logger/messages/debug.ts +++ b/src/logger/messages/debug.ts @@ -1,49 +1,49 @@ -import { ENGINE_COMBINER_AND, ENGINE_COMBINER_IFELSEIF, ENGINE_COMBINER_IFELSEIF_NO_TREATMENT, ENGINE_BUCKET, ENGINE_MATCHER_ALL, ENGINE_MATCHER_BETWEEN, ENGINE_MATCHER_BOOLEAN, ENGINE_MATCHER_CONTAINS_ALL, ENGINE_MATCHER_CONTAINS_ANY, ENGINE_MATCHER_CONTAINS_STRING, ENGINE_MATCHER_DEPENDENCY, ENGINE_MATCHER_DEPENDENCY_PRE, ENGINE_MATCHER_EQUAL, ENGINE_MATCHER_EQUAL_TO_SET, ENGINE_MATCHER_ENDS_WITH, ENGINE_MATCHER_GREATER, ENGINE_MATCHER_LESS, ENGINE_MATCHER_PART_OF, ENGINE_MATCHER_SEGMENT, ENGINE_MATCHER_STRING, ENGINE_MATCHER_STRING_INVALID, ENGINE_MATCHER_STARTS_WITH, ENGINE_MATCHER_WHITELIST, ENGINE_VALUE, ENGINE_SANITIZE, RETRIEVE_CLIENT_DEFAULT, RETRIEVE_CLIENT_EXISTING, RETRIEVE_MANAGER, SYNC_OFFLINE_DATA, SYNC_SPLITS_FETCH, SYNC_SPLITS_NEW, SYNC_SPLITS_REMOVED, SYNC_SPLITS_SEGMENTS, STREAMING_NEW_MESSAGE, SYNC_TASK_START, SYNC_TASK_EXECUTE, SYNC_TASK_STOP, SETTINGS_SPLITS_FILTER, logPrefixSettings, logPrefixEngine, logPrefixEngineCombiner, logPrefixEngineMatcher, logPrefixEngineValue, logPrefixSyncOffline, logPrefixSync, logPrefixSyncSplits, logPrefixSyncStreaming, logPrefixCleanup, CLEANUP_REGISTERING, CLEANUP_DEREGISTERING } from '../constants'; +import * as c from '../constants'; import { codesInfo } from './info'; export const codesDebug: [number, string][] = codesInfo.concat([ // evaluator - [ENGINE_COMBINER_AND, logPrefixEngineCombiner + '[andCombiner] evaluates to %s'], - [ENGINE_COMBINER_IFELSEIF, logPrefixEngineCombiner + 'Treatment found: %s'], - [ENGINE_COMBINER_IFELSEIF_NO_TREATMENT, logPrefixEngineCombiner + 'All predicates evaluated, no treatment found.'], - [ENGINE_BUCKET, logPrefixEngine + ': using algo "murmur" bucket %s for key %s using seed %s - treatment %s'], - [ENGINE_MATCHER_ALL, logPrefixEngineMatcher + '[allMatcher] is always true'], - [ENGINE_MATCHER_BETWEEN, logPrefixEngineMatcher + '[betweenMatcher] is %s between %s and %s? %s'], - [ENGINE_MATCHER_BOOLEAN, logPrefixEngineMatcher + '[booleanMatcher] %s === %s'], - [ENGINE_MATCHER_CONTAINS_ALL, logPrefixEngineMatcher + '[containsAllMatcher] %s contains all elements of %s? %s'], - [ENGINE_MATCHER_CONTAINS_ANY, logPrefixEngineMatcher + '[containsAnyMatcher] %s contains at least an element of %s? %s'], - [ENGINE_MATCHER_CONTAINS_STRING, logPrefixEngineMatcher + '[containsStringMatcher] %s contains %s? %s'], - [ENGINE_MATCHER_DEPENDENCY, logPrefixEngineMatcher + '[dependencyMatcher] parent split "%s" evaluated to "%s" with label "%s". %s evaluated treatment is part of [%s] ? %s.'], - [ENGINE_MATCHER_DEPENDENCY_PRE, logPrefixEngineMatcher + '[dependencyMatcher] will evaluate parent split: "%s" with key: %s %s'], - [ENGINE_MATCHER_EQUAL, logPrefixEngineMatcher + '[equalToMatcher] is %s equal to %s? %s'], - [ENGINE_MATCHER_EQUAL_TO_SET, logPrefixEngineMatcher + '[equalToSetMatcher] is %s equal to set %s? %s'], - [ENGINE_MATCHER_ENDS_WITH, logPrefixEngineMatcher + '[endsWithMatcher] %s ends with %s? %s'], - [ENGINE_MATCHER_GREATER, logPrefixEngineMatcher + '[greaterThanEqualMatcher] is %s greater than %s? %s'], - [ENGINE_MATCHER_LESS, logPrefixEngineMatcher + '[lessThanEqualMatcher] is %s less than %s? %s'], - [ENGINE_MATCHER_PART_OF, logPrefixEngineMatcher + '[partOfMatcher] %s is part of %s? %s'], - [ENGINE_MATCHER_SEGMENT, logPrefixEngineMatcher + '[segmentMatcher] evaluated %s / %s => %s'], - [ENGINE_MATCHER_STRING, logPrefixEngineMatcher + '[stringMatcher] does %s matches with %s? %s'], - [ENGINE_MATCHER_STRING_INVALID, logPrefixEngineMatcher + '[stringMatcher] %s is an invalid regex'], - [ENGINE_MATCHER_STARTS_WITH, logPrefixEngineMatcher + '[startsWithMatcher] %s starts with %s? %s'], - [ENGINE_MATCHER_WHITELIST, logPrefixEngineMatcher + '[whitelistMatcher] evaluated %s in [%s] => %s'], - [ENGINE_VALUE, logPrefixEngineValue + 'Extracted attribute [%s], [%s] will be used for matching.'], - [ENGINE_SANITIZE, logPrefixEngine + ':sanitize: Attempted to sanitize [%s] which should be of type [%s]. Sanitized and processed value => [%s]'], + [c.ENGINE_COMBINER_AND, c.logPrefixEngineCombiner + '[andCombiner] evaluates to %s'], + [c.ENGINE_COMBINER_IFELSEIF, c.logPrefixEngineCombiner + 'Treatment found: %s'], + [c.ENGINE_COMBINER_IFELSEIF_NO_TREATMENT, c.logPrefixEngineCombiner + 'All predicates evaluated, no treatment found.'], + [c.ENGINE_BUCKET, c.logPrefixEngine + ': using algo "murmur" bucket %s for key %s using seed %s - treatment %s'], + [c.ENGINE_MATCHER_ALL, c.logPrefixEngineMatcher + '[allMatcher] is always true'], + [c.ENGINE_MATCHER_BETWEEN, c.logPrefixEngineMatcher + '[betweenMatcher] is %s between %s and %s? %s'], + [c.ENGINE_MATCHER_BOOLEAN, c.logPrefixEngineMatcher + '[booleanMatcher] %s === %s'], + [c.ENGINE_MATCHER_CONTAINS_ALL, c.logPrefixEngineMatcher + '[containsAllMatcher] %s contains all elements of %s? %s'], + [c.ENGINE_MATCHER_CONTAINS_ANY, c.logPrefixEngineMatcher + '[containsAnyMatcher] %s contains at least an element of %s? %s'], + [c.ENGINE_MATCHER_CONTAINS_STRING, c.logPrefixEngineMatcher + '[containsStringMatcher] %s contains %s? %s'], + [c.ENGINE_MATCHER_DEPENDENCY, c.logPrefixEngineMatcher + '[dependencyMatcher] parent split "%s" evaluated to "%s" with label "%s". %s evaluated treatment is part of [%s] ? %s.'], + [c.ENGINE_MATCHER_DEPENDENCY_PRE, c.logPrefixEngineMatcher + '[dependencyMatcher] will evaluate parent split: "%s" with key: %s %s'], + [c.ENGINE_MATCHER_EQUAL, c.logPrefixEngineMatcher + '[equalToMatcher] is %s equal to %s? %s'], + [c.ENGINE_MATCHER_EQUAL_TO_SET, c.logPrefixEngineMatcher + '[equalToSetMatcher] is %s equal to set %s? %s'], + [c.ENGINE_MATCHER_ENDS_WITH, c.logPrefixEngineMatcher + '[endsWithMatcher] %s ends with %s? %s'], + [c.ENGINE_MATCHER_GREATER, c.logPrefixEngineMatcher + '[greaterThanEqualMatcher] is %s greater than %s? %s'], + [c.ENGINE_MATCHER_LESS, c.logPrefixEngineMatcher + '[lessThanEqualMatcher] is %s less than %s? %s'], + [c.ENGINE_MATCHER_PART_OF, c.logPrefixEngineMatcher + '[partOfMatcher] %s is part of %s? %s'], + [c.ENGINE_MATCHER_SEGMENT, c.logPrefixEngineMatcher + '[segmentMatcher] evaluated %s / %s => %s'], + [c.ENGINE_MATCHER_STRING, c.logPrefixEngineMatcher + '[stringMatcher] does %s matches with %s? %s'], + [c.ENGINE_MATCHER_STRING_INVALID, c.logPrefixEngineMatcher + '[stringMatcher] %s is an invalid regex'], + [c.ENGINE_MATCHER_STARTS_WITH, c.logPrefixEngineMatcher + '[startsWithMatcher] %s starts with %s? %s'], + [c.ENGINE_MATCHER_WHITELIST, c.logPrefixEngineMatcher + '[whitelistMatcher] evaluated %s in [%s] => %s'], + [c.ENGINE_VALUE, c.logPrefixEngineValue + 'Extracted attribute [%s], [%s] will be used for matching.'], + [c.ENGINE_SANITIZE, c.logPrefixEngine + ':sanitize: Attempted to sanitize [%s] which should be of type [%s]. Sanitized and processed value => [%s]'], // SDK - [CLEANUP_REGISTERING, logPrefixCleanup + 'Registering cleanup handler %s'], - [CLEANUP_DEREGISTERING, logPrefixCleanup + 'Deregistering cleanup handler %s'], - [RETRIEVE_CLIENT_DEFAULT, ' Retrieving default SDK client.'], - [RETRIEVE_CLIENT_EXISTING, ' Retrieving existing SDK client.'], - [RETRIEVE_MANAGER, ' Retrieving manager instance.'], + [c.CLEANUP_REGISTERING, c.logPrefixCleanup + 'Registering cleanup handler %s'], + [c.CLEANUP_DEREGISTERING, c.logPrefixCleanup + 'Deregistering cleanup handler %s'], + [c.RETRIEVE_CLIENT_DEFAULT, ' Retrieving default SDK client.'], + [c.RETRIEVE_CLIENT_EXISTING, ' Retrieving existing SDK client.'], + [c.RETRIEVE_MANAGER, ' Retrieving manager instance.'], // synchronizer - [SYNC_OFFLINE_DATA, logPrefixSyncOffline + 'Splits data: \n%s'], - [SYNC_SPLITS_FETCH, logPrefixSyncSplits + 'Spin up split update using since = %s'], - [SYNC_SPLITS_NEW, logPrefixSyncSplits + 'New splits %s'], - [SYNC_SPLITS_REMOVED, logPrefixSyncSplits + 'Removed splits %s'], - [SYNC_SPLITS_SEGMENTS, logPrefixSyncSplits + 'Segment names collected %s'], - [STREAMING_NEW_MESSAGE, logPrefixSyncStreaming + 'New SSE message received, with data: %s.'], - [SYNC_TASK_START, logPrefixSync + ': Starting %s. Running each %s millis'], - [SYNC_TASK_EXECUTE, logPrefixSync + ': Running %s'], - [SYNC_TASK_STOP, logPrefixSync + ': Stopping %s'], + [c.SYNC_OFFLINE_DATA, c.logPrefixSyncOffline + 'Splits data: \n%s'], + [c.SYNC_SPLITS_FETCH, c.logPrefixSyncSplits + 'Spin up split update using since = %s'], + [c.SYNC_SPLITS_NEW, c.logPrefixSyncSplits + 'New splits %s'], + [c.SYNC_SPLITS_REMOVED, c.logPrefixSyncSplits + 'Removed splits %s'], + [c.SYNC_SPLITS_SEGMENTS, c.logPrefixSyncSplits + 'Segment names collected %s'], + [c.STREAMING_NEW_MESSAGE, c.logPrefixSyncStreaming + 'New SSE message received, with data: %s.'], + [c.SYNC_TASK_START, c.logPrefixSync + ': Starting %s. Running each %s millis'], + [c.SYNC_TASK_EXECUTE, c.logPrefixSync + ': Running %s'], + [c.SYNC_TASK_STOP, c.logPrefixSync + ': Stopping %s'], // initialization / settings validation - [SETTINGS_SPLITS_FILTER, logPrefixSettings + ': splits filtering criteria is "%s".'] + [c.SETTINGS_SPLITS_FILTER, c.logPrefixSettings + ': splits filtering criteria is "%s".'] ]); diff --git a/src/logger/messages/error.ts b/src/logger/messages/error.ts index 2e4eb9c7..0eea8c02 100644 --- a/src/logger/messages/error.ts +++ b/src/logger/messages/error.ts @@ -1,33 +1,33 @@ -import { ERROR_ENGINE_COMBINER_IFELSEIF, ERROR_LOGLEVEL_INVALID, ERROR_CLIENT_LISTENER, ERROR_CLIENT_CANNOT_GET_READY, ERROR_SYNC_OFFLINE_LOADING, ERROR_STREAMING_SSE, ERROR_STREAMING_AUTH, ERROR_IMPRESSIONS_TRACKER, ERROR_IMPRESSIONS_LISTENER, ERROR_EVENT_TYPE_FORMAT, ERROR_NOT_PLAIN_OBJECT, ERROR_SIZE_EXCEEDED, ERROR_NOT_FINITE, ERROR_CLIENT_DESTROYED, ERROR_NULL, ERROR_TOO_LONG, ERROR_INVALID_KEY_OBJECT, ERROR_INVALID, ERROR_EMPTY, ERROR_EMPTY_ARRAY, ERROR_INVALID_IMPRESSIONS_MODE, ERROR_HTTP, logPrefixSettings, logPrefixEngineCombiner, logPrefixSyncOffline, logPrefixSyncStreaming, logPrefixImpressionsTracker, ERROR_EVENTS_TRACKER, logPrefixEventsTracker } from '../constants'; +import * as c from '../constants'; export const codesError: [number, string][] = [ // evaluator - [ERROR_ENGINE_COMBINER_IFELSEIF, logPrefixEngineCombiner + 'Invalid Split, no valid rules found'], + [c.ERROR_ENGINE_COMBINER_IFELSEIF, c.logPrefixEngineCombiner + 'Invalid Split, no valid rules found'], // SDK - [ERROR_LOGLEVEL_INVALID, 'logger: Invalid Log Level - No changes to the logs will be applied.'], - [ERROR_CLIENT_CANNOT_GET_READY, ' The SDK will not get ready. Reason: %s'], - [ERROR_IMPRESSIONS_TRACKER, logPrefixImpressionsTracker + 'Could not store impressions bulk with %s impression(s). Error: %s'], - [ERROR_IMPRESSIONS_LISTENER, logPrefixImpressionsTracker + 'Impression listener logImpression method threw: %s.'], - [ERROR_EVENTS_TRACKER, logPrefixEventsTracker + 'Failed to queue %s'], + [c.ERROR_LOGLEVEL_INVALID, 'logger: Invalid Log Level - No changes to the logs will be applied.'], + [c.ERROR_CLIENT_CANNOT_GET_READY, ' The SDK will not get ready. Reason: %s'], + [c.ERROR_IMPRESSIONS_TRACKER, c.logPrefixImpressionsTracker + 'Could not store impressions bulk with %s impression(s). Error: %s'], + [c.ERROR_IMPRESSIONS_LISTENER, c.logPrefixImpressionsTracker + 'Impression listener logImpression method threw: %s.'], + [c.ERROR_EVENTS_TRACKER, c.logPrefixEventsTracker + 'Failed to queue %s'], // synchronizer - [ERROR_SYNC_OFFLINE_LOADING, logPrefixSyncOffline + 'There was an issue loading the mock Splits data, no changes will be applied to the current cache. %s'], - [ERROR_STREAMING_SSE, logPrefixSyncStreaming + 'Fail to connect to streaming, with error message: %s'], - [ERROR_STREAMING_AUTH, logPrefixSyncStreaming + 'Failed to authenticate for streaming. Error: "%s".'], - [ERROR_HTTP, ' Response status is not OK. Status: %s. URL: %s. Message: %s'], + [c.ERROR_SYNC_OFFLINE_LOADING, c.logPrefixSyncOffline + 'There was an issue loading the mock Splits data, no changes will be applied to the current cache. %s'], + [c.ERROR_STREAMING_SSE, c.logPrefixSyncStreaming + 'Fail to connect to streaming, with error message: %s'], + [c.ERROR_STREAMING_AUTH, c.logPrefixSyncStreaming + 'Failed to authenticate for streaming. Error: "%s".'], + [c.ERROR_HTTP, ' Response status is not OK. Status: %s. URL: %s. Message: %s'], // client status - [ERROR_CLIENT_LISTENER, 'A listener was added for %s on the SDK, which has already fired and won\'t be emitted again. The callback won\'t be executed.'], - [ERROR_CLIENT_DESTROYED, '%s: Client has already been destroyed - no calls possible.'], + [c.ERROR_CLIENT_LISTENER, 'A listener was added for %s on the SDK, which has already fired and won\'t be emitted again. The callback won\'t be executed.'], + [c.ERROR_CLIENT_DESTROYED, '%s: Client has already been destroyed - no calls possible.'], // input validation - [ERROR_EVENT_TYPE_FORMAT, '%s: you passed "%s", event_type must adhere to the regular expression /^[a-zA-Z0-9][-_.:a-zA-Z0-9]{0,79}$/g. This means an event_type must be alphanumeric, cannot be more than 80 characters long, and can only include a dash, underscore, period, or colon as separators of alphanumeric characters.'], - [ERROR_NOT_PLAIN_OBJECT, '%s: %s must be a plain object.'], - [ERROR_SIZE_EXCEEDED, '%s: the maximum size allowed for the properties is 32768 bytes, which was exceeded. Event not queued.'], - [ERROR_NOT_FINITE, '%s: value must be a finite number.'], - [ERROR_NULL, '%s: you passed a null or undefined %s. It must be a non-empty string.'], - [ERROR_TOO_LONG, '%s: %s too long. It must have 250 characters or less.'], - [ERROR_INVALID_KEY_OBJECT, '%s: Key must be an object with bucketingKey and matchingKey with valid string properties.'], - [ERROR_INVALID, '%s: you passed an invalid %s. It must be a non-empty string.'], - [ERROR_EMPTY, '%s: you passed an empty %s. It must be a non-empty string.'], - [ERROR_EMPTY_ARRAY, '%s: %s must be a non-empty array.'], + [c.ERROR_EVENT_TYPE_FORMAT, '%s: you passed "%s", event_type must adhere to the regular expression /^[a-zA-Z0-9][-_.:a-zA-Z0-9]{0,79}$/g. This means an event_type must be alphanumeric, cannot be more than 80 characters long, and can only include a dash, underscore, period, or colon as separators of alphanumeric characters.'], + [c.ERROR_NOT_PLAIN_OBJECT, '%s: %s must be a plain object.'], + [c.ERROR_SIZE_EXCEEDED, '%s: the maximum size allowed for the properties is 32768 bytes, which was exceeded. Event not queued.'], + [c.ERROR_NOT_FINITE, '%s: value must be a finite number.'], + [c.ERROR_NULL, '%s: you passed a null or undefined %s. It must be a non-empty string.'], + [c.ERROR_TOO_LONG, '%s: %s too long. It must have 250 characters or less.'], + [c.ERROR_INVALID_KEY_OBJECT, '%s: Key must be an object with bucketingKey and matchingKey with valid string properties.'], + [c.ERROR_INVALID, '%s: you passed an invalid %s. It must be a non-empty string.'], + [c.ERROR_EMPTY, '%s: you passed an empty %s. It must be a non-empty string.'], + [c.ERROR_EMPTY_ARRAY, '%s: %s must be a non-empty array.'], // initialization / settings validation - [ERROR_INVALID_IMPRESSIONS_MODE, logPrefixSettings + ': you passed an invalid "impressionsMode". It should be one of the following values: %s. Defaulting to "%s" mode.'], + [c.ERROR_INVALID_IMPRESSIONS_MODE, c.logPrefixSettings + ': you passed an invalid "impressionsMode". It should be one of the following values: %s. Defaulting to "%s" mode.'], ]; diff --git a/src/logger/messages/info.ts b/src/logger/messages/info.ts index 6c00a5ff..2877a9d8 100644 --- a/src/logger/messages/info.ts +++ b/src/logger/messages/info.ts @@ -1,33 +1,33 @@ -import { CLIENT_READY_FROM_CACHE, CLIENT_READY, IMPRESSION, IMPRESSION_QUEUEING, NEW_SHARED_CLIENT, NEW_FACTORY, POLLING_SMART_PAUSING, POLLING_START, POLLING_STOP, SYNC_SPLITS_FETCH_RETRY, STREAMING_REFRESH_TOKEN, STREAMING_RECONNECT, STREAMING_CONNECTING, STREAMING_DISABLED, STREAMING_DISCONNECTING, SUBMITTERS_PUSH_FULL_EVENTS_QUEUE, SUBMITTERS_PUSH, SYNC_START_POLLING, SYNC_CONTINUE_POLLING, SYNC_STOP_POLLING, EVENTS_TRACKER_SUCCESS, logPrefixEventsTracker, logPrefixSyncManager, logPrefixSyncPolling, logPrefixSyncSplits, logPrefixSyncStreaming, logPrefixSyncSubmitters, logPrefixImpressionsTracker, IMPRESSIONS_TRACKER_SUCCESS } from '../constants'; +import * as c from '../constants'; import { codesWarn } from './warn'; const READY_MSG = 'Split SDK is ready'; export const codesInfo: [number, string][] = codesWarn.concat([ // client status - [CLIENT_READY_FROM_CACHE, READY_MSG + ' from cache'], - [CLIENT_READY, READY_MSG], + [c.CLIENT_READY_FROM_CACHE, READY_MSG + ' from cache'], + [c.CLIENT_READY, READY_MSG], // SDK - [IMPRESSION, logPrefixImpressionsTracker +'Split: %s. Key: %s. Evaluation: %s. Label: %s'], - [IMPRESSION_QUEUEING, logPrefixImpressionsTracker +'Queueing corresponding impression.'], - [NEW_SHARED_CLIENT, ' New shared client instance created.'], - [NEW_FACTORY, ' New Split SDK instance created.'], - [EVENTS_TRACKER_SUCCESS, logPrefixEventsTracker + 'Successfully qeued %s'], - [IMPRESSIONS_TRACKER_SUCCESS, logPrefixImpressionsTracker + 'Successfully stored %s impression(s).'], + [c.IMPRESSION, c.logPrefixImpressionsTracker +'Split: %s. Key: %s. Evaluation: %s. Label: %s'], + [c.IMPRESSION_QUEUEING, c.logPrefixImpressionsTracker +'Queueing corresponding impression.'], + [c.NEW_SHARED_CLIENT, ' New shared client instance created.'], + [c.NEW_FACTORY, ' New Split SDK instance created.'], + [c.EVENTS_TRACKER_SUCCESS, c.logPrefixEventsTracker + 'Successfully qeued %s'], + [c.IMPRESSIONS_TRACKER_SUCCESS, c.logPrefixImpressionsTracker + 'Successfully stored %s impression(s).'], // synchronizer - [POLLING_SMART_PAUSING, logPrefixSyncPolling + 'Turning segments data polling %s.'], - [POLLING_START, logPrefixSyncPolling + 'Starting polling'], - [POLLING_STOP, logPrefixSyncPolling + 'Stopping polling'], - [SYNC_SPLITS_FETCH_RETRY, logPrefixSyncSplits + 'Retrying download of splits #%s. Reason: %s'], - [SUBMITTERS_PUSH_FULL_EVENTS_QUEUE, logPrefixSyncSubmitters + 'Flushing full events queue and reseting timer.'], - [SUBMITTERS_PUSH, logPrefixSyncSubmitters + 'Pushing %s %s.'], - [STREAMING_REFRESH_TOKEN, logPrefixSyncStreaming + 'Refreshing streaming token in %s seconds.'], - [STREAMING_RECONNECT, logPrefixSyncStreaming + 'Attempting to reconnect in %s seconds.'], - [STREAMING_CONNECTING, logPrefixSyncStreaming + 'Connecting to streaming.'], - [STREAMING_DISABLED, logPrefixSyncStreaming + 'Streaming is disabled for given Api key. Switching to polling mode.'], - [STREAMING_DISCONNECTING, logPrefixSyncStreaming + 'Disconnecting from streaming.'], - [SYNC_START_POLLING, logPrefixSyncManager + 'Streaming not available. Starting polling.'], - [SYNC_CONTINUE_POLLING, logPrefixSyncManager + 'Streaming couldn\'t connect. Continue polling.'], - [SYNC_STOP_POLLING, logPrefixSyncManager + 'Streaming (re)connected. Syncing and stopping polling.'], + [c.POLLING_SMART_PAUSING, c.logPrefixSyncPolling + 'Turning segments data polling %s.'], + [c.POLLING_START, c.logPrefixSyncPolling + 'Starting polling'], + [c.POLLING_STOP, c.logPrefixSyncPolling + 'Stopping polling'], + [c.SYNC_SPLITS_FETCH_RETRY, c.logPrefixSyncSplits + 'Retrying download of splits #%s. Reason: %s'], + [c.SUBMITTERS_PUSH_FULL_EVENTS_QUEUE, c.logPrefixSyncSubmitters + 'Flushing full events queue and reseting timer.'], + [c.SUBMITTERS_PUSH, c.logPrefixSyncSubmitters + 'Pushing %s %s.'], + [c.STREAMING_REFRESH_TOKEN, c.logPrefixSyncStreaming + 'Refreshing streaming token in %s seconds.'], + [c.STREAMING_RECONNECT, c.logPrefixSyncStreaming + 'Attempting to reconnect in %s seconds.'], + [c.STREAMING_CONNECTING, c.logPrefixSyncStreaming + 'Connecting to streaming.'], + [c.STREAMING_DISABLED, c.logPrefixSyncStreaming + 'Streaming is disabled for given Api key. Switching to polling mode.'], + [c.STREAMING_DISCONNECTING, c.logPrefixSyncStreaming + 'Disconnecting from streaming.'], + [c.SYNC_START_POLLING, c.logPrefixSyncManager + 'Streaming not available. Starting polling.'], + [c.SYNC_CONTINUE_POLLING, c.logPrefixSyncManager + 'Streaming couldn\'t connect. Continue polling.'], + [c.SYNC_STOP_POLLING, c.logPrefixSyncManager + 'Streaming (re)connected. Syncing and stopping polling.'], ]); diff --git a/src/logger/messages/warn.ts b/src/logger/messages/warn.ts index b246e0fb..e10da2f5 100644 --- a/src/logger/messages/warn.ts +++ b/src/logger/messages/warn.ts @@ -1,34 +1,34 @@ -import { ENGINE_VALUE_INVALID, ENGINE_VALUE_NO_ATTRIBUTES, CLIENT_NO_LISTENER, SYNC_MYSEGMENTS_FETCH_RETRY, SYNC_SPLITS_FETCH_FAILS, STREAMING_PARSING_ERROR_FAILS, STREAMING_PARSING_MESSAGE_FAILS, STREAMING_FALLBACK, SUBMITTERS_PUSH_FAILS, SUBMITTERS_PUSH_RETRY, WARN_SETTING_NULL, WARN_TRIMMING_PROPERTIES, CLIENT_NOT_READY, WARN_CONVERTING, WARN_TRIMMING, WARN_NOT_EXISTENT_SPLIT, WARN_LOWERCASE_TRAFFIC_TYPE, WARN_NOT_EXISTENT_TT, WARN_INTEGRATION_INVALID, WARN_SPLITS_FILTER_IGNORED, WARN_SPLITS_FILTER_INVALID, WARN_SPLITS_FILTER_EMPTY, WARN_STORAGE_INVALID, WARN_API_KEY, logPrefixSettings, logPrefixEngineValue, logPrefixSyncMysegments, logPrefixSyncSplits, logPrefixSyncStreaming, logPrefixSyncSubmitters } from '../constants'; +import * as c from '../constants'; import { codesError } from './error'; export const codesWarn: [number, string][] = codesError.concat([ // evaluator - [ENGINE_VALUE_INVALID, logPrefixEngineValue + 'Value %s doesn\'t match with expected type.'], - [ENGINE_VALUE_NO_ATTRIBUTES, logPrefixEngineValue + 'Defined attribute [%s], no attributes received.'], + [c.ENGINE_VALUE_INVALID, c.logPrefixEngineValue + 'Value %s doesn\'t match with expected type.'], + [c.ENGINE_VALUE_NO_ATTRIBUTES, c.logPrefixEngineValue + 'Defined attribute [%s], no attributes received.'], // synchronizer - [SYNC_MYSEGMENTS_FETCH_RETRY, logPrefixSyncMysegments + 'Retrying download of segments #%s. Reason: %s'], - [SYNC_SPLITS_FETCH_FAILS, logPrefixSyncSplits + 'Error while doing fetch of Splits. %s'], - [STREAMING_PARSING_ERROR_FAILS, logPrefixSyncStreaming + 'Error parsing SSE error notification: %s'], - [STREAMING_PARSING_MESSAGE_FAILS, logPrefixSyncStreaming + 'Error parsing SSE message notification: %s'], - [STREAMING_FALLBACK, logPrefixSyncStreaming + 'Falling back to polling mode. Reason: %s'], - [SUBMITTERS_PUSH_FAILS, logPrefixSyncSubmitters + 'Droping %s %s after retry. Reason: %s.'], - [SUBMITTERS_PUSH_RETRY, logPrefixSyncSubmitters + 'Failed to push %s %s, keeping data to retry on next iteration. Reason: %s.'], + [c.SYNC_MYSEGMENTS_FETCH_RETRY, c.logPrefixSyncMysegments + 'Retrying download of segments #%s. Reason: %s'], + [c.SYNC_SPLITS_FETCH_FAILS, c.logPrefixSyncSplits + 'Error while doing fetch of Splits. %s'], + [c.STREAMING_PARSING_ERROR_FAILS, c.logPrefixSyncStreaming + 'Error parsing SSE error notification: %s'], + [c.STREAMING_PARSING_MESSAGE_FAILS, c.logPrefixSyncStreaming + 'Error parsing SSE message notification: %s'], + [c.STREAMING_FALLBACK, c.logPrefixSyncStreaming + 'Falling back to polling mode. Reason: %s'], + [c.SUBMITTERS_PUSH_FAILS, c.logPrefixSyncSubmitters + 'Droping %s %s after retry. Reason: %s.'], + [c.SUBMITTERS_PUSH_RETRY, c.logPrefixSyncSubmitters + 'Failed to push %s %s, keeping data to retry on next iteration. Reason: %s.'], // client status - [CLIENT_NOT_READY, '%s: the SDK is not ready, results may be incorrect. Make sure to wait for SDK readiness before using this method.'], - [CLIENT_NO_LISTENER, 'No listeners for SDK Readiness detected. Incorrect control treatments could have been logged if you called getTreatment/s while the SDK was not yet ready.'], + [c.CLIENT_NOT_READY, '%s: the SDK is not ready, results may be incorrect. Make sure to wait for SDK readiness before using this method.'], + [c.CLIENT_NO_LISTENER, 'No listeners for SDK Readiness detected. Incorrect control treatments could have been logged if you called getTreatment/s while the SDK was not yet ready.'], // input validation - [WARN_SETTING_NULL, '%s: Property "%s" is of invalid type. Setting value to null.'], - [WARN_TRIMMING_PROPERTIES, '%s: Event has more than 300 properties. Some of them will be trimmed when processed.'], - [WARN_CONVERTING, '%s: %s "%s" is not of type string, converting.'], - [WARN_TRIMMING, '%s: %s "%s" has extra whitespace, trimming.'], - [WARN_NOT_EXISTENT_SPLIT, '%s: split "%s" does not exist in this environment, please double check what splits exist in the web console.'], - [WARN_LOWERCASE_TRAFFIC_TYPE, '%s: traffic_type_name should be all lowercase - converting string to lowercase.'], - [WARN_NOT_EXISTENT_TT, '%s: traffic type "%s" does not have any corresponding split in this environment, make sure you\'re tracking your events to a valid traffic type defined in the web console.'], + [c.WARN_SETTING_NULL, '%s: Property "%s" is of invalid type. Setting value to null.'], + [c.WARN_TRIMMING_PROPERTIES, '%s: Event has more than 300 properties. Some of them will be trimmed when processed.'], + [c.WARN_CONVERTING, '%s: %s "%s" is not of type string, converting.'], + [c.WARN_TRIMMING, '%s: %s "%s" has extra whitespace, trimming.'], + [c.WARN_NOT_EXISTENT_SPLIT, '%s: split "%s" does not exist in this environment, please double check what splits exist in the web console.'], + [c.WARN_LOWERCASE_TRAFFIC_TYPE, '%s: traffic_type_name should be all lowercase - converting string to lowercase.'], + [c.WARN_NOT_EXISTENT_TT, '%s: traffic type "%s" does not have any corresponding split in this environment, make sure you\'re tracking your events to a valid traffic type defined in the web console.'], // initialization / settings validation - [WARN_INTEGRATION_INVALID, logPrefixSettings+': %s integration %s at settings %s invalid. %s'], - [WARN_SPLITS_FILTER_IGNORED, logPrefixSettings+': split filters have been configured but will have no effect if mode is not "%s", since synchronization is being deferred to an external tool.'], - [WARN_SPLITS_FILTER_INVALID, logPrefixSettings+': split filter at position %s is invalid. It must be an object with a valid filter type ("byName" or "byPrefix") and a list of "values".'], - [WARN_SPLITS_FILTER_EMPTY, logPrefixSettings+': splitFilters configuration must be a non-empty array of filter objects.'], - [WARN_STORAGE_INVALID, logPrefixSettings+': The provided storage is invalid. Fallbacking into default MEMORY storage'], - [WARN_API_KEY, logPrefixSettings+': You already have %s. We recommend keeping only one instance of the factory at all times (Singleton pattern) and reusing it throughout your application'] + [c.WARN_INTEGRATION_INVALID, c.logPrefixSettings+': %s integration %s at settings %s invalid. %s'], + [c.WARN_SPLITS_FILTER_IGNORED, c.logPrefixSettings+': split filters have been configured but will have no effect if mode is not "%s", since synchronization is being deferred to an external tool.'], + [c.WARN_SPLITS_FILTER_INVALID, c.logPrefixSettings+': split filter at position %s is invalid. It must be an object with a valid filter type ("byName" or "byPrefix") and a list of "values".'], + [c.WARN_SPLITS_FILTER_EMPTY, c.logPrefixSettings+': splitFilters configuration must be a non-empty array of filter objects.'], + [c.WARN_STORAGE_INVALID, c.logPrefixSettings+': The provided storage is invalid. Fallbacking into default MEMORY storage'], + [c.WARN_API_KEY, c.logPrefixSettings+': You already have %s. We recommend keeping only one instance of the factory at all times (Singleton pattern) and reusing it throughout your application'] ]); From 4811f19c86f620ef83e6e838401f79c63363f077 Mon Sep 17 00:00:00 2001 From: Emiliano Sanchez Date: Fri, 26 Mar 2021 15:29:51 -0300 Subject: [PATCH 3/4] ordered constant values --- src/logger/constants.ts | 148 ++++++++++++++++++++-------------------- 1 file changed, 74 insertions(+), 74 deletions(-) diff --git a/src/logger/constants.ts b/src/logger/constants.ts index 75e18f7e..46cac217 100644 --- a/src/logger/constants.ts +++ b/src/logger/constants.ts @@ -23,28 +23,28 @@ export const ENGINE_MATCHER_ENDS_WITH = 14; export const ENGINE_MATCHER_GREATER = 15; export const ENGINE_MATCHER_LESS = 16; export const ENGINE_MATCHER_PART_OF = 17; -export const ENGINE_MATCHER_SEGMENT = 19; -export const ENGINE_MATCHER_STRING = 20; -export const ENGINE_MATCHER_STRING_INVALID = 21; -export const ENGINE_MATCHER_STARTS_WITH = 22; -export const ENGINE_MATCHER_WHITELIST = 23; -export const ENGINE_VALUE = 24; -export const ENGINE_SANITIZE = 25; -export const CLEANUP_REGISTERING = 26; -export const CLEANUP_DEREGISTERING = 27; -export const RETRIEVE_CLIENT_DEFAULT = 32; -export const RETRIEVE_CLIENT_EXISTING = 33; -export const RETRIEVE_MANAGER = 34; -export const SYNC_OFFLINE_DATA = 36; -export const SYNC_SPLITS_FETCH = 42; -export const SYNC_SPLITS_NEW = 43; -export const SYNC_SPLITS_REMOVED = 44; -export const SYNC_SPLITS_SEGMENTS = 45; -export const STREAMING_NEW_MESSAGE = 46; -export const SYNC_TASK_START = 47; -export const SYNC_TASK_EXECUTE = 48; -export const SYNC_TASK_STOP = 49; -export const SETTINGS_SPLITS_FILTER = 51; +export const ENGINE_MATCHER_SEGMENT = 18; +export const ENGINE_MATCHER_STRING = 19; +export const ENGINE_MATCHER_STRING_INVALID = 20; +export const ENGINE_MATCHER_STARTS_WITH = 21; +export const ENGINE_MATCHER_WHITELIST = 22; +export const ENGINE_VALUE = 23; +export const ENGINE_SANITIZE = 24; +export const CLEANUP_REGISTERING = 25; +export const CLEANUP_DEREGISTERING = 26; +export const RETRIEVE_CLIENT_DEFAULT = 27; +export const RETRIEVE_CLIENT_EXISTING = 28; +export const RETRIEVE_MANAGER = 29; +export const SYNC_OFFLINE_DATA = 30; +export const SYNC_SPLITS_FETCH = 31; +export const SYNC_SPLITS_NEW = 32; +export const SYNC_SPLITS_REMOVED = 33; +export const SYNC_SPLITS_SEGMENTS = 34; +export const STREAMING_NEW_MESSAGE = 35; +export const SYNC_TASK_START = 36; +export const SYNC_TASK_EXECUTE = 37; +export const SYNC_TASK_STOP = 38; +export const SETTINGS_SPLITS_FILTER = 39; export const CLIENT_READY_FROM_CACHE = 100; export const CLIENT_READY = 101; @@ -52,27 +52,27 @@ export const IMPRESSION = 102; export const IMPRESSION_QUEUEING = 103; export const NEW_SHARED_CLIENT = 104; export const NEW_FACTORY = 105; -export const POLLING_SMART_PAUSING = 107; -export const POLLING_START = 108; -export const POLLING_STOP = 109; -export const SYNC_SPLITS_FETCH_RETRY = 110; -export const STREAMING_REFRESH_TOKEN = 111; -export const STREAMING_RECONNECT = 112; -export const STREAMING_CONNECTING = 113; -export const STREAMING_DISABLED = 114; -export const STREAMING_DISCONNECTING = 115; -export const SUBMITTERS_PUSH_FULL_EVENTS_QUEUE = 116; -export const SUBMITTERS_PUSH = 117; -export const SYNC_START_POLLING = 118; -export const SYNC_CONTINUE_POLLING = 119; -export const SYNC_STOP_POLLING = 120; -export const EVENTS_TRACKER_SUCCESS = 121; -export const IMPRESSIONS_TRACKER_SUCCESS = 122; +export const POLLING_SMART_PAUSING = 106; +export const POLLING_START = 107; +export const POLLING_STOP = 108; +export const SYNC_SPLITS_FETCH_RETRY = 109; +export const STREAMING_REFRESH_TOKEN = 110; +export const STREAMING_RECONNECT = 111; +export const STREAMING_CONNECTING = 112; +export const STREAMING_DISABLED = 113; +export const STREAMING_DISCONNECTING = 114; +export const SUBMITTERS_PUSH_FULL_EVENTS_QUEUE = 115; +export const SUBMITTERS_PUSH = 116; +export const SYNC_START_POLLING = 117; +export const SYNC_CONTINUE_POLLING = 118; +export const SYNC_STOP_POLLING = 119; +export const EVENTS_TRACKER_SUCCESS = 120; +export const IMPRESSIONS_TRACKER_SUCCESS = 121; export const ENGINE_VALUE_INVALID = 200; export const ENGINE_VALUE_NO_ATTRIBUTES = 201; export const CLIENT_NO_LISTENER = 202; -export const CLIENT_NOT_READY = 214; +export const CLIENT_NOT_READY = 203; export const SYNC_MYSEGMENTS_FETCH_RETRY = 204; export const SYNC_SPLITS_FETCH_FAILS = 205; export const STREAMING_PARSING_ERROR_FAILS = 206; @@ -80,43 +80,43 @@ export const STREAMING_PARSING_MESSAGE_FAILS = 207; export const STREAMING_FALLBACK = 208; export const SUBMITTERS_PUSH_FAILS = 209; export const SUBMITTERS_PUSH_RETRY = 210; -export const WARN_SETTING_NULL = 212; -export const WARN_TRIMMING_PROPERTIES = 213; -export const WARN_CONVERTING = 215; -export const WARN_TRIMMING = 217; -export const WARN_NOT_EXISTENT_SPLIT = 218; -export const WARN_LOWERCASE_TRAFFIC_TYPE = 219; -export const WARN_NOT_EXISTENT_TT = 220; -export const WARN_INTEGRATION_INVALID = 221; -export const WARN_SPLITS_FILTER_IGNORED = 222; -export const WARN_SPLITS_FILTER_INVALID = 223; -export const WARN_SPLITS_FILTER_EMPTY = 224; -export const WARN_STORAGE_INVALID = 225; -export const WARN_API_KEY = 226; +export const WARN_SETTING_NULL = 211; +export const WARN_TRIMMING_PROPERTIES = 212; +export const WARN_CONVERTING = 213; +export const WARN_TRIMMING = 214; +export const WARN_NOT_EXISTENT_SPLIT = 215; +export const WARN_LOWERCASE_TRAFFIC_TYPE = 216; +export const WARN_NOT_EXISTENT_TT = 217; +export const WARN_INTEGRATION_INVALID = 218; +export const WARN_SPLITS_FILTER_IGNORED = 219; +export const WARN_SPLITS_FILTER_INVALID = 220; +export const WARN_SPLITS_FILTER_EMPTY = 221; +export const WARN_STORAGE_INVALID = 222; +export const WARN_API_KEY = 223; export const ERROR_ENGINE_COMBINER_IFELSEIF = 300; -export const ERROR_LOGLEVEL_INVALID = 302; -export const ERROR_CLIENT_LISTENER = 303; -export const ERROR_CLIENT_CANNOT_GET_READY = 305; -export const ERROR_SYNC_OFFLINE_LOADING = 307; -export const ERROR_STREAMING_SSE = 309; -export const ERROR_STREAMING_AUTH = 310; -export const ERROR_IMPRESSIONS_TRACKER = 311; -export const ERROR_IMPRESSIONS_LISTENER = 312; -export const ERROR_EVENTS_TRACKER = 313; -export const ERROR_EVENT_TYPE_FORMAT = 314; -export const ERROR_NOT_PLAIN_OBJECT = 318; -export const ERROR_SIZE_EXCEEDED = 319; -export const ERROR_NOT_FINITE = 320; -export const ERROR_CLIENT_DESTROYED = 321; -export const ERROR_NULL = 322; -export const ERROR_TOO_LONG = 323; -export const ERROR_INVALID_KEY_OBJECT = 326; -export const ERROR_INVALID = 332; -export const ERROR_EMPTY = 333; -export const ERROR_EMPTY_ARRAY = 334; -export const ERROR_INVALID_IMPRESSIONS_MODE = 338; -export const ERROR_HTTP = 339; +export const ERROR_LOGLEVEL_INVALID = 301; +export const ERROR_CLIENT_LISTENER = 302; +export const ERROR_CLIENT_CANNOT_GET_READY = 303; +export const ERROR_SYNC_OFFLINE_LOADING = 304; +export const ERROR_STREAMING_SSE = 305; +export const ERROR_STREAMING_AUTH = 306; +export const ERROR_IMPRESSIONS_TRACKER = 307; +export const ERROR_IMPRESSIONS_LISTENER = 308; +export const ERROR_EVENTS_TRACKER = 309; +export const ERROR_EVENT_TYPE_FORMAT = 310; +export const ERROR_NOT_PLAIN_OBJECT = 311; +export const ERROR_SIZE_EXCEEDED = 312; +export const ERROR_NOT_FINITE = 313; +export const ERROR_CLIENT_DESTROYED = 314; +export const ERROR_NULL = 315; +export const ERROR_TOO_LONG = 316; +export const ERROR_INVALID_KEY_OBJECT = 317; +export const ERROR_INVALID = 318; +export const ERROR_EMPTY = 319; +export const ERROR_EMPTY_ARRAY = 320; +export const ERROR_INVALID_IMPRESSIONS_MODE = 321; +export const ERROR_HTTP = 322; // Log prefixes (a.k.a. tags or categories) export const logPrefixSettings = 'settings'; From 55d299d5fdf51b139afc88f4c59bd6e290394742 Mon Sep 17 00:00:00 2001 From: Emiliano Sanchez Date: Fri, 26 Mar 2021 15:56:37 -0300 Subject: [PATCH 4/4] polishing on UTs --- src/integrations/__tests__/browser.spec.ts | 8 ++-- .../ga/__tests__/GaToSplit.spec.ts | 2 +- .../ga/__tests__/SplitToGa.spec.ts | 14 +++---- src/listeners/__tests__/browser.spec.ts | 26 ++++++------ src/listeners/__tests__/node.spec.ts | 42 +++++++++---------- .../__tests__/sdkReadinessManager.spec.ts | 32 +++++++------- .../__tests__/sdkClientMethod.spec.ts | 4 +- .../__tests__/ImpressionsCacheInRedis.spec.ts | 4 +- .../inRedis/__tests__/RedisAdapter.spec.ts | 2 +- .../__tests__/splitChangesUpdater.spec.ts | 6 +-- .../SSEClient/__tests__/index.spec.ts | 10 ++--- src/trackers/__tests__/eventTracker.spec.ts | 6 +-- .../__tests__/impressionsTracker.spec.ts | 20 ++++----- .../__tests__/attributes.spec.ts | 10 ++--- .../inputValidation/__tests__/split.spec.ts | 6 +-- .../__tests__/splitExistance.spec.ts | 12 +++--- .../inputValidation/__tests__/splits.spec.ts | 20 ++++----- .../__tests__/trafficType.spec.ts | 12 +++--- src/utils/lang/__tests__/index.spec.ts | 6 +-- 19 files changed, 121 insertions(+), 121 deletions(-) diff --git a/src/integrations/__tests__/browser.spec.ts b/src/integrations/__tests__/browser.spec.ts index e4237f91..9bab3e99 100644 --- a/src/integrations/__tests__/browser.spec.ts +++ b/src/integrations/__tests__/browser.spec.ts @@ -47,8 +47,8 @@ describe('IntegrationsManagerFactory for browser', () => { let integrations: BrowserIntegration[] = [{ type: GOOGLE_ANALYTICS_TO_SPLIT }, { type: SPLIT_TO_GOOGLE_ANALYTICS }]; const instance2 = browserIMF(integrations, fakeParams as any) as IIntegrationManager; - expect((GaToSplitMock as jest.Mock).mock.calls.length).toBe(1); // GaToSplit invoked once - expect((SplitToGaMock as unknown as jest.Mock).mock.calls.length).toBe(1); // SplitToGa invoked once + expect(GaToSplitMock).toBeCalledTimes(1); // GaToSplit invoked once + expect(SplitToGaMock).toBeCalledTimes(1); // SplitToGa invoked once expect(typeof instance2.handleImpression).toBe('function'); // The instance should implement the handleImpression method if settings.integrations has items that register a listener. expect(typeof instance2.handleEvent).toBe('function'); // The instance should implement the handleEvent method if settings.integrations has items that register a listener. @@ -56,8 +56,8 @@ describe('IntegrationsManagerFactory for browser', () => { integrations = [{ type: GOOGLE_ANALYTICS_TO_SPLIT }, { type: SPLIT_TO_GOOGLE_ANALYTICS }, { type: GOOGLE_ANALYTICS_TO_SPLIT }, { type: SPLIT_TO_GOOGLE_ANALYTICS }, { type: SPLIT_TO_GOOGLE_ANALYTICS }]; browserIMF(integrations, fakeParams as any); - expect((GaToSplitMock as jest.Mock).mock.calls.length).toBe(2); // GaToSplit invoked twice - expect((SplitToGaMock as unknown as jest.Mock).mock.calls.length).toBe(3); // SplitToGa invoked thrice + expect(GaToSplitMock).toBeCalledTimes(2); // GaToSplit invoked twice + expect(SplitToGaMock).toBeCalledTimes(3); // SplitToGa invoked thrice clearMocks(); }); diff --git a/src/integrations/ga/__tests__/GaToSplit.spec.ts b/src/integrations/ga/__tests__/GaToSplit.spec.ts index d9005ead..21c4a1ef 100644 --- a/src/integrations/ga/__tests__/GaToSplit.spec.ts +++ b/src/integrations/ga/__tests__/GaToSplit.spec.ts @@ -246,7 +246,7 @@ test('GaToSplit: `hits` flag param', () => { // send hit and assert that it was not tracked as a Split event (fakeStorage.events.track as jest.Mock).mockClear(); window.ga('send', hitSample); - expect((fakeStorage.events.track as jest.Mock).mock.calls.length).toBe(0); + expect(fakeStorage.events.track).toBeCalledTimes(0); // test teardown gaRemove(); diff --git a/src/integrations/ga/__tests__/SplitToGa.spec.ts b/src/integrations/ga/__tests__/SplitToGa.spec.ts index 33581122..849350ca 100644 --- a/src/integrations/ga/__tests__/SplitToGa.spec.ts +++ b/src/integrations/ga/__tests__/SplitToGa.spec.ts @@ -86,7 +86,7 @@ describe('SplitToGa', () => { let integration = new SplitToGa(loggerMock, {}); expect(typeof integration).toBe('object'); - expect(loggerMock.warn.mock.calls.length).toBe(0); + expect(loggerMock.warn).not.toBeCalled(); gaRemove(); expect(SplitToGa.getGa()).toBe(undefined); // should return undefined if ga command queue does not exist @@ -110,13 +110,13 @@ describe('SplitToGa', () => { const instance = new SplitToGa(loggerMock, {}) as SplitToGa; instance.queue(fakeImpression); // should queue `ga send` with the default mapped FieldsObject for impressions, appended with `splitHit` field - expect(ga.mock.calls[ga.mock.calls.length - 1]).toEqual(['send', { ...defaultImpressionFieldsObject, splitHit: true }]); + expect(ga).lastCalledWith('send', { ...defaultImpressionFieldsObject, splitHit: true }); instance.queue(fakeEvent); // should queue `ga send` with the default mapped FieldsObject for events, appended with `splitHit` field - expect(ga.mock.calls[ga.mock.calls.length - 1]).toEqual(['send', { ...defaultEventFieldsObject, splitHit: true }]); + expect(ga).lastCalledWith('send', { ...defaultEventFieldsObject, splitHit: true }); - expect(ga.mock.calls.length).toBe(2); + expect(ga).toBeCalledTimes(2); /** Custom behaviour **/ // Custom filter @@ -146,7 +146,7 @@ describe('SplitToGa', () => { [`${trackerNames[1]}.send`, { ...customMapper(), splitHit: true }] ]); // should queue `ga send` with the custom trackerName and FieldsObject from customMapper, appended with `splitHit` field - expect(ga.mock.calls.length).toBe(2); + expect(ga).toBeCalledTimes(2); // Custom mapper that returns the default FieldsObject function customMapper2(data: SplitIO.IntegrationData, defaultFieldsObject: UniversalAnalytics.FieldsObject) { @@ -158,9 +158,9 @@ describe('SplitToGa', () => { ga.mockClear(); instance3.queue(fakeImpression); // should queue `ga send` with the custom FieldsObject from customMapper2, appended with `splitHit` field - expect(ga.mock.calls[ga.mock.calls.length - 1]).toEqual(['send', { ...customMapper2(fakeImpression, defaultImpressionFieldsObject), splitHit: true }]); + expect(ga).lastCalledWith('send', { ...customMapper2(fakeImpression, defaultImpressionFieldsObject), splitHit: true }); - expect(ga.mock.calls.length).toBe(1); + expect(ga).toBeCalledTimes(1); // Custom mapper that throws an error function customMapper3() { diff --git a/src/listeners/__tests__/browser.spec.ts b/src/listeners/__tests__/browser.spec.ts index 03a98c79..32c69f59 100644 --- a/src/listeners/__tests__/browser.spec.ts +++ b/src/listeners/__tests__/browser.spec.ts @@ -118,15 +118,15 @@ test('Browser JS listener / Impressions optimized mode', (done) => { setTimeout(() => { // Unload event was triggered. Thus sendBeacon method should have been called three times. - expect((global.window.navigator.sendBeacon as jest.Mock).mock.calls.length).toBe(3); + expect(global.window.navigator.sendBeacon).toBeCalledTimes(3); // Http post services should have not been called - expect((fakeSplitApi.postTestImpressionsBulk as jest.Mock).mock.calls.length).toBe(0); - expect((fakeSplitApi.postEventsBulk as jest.Mock).mock.calls.length).toBe(0); - expect((fakeSplitApi.postTestImpressionsCount as jest.Mock).mock.calls.length).toBe(0); + expect(fakeSplitApi.postTestImpressionsBulk).not.toBeCalled(); + expect(fakeSplitApi.postEventsBulk).not.toBeCalled(); + expect(fakeSplitApi.postTestImpressionsCount).not.toBeCalled(); // pre-check and call stop - expect((global.window.removeEventListener as jest.Mock).mock.calls.length).toBe(0); + expect(global.window.removeEventListener).not.toBeCalled(); listener.stop(); // removed correct listener from correct signal on stop. @@ -149,12 +149,12 @@ test('Browser JS listener / Impressions debug mode', (done) => { setTimeout(() => { // Unload event was triggered. Thus sendBeacon method should have been called twice. - expect((global.window.navigator.sendBeacon as jest.Mock).mock.calls.length).toBe(2); + expect(global.window.navigator.sendBeacon).toBeCalledTimes(2); // Http post services should have not been called - expect((fakeSplitApi.postTestImpressionsBulk as jest.Mock).mock.calls.length).toBe(0); - expect((fakeSplitApi.postEventsBulk as jest.Mock).mock.calls.length).toBe(0); - expect((fakeSplitApi.postTestImpressionsCount as jest.Mock).mock.calls.length).toBe(0); + expect(fakeSplitApi.postTestImpressionsBulk).not.toBeCalled(); + expect(fakeSplitApi.postEventsBulk).not.toBeCalled(); + expect(fakeSplitApi.postTestImpressionsCount).not.toBeCalled(); // pre-check and call stop expect(global.window.removeEventListener).not.toBeCalled(); @@ -183,12 +183,12 @@ test('Browser JS listener / Impressions debug mode without sendBeacon API', (don setTimeout(() => { // Unload event was triggered. Thus sendBeacon method should have been called twice. - expect((sendBeacon as jest.Mock).mock.calls.length).toBe(0); + expect(sendBeacon).not.toBeCalled(); // Http post services should have not been called - expect((fakeSplitApi.postTestImpressionsBulk as jest.Mock).mock.calls.length).toBe(1); - expect((fakeSplitApi.postEventsBulk as jest.Mock).mock.calls.length).toBe(1); - expect((fakeSplitApi.postTestImpressionsCount as jest.Mock).mock.calls.length).toBe(0); + expect(fakeSplitApi.postTestImpressionsBulk).toBeCalledTimes(1); + expect(fakeSplitApi.postEventsBulk).toBeCalledTimes(1); + expect(fakeSplitApi.postTestImpressionsCount).not.toBeCalled(); // pre-check and call stop expect(global.window.removeEventListener).not.toBeCalled(); diff --git a/src/listeners/__tests__/node.spec.ts b/src/listeners/__tests__/node.spec.ts index 94f6e14c..cf5794ed 100644 --- a/src/listeners/__tests__/node.spec.ts +++ b/src/listeners/__tests__/node.spec.ts @@ -35,19 +35,19 @@ test('Node JS listener / Signal Listener SIGTERM callback with sync handler', () jest.spyOn(listener, 'stop'); // Control asserts. - expect((listener.stop as jest.Mock).mock.calls.length).toBe(0); - expect(handlerMock.mock.calls.length).toBe(0); - expect(processKillSpy.mock.calls.length).toBe(0); + expect(listener.stop).not.toBeCalled(); + expect(handlerMock).not.toBeCalled(); + expect(processKillSpy).not.toBeCalled(); // Call function // @ts-expect-error listener._sigtermHandler(); // Handler was properly called. - expect(handlerMock.mock.calls.length).toBe(1); + expect(handlerMock).toBeCalledTimes(1); // Clean up is called. - expect((listener.stop as jest.Mock).mock.calls.length).toBe(1); + expect(listener.stop).toBeCalledTimes(1); // It called for kill again, so the shutdown keeps going. expect(processKillSpy.mock.calls).toEqual([[process.pid, 'SIGTERM']]); @@ -64,21 +64,21 @@ test('Node JS listener / Signal Listener SIGTERM callback with sync handler that jest.spyOn(listener, 'stop'); // Control asserts. - expect((listener.stop as jest.Mock).mock.calls.length).toBe(0); - expect(handlerMock.mock.calls.length).toBe(0); - expect(processKillSpy.mock.calls.length).toBe(0); + expect(listener.stop).not.toBeCalled(); + expect(handlerMock).not.toBeCalled(); + expect(processKillSpy).not.toBeCalled(); // Call function. // @ts-expect-error listener._sigtermHandler(); // Handler was properly called. - expect(handlerMock.mock.calls.length).toBe(1); + expect(handlerMock).toBeCalledTimes(1); // Even if the handler throws, clean up is called. - expect((listener.stop as jest.Mock).mock.calls.length).toBe(1); + expect(listener.stop).toBeCalledTimes(1); // Even if the handler throws, it should call for kill again, so the shutdown keeps going. - expect(processKillSpy.mock.calls.length).toBe(1); + expect(processKillSpy).toBeCalledTimes(1); expect(processKillSpy.mock.calls).toEqual([[process.pid, 'SIGTERM']]); // Reset the kill spy since it's used on other tests. @@ -107,17 +107,17 @@ test('Node JS listener / Signal Listener SIGTERM callback with async handler', a listener._sigtermHandler(); // Handler was properly called. - expect(handlerMock.mock.calls.length).toBe(1); + expect(handlerMock).toBeCalledTimes(1); // Check that the wrap up is waiting for the promise to be resolved. - expect((listener.stop as jest.Mock).mock.calls.length).toBe(0); - expect(processKillSpy.mock.calls.length).toBe(0); + expect(listener.stop).not.toBeCalled(); + expect(processKillSpy).not.toBeCalled(); fakePromise.then(() => { // Clean up is called even if there is an error. - expect((listener.stop as jest.Mock).mock.calls.length).toBe(1); + expect(listener.stop).toBeCalledTimes(1); // It called for kill again, so the shutdown keeps going. - expect(processKillSpy.mock.calls.length).toBe(1); + expect(processKillSpy).toBeCalledTimes(1); expect(processKillSpy.mock.calls).toEqual([[process.pid, 'SIGTERM']]); // Reset the kill spy since it's used on other tests. @@ -151,18 +151,18 @@ test('Node JS listener / Signal Listener SIGTERM callback with async handler tha const handlerPromise = listener._sigtermHandler(); // Handler was properly called. - expect(handlerMock.mock.calls.length).toBe(1); + expect(handlerMock).toBeCalledTimes(1); // Check that the wrap up is waiting for the promise to be resolved. - expect((listener.stop as jest.Mock).mock.calls.length).toBe(0); - expect(processKillSpy.mock.calls.length).toBe(0); + expect(listener.stop).not.toBeCalled(); + expect(processKillSpy).not.toBeCalled(); // Calling .then since the wrapUp handler does not throw. (handlerPromise as Promise).then(() => { // Clean up is called. - expect((listener.stop as jest.Mock).mock.calls.length).toBe(1); + expect(listener.stop).toBeCalledTimes(1); // It called for kill again, so the shutdown keeps going. - expect(processKillSpy.mock.calls.length).toBe(1); + expect(processKillSpy).toBeCalledTimes(1); expect(processKillSpy.mock.calls).toEqual([[process.pid, 'SIGTERM']]); /* Clean up everything */ diff --git a/src/readiness/__tests__/sdkReadinessManager.spec.ts b/src/readiness/__tests__/sdkReadinessManager.spec.ts index ca032224..3cc3c765 100644 --- a/src/readiness/__tests__/sdkReadinessManager.spec.ts +++ b/src/readiness/__tests__/sdkReadinessManager.spec.ts @@ -57,7 +57,7 @@ describe('SDK Readiness Manager - Event emitter', () => { expect(sdkStatus.Event.SDK_READY_TIMED_OUT).toBe(SDK_READY_TIMED_OUT); // which contains the constants for the events, for backwards compatibility. expect(sdkStatus.Event.SDK_UPDATE).toBe(SDK_UPDATE); // which contains the constants for the events, for backwards compatibility. - expect(gateMock.once.mock.calls.length).toBe(3); // It should make three one time only subscriptions + expect(gateMock.once).toBeCalledTimes(3); // It should make three one time only subscriptions const sdkReadyResolvePromiseCall = gateMock.once.mock.calls[0]; const sdkReadyRejectPromiseCall = gateMock.once.mock.calls[1]; @@ -66,7 +66,7 @@ describe('SDK Readiness Manager - Event emitter', () => { expect(sdkReadyRejectPromiseCall[0]).toBe(SDK_READY_TIMED_OUT); // A one time only subscription is also on the SDK_READY_TIMED_OUT event, for rejecting the full blown ready promise. expect(sdkReadyFromCacheListenersCheckCall[0]).toBe(SDK_READY_FROM_CACHE); // A one time only subscription is on the SDK_READY_FROM_CACHE event, to log the event and update internal state. - expect(gateMock.on.mock.calls.length).toBe(2); // It should also add two persistent listeners + expect(gateMock.on).toBeCalledTimes(2); // It should also add two persistent listeners const removeListenerSubCall = gateMock.on.mock.calls[0]; const addListenerSubCall = gateMock.on.mock.calls[1]; @@ -81,7 +81,7 @@ describe('SDK Readiness Manager - Event emitter', () => { const readyFromCacheEventCB = gateMock.once.mock.calls[2][1]; readyFromCacheEventCB(); - expect(loggerMock.info.mock.calls.length).toBe(1); // If the SDK_READY_FROM_CACHE event fires, we get a info message. + expect(loggerMock.info).toBeCalledTimes(1); // If the SDK_READY_FROM_CACHE event fires, we get a info message. expect(loggerMock.info).toBeCalledWith(CLIENT_READY_FROM_CACHE); // Telling us the SDK is ready to be used with data from cache. }); @@ -93,15 +93,15 @@ describe('SDK Readiness Manager - Event emitter', () => { emitReadyEvent(sdkReadinessManager.readinessManager); - expect(loggerMock.warn.mock.calls.length).toBe(1); // If the SDK_READY event fires and we have no callbacks for it (neither event nor ready promise) we get a warning. + expect(loggerMock.warn).toBeCalledTimes(1); // If the SDK_READY event fires and we have no callbacks for it (neither event nor ready promise) we get a warning. expect(loggerMock.warn).toBeCalledWith(CLIENT_NO_LISTENER); // Telling us there were no listeners and evaluations before this point may have been incorrect. - expect(loggerMock.info.mock.calls.length).toBe(1); // If the SDK_READY event fires, we get a info message. + expect(loggerMock.info).toBeCalledTimes(1); // If the SDK_READY event fires, we get a info message. expect(loggerMock.info).toBeCalledWith(CLIENT_READY); // Telling us the SDK is ready. // Now it's marked as ready. addListenerCB('this event we do not care'); - expect(loggerMock.error.mock.calls.length).toBe(0); // Now if we add a listener to an event unrelated with readiness, we get no errors logged. + expect(loggerMock.error).not.toBeCalled(); // Now if we add a listener to an event unrelated with readiness, we get no errors logged. addListenerCB(SDK_READY); expect(loggerMock.error).toBeCalledWith(ERROR_CLIENT_LISTENER, ['SDK_READY']); // If we try to add a listener for the already emitted SDK_READY event, we get the corresponding error. @@ -118,14 +118,14 @@ describe('SDK Readiness Manager - Event emitter', () => { const addListenerCB = sdkReadinessManager.readinessManager.gate.on.mock.calls[1][1]; addListenerCB(SDK_READY); - expect(loggerMock.warn.mock.calls.length).toBe(0); // We are adding a listener to the ready event before it is ready, so no warnings are logged. - expect(loggerMock.error.mock.calls.length).toBe(0); // We are adding a listener to the ready event before it is ready, so no errors are logged. + expect(loggerMock.warn).not.toBeCalled(); // We are adding a listener to the ready event before it is ready, so no warnings are logged. + expect(loggerMock.error).not.toBeCalled(); // We are adding a listener to the ready event before it is ready, so no errors are logged. emitReadyEvent(sdkReadinessManager.readinessManager); - expect(loggerMock.warn.mock.calls.length).toBe(0); // As we had at least one listener, we get no warnings. - expect(loggerMock.error.mock.calls.length).toBe(0); // As we had at least one listener, we get no errors. + expect(loggerMock.warn).not.toBeCalled(); // As we had at least one listener, we get no warnings. + expect(loggerMock.error).not.toBeCalled(); // As we had at least one listener, we get no errors. - expect(loggerMock.info.mock.calls.length).toBe(1); // If the SDK_READY event fires, we get a info message. + expect(loggerMock.info).toBeCalledTimes(1); // If the SDK_READY event fires, we get a info message. expect(loggerMock.info).toBeCalledWith(CLIENT_READY); // Telling us the SDK is ready. }); @@ -167,7 +167,7 @@ describe('SDK Readiness Manager - Event emitter', () => { removeListenerCB('random event'); emitReadyEvent(sdkReadinessManager.readinessManager); - expect(loggerMock.warn.mock.calls.length).toBe(0); // No warning when the SDK is ready as we still have one listener. + expect(loggerMock.warn).not.toBeCalled(); // No warning when the SDK is ready as we still have one listener. }); test('The event callbacks should work as expected - SDK_READY emits with expected internal callbacks', () => { @@ -184,12 +184,12 @@ describe('SDK Readiness Manager - Event emitter', () => { addListenerCB(SDK_READY); removeListenerCB(SDK_READY); - expect(loggerMock.warn.mock.calls.length).toBe(0); // We are adding/removing listeners to the ready event before it is ready, so no warnings are logged. - expect(loggerMock.error.mock.calls.length).toBe(0); // We are adding/removing listeners to the ready event before it is ready, so no errors are logged. + expect(loggerMock.warn).not.toBeCalled(); // We are adding/removing listeners to the ready event before it is ready, so no warnings are logged. + expect(loggerMock.error).not.toBeCalled(); // We are adding/removing listeners to the ready event before it is ready, so no errors are logged. emitReadyEvent(sdkReadinessManager.readinessManager); - expect(loggerMock.warn.mock.calls.length).not.toBe(0); // As we had the same amount of listeners that the expected, we get a warning. - expect(loggerMock.error.mock.calls.length).toBe(0); // As we had at least one listener, we get no errors. + expect(loggerMock.warn).toBeCalled(); // As we had the same amount of listeners that the expected, we get a warning. + expect(loggerMock.error).not.toBeCalled(); // As we had at least one listener, we get no errors. }); }); diff --git a/src/sdkClient/__tests__/sdkClientMethod.spec.ts b/src/sdkClient/__tests__/sdkClientMethod.spec.ts index 278ec615..5adc1d88 100644 --- a/src/sdkClient/__tests__/sdkClientMethod.spec.ts +++ b/src/sdkClient/__tests__/sdkClientMethod.spec.ts @@ -40,14 +40,14 @@ test.each(paramMocks)('sdkClientMethodFactory', (params) => { // `client.destroy` method should stop internal components (other client methods where validated in `client.spec.ts`) client.destroy().then(() => { - expect(params.sdkReadinessManager.readinessManager.destroy.mock.calls.length).toBe(1); + expect(params.sdkReadinessManager.readinessManager.destroy).toBeCalledTimes(1); expect(params.storage.destroy).toBeCalledTimes(1); if (params.syncManager) { expect(params.syncManager.stop).toBeCalledTimes(1); expect(params.syncManager.flush).toBeCalledTimes(1); } - if (params.signalListener) expect(params.signalListener.stop.mock.calls.length).toBe(1); + if (params.signalListener) expect(params.signalListener.stop).toBeCalledTimes(1); }); // calling the function with parameters should throw an error diff --git a/src/storages/inRedis/__tests__/ImpressionsCacheInRedis.spec.ts b/src/storages/inRedis/__tests__/ImpressionsCacheInRedis.spec.ts index 70e4724a..36892885 100644 --- a/src/storages/inRedis/__tests__/ImpressionsCacheInRedis.spec.ts +++ b/src/storages/inRedis/__tests__/ImpressionsCacheInRedis.spec.ts @@ -96,9 +96,9 @@ test('IMPRESSIONS CACHE IN REDIS / should not resolve track before calling expir // @ts-expect-error c.track([i1, i2]).then(() => { connection.quit(); // Try to disconnect right away. - expect(spy1.mock.calls.length).not.toBe(0); // Redis rpush was called once before executing external callback. + expect(spy1).toBeCalled(); // Redis rpush was called once before executing external callback. // Following assertion fails if the expire takes place after disconnected and throws unhandledPromiseRejection - expect(spy2.mock.calls.length).not.toBe(0); // Redis expire was called once before executing external callback. + expect(spy2).toBeCalled(); // Redis expire was called once before executing external callback. }).catch(e => { throw new Error(`An error was generated from the redis expire tests: ${e}`); }).then(() => { diff --git a/src/storages/inRedis/__tests__/RedisAdapter.spec.ts b/src/storages/inRedis/__tests__/RedisAdapter.spec.ts index 918c895e..ba369d8c 100644 --- a/src/storages/inRedis/__tests__/RedisAdapter.spec.ts +++ b/src/storages/inRedis/__tests__/RedisAdapter.spec.ts @@ -276,7 +276,7 @@ describe('STORAGE Redis Adapter', () => { expect(ioredisMock[methodName]).toBeCalled(); // Original method (${methodName}) is called right away (through wrapper) when we are not queueing anymore. expect(instance._runningCommands.size).toBe(previousRunningCommandsSize + 1); // If the result of the operation was a thenable it will add the item to the running commands queue. - expect(timeout.mock.calls.length).toBe(previousTimeoutCalls + 1); // The promise returned by the original method should have a timeout wrapper. + expect(timeout).toBeCalledTimes(previousTimeoutCalls + 1); // The promise returned by the original method should have a timeout wrapper. // Get the original promise (the one passed to timeout) const commandTimeoutResolver = timeoutPromiseResolvers[0]; diff --git a/src/sync/polling/syncTasks/__tests__/splitChangesUpdater.spec.ts b/src/sync/polling/syncTasks/__tests__/splitChangesUpdater.spec.ts index ef1e20aa..9fb8ab89 100644 --- a/src/sync/polling/syncTasks/__tests__/splitChangesUpdater.spec.ts +++ b/src/sync/polling/syncTasks/__tests__/splitChangesUpdater.spec.ts @@ -73,11 +73,11 @@ test('splitChangesUpdater / factory', (done) => { const splitChangesUpdater = splitChangesUpdaterFactory(loggerMock, splitChangesFetcher, splitsCache, segmentsCache, readinessManager.splits, 1000, 1); splitChangesUpdater().then((result) => { - expect(setChangeNumber.mock.calls.length).toBe(1); + expect(setChangeNumber).toBeCalledTimes(1); expect(setChangeNumber).lastCalledWith(splitChangesMock1.till); - expect(addSplits.mock.calls.length).toBe(1); + expect(addSplits).toBeCalledTimes(1); expect(addSplits.mock.calls[0][0].length).toBe(splitChangesMock1.splits.length); - expect(removeSplits.mock.calls.length).toBe(1); + expect(removeSplits).toBeCalledTimes(1); expect(removeSplits).lastCalledWith([]); expect(registerSegments).toBeCalledTimes(1); expect(splitsEmitSpy).toBeCalledWith('SDK_SPLITS_ARRIVED'); diff --git a/src/sync/streaming/SSEClient/__tests__/index.spec.ts b/src/sync/streaming/SSEClient/__tests__/index.spec.ts index 0e1e3170..c660ad09 100644 --- a/src/sync/streaming/SSEClient/__tests__/index.spec.ts +++ b/src/sync/streaming/SSEClient/__tests__/index.spec.ts @@ -35,7 +35,7 @@ test('SSClient / setEventHandler, open and close methods', () => { instance.open(authDataSample); let esconnection = instance.connection; // instance of EventSource used to mock events esconnection.emitOpen(); - expect(handler.handleOpen.mock.calls.length).toBe(1); // handleOpen called when connection is opened + expect(handler.handleOpen).toBeCalledTimes(1); // handleOpen called when connection is opened handler.handleOpen.mockClear(); // emit message @@ -56,25 +56,25 @@ test('SSClient / setEventHandler, open and close methods', () => { // open attempt without open event emitted instance.open(authDataSample); - expect(handler.handleOpen.mock.calls.length).toBe(0); // handleOpen not called until open event is emitted + expect(handler.handleOpen).not.toBeCalled(); // handleOpen not called until open event is emitted // open a new connection instance.open(authDataSample); instance.connection.emitOpen(); - expect(handler.handleOpen.mock.calls.length).toBe(1); // handleOpen called when connection is open + expect(handler.handleOpen).toBeCalledTimes(1); // handleOpen called when connection is open // reopen the connection handler.handleOpen.mockClear(); instance.reopen(); instance.connection.emitOpen(); - expect(handler.handleOpen.mock.calls.length).toBe(1); // handleOpen called if connection is reopen + expect(handler.handleOpen).toBeCalledTimes(1); // handleOpen called if connection is reopen // remove event handler before opening a new connection handler.handleOpen.mockClear(); instance.setEventHandler(undefined); instance.open(authDataSample); instance.connection.emitOpen(); - expect(handler.handleOpen.mock.calls.length).toBe(0); // handleOpen not called if connection is open but the handler was removed + expect(handler.handleOpen).not.toBeCalled(); // handleOpen not called if connection is open but the handler was removed }); diff --git a/src/trackers/__tests__/eventTracker.spec.ts b/src/trackers/__tests__/eventTracker.spec.ts index 7c6b11fb..0edb462e 100644 --- a/src/trackers/__tests__/eventTracker.spec.ts +++ b/src/trackers/__tests__/eventTracker.spec.ts @@ -50,7 +50,7 @@ describe('Event Tracker', () => { const result1 = tracker.track(fakeEvent, 1); expect(fakeEventsCache.track.mock.calls[0]).toEqual([fakeEvent, 1]); // Should be present in the event cache. - expect(fakeIntegrationsManager.handleEvent.mock.calls.length).toBe(0); // The integration manager handleEvent method should not be executed synchronously. + expect(fakeIntegrationsManager.handleEvent).not.toBeCalled(); // The integration manager handleEvent method should not be executed synchronously. expect(result1).toBe(true); // Should return the value of the event cache. setTimeout(() => { @@ -65,14 +65,14 @@ describe('Event Tracker', () => { expect(tracked).toBe(false); // Should return the value of the event cache resolved promise. setTimeout(() => { - expect(fakeIntegrationsManager.handleEvent.mock.calls.length).toBe(1); // Untracked event should not be sent to integration manager. + expect(fakeIntegrationsManager.handleEvent).toBeCalledTimes(1); // Untracked event should not be sent to integration manager. const result3 = tracker.track(fakeEvent, 3) as Promise; expect(fakeEventsCache.track.mock.calls[2]).toEqual([fakeEvent, 3]); // Should be present in the event cache. result3.then(tracked => { - expect(fakeIntegrationsManager.handleEvent.mock.calls.length).toBe(1); // Tracked event should not be sent to integration manager synchronously + expect(fakeIntegrationsManager.handleEvent).toBeCalledTimes(1); // Tracked event should not be sent to integration manager synchronously expect(tracked).toBe(true); // Should return the value of the event cache resolved promise. setTimeout(() => { diff --git a/src/trackers/__tests__/impressionsTracker.spec.ts b/src/trackers/__tests__/impressionsTracker.spec.ts index 43988799..9a89a61d 100644 --- a/src/trackers/__tests__/impressionsTracker.spec.ts +++ b/src/trackers/__tests__/impressionsTracker.spec.ts @@ -55,7 +55,7 @@ describe('Impressions Tracker', () => { feature: '30', } as ImpressionDTO; - expect(fakeImpressionsCache.track.mock.calls.length).toBe(0); // cache method should not be called by just creating a tracker + expect(fakeImpressionsCache.track).not.toBeCalled(); // cache method should not be called by just creating a tracker tracker.track([imp1, imp2, imp3]); @@ -76,20 +76,20 @@ describe('Impressions Tracker', () => { fake: 'attributes' }; - expect(fakeImpressionsCache.track.mock.calls.length).toBe(0); // The storage should not be invoked if we haven't tracked impressions. - expect(fakeListener.logImpression.mock.calls.length).toBe(0); // The listener should not be invoked if we haven't tracked impressions. - expect(fakeIntegrationsManager.handleImpression.mock.calls.length).toBe(0); // The integrations manager handleImpression method should not be invoked if we haven't tracked impressions. + expect(fakeImpressionsCache.track).not.toBeCalled(); // The storage should not be invoked if we haven't tracked impressions. + expect(fakeListener.logImpression).not.toBeCalled(); // The listener should not be invoked if we haven't tracked impressions. + expect(fakeIntegrationsManager.handleImpression).not.toBeCalled(); // The integrations manager handleImpression method should not be invoked if we haven't tracked impressions. // We signal that we actually want to track the queued impressions. tracker.track([fakeImpression, fakeImpression2], fakeAttributes); expect(fakeImpressionsCache.track.mock.calls[0][0]).toEqual([fakeImpression, fakeImpression2]); // Even with a listener, impression should be sent to the cache - expect(fakeListener.logImpression.mock.calls.length).toBe(0); // The listener should not be executed synchronously. - expect(fakeIntegrationsManager.handleImpression.mock.calls.length).toBe(0); // The integrations manager handleImpression method should not be executed synchronously. + expect(fakeListener.logImpression).not.toBeCalled(); // The listener should not be executed synchronously. + expect(fakeIntegrationsManager.handleImpression).not.toBeCalled(); // The integrations manager handleImpression method should not be executed synchronously. setTimeout(() => { - expect(fakeListener.logImpression.mock.calls.length).toBe(2); // The listener should be executed after the timeout wrapping make it to the queue stack, once per each tracked impression. - expect(fakeIntegrationsManager.handleImpression.mock.calls.length).toBe(2); // The integrations manager handleImpression method should be executed after the timeout wrapping make it to the queue stack, once per each tracked impression. + expect(fakeListener.logImpression).toBeCalledTimes(2); // The listener should be executed after the timeout wrapping make it to the queue stack, once per each tracked impression. + expect(fakeIntegrationsManager.handleImpression).toBeCalledTimes(2); // The integrations manager handleImpression method should be executed after the timeout wrapping make it to the queue stack, once per each tracked impression. const impressionData1 = { impression: fakeImpression, attributes: fakeAttributes, sdkLanguageVersion: fakeMetadata.version, ip: fakeMetadata.ip, hostname: fakeMetadata.hostname }; const impressionData2 = { impression: fakeImpression2, attributes: fakeAttributes, sdkLanguageVersion: fakeMetadata.version, ip: fakeMetadata.ip, hostname: fakeMetadata.hostname }; @@ -143,7 +143,7 @@ describe('Impressions Tracker', () => { impressionsTrackerFactory(loggerMock, fakeImpressionsCache, fakeMetadata, undefined, undefined, impressionObserverCSFactory()) ]; - expect(fakeImpressionsCache.track.mock.calls.length).toBe(0); // storage method should not be called until impressions are tracked. + expect(fakeImpressionsCache.track).not.toBeCalled(); // storage method should not be called until impressions are tracked. trackers.forEach(tracker => { tracker.track([impression, impression2, impression3]); @@ -170,7 +170,7 @@ describe('Impressions Tracker', () => { const impressionCountsCache = new ImpressionCountsCacheInMemory(); const tracker = impressionsTrackerFactory(loggerMock, fakeImpressionsCache, fakeMetadata, undefined, undefined, impressionObserverCSFactory(), impressionCountsCache); - expect(fakeImpressionsCache.track.mock.calls.length).toBe(0); // cache method should not be called by just creating a tracker + expect(fakeImpressionsCache.track).not.toBeCalled(); // cache method should not be called by just creating a tracker tracker.track([impression, impression2, impression3]); diff --git a/src/utils/inputValidation/__tests__/attributes.spec.ts b/src/utils/inputValidation/__tests__/attributes.spec.ts index ae7b2c9b..e414b4ea 100644 --- a/src/utils/inputValidation/__tests__/attributes.spec.ts +++ b/src/utils/inputValidation/__tests__/attributes.spec.ts @@ -25,15 +25,15 @@ describe('INPUT VALIDATION for Attributes', () => { const validAttributes = { amIvalid: 'yes', 'are_you_sure': true, howMuch: 10 }; expect(validateAttributes(loggerMock, validAttributes, 'some_method_attrs')).toEqual(validAttributes); // It should return the passed map if it is valid. - expect(loggerMock.error.mock.calls.length).toBe(0); // Should not log any errors. - expect(loggerMock.warn.mock.calls.length).toBe(0); // It should have not logged any warnings. + expect(loggerMock.error).not.toBeCalled(); // Should not log any errors. + expect(loggerMock.warn).not.toBeCalled(); // It should have not logged any warnings. }); test('Should return the passed value if it is null or undefined (since attributes are optional) without logging any errors', () => { expect(validateAttributes(loggerMock, null, 'some_method_attrs')).toBe(null); // It should return the passed null. expect(validateAttributes(loggerMock, undefined, 'some_method_attrs')).toBe(undefined); // It should return the passed undefined. - expect(loggerMock.error.mock.calls.length).toBe(0); // Should not log any errors. - expect(loggerMock.warn.mock.calls.length).toBe(0); // It should have not logged any warnings. + expect(loggerMock.error).not.toBeCalled(); // Should not log any errors. + expect(loggerMock.warn).not.toBeCalled(); // It should have not logged any warnings. }); test('Should return false and log error if attributes map is invalid', () => { @@ -46,6 +46,6 @@ describe('INPUT VALIDATION for Attributes', () => { loggerMock.error.mockClear(); } - expect(loggerMock.warn.mock.calls.length).toBe(0); // It should have not logged any warnings. + expect(loggerMock.warn).not.toBeCalled(); // It should have not logged any warnings. }); }); diff --git a/src/utils/inputValidation/__tests__/split.spec.ts b/src/utils/inputValidation/__tests__/split.spec.ts index 13ccfaa3..85d14be6 100644 --- a/src/utils/inputValidation/__tests__/split.spec.ts +++ b/src/utils/inputValidation/__tests__/split.spec.ts @@ -39,7 +39,7 @@ describe('INPUT VALIDATION for Split name', () => { expect(validateSplit(loggerMock, 'A_split-name_29', 'some_method_splitName')).toBe('A_split-name_29'); // It should return the provided string if it is valid. expect(loggerMock.error.mock.calls[0]).not.toEqual('some_method_splitName'); // Should not log any errors. - expect(loggerMock.warn.mock.calls.length).toBe(0); // It should have not logged any warnings. + expect(loggerMock.warn).not.toBeCalled(); // It should have not logged any warnings. }); test('Should trim split name if it is a valid string with trimmable spaces and log a warning (if those are enabled)', () => { @@ -51,7 +51,7 @@ describe('INPUT VALIDATION for Split name', () => { loggerMock.warn.mockClear(); } - expect(loggerMock.error.mock.calls.length).toBe(0); // It should have not logged any errors. + expect(loggerMock.error).not.toBeCalled(); // It should have not logged any errors. }); test('Should return false and log error if split name is not a valid string', () => { @@ -66,6 +66,6 @@ describe('INPUT VALIDATION for Split name', () => { loggerMock.error.mockClear(); } - expect(loggerMock.warn.mock.calls.length).toBe(0); // It should have not logged any warnings. + expect(loggerMock.warn).not.toBeCalled(); // It should have not logged any warnings. }); }); diff --git a/src/utils/inputValidation/__tests__/splitExistance.spec.ts b/src/utils/inputValidation/__tests__/splitExistance.spec.ts index 6b72ad87..4bc2b8e8 100644 --- a/src/utils/inputValidation/__tests__/splitExistance.spec.ts +++ b/src/utils/inputValidation/__tests__/splitExistance.spec.ts @@ -23,8 +23,8 @@ describe('Split existance (special case)', () => { expect(validateSplitExistance(loggerMock, readinessManagerMock, 'some_split', 'a label', 'test_method')).toBe(true); // Should always return true when the SDK is not ready. expect(validateSplitExistance(loggerMock, readinessManagerMock, 'some_split', LabelConstants.SPLIT_NOT_FOUND, 'test_method')).toBe(true); // Should always return true when the SDK is not ready. - expect(loggerMock.warn.mock.calls.length).toBe(0); // There should have been no warning logs since the SDK was not ready yet. - expect(loggerMock.error.mock.calls.length).toBe(0); // There should have been no error logs since the SDK was not ready yet. + expect(loggerMock.warn).not.toBeCalled(); // There should have been no warning logs since the SDK was not ready yet. + expect(loggerMock.error).not.toBeCalled(); // There should have been no error logs since the SDK was not ready yet. // Prepare the mock to fake that the SDK is ready now. (readinessManagerMock.isReady as jest.Mock).mockImplementation(() => true); @@ -32,16 +32,16 @@ describe('Split existance (special case)', () => { expect(validateSplitExistance(loggerMock, readinessManagerMock, 'other_split', {}, 'other_method')).toBe(true); // Should return true if it receives a Split Object instead of null (when the object is not found, for manager). expect(validateSplitExistance(loggerMock, readinessManagerMock, 'other_split', 'a label', 'other_method')).toBe(true); // Should return true if it receives a Label and it is not split not found (when the Split was not found on the storage, for client). - expect(loggerMock.warn.mock.calls.length).toBe(0); // There should have been no warning logs since the values we used so far were considered valid. - expect(loggerMock.error.mock.calls.length).toBe(0); // There should have been no error logs since the values we used so far were considered valid. + expect(loggerMock.warn).not.toBeCalled(); // There should have been no warning logs since the values we used so far were considered valid. + expect(loggerMock.error).not.toBeCalled(); // There should have been no error logs since the values we used so far were considered valid. expect(validateSplitExistance(loggerMock, readinessManagerMock, 'other_split', null, 'other_method')).toBe(false); // Should return false if it receives a non-truthy value as a split object or label expect(validateSplitExistance(loggerMock, readinessManagerMock, 'other_split', undefined, 'other_method')).toBe(false); // Should return false if it receives a non-truthy value as a split object or label expect(validateSplitExistance(loggerMock, readinessManagerMock, 'other_split', LabelConstants.SPLIT_NOT_FOUND, 'other_method')).toBe(false); // Should return false if it receives a label but it is the split not found one. - expect(loggerMock.warn.mock.calls.length).toBe(3); // It should have logged 3 warnings, one per each time we called it + expect(loggerMock.warn).toBeCalledTimes(3); // It should have logged 3 warnings, one per each time we called it loggerMock.warn.mock.calls.forEach(call => expect(call).toEqual([WARN_NOT_EXISTENT_SPLIT, ['other_method', 'other_split']])); // Warning logs should have the correct message. - expect(loggerMock.error.mock.calls.length).toBe(0); // We log warnings, not errors. + expect(loggerMock.error).not.toBeCalled(); // We log warnings, not errors. }); }); diff --git a/src/utils/inputValidation/__tests__/splits.spec.ts b/src/utils/inputValidation/__tests__/splits.spec.ts index a4d51b71..221cbf1b 100644 --- a/src/utils/inputValidation/__tests__/splits.spec.ts +++ b/src/utils/inputValidation/__tests__/splits.spec.ts @@ -43,32 +43,32 @@ describe('INPUT VALIDATION for Split names', () => { const validArr = ['splitName1', 'split_name_2', 'split-name-3']; expect(validateSplits(loggerMock, validArr, 'some_method_splits')).toEqual(validArr); // It should return the provided array without changes if it is valid. - expect(validateSplitMock.mock.calls.length).toBe(validArr.length); // Should have validated each value independently. - expect(loggerMock.error.mock.calls.length).toBe(0); // Should not log any errors on the collection. + expect(validateSplitMock).toBeCalledTimes(validArr.length); // Should have validated each value independently. + expect(loggerMock.error).not.toBeCalled(); // Should not log any errors on the collection. - expect(loggerMock.warn.mock.calls.length).toBe(0); // It should have not logged any warnings. + expect(loggerMock.warn).not.toBeCalled(); // It should have not logged any warnings. }); test('Should return the provided array if it is a valid splits names array removing duplications, without logging any errors', () => { const validArr = ['split_name', 'split_name', 'split-name']; expect(validateSplits(loggerMock, validArr, 'some_method_splits')).toEqual(uniq(validArr)); // It should return the provided array without changes if it is valid. - expect(validateSplitMock.mock.calls.length).toBe(validArr.length); // Should have validated each value independently. - expect(loggerMock.error.mock.calls.length).toBe(0); // Should not log any errors on the collection. + expect(validateSplitMock).toBeCalledTimes(validArr.length); // Should have validated each value independently. + expect(loggerMock.error).not.toBeCalled(); // Should not log any errors on the collection. - expect(loggerMock.warn.mock.calls.length).toBe(0); // It should have not logged any warnings. + expect(loggerMock.warn).not.toBeCalled(); // It should have not logged any warnings. }); test('Should return false and log an error for the array if it is invalid', () => { for (let i = 0; i < invalidSplits.length; i++) { expect(validateSplits(loggerMock, invalidSplits[i], 'test_method')).toBe(false); // It will return false as the array is of an incorrect type. expect(loggerMock.error).toBeCalledWith(ERROR_EMPTY_ARRAY, ['test_method', 'split_names']); // Should log the error for the collection. - expect(validateSplitMock.mock.calls.length).toBe(0); // Should not try to validate any inner value if there is no valid array. + expect(validateSplitMock).not.toBeCalled(); // Should not try to validate any inner value if there is no valid array. loggerMock.error.mockClear(); } - expect(loggerMock.warn.mock.calls.length).toBe(0); // It should have not logged any warnings. + expect(loggerMock.warn).not.toBeCalled(); // It should have not logged any warnings. }); test('Should strip out any invalid value from the array', () => { @@ -82,7 +82,7 @@ describe('INPUT VALIDATION for Split names', () => { expect(validateSplitMock.mock.calls[i]).toEqual([loggerMock, myArr[i], 'test_method', 'split name']); // Should validate any inner value independently. } - expect(loggerMock.error.mock.calls.length).toBe(0); // Should not log any error for the collection. - expect(loggerMock.warn.mock.calls.length).toBe(0); // It should have not logged any warnings for the collection. + expect(loggerMock.error).not.toBeCalled(); // Should not log any error for the collection. + expect(loggerMock.warn).not.toBeCalled(); // It should have not logged any warnings for the collection. }); }); diff --git a/src/utils/inputValidation/__tests__/trafficType.spec.ts b/src/utils/inputValidation/__tests__/trafficType.spec.ts index 43355676..bbea3d23 100644 --- a/src/utils/inputValidation/__tests__/trafficType.spec.ts +++ b/src/utils/inputValidation/__tests__/trafficType.spec.ts @@ -33,13 +33,13 @@ describe('INPUT VALIDATION for Traffic Types', () => { test('Should return the provided traffic type if it is a valid string without logging any errors', () => { expect(validateTrafficType(loggerMock, 'traffictype', 'some_method_trafficType')).toBe('traffictype'); // It should return the provided string if it is valid. - expect(loggerMock.error.mock.calls.length).toBe(0); // Should not log any errors. + expect(loggerMock.error).not.toBeCalled(); // Should not log any errors. expect(validateTrafficType(loggerMock, 'traffic_type', 'some_method_trafficType')).toBe('traffic_type'); // It should return the provided string if it is valid. - expect(loggerMock.error.mock.calls.length).toBe(0); // Should not log any errors. + expect(loggerMock.error).not.toBeCalled(); // Should not log any errors. expect(validateTrafficType(loggerMock, 'traffic-type-23', 'some_method_trafficType')).toBe('traffic-type-23'); // It should return the provided string if it is valid. - expect(loggerMock.error.mock.calls.length).toBe(0); // Should not log any errors. + expect(loggerMock.error).not.toBeCalled(); // Should not log any errors. - expect(loggerMock.warn.mock.calls.length).toBe(0); // It should have not logged any warnings. + expect(loggerMock.warn).not.toBeCalled(); // It should have not logged any warnings. }); test('Should lowercase the whole traffic type if it is a valid string with uppercases and log a warning (if those are enabled)', () => { @@ -50,7 +50,7 @@ describe('INPUT VALIDATION for Traffic Types', () => { expect(loggerMock.warn.mock.calls[i]).toEqual([WARN_LOWERCASE_TRAFFIC_TYPE, ['some_method_trafficType']]); // Should log a warning. } - expect(loggerMock.error.mock.calls.length).toBe(0); // It should have not logged any errors. + expect(loggerMock.error).not.toBeCalled(); // It should have not logged any errors. }); test('Should return false and log error if traffic type is not a valid string', () => { @@ -62,6 +62,6 @@ describe('INPUT VALIDATION for Traffic Types', () => { expect(loggerMock.error.mock.calls[i]).toEqual([expectedLog, ['test_method']]); // Should log the error for the invalid traffic type. } - expect(loggerMock.warn.mock.calls.length).toBe(0); // It should have not logged any warnings. + expect(loggerMock.warn).not.toBeCalled(); // It should have not logged any warnings. }); }); diff --git a/src/utils/lang/__tests__/index.spec.ts b/src/utils/lang/__tests__/index.spec.ts index 965153b5..51a62ccc 100644 --- a/src/utils/lang/__tests__/index.spec.ts +++ b/src/utils/lang/__tests__/index.spec.ts @@ -139,7 +139,7 @@ test('LANG UTILS / find', () => { const obj = { myKey: 'myVal', myOtherKey: 'myOtherVal' }; find(obj, spy); - expect(spy.mock.calls.length === 2).toBe(true); // The iteratee should be called as many times as elements we have on the collection. + expect(spy).toBeCalledTimes(2); // The iteratee should be called as many times as elements we have on the collection. expect(spy.mock.calls[0]).toEqual(['myVal', 'myKey', obj]); // When iterating on an object the iteratee should be called with (val, key, collection) expect(spy.mock.calls[1]).toEqual(['myOtherVal', 'myOtherKey', obj]); // When iterating on an object the iteratee should be called with (val, key, collection) @@ -147,7 +147,7 @@ test('LANG UTILS / find', () => { spy.mockClear(); find(arr, spy); - expect(spy.mock.calls.length === 2).toBe(true); // The iteratee should be called as many times as elements we have on the collection. + expect(spy).toBeCalledTimes(2); // The iteratee should be called as many times as elements we have on the collection. expect(spy.mock.calls[0]).toEqual(['one', 0, arr]); // When iterating on an array the iteratee should be called with (val, index, collection) expect(spy.mock.calls[1]).toEqual(['two', 1, arr]); // When iterating on an array the iteratee should be called with (val, index, collection) @@ -486,7 +486,7 @@ test('LANG UTILS / forOwn', () => { const obj = { myKey: 'myVal', myOtherKey: 'myOtherVal' }; forOwn(obj, spy); - expect(spy.mock.calls.length === 2).toBe(true); // The iteratee should be called as many times as elements we have on the object. + expect(spy).toBeCalledTimes(2); // The iteratee should be called as many times as elements we have on the object. expect(spy.mock.calls[0]).toEqual(['myVal', 'myKey', obj]); // When iterating on an object the iteratee should be called with (val, key, collection) expect(spy.mock.calls[1]).toEqual(['myOtherVal', 'myOtherKey', obj]); // When iterating on an object the iteratee should be called with (val, key, collection)