← Files Sulekha EventsARCHIVED FILE
source/test/events.test.js
16 KB · Nov 30, 2026 · 07:53 UTC
import test from "node:test";
import assert from "node:assert/strict";
import { normalizeEvent, searchEvents, searchEventResults } from "../src/data/events.js";
process.env.SULEKHA_EVENTS_WEB_BASE_URL ??= "https://app.example.test/";
process.env.SULEKHA_EVENTS_WEB_SEARCH_PATH ??= "api/1.0/plugai/getsearchresultsnriai";
process.env.SearchApiAuth__ClientId = "test-client";
process.env.SearchApiAuth__Secret = "test-secret";
const metroEvent = {
search: "hostedbyevent",
contentid: 401057,
title: "A Musical Evening",
cityname: "Matawan",
statecode: "NJ",
eventdatetime: "Oct 3, Sat at 7:00 PM",
eventdate: "2026-10-03T19:00:00",
imageurl: "https://usimg.sulekha.io/event.webp",
price: "$25",
eventtrend: "Available",
hostedby: "Sulekha Events",
ticketingid: 2116765,
latitude: 40.4,
longitude: -74.2,
trackurl: "https://events.sulekha.com/event_401057"
};
test("normalizes a staging event record", () => {
assert.deepEqual(normalizeEvent(metroEvent), {
id: "401057",
title: "A Musical Evening",
city: "Matawan",
region: "NJ",
dateTime: "Oct 3, Sat at 7:00 PM",
startsAt: "2026-10-03T19:00:00",
imageUrl: "https://usimg.sulekha.io/event.webp",
price: "$25",
startPrice: undefined,
soldOut: undefined,
status: "Available",
organizer: "Sulekha Events",
url: "https://events.sulekha.com/event_401057",
latitude: 40.4,
longitude: -74.2
});
});
test("event posters prefer eveimageurl and retain valid legacy fallbacks", () => {
const poster = "https://usimg.sulekha.io/event-poster.webp";
assert.equal(normalizeEvent({ ...metroEvent, eveimageurl: poster }).imageUrl, poster);
for (const eveimageurl of [undefined, null, "", "invalid", "javascript:alert(1)"]) {
assert.equal(normalizeEvent({ ...metroEvent, eveimageurl }).imageUrl, metroEvent.imageurl);
}
assert.equal(normalizeEvent({ ...metroEvent, imageurl: undefined, eveimageurl: poster }).imageUrl, poster);
});
function response(rows) {
const encoded = JSON.stringify(JSON.stringify(rows));
return { ok: true, text: async () => `fncommonsearchsEventHeader(${encoded})` };
}
test("missing upstream media and prices stay absent rather than being invented", () => {
const { imageurl, price, ...row } = metroEvent;
const event = normalizeEvent(row);
assert.equal(event.imageUrl, undefined);
assert.equal(event.price, undefined);
});
test("later duplicate records fill missing image and price before limiting results", async () => {
const { imageurl, price, ...sparse } = metroEvent;
const results = await searchEvents({ limit: 1 }, {
fetchImpl: async () => response([
sparse,
{ ...metroEvent, contentid: 2 },
{ ...metroEvent, search: "latlong" }
])
});
assert.equal(results.length, 1);
assert.equal(results[0].id, String(metroEvent.contentid));
assert.equal(results[0].imageUrl, metroEvent.imageurl);
assert.equal(results[0].price, metroEvent.price);
});
test("zero ticket prices are preserved", () => {
assert.equal(normalizeEvent({ ...metroEvent, price: 0 }).price, "0");
});
test("searches San Jose and filters mixed suggestions before applying the limit", async () => {
const nearby = { ...metroEvent, latitude: 37.34, longitude: -121.89 };
const results = await searchEvents({ query: "music", cityUrl: "san-jose-ca", limit: 2 }, {
fetchImpl: async url => {
for (const [key, value] of Object.entries({
lat: "37.3738", long: "-121.793", perflat: "37.3738", perflong: "-121.793",
radius: "50", passingcityurl: "san-jose-ca", searchtxt: "music", srvtech: "Events"
})) assert.equal(url.searchParams.get(key), value);
return response([metroEvent, { ...nearby, search: "artist" }, nearby, nearby,
{ ...nearby, search: "latlong", contentid: 2 }, { ...nearby, contentid: 3 }]);
}
});
assert.deepEqual(results.map(event => event.id), ["401057", "2"]);
});
test("throws when the staging API fails", async () => {
const fetchImpl = async () => ({ ok: false, status: 503 });
await assert.rejects(() => searchEvents({}, { fetchImpl }), /HTTP 503/);
});
for (const status of [401, 403, 503]) {
test(`classifies upstream HTTP ${status} without exposing credentials`, async () => {
await assert.rejects(searchEvents({}, {
fetchImpl: async () => ({ ok: false, status })
}), { code: status === 503 ? "SEARCH_UPSTREAM_ERROR" : "SEARCH_AUTH_REJECTED" });
});
}
test("rejects an upstream error payload instead of reporting no events", async () => {
const fetchImpl = async () => ({ ok: true, text: async () => JSON.stringify({ error: "unavailable" }) });
await assert.rejects(() => searchEvents({}, { fetchImpl }), /unexpected response/);
});
test("missing coordinates are not converted into zero coordinates", () => {
const event = normalizeEvent({ eventid: 1, latitude: null, longitude: "" });
assert.equal(event.latitude, undefined);
assert.equal(event.longitude, undefined);
});
for (const mode of ["missing", "blank", "override"]) {
test(`API settings: ${mode} environment values`, async (t) => {
const keys = ["SULEKHA_EVENTS_WEB_BASE_URL", "SULEKHA_EVENTS_WEB_SEARCH_PATH"];
const previous = keys.map(key => process.env[key]);
t.after(() => keys.forEach((key, index) => {
if (previous[index] === undefined) delete process.env[key];
else process.env[key] = previous[index];
}));
if (mode === "missing") keys.forEach(key => delete process.env[key]);
if (mode === "blank") keys.forEach(key => { process.env[key] = " "; });
if (mode === "override") {
process.env[keys[0]] = " https://override.example.test/ ";
process.env[keys[1]] = " custom/search ";
}
let requested;
await searchEvents({ cityUrl: "new-york-ny" }, { fetchImpl: async (url) => {
requested = url;
return response([]);
}});
const expected = mode === "override"
? "https://override.example.test/custom/search"
: "https://sulnriwebapps.azurewebsites.net/api/1.0/plugai/getsearchresultsnriai";
assert.equal(requested.origin + requested.pathname, expected);
assert.equal(requested.searchParams.get("lat"), "40.7128");
assert.equal(requested.searchParams.get("long"), "-74.006");
});
}
test("signatures cover the encoded request and each request has a fresh nonce", async () => {
const { webcrypto } = await import("node:crypto");
const key = await webcrypto.subtle.importKey("raw", new TextEncoder().encode("test-secret"),
{ name: "HMAC", hash: "SHA-256" }, false, ["verify"]);
const nonces = new Set();
const fetchImpl = async (url, options) => {
const h = options.headers;
assert.equal(h["X-Client-Id"], "test-client");
assert.equal(options.method, "GET");
assert.equal(options.redirect, "error");
assert.ok(Math.abs(Date.now() / 1000 - Number(h["X-Timestamp"])) < 2);
assert.ok(h["X-Nonce"].length > 0 && h["X-Nonce"].length <= 100);
assert.ok(!nonces.has(h["X-Nonce"]));
nonces.add(h["X-Nonce"]);
assert.match(h["X-Signature"], /^[a-f0-9]{64}$/);
const payload = `${h["X-Timestamp"]}\n${h["X-Nonce"]}\nGET\n${url.pathname}${url.search}`;
const verify = text => webcrypto.subtle.verify("HMAC", key,
Buffer.from(h["X-Signature"], "hex"), new TextEncoder().encode(text));
assert.equal(await verify(payload), true);
assert.equal(await verify(payload + "&tampered=1"), false);
assert.equal(url.searchParams.get("searchtxt"), "music & dance + தமிழ்");
return response([]);
};
for (let i = 0; i < 2; i++) await searchEvents({ query: "music & dance + தமிழ்" }, { fetchImpl });
});
for (const key of ["SearchApiAuth__ClientId", "SearchApiAuth__Secret"]) {
for (const value of [undefined, "", " "]) {
test(`rejects missing/blank ${key}: ${JSON.stringify(value)}`, async t => {
const previous = process.env[key];
t.after(() => { process.env[key] = previous; });
if (value === undefined) delete process.env[key];
else process.env[key] = value;
await assert.rejects(searchEvents({}, { fetchImpl: async () => {
assert.fail("Unauthenticated requests must never be sent");
}}), { code: "SEARCH_AUTH_NOT_CONFIGURED" });
});
}
}
test("location-only PA search leaves the keyword empty and excludes neighboring states and artists", async () => {
const result = await searchEvents({ stateCode: "pa", latitude: 40.9, longitude: -77.8, distance: 500, limit: 2 }, {
fetchImpl: async url => {
assert.equal(url.searchParams.get("searchtxt"), "");
assert.equal(url.searchParams.get("cityurl"), "");
return response([
metroEvent,
{ ...metroEvent, contentid: 479, search: "artist", statecode: "PA", mapurl: "https://events.sulekha.com/fake_event-in_pa_479" },
{ ...metroEvent, contentid: 2, statecode: "PA", cityname: "Pittsburgh", latitude: 40.44, longitude: -79.99 },
{ ...metroEvent, contentid: 3, statecode: "PA", cityname: "Philadelphia", latitude: 39.95, longitude: -75.16 }
]);
}
});
assert.deepEqual(result.map(event => event.id), ["2", "3"]);
});
for (const stateCode of ["NJ", "CA", "TX"]) {
test(`location-only ${stateCode} search filters state before limiting`, async () => {
const result = await searchEvents({ stateCode, limit: 1 }, {
fetchImpl: async url => {
assert.equal(url.searchParams.get("searchtxt"), "");
return response([
{ ...metroEvent, statecode: "NY" },
{ ...metroEvent, contentid: 2, statecode: stateCode }
]);
}
});
assert.deepEqual(result.map(event => event.region), [stateCode]);
});
}
test("explicit artist searches preserve the keyword but return only event records", async () => {
const result = await searchEvents({ query: "Sonu Nigam", stateCode: "NJ" }, {
fetchImpl: async url => {
assert.equal(url.searchParams.get("searchtxt"), "Sonu Nigam");
return response([{ ...metroEvent, search: "artist" }, { ...metroEvent, title: "Sonu Nigam Live" }]);
}
});
assert.equal(result.length, 1);
assert.equal(result[0].title, "Sonu Nigam Live");
});
test("Canada searches preserve user keywords and exclude US events before limiting", async () => {
const results = await searchEvents({ query: "தமிழ் live music", country: "CA", stateCode: "ON", limit: 1 }, {
fetchImpl: async url => {
assert.equal(url.searchParams.get("searchtxt"), "தமிழ் live music");
return response([metroEvent,
{ ...metroEvent, contentid: 2, statecode: "BC" },
{ ...metroEvent, contentid: 3, statecode: "ON", cityname: "Toronto" }]);
}
});
assert.deepEqual(results.map(event => event.id), ["3"]);
});
test("US searches exclude Canadian records", async () => {
const results = await searchEvents({ country: "US" }, {
fetchImpl: async () => response([{ ...metroEvent, statecode: "ON" }, metroEvent])
});
assert.equal(results.length, 1);
assert.equal(results[0].region, "NJ");
});
for (const [country, stateCode] of [["CA", "CA"], ["US", "ON"]]) {
test(`rejects incompatible country ${country} and region ${stateCode}`, async () => {
await assert.rejects(searchEvents({ country, stateCode }, {
fetchImpl: async () => assert.fail("Invalid location must not reach upstream")
}), { code: "SEARCH_INVALID_LOCATION" });
});
}
test("forwards the complete original message unchanged alongside extracted keywords", async () => {
const rawQuery = " Show me தமிழ் music & dance in Toronto?!\nUnder $50 + friends ";
await searchEvents({ rawQuery, query: "தமிழ் music & dance", country: "CA" }, {
fetchImpl: async (url, options) => {
assert.equal(url.searchParams.get("rawQuery"), rawQuery);
assert.equal(url.searchParams.get("searchtxt"), "தமிழ் music & dance");
const { createHmac } = await import("node:crypto");
const headers = options.headers;
const payload = [headers["X-Timestamp"], headers["X-Nonce"], "GET", url.pathname + url.search].join("\n");
assert.equal(headers["X-Signature"], createHmac("sha256", "test-secret").update(payload).digest("hex"));
return response([]);
}
});
});
test("location-only search forwards the original message with empty keywords", async () => {
await searchEvents({ rawQuery: "show me events in PA", stateCode: "PA" }, {
fetchImpl: async url => {
assert.equal(url.searchParams.get("rawQuery"), "show me events in PA");
assert.equal(url.searchParams.get("searchtxt"), "");
return response([]);
}
});
});
test("older clients do not fabricate an original user message", async () => {
await searchEvents({ query: "music" }, {
fetchImpl: async url => {
assert.equal(url.searchParams.has("rawQuery"), false);
return response([]);
}
});
});
test('forwards platform alongside original query', async () => {
for (const platform of ['appsSDK', 'Claude', 'Perplexity', 'unknown']) {
await searchEvents({ rawQuery: 'show me events in PA', stateCode: 'PA' }, {
platform,
fetchImpl: async url => {
assert.equal(url.searchParams.get('platform'), platform);
assert.equal(url.searchParams.get('rawQuery'), 'show me events in PA');
return response([]);
}
});
}
});
test("keeps artist and tour profiles separate, uses API images and deduplicates profile links", async () => {
const artist = { search: "artist", contentid: 12, title: "Sonu Nigam", imageurl: "https://usimg.sulekha.io/sonu.webp", artisteventcount: 3,
statecode: "ST", cityname: "cityname", eventdatetime: "placeholder date", trackurl: "https://events.sulekha.com/sonu-nigam_tickets_artist_12" };
const result = await searchEventResults({ stateCode: "NJ" }, { fetchImpl: async () => response([
metroEvent,
{ ...artist, search: "yoursearch", imageurl: "", artisteventcount: undefined, contentid: 99, isdisplay: 1 },
artist,
{ search: "tour", contentid: 22, title: "Concert tour", imageurl: "", trackurl: "https://events.sulekha.com/music_tour_22" },
{ ...artist, contentid: 23, trackurl: "https://evil.test/profile" },
{ ...artist, contentid: 24, search: "article" },
{ ...artist, contentid: 25, search: "yoursearch", isdisplay: 0, trackurl: "https://events.sulekha.com/hidden_tickets_artist_25" }
]) });
assert.equal(result.events.length, 1);
assert.equal(result.related.length, 2);
assert.equal(result.related[0].imageUrl, artist.imageurl);
assert.equal(result.related[0].eventCount, 3);
assert.equal(result.related[0].kind, "artist");
for (const key of ["dateTime", "startsAt", "city", "region", "latitude", "longitude"]) assert.equal(key in result.related[0], false);
assert.equal(result.related[1].kind, "tour");
assert.equal(result.related[1].imageUrl, undefined);
});
test("venue profiles preserve API images and links without exposing placeholder dates or conflicting states", async () => {
const venue = { search: "venue", contentid: 1035, title: "San Jose Civic", cityname: "San Jose", statecode: "OH", cityurl: "san-jose-ca",
eventdatetime: "placeholder", imageurl: "https://usimg.sulekha.io/venue.webp", trackurl: "https://events.sulekha.com/san-jose-civic-tickets-in-san-jose-ca_venue_1035" };
const result = await searchEventResults({}, { fetchImpl: async () => response([venue, metroEvent]) });
assert.equal(result.related[0].kind, "venue");
assert.equal(result.related[0].imageUrl, venue.imageurl);
assert.equal(result.related[0].url, venue.trackurl);
assert.equal(result.related[0].region, undefined);
assert.equal(result.related[0].dateTime, undefined);
assert.equal(result.events[0].organizer, metroEvent.hostedby);
});
test("starting prices and sold-out flags retain zero and normalize API values", () => {
for (const value of [0, "0", false]) assert.equal(normalizeEvent({ ...metroEvent, soldout: value }).soldOut, false);
for (const value of [1, "1", true]) assert.equal(normalizeEvent({ ...metroEvent, soldout: value }).soldOut, true);
assert.equal(normalizeEvent({ ...metroEvent, startprice: "29.99" }).startPrice, "29.99");
assert.equal(normalizeEvent({ ...metroEvent, startprice: 0 }).startPrice, "0");
assert.equal(normalizeEvent({ ...metroEvent, soldout: "unknown" }).soldOut, undefined);
});
SHA-256: a75a2d81f467d9ab35c73a7465ae1de2363061fb71274dd475af7bd5c321ca46