Skip to content

Commit

Permalink
Refactoring Some More
Browse files Browse the repository at this point in the history
  • Loading branch information
AliRKat committed Oct 14, 2024
1 parent ade4be6 commit ac5c8f1
Show file tree
Hide file tree
Showing 5 changed files with 76 additions and 99 deletions.
55 changes: 35 additions & 20 deletions test/helpers/helper_functions.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
/* eslint-disable no-unused-vars */
/* eslint-disable no-console */
/* global runthis */
var path = require("path");
var assert = require("assert");
var fs = require("fs");
Expand Down Expand Up @@ -203,28 +205,41 @@ function sessionRequestValidator(beginSs, endSs, time, id) {
assert.equal(time, endSs.session_duration);
}
}
/**
* bunch of tests specifically gathered for testing user details
* @param {Object} originalDetails - Original object that contains user details
* @param {Object} details - Object from cly_queue that corresponds to user details recording
*/
function userDetailRequestValidator(originalDetails, details) {
requestBaseParamValidator(details);
var user = JSON.parse(details.user_details);
assert.equal(originalDetails.name, user.name);
assert.equal(originalDetails.username, user.username);
assert.equal(originalDetails.email, user.email);
assert.equal(originalDetails.organization, user.organization);
assert.equal(originalDetails.phone, user.phone);
assert.equal(originalDetails.picture, user.picture);
assert.equal(originalDetails.gender, user.gender);
assert.equal(originalDetails.byear, user.byear);
if (typeof originalDetails.custom !== 'undefined') {
for (var key in originalDetails.custom) {
assert.deepStrictEqual(originalDetails.custom[key], user.custom[key]);

function validateUserDetails(actual, expected) {
// Helper function to remove undefined values
const cleanObj = (obj) => {
if (typeof obj === "string") {
try {
// Parse if it's a JSON string
obj = JSON.parse(obj);
}
catch (e) {
console.error("Invalid JSON string:", obj);
// Return null for invalid JSON
return null;
}
}
// Remove properties with undefined values
return Object.fromEntries(Object.entries(obj).filter(([_, value]) => value !== undefined));
};
const cleanedActual = cleanObj(actual);
const cleanedExpected = cleanObj(expected);
if (!cleanedActual || !cleanedExpected) {
// If either cleaned object is null, validation fails
return false;
}
// Perform deep strict comparison after cleaning up undefined values
try {
assert.deepStrictEqual(cleanedActual, cleanedExpected);
return true;
}
catch (e) {
console.log("Validation failed:", e);
return false;
}
}

/**
* bunch of tests specifically gathered for testing page views
* @param {Object} name - page name
Expand Down Expand Up @@ -257,7 +272,7 @@ module.exports = {
eventValidator,
crashRequestValidator,
sessionRequestValidator,
userDetailRequestValidator,
validateUserDetails,
viewEventValidator,
doesFileStoragePathsExist,
};
4 changes: 1 addition & 3 deletions test/helpers/test_utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,15 +31,13 @@ var userDetailObj = {
phone: "+987654321",
picture: "https://example.com/images/profile_alex.jpg",
gender: "Female",
byear: 1992, // birth year
byear: 1992,
custom: {
string_value: "example",
number_value: 42,
boolean_value: true,
array_value: ["item1", "item2"],
object_value: { nested_key: "nested_value" },
null_value: null,
undefined_value: undefined,
},
};

Expand Down
89 changes: 29 additions & 60 deletions test/tests_bulk.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@ var testUtils = require("./helpers/test_utils");

const { StorageTypes } = CountlyBulk;

var appKey = "YOUR_APP_KEY";
var serverUrl = "https://tests.url.cly";

function validateCrash(validator, nonfatal) {
assert.ok(validator.crash._os);
assert.ok(validator.crash._os_version);
Expand All @@ -20,58 +23,6 @@ function validateCrash(validator, nonfatal) {
assert.equal(true, validator.crash._not_os_specific);
}

// note: this can replace the current one in the helper functions
function validateUserDetails(actual, expected) {
const keys = ['name', 'username', 'email', 'organization', 'phone', 'picture', 'gender', 'byear', 'custom'];
let isValid = true;

keys.forEach((key) => {
if (typeof actual[key] === 'object' && actual[key] !== null) {
if (Array.isArray(actual[key])) {
if (!Array.isArray(expected[key]) || JSON.stringify(actual[key]) !== JSON.stringify(expected[key])) {
console.error(`Mismatch for key "${key}": expected "${JSON.stringify(expected[key])}", but got "${JSON.stringify(actual[key])}"`);
isValid = false;
}
}
else {
if (JSON.stringify(actual[key]) !== JSON.stringify(expected[key])) {
console.error(`Mismatch for key "${key}": expected "${JSON.stringify(expected[key])}", but got "${JSON.stringify(actual[key])}"`);
isValid = false;
}
}
}
else if (actual[key] !== expected[key]) {
console.error(`Mismatch for key "${key}": expected "${expected[key]}", but got "${actual[key]}"`);
isValid = false;
}
});
// Validate nested custom object separately
if (expected.custom && actual.custom) {
const customKeys = Object.keys(expected.custom);
customKeys.forEach((key) => {
if (typeof actual.custom[key] === 'object' && actual.custom[key] !== null) {
if (Array.isArray(actual.custom[key])) {
if (!Array.isArray(expected.custom[key]) || JSON.stringify(actual.custom[key]) !== JSON.stringify(expected.custom[key])) {
console.error(`Mismatch in custom object for key "${key}": expected "${JSON.stringify(expected.custom[key])}", but got "${JSON.stringify(actual.custom[key])}"`);
isValid = false;
}
}
else {
if (JSON.stringify(actual.custom[key]) !== JSON.stringify(expected.custom[key])) {
console.error(`Mismatch in custom object for key "${key}": expected "${JSON.stringify(expected.custom[key])}", but got "${JSON.stringify(actual.custom[key])}"`);
isValid = false;
}
}
}
else if (actual.custom[key] !== expected.custom[key]) {
console.error(`Mismatch in custom object for key "${key}": expected "${expected.custom[key]}", but got "${actual.custom[key]}"`);
isValid = false;
}
});
}
return isValid;
}

// Create bulk data
function createBulkData(bulk) {
// Add an event
Expand Down Expand Up @@ -121,7 +72,7 @@ function validateCreatedBulkData(bulk) {

var req = reqQueue[0]; // read user details queue
const actualUserDetails = req.user_details; // Extract the user_details from the actual request
const isValid = validateUserDetails(actualUserDetails, testUtils.getUserDetailsObj());
const isValid = hp.validateUserDetails(actualUserDetails, testUtils.getUserDetailsObj());
assert.equal(true, isValid);

var testUser3Request = reqQueue.find((request) => request.device_id === "TestUser3");
Expand All @@ -147,8 +98,8 @@ describe("Bulk Tests", () => {

it("1- CNR", (done) => {
var bulk = new CountlyBulk({
app_key: "YOUR_APP_KEY",
url: "https://try.count.ly",
app_key: appKey,
url: serverUrl,
});
assert.equal(storage.getStoragePath(), undefined);
shouldFilesExist(false);
Expand All @@ -163,8 +114,8 @@ describe("Bulk Tests", () => {

it("2- CNR_cPath_file", (done) => {
var bulk = new CountlyBulk({
app_key: "YOUR_APP_KEY",
url: "https://try.count.ly",
app_key: appKey,
url: serverUrl,
storage_path: "../test/customStorageDirectory/",
storage_type: StorageTypes.FILE,
});
Expand All @@ -182,8 +133,8 @@ describe("Bulk Tests", () => {

it("3- CNR_file", (done) => {
var bulk = new CountlyBulk({
app_key: "YOUR_APP_KEY",
url: "https://try.count.ly",
app_key: appKey,
url: serverUrl,
storage_type: StorageTypes.FILE,
});
assert.equal(storage.getStoragePath(), "../bulk_data/");
Expand All @@ -197,9 +148,27 @@ describe("Bulk Tests", () => {
done();
}, hp.mWait);
});

it("4- CNR_memory", (done) => {
var bulk = new CountlyBulk({
app_key: appKey,
url: serverUrl,
storage_type: StorageTypes.MEMORY,
});
assert.equal(storage.getStoragePath(), undefined);
shouldFilesExist(true);
createBulkData(bulk);

setTimeout(() => {
validateCreatedBulkData(bulk);
shouldFilesExist(true);
assert.equal(storage.getStoragePath(), undefined);
done();
}, hp.mWait);
});
});

// Currently tested: CNR, CNR_cPath_file, CNR_file
// TODO: Add tests for the following:
// - CNR: memory, cPath_memory, persistTrue, persistFalse, cPath_persistTrue, cPath_persistFalse, persistTrue_file, persistFalse_file, cPath_persistTrue_file, cPath_persistFalse_file
// - CNR: cPath_memory, persistTrue, persistFalse, cPath_persistTrue, cPath_persistFalse, persistTrue_file, persistFalse_file, cPath_persistTrue_file, cPath_persistFalse_file
// - CR_CG for all of the above
2 changes: 1 addition & 1 deletion test/tests_storage.js
Original file line number Diff line number Diff line change
Expand Up @@ -379,7 +379,7 @@ describe("Storage Tests", () => {
Countly.user_details(testUtils.getUserDetailsObj);
const storedData = storage.storeGet("cly_queue", null);
const userDetailsReq = storedData[0];
hp.userDetailRequestValidator(testUtils.getUserDetailsObj, userDetailsReq);
hp.validateUserDetails(testUtils.getUserDetailsObj, userDetailsReq);
done();
});

Expand Down
25 changes: 10 additions & 15 deletions test/tests_user_details.js
Original file line number Diff line number Diff line change
@@ -1,31 +1,26 @@
/* eslint-disable no-console */
const assert = require("assert");
var Countly = require("../lib/countly");
var hp = require("./helpers/helper_functions");
var testUtils = require("./helpers/test_utils");

// init function
function initMain() {
Countly.init({
app_key: "YOUR_APP_KEY",
url: "https://try.count.ly",
interval: 10000,
max_events: -1,
});
}

describe("User details tests", () => {
beforeEach(async() => {
await hp.clearStorage();
});
it("Record and validate all user details", (done) => {
// initialize SDK
initMain();
// send user details
Countly.user_details(testUtils.getUserDetailsObj());
Countly.init({
app_key: "YOUR_APP_KEY",
url: "https://try.count.ly",
});
var userDetailObj = testUtils.getUserDetailsObj();
Countly.user_details(userDetailObj);
// read event queue
setTimeout(() => {
var req = hp.readRequestQueue()[0];
hp.userDetailRequestValidator(testUtils.getUserDetailsObj(), req);
const actualUserDetails = req.user_details;
const isValid = hp.validateUserDetails(actualUserDetails, userDetailObj);
assert.equal(true, isValid);
done();
}, hp.sWait);
});
Expand Down

0 comments on commit ac5c8f1

Please sign in to comment.