DiscoveryStreamFeed.test.js 64 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852
  1. import {actionCreators as ac, actionTypes as at, actionUtils as au} from "common/Actions.jsm";
  2. import {combineReducers, createStore} from "redux";
  3. import {GlobalOverrider} from "test/unit/utils";
  4. import injector from "inject!lib/DiscoveryStreamFeed.jsm";
  5. import {reducers} from "common/Reducers.jsm";
  6. const CONFIG_PREF_NAME = "discoverystream.config";
  7. const DUMMY_ENDPOINT = "https://getpocket.cdn.mozilla.net/dummy";
  8. const ENDPOINTS_PREF_NAME = "discoverystream.endpoints";
  9. const SPOC_IMPRESSION_TRACKING_PREF = "discoverystream.spoc.impressions";
  10. const REC_IMPRESSION_TRACKING_PREF = "discoverystream.rec.impressions";
  11. const THIRTY_MINUTES = 30 * 60 * 1000;
  12. const ONE_WEEK = 7 * 24 * 60 * 60 * 1000; // 1 week
  13. describe("DiscoveryStreamFeed", () => { // eslint-disable-line max-statements
  14. let DiscoveryStreamFeed;
  15. let feed;
  16. let sandbox;
  17. let fetchStub;
  18. let clock;
  19. let fakeNewTabUtils;
  20. let globals;
  21. const setPref = (name, value) => {
  22. const action = {
  23. type: at.PREF_CHANGED,
  24. data: {
  25. name,
  26. value: typeof value === "object" ? JSON.stringify(value) : value,
  27. },
  28. };
  29. feed.store.dispatch(action);
  30. feed.onAction(action);
  31. };
  32. beforeEach(() => {
  33. sandbox = sinon.createSandbox();
  34. class FakeUserDomainAffinityProvider {
  35. constructor(timeSegments, parameterSets, maxHistoryQueryResults, version, scores) {
  36. this.timeSegments = timeSegments;
  37. this.parameterSets = parameterSets;
  38. this.maxHistoryQueryResults = maxHistoryQueryResults;
  39. this.version = version;
  40. this.scores = scores;
  41. }
  42. getAffinities() {
  43. return {};
  44. }
  45. }
  46. // Fetch
  47. fetchStub = sandbox.stub(global, "fetch");
  48. // Time
  49. clock = sinon.useFakeTimers();
  50. // Injector
  51. ({
  52. DiscoveryStreamFeed,
  53. } = injector({
  54. "lib/UserDomainAffinityProvider.jsm": {UserDomainAffinityProvider: FakeUserDomainAffinityProvider},
  55. }));
  56. // Feed
  57. feed = new DiscoveryStreamFeed();
  58. feed.store = createStore(combineReducers(reducers), {
  59. Prefs: {
  60. values: {
  61. [CONFIG_PREF_NAME]: JSON.stringify({enabled: false, show_spocs: false, layout_endpoint: DUMMY_ENDPOINT}),
  62. [ENDPOINTS_PREF_NAME]: DUMMY_ENDPOINT,
  63. },
  64. },
  65. });
  66. global.fetch.resetHistory();
  67. sandbox.stub(feed, "_maybeUpdateCachedData").resolves();
  68. globals = new GlobalOverrider();
  69. globals.set("setTimeout", callback => { callback(); });
  70. fakeNewTabUtils = {
  71. blockedLinks: {
  72. links: [],
  73. isBlocked: () => false,
  74. },
  75. };
  76. globals.set("NewTabUtils", fakeNewTabUtils);
  77. });
  78. afterEach(() => {
  79. clock.restore();
  80. sandbox.restore();
  81. globals.restore();
  82. });
  83. describe("#fetchFromEndpoint", () => {
  84. beforeEach(() => {
  85. feed._prefCache = {
  86. config: {
  87. api_key_pref: "",
  88. },
  89. };
  90. fetchStub.resolves({
  91. json: () => Promise.resolve("hi"),
  92. ok: true,
  93. });
  94. });
  95. it("should get a response", async () => {
  96. const response = await feed.fetchFromEndpoint(DUMMY_ENDPOINT);
  97. assert.equal(response, "hi");
  98. });
  99. it("should not send cookies", async () => {
  100. await feed.fetchFromEndpoint(DUMMY_ENDPOINT);
  101. assert.propertyVal(fetchStub.firstCall.args[1], "credentials", "omit");
  102. });
  103. it("should allow unexpected response", async () => {
  104. fetchStub.resolves({ok: false});
  105. const response = await feed.fetchFromEndpoint(DUMMY_ENDPOINT);
  106. assert.equal(response, null);
  107. });
  108. it("should disallow unexpected endpoints", async () => {
  109. feed.store.getState = () => ({
  110. Prefs: {values: {[ENDPOINTS_PREF_NAME]: "https://other.site"}},
  111. });
  112. const response = await feed.fetchFromEndpoint(DUMMY_ENDPOINT);
  113. assert.equal(response, null);
  114. });
  115. it("should allow multiple endpoints", async () => {
  116. feed.store.getState = () => ({
  117. Prefs: {values: {[ENDPOINTS_PREF_NAME]: `https://other.site,${DUMMY_ENDPOINT}`}},
  118. });
  119. const response = await feed.fetchFromEndpoint(DUMMY_ENDPOINT);
  120. assert.equal(response, "hi");
  121. });
  122. it("should replace urls with $apiKey", async () => {
  123. sandbox.stub(global.Services.prefs, "getCharPref").returns("replaced");
  124. await feed.fetchFromEndpoint("https://getpocket.cdn.mozilla.net/dummy?consumer_key=$apiKey");
  125. assert.calledWithMatch(fetchStub, "https://getpocket.cdn.mozilla.net/dummy?consumer_key=replaced", {credentials: "omit"});
  126. });
  127. });
  128. describe("#loadLayout", () => {
  129. it("should fetch data and populate the cache if it is empty", async () => {
  130. const resp = {layout: ["foo", "bar"]};
  131. const fakeCache = {};
  132. sandbox.stub(feed.cache, "get").returns(Promise.resolve(fakeCache));
  133. sandbox.stub(feed.cache, "set").returns(Promise.resolve());
  134. fetchStub.resolves({ok: true, json: () => Promise.resolve(resp)});
  135. await feed.loadLayout(feed.store.dispatch);
  136. assert.calledOnce(fetchStub);
  137. assert.equal(feed.cache.set.firstCall.args[0], "layout");
  138. assert.deepEqual(feed.cache.set.firstCall.args[1].layout, resp.layout);
  139. });
  140. it("should fetch data and populate the cache if the cached data is older than 30 mins", async () => {
  141. const resp = {layout: ["foo", "bar"]};
  142. const fakeCache = {layout: {layout: ["hello"], lastUpdated: Date.now()}};
  143. sandbox.stub(feed.cache, "get").returns(Promise.resolve(fakeCache));
  144. sandbox.stub(feed.cache, "set").returns(Promise.resolve());
  145. fetchStub.resolves({ok: true, json: () => Promise.resolve(resp)});
  146. clock.tick(THIRTY_MINUTES + 1);
  147. await feed.loadLayout(feed.store.dispatch);
  148. assert.calledOnce(fetchStub);
  149. assert.equal(feed.cache.set.firstCall.args[0], "layout");
  150. assert.deepEqual(feed.cache.set.firstCall.args[1].layout, resp.layout);
  151. });
  152. it("should use the cached data and not fetch if the cached data is less than 30 mins old", async () => {
  153. const fakeCache = {layout: {layout: ["hello"], lastUpdated: Date.now()}};
  154. sandbox.stub(feed.cache, "get").returns(Promise.resolve(fakeCache));
  155. sandbox.stub(feed.cache, "set").returns(Promise.resolve());
  156. clock.tick(THIRTY_MINUTES - 1);
  157. await feed.loadLayout(feed.store.dispatch);
  158. assert.notCalled(fetchStub);
  159. assert.notCalled(feed.cache.set);
  160. });
  161. it("should set spocs_endpoint from layout", async () => {
  162. const resp = {layout: ["foo", "bar"], spocs: {url: "foo.com"}};
  163. const fakeCache = {};
  164. sandbox.stub(feed.cache, "get").returns(Promise.resolve(fakeCache));
  165. sandbox.stub(feed.cache, "set").returns(Promise.resolve());
  166. fetchStub.resolves({ok: true, json: () => Promise.resolve(resp)});
  167. await feed.loadLayout(feed.store.dispatch);
  168. assert.equal(feed.store.getState().DiscoveryStream.spocs.spocs_endpoint, "foo.com");
  169. });
  170. it("should use local layout with hardcoded_layout being true", async () => {
  171. feed.config.hardcoded_layout = true;
  172. sandbox.stub(feed, "fetchLayout").returns(Promise.resolve(""));
  173. await feed.loadLayout(feed.store.dispatch);
  174. assert.notCalled(feed.fetchLayout);
  175. assert.equal(feed.store.getState().DiscoveryStream.spocs.spocs_endpoint, "https://getpocket.cdn.mozilla.net/v3/firefox/unique-spocs?consumer_key=$apiKey");
  176. });
  177. it("should fetch local layout for invalid layout endpoint or when fetch layout fails", async () => {
  178. feed.config.hardcoded_layout = false;
  179. fetchStub.resolves({ok: false});
  180. await feed.loadLayout(feed.store.dispatch, true);
  181. assert.calledOnce(fetchStub);
  182. assert.equal(feed.store.getState().DiscoveryStream.spocs.spocs_endpoint, "https://getpocket.cdn.mozilla.net/v3/firefox/unique-spocs?consumer_key=$apiKey");
  183. });
  184. });
  185. describe("#loadLayoutEndPointUsingPref", () => {
  186. it("should return endpoint if valid key", async () => {
  187. const endpoint = feed.finalLayoutEndpoint("https://somedomain.org/stories?consumer_key=$apiKey", "test_key_val");
  188. assert.equal("https://somedomain.org/stories?consumer_key=test_key_val", endpoint);
  189. });
  190. it("should throw error if key is empty", async () => {
  191. assert.throws(() => {
  192. feed.finalLayoutEndpoint("https://somedomain.org/stories?consumer_key=$apiKey", "");
  193. });
  194. });
  195. it("should return url if $apiKey is missing in layout_endpoint", async () => {
  196. const endpoint = feed.finalLayoutEndpoint("https://somedomain.org/stories?consumer_key=", "test_key_val");
  197. assert.equal("https://somedomain.org/stories?consumer_key=", endpoint);
  198. });
  199. it("should update config layout_endpoint based on api_key_pref value", async () => {
  200. feed.store.getState = () => ({
  201. Prefs: {
  202. values: {
  203. [CONFIG_PREF_NAME]: JSON.stringify({
  204. api_key_pref: "test_api_key_pref",
  205. enabled: true,
  206. layout_endpoint: "https://somedomain.org/stories?consumer_key=$apiKey",
  207. }),
  208. },
  209. },
  210. });
  211. sandbox.stub(global.Services.prefs, "getCharPref").returns("test_api_key_val");
  212. assert.equal("https://somedomain.org/stories?consumer_key=test_api_key_val", feed.config.layout_endpoint);
  213. });
  214. it("should not update config layout_endpoint if api_key_pref missing", async () => {
  215. feed.store.getState = () => ({
  216. Prefs: {
  217. values: {
  218. [CONFIG_PREF_NAME]: JSON.stringify({
  219. enabled: true,
  220. layout_endpoint: "https://somedomain.org/stories?consumer_key=1234",
  221. }),
  222. },
  223. },
  224. });
  225. sandbox.stub(global.Services.prefs, "getCharPref").returns("test_api_key_val");
  226. assert.notCalled(global.Services.prefs.getCharPref);
  227. assert.equal("https://somedomain.org/stories?consumer_key=1234", feed.config.layout_endpoint);
  228. });
  229. it("should not set config layout_endpoint if layout_endpoint missing in prefs", async () => {
  230. feed.store.getState = () => ({
  231. Prefs: {
  232. values: {
  233. [CONFIG_PREF_NAME]: JSON.stringify({
  234. enabled: true,
  235. }),
  236. },
  237. },
  238. });
  239. sandbox.stub(global.Services.prefs, "getCharPref").returns("test_api_key_val");
  240. assert.notCalled(global.Services.prefs.getCharPref);
  241. assert.isUndefined(feed.config.layout_endpoint);
  242. });
  243. });
  244. describe("#loadComponentFeeds", () => {
  245. let fakeCache;
  246. let fakeDiscoveryStream;
  247. beforeEach(() => {
  248. fakeDiscoveryStream = {
  249. DiscoveryStream: {
  250. layout: [
  251. {components: [{feed: {url: "foo.com"}}]},
  252. {components: [{}]},
  253. {},
  254. ],
  255. },
  256. };
  257. fakeCache = {};
  258. sandbox.stub(feed.store, "getState").returns(fakeDiscoveryStream);
  259. sandbox.stub(feed.cache, "set").returns(Promise.resolve());
  260. });
  261. afterEach(() => {
  262. sandbox.restore();
  263. });
  264. it("should not dispatch updates when layout is not defined", async () => {
  265. fakeDiscoveryStream = {
  266. DiscoveryStream: {},
  267. };
  268. feed.store.getState.returns(fakeDiscoveryStream);
  269. sandbox.spy(feed.store, "dispatch");
  270. await feed.loadComponentFeeds(feed.store.dispatch);
  271. assert.notCalled(feed.store.dispatch);
  272. });
  273. it("should populate feeds cache", async () => {
  274. fakeCache = {feeds: {"foo.com": {"lastUpdated": Date.now(), "data": "data"}}};
  275. sandbox.stub(feed.cache, "get").returns(Promise.resolve(fakeCache));
  276. await feed.loadComponentFeeds(feed.store.dispatch);
  277. assert.calledWith(feed.cache.set, "feeds", {"foo.com": {"data": "data", "lastUpdated": 0}});
  278. });
  279. it("should send feed update events with new feed data",
  280. async () => {
  281. sandbox.stub(feed.cache, "get").returns(Promise.resolve(fakeCache));
  282. sandbox.spy(feed.store, "dispatch");
  283. feed._prefCache = {
  284. config: {
  285. api_key_pref: "",
  286. },
  287. };
  288. await feed.loadComponentFeeds(feed.store.dispatch);
  289. assert.calledWith(feed.store.dispatch.firstCall, {
  290. type: at.DISCOVERY_STREAM_FEED_UPDATE,
  291. data: {feed: {data: {status: "failed"}}, url: "foo.com"},
  292. });
  293. assert.calledWith(feed.store.dispatch.secondCall, {
  294. type: at.DISCOVERY_STREAM_FEEDS_UPDATE,
  295. });
  296. });
  297. it("should return number of promises equal to unique urls",
  298. async () => {
  299. sandbox.stub(feed.cache, "get").returns(Promise.resolve(fakeCache));
  300. sandbox.stub(global.Promise, "all").resolves();
  301. fakeDiscoveryStream = {
  302. DiscoveryStream: {
  303. layout: [
  304. {components: [{feed: {url: "foo.com"}}, {feed: {url: "bar.com"}}]},
  305. {components: [{feed: {url: "foo.com"}}]},
  306. {},
  307. {components: [{feed: {url: "baz.com"}}]},
  308. ],
  309. },
  310. };
  311. feed.store.getState.returns(fakeDiscoveryStream);
  312. await feed.loadComponentFeeds(feed.store.dispatch);
  313. assert.calledOnce(global.Promise.all);
  314. const {args} = global.Promise.all.firstCall;
  315. assert.equal(args[0].length, 3);
  316. }
  317. );
  318. it("should not record the request time if no fetch request was issued", async () => {
  319. const fakeComponents = {components: []};
  320. const fakeLayout = [fakeComponents, {components: [{}]}, {}];
  321. fakeDiscoveryStream = {DiscoveryStream: {layout: fakeLayout}};
  322. fakeCache = {feeds: {"foo.com": {"lastUpdated": Date.now(), "data": "data"}}};
  323. sandbox.stub(feed.cache, "get").returns(Promise.resolve(fakeCache));
  324. feed.componentFeedRequestTime = undefined;
  325. await feed.loadComponentFeeds(feed.store.dispatch);
  326. assert.isUndefined(feed.componentFeedRequestTime);
  327. });
  328. });
  329. describe("#getComponentFeed", () => {
  330. it("should fetch fresh data if cache is empty", async () => {
  331. const fakeCache = {};
  332. sandbox.stub(feed.cache, "get").returns(Promise.resolve(fakeCache));
  333. sandbox.stub(feed, "rotate").callsFake(val => val);
  334. sandbox.stub(feed, "scoreItems").callsFake(val => ({data: val, filtered: []}));
  335. sandbox.stub(feed, "fetchFromEndpoint").resolves({
  336. recommendations: "data",
  337. settings: {
  338. recsExpireTime: 1,
  339. },
  340. });
  341. const feedResp = await feed.getComponentFeed("foo.com");
  342. assert.equal(feedResp.data.recommendations, "data");
  343. });
  344. it("should fetch fresh data if cache is old", async () => {
  345. const fakeCache = {feeds: {"foo.com": {lastUpdated: Date.now()}}};
  346. sandbox.stub(feed.cache, "get").returns(Promise.resolve(fakeCache));
  347. sandbox.stub(feed, "fetchFromEndpoint").resolves({
  348. recommendations: "data",
  349. settings: {
  350. recsExpireTime: 1,
  351. },
  352. });
  353. sandbox.stub(feed, "rotate").callsFake(val => val);
  354. sandbox.stub(feed, "scoreItems").callsFake(val => ({data: val, filtered: []}));
  355. clock.tick(THIRTY_MINUTES + 1);
  356. const feedResp = await feed.getComponentFeed("foo.com");
  357. assert.equal(feedResp.data.recommendations, "data");
  358. });
  359. it("should return data from cache if it is fresh", async () => {
  360. const fakeCache = {feeds: {"foo.com": {lastUpdated: Date.now(), data: "data"}}};
  361. sandbox.stub(feed.cache, "get").resolves(fakeCache);
  362. sandbox.stub(feed, "fetchFromEndpoint").resolves("old data");
  363. clock.tick(THIRTY_MINUTES - 1);
  364. const feedResp = await feed.getComponentFeed("foo.com");
  365. assert.equal(feedResp.data, "data");
  366. });
  367. it("should return null if no response was received", async () => {
  368. sandbox.stub(feed, "fetchFromEndpoint").resolves(null);
  369. const feedResp = await feed.getComponentFeed("foo.com");
  370. assert.deepEqual(feedResp, {data: {status: "failed"}});
  371. });
  372. });
  373. describe("#loadSpocs", () => {
  374. beforeEach(() => {
  375. Object.defineProperty(feed, "showSpocs", {get: () => true});
  376. });
  377. it("should not fetch or update cache if no spocs endpoint is defined", async () => {
  378. feed.store.dispatch(ac.BroadcastToContent({
  379. type: at.DISCOVERY_STREAM_SPOCS_ENDPOINT,
  380. data: "",
  381. }));
  382. sandbox.spy(feed.cache, "set");
  383. await feed.loadSpocs(feed.store.dispatch);
  384. assert.notCalled(global.fetch);
  385. assert.notCalled(feed.cache.set);
  386. });
  387. it("should fetch fresh data if cache is empty", async () => {
  388. sandbox.stub(feed.cache, "get").returns(Promise.resolve());
  389. sandbox.stub(feed, "fetchFromEndpoint").resolves("data");
  390. sandbox.stub(feed.cache, "set").returns(Promise.resolve());
  391. await feed.loadSpocs(feed.store.dispatch);
  392. assert.calledWith(feed.cache.set, "spocs", {"data": "data", "lastUpdated": 0});
  393. assert.equal(feed.store.getState().DiscoveryStream.spocs.data, "data");
  394. });
  395. it("should fetch fresh data if cache is old", async () => {
  396. const cachedSpoc = {"data": "old", "lastUpdated": Date.now()};
  397. const cachedData = {"spocs": cachedSpoc};
  398. sandbox.stub(feed.cache, "get").returns(Promise.resolve(cachedData));
  399. sandbox.stub(feed, "fetchFromEndpoint").resolves("new");
  400. sandbox.stub(feed.cache, "set").returns(Promise.resolve());
  401. clock.tick(THIRTY_MINUTES + 1);
  402. await feed.loadSpocs(feed.store.dispatch);
  403. assert.equal(feed.store.getState().DiscoveryStream.spocs.data, "new");
  404. });
  405. it("should return data from cache if it is fresh", async () => {
  406. const cachedSpoc = {"data": "old", "lastUpdated": Date.now()};
  407. const cachedData = {"spocs": cachedSpoc};
  408. sandbox.stub(feed.cache, "get").returns(Promise.resolve(cachedData));
  409. sandbox.stub(feed, "fetchFromEndpoint").resolves("new");
  410. sandbox.stub(feed.cache, "set").returns(Promise.resolve());
  411. clock.tick(THIRTY_MINUTES - 1);
  412. await feed.loadSpocs(feed.store.dispatch);
  413. assert.equal(feed.store.getState().DiscoveryStream.spocs.data, "old");
  414. });
  415. });
  416. describe("#showSpocs", () => {
  417. it("should return false from showSpocs if user pref showSponsored is false", async () => {
  418. feed.store.getState = () => ({
  419. Prefs: {values: {showSponsored: false}},
  420. });
  421. Object.defineProperty(feed, "config", {get: () => ({show_spocs: true})});
  422. assert.isFalse(feed.showSpocs);
  423. });
  424. it("should return false from showSpocs if DiscoveryStream pref show_spocs is false", async () => {
  425. feed.store.getState = () => ({
  426. Prefs: {values: {showSponsored: true}},
  427. });
  428. Object.defineProperty(feed, "config", {get: () => ({show_spocs: false})});
  429. assert.isFalse(feed.showSpocs);
  430. });
  431. it("should return true from showSpocs if both prefs are true", async () => {
  432. feed.store.getState = () => ({
  433. Prefs: {values: {showSponsored: true}},
  434. });
  435. Object.defineProperty(feed, "config", {get: () => ({show_spocs: true})});
  436. assert.isTrue(feed.showSpocs);
  437. });
  438. });
  439. describe("#rotate", () => {
  440. it("should move seen first story to the back of the response", () => {
  441. const recsExpireTime = 5600;
  442. const feedResponse = {
  443. recommendations: [
  444. {
  445. id: "first",
  446. },
  447. {
  448. id: "second",
  449. },
  450. {
  451. id: "third",
  452. },
  453. {
  454. id: "fourth",
  455. },
  456. ],
  457. settings: {
  458. recsExpireTime,
  459. },
  460. };
  461. const fakeImpressions = {
  462. "first": Date.now() - (recsExpireTime * 1000),
  463. "third": Date.now(),
  464. };
  465. sandbox.stub(feed, "readImpressionsPref").returns(fakeImpressions);
  466. const result = feed.rotate(feedResponse.recommendations, feedResponse.settings.recsExpireTime);
  467. assert.equal(result[3].id, "first");
  468. });
  469. });
  470. describe("#resetCache", () => {
  471. it("should set .layout, .feeds .spocs and .affinities to {", async () => {
  472. sandbox.stub(feed.cache, "set").returns(Promise.resolve());
  473. await feed.resetCache();
  474. assert.callCount(feed.cache.set, 4);
  475. const firstCall = feed.cache.set.getCall(0);
  476. const secondCall = feed.cache.set.getCall(1);
  477. const thirdCall = feed.cache.set.getCall(2);
  478. const fourthCall = feed.cache.set.getCall(3);
  479. assert.deepEqual(firstCall.args, ["layout", {}]);
  480. assert.deepEqual(secondCall.args, ["feeds", {}]);
  481. assert.deepEqual(thirdCall.args, ["spocs", {}]);
  482. assert.deepEqual(fourthCall.args, ["affinities", {}]);
  483. });
  484. });
  485. describe("#transform", () => {
  486. it("should return initial data if spocs are empty", () => {
  487. const {data: result} = feed.transform({spocs: []});
  488. assert.equal(result.spocs.length, 0);
  489. });
  490. it("should sort based on item_score", () => {
  491. const {data: result} = feed.transform({
  492. spocs: [
  493. {id: 2, campaign_id: 2, item_score: 0.8, min_score: 0.1},
  494. {id: 3, campaign_id: 3, item_score: 0.7, min_score: 0.1},
  495. {id: 1, campaign_id: 1, item_score: 0.9, min_score: 0.1},
  496. ],
  497. });
  498. assert.deepEqual(result.spocs, [
  499. {id: 1, campaign_id: 1, item_score: 0.9, score: 0.9, min_score: 0.1},
  500. {id: 2, campaign_id: 2, item_score: 0.8, score: 0.8, min_score: 0.1},
  501. {id: 3, campaign_id: 3, item_score: 0.7, score: 0.7, min_score: 0.1},
  502. ]);
  503. });
  504. it("should remove items with scores lower than min_score", () => {
  505. const {data: result, filtered} = feed.transform({
  506. spocs: [
  507. {id: 2, campaign_id: 2, item_score: 0.8, min_score: 0.9},
  508. {id: 3, campaign_id: 3, item_score: 0.7, min_score: 0.7},
  509. {id: 1, campaign_id: 1, item_score: 0.9, min_score: 0.8},
  510. ],
  511. });
  512. assert.deepEqual(result.spocs, [
  513. {id: 1, campaign_id: 1, item_score: 0.9, score: 0.9, min_score: 0.8},
  514. {id: 3, campaign_id: 3, item_score: 0.7, score: 0.7, min_score: 0.7},
  515. ]);
  516. assert.deepEqual(filtered.below_min_score,
  517. [{id: 2, campaign_id: 2, item_score: 0.8, min_score: 0.9, score: 0.8}]);
  518. });
  519. it("should add a score prop to spocs", () => {
  520. const {data: result} = feed.transform({
  521. spocs: [
  522. {campaign_id: 1, item_score: 0.9, min_score: 0.1},
  523. ],
  524. });
  525. assert.equal(result.spocs[0].score, 0.9);
  526. });
  527. it("should filter out duplicate campigns", () => {
  528. const {data: result, filtered} = feed.transform({
  529. spocs: [
  530. {id: 1, campaign_id: 2, item_score: 0.8, min_score: 0.1},
  531. {id: 2, campaign_id: 3, item_score: 0.6, min_score: 0.1},
  532. {id: 3, campaign_id: 1, item_score: 0.9, min_score: 0.1},
  533. {id: 4, campaign_id: 3, item_score: 0.7, min_score: 0.1},
  534. {id: 5, campaign_id: 1, item_score: 0.9, min_score: 0.1},
  535. ],
  536. });
  537. assert.deepEqual(result.spocs, [
  538. {id: 3, campaign_id: 1, item_score: 0.9, score: 0.9, min_score: 0.1},
  539. {id: 1, campaign_id: 2, item_score: 0.8, score: 0.8, min_score: 0.1},
  540. {id: 4, campaign_id: 3, item_score: 0.7, score: 0.7, min_score: 0.1},
  541. ]);
  542. assert.deepEqual(filtered.campaign_duplicate, [
  543. {id: 5, campaign_id: 1, item_score: 0.9, min_score: 0.1, score: 0.9},
  544. {id: 2, campaign_id: 3, item_score: 0.6, min_score: 0.1, score: 0.6},
  545. ]);
  546. });
  547. it("should filter out duplicate campigns while using spocs_per_domain", () => {
  548. sandbox.stub(feed.store, "getState").returns({
  549. DiscoveryStream: {
  550. spocs: {spocs_per_domain: 2},
  551. },
  552. });
  553. const {data: result, filtered} = feed.transform({
  554. spocs: [
  555. {id: 1, campaign_id: 2, item_score: 0.8, min_score: 0.1},
  556. {id: 2, campaign_id: 3, item_score: 0.6, min_score: 0.1},
  557. {id: 3, campaign_id: 1, item_score: 0.6, min_score: 0.1},
  558. {id: 4, campaign_id: 3, item_score: 0.7, min_score: 0.1},
  559. {id: 5, campaign_id: 1, item_score: 0.9, min_score: 0.1},
  560. {id: 6, campaign_id: 2, item_score: 0.6, min_score: 0.1},
  561. {id: 7, campaign_id: 3, item_score: 0.7, min_score: 0.1},
  562. {id: 8, campaign_id: 1, item_score: 0.8, min_score: 0.1},
  563. {id: 9, campaign_id: 3, item_score: 0.7, min_score: 0.1},
  564. {id: 10, campaign_id: 1, item_score: 0.8, min_score: 0.1},
  565. ],
  566. });
  567. assert.deepEqual(result.spocs, [
  568. {id: 5, campaign_id: 1, item_score: 0.9, score: 0.9, min_score: 0.1},
  569. {id: 1, campaign_id: 2, item_score: 0.8, score: 0.8, min_score: 0.1},
  570. {id: 8, campaign_id: 1, item_score: 0.8, score: 0.8, min_score: 0.1},
  571. {id: 4, campaign_id: 3, item_score: 0.7, score: 0.7, min_score: 0.1},
  572. {id: 7, campaign_id: 3, item_score: 0.7, score: 0.7, min_score: 0.1},
  573. {id: 6, campaign_id: 2, item_score: 0.6, score: 0.6, min_score: 0.1},
  574. ]);
  575. assert.deepEqual(filtered.campaign_duplicate, [
  576. {id: 10, campaign_id: 1, item_score: 0.8, min_score: 0.1, score: 0.8},
  577. {id: 9, campaign_id: 3, item_score: 0.7, min_score: 0.1, score: 0.7},
  578. {id: 2, campaign_id: 3, item_score: 0.6, min_score: 0.1, score: 0.6},
  579. {id: 3, campaign_id: 1, item_score: 0.6, min_score: 0.1, score: 0.6},
  580. ]);
  581. });
  582. });
  583. describe("#filterBlocked", () => {
  584. it("should return initial data if spocs are empty", () => {
  585. const {data: result} = feed.filterBlocked({spocs: []});
  586. assert.equal(result.spocs.length, 0);
  587. });
  588. it("should return initial spocs data if links are not blocked", () => {
  589. const {data: result} = feed.filterBlocked({
  590. spocs: [
  591. {url: "https://foo.com"},
  592. {url: "test.com"},
  593. ],
  594. }, "spocs");
  595. assert.equal(result.spocs.length, 2);
  596. });
  597. it("should return filtered out spocs based on blockedlist", () => {
  598. fakeNewTabUtils.blockedLinks.links = [{url: "https://foo.com"}];
  599. fakeNewTabUtils.blockedLinks.isBlocked = site => (fakeNewTabUtils.blockedLinks.links[0].url === site.url);
  600. const {data: result, filtered} = feed.filterBlocked({
  601. spocs: [
  602. {id: 1, url: "https://foo.com"},
  603. {id: 2, url: "test.com"},
  604. ],
  605. }, "spocs");
  606. assert.lengthOf(result.spocs, 1);
  607. assert.equal(result.spocs[0].url, "test.com");
  608. assert.notInclude(result.spocs, fakeNewTabUtils.blockedLinks.links[0]);
  609. assert.deepEqual(filtered, [{id: 1, url: "https://foo.com"}]);
  610. });
  611. it("should return initial recommendations data if links are not blocked", () => {
  612. const {data: result} = feed.filterBlocked({
  613. recommendations: [
  614. {url: "https://foo.com"},
  615. {url: "test.com"},
  616. ],
  617. }, "recommendations");
  618. assert.equal(result.recommendations.length, 2);
  619. });
  620. it("should return filtered out recommendations based on blockedlist", () => {
  621. fakeNewTabUtils.blockedLinks.links = [{url: "https://foo.com"}];
  622. fakeNewTabUtils.blockedLinks.isBlocked = site => (fakeNewTabUtils.blockedLinks.links[0].url === site.url);
  623. const {data: result} = feed.filterBlocked({
  624. recommendations: [
  625. {url: "https://foo.com"},
  626. {url: "test.com"},
  627. ],
  628. }, "recommendations");
  629. assert.lengthOf(result.recommendations, 1);
  630. assert.equal(result.recommendations[0].url, "test.com");
  631. assert.notInclude(result.recommendations, fakeNewTabUtils.blockedLinks.links[0]);
  632. });
  633. it("filterRecommendations based on blockedlist by passing feed data", () => {
  634. fakeNewTabUtils.blockedLinks.links = [{url: "https://foo.com"}];
  635. fakeNewTabUtils.blockedLinks.isBlocked = site => (fakeNewTabUtils.blockedLinks.links[0].url === site.url);
  636. const result = feed.filterRecommendations({
  637. lastUpdated: 4,
  638. data: {
  639. recommendations: [
  640. {url: "https://foo.com"},
  641. {url: "test.com"},
  642. ],
  643. },
  644. });
  645. assert.equal(result.lastUpdated, 4);
  646. assert.lengthOf(result.data.recommendations, 1);
  647. assert.equal(result.data.recommendations[0].url, "test.com");
  648. assert.notInclude(result.data.recommendations, fakeNewTabUtils.blockedLinks.links[0]);
  649. });
  650. });
  651. describe("#frequencyCapSpocs", () => {
  652. it("should return filtered out spocs based on frequency caps", () => {
  653. const fakeSpocs = {
  654. spocs: [
  655. {
  656. id: 1,
  657. campaign_id: "seen",
  658. caps: {
  659. lifetime: 3,
  660. campaign: {
  661. count: 1,
  662. period: 1,
  663. },
  664. },
  665. },
  666. {
  667. id: 2,
  668. campaign_id: "not-seen",
  669. caps: {
  670. lifetime: 3,
  671. campaign: {
  672. count: 1,
  673. period: 1,
  674. },
  675. },
  676. },
  677. ],
  678. };
  679. const fakeImpressions = {
  680. "seen": [Date.now() - 1],
  681. };
  682. sandbox.stub(feed, "readImpressionsPref").returns(fakeImpressions);
  683. const {data: result, filtered} = feed.frequencyCapSpocs(fakeSpocs);
  684. assert.equal(result.spocs.length, 1);
  685. assert.equal(result.spocs[0].campaign_id, "not-seen");
  686. assert.deepEqual(filtered, [fakeSpocs.spocs[0]]);
  687. });
  688. });
  689. describe("#isBelowFrequencyCap", () => {
  690. it("should return true if there are no campaign impressions", () => {
  691. const fakeImpressions = {
  692. "seen": [Date.now() - 1],
  693. };
  694. const fakeSpoc = {
  695. campaign_id: "not-seen",
  696. caps: {
  697. lifetime: 3,
  698. campaign: {
  699. count: 1,
  700. period: 1,
  701. },
  702. },
  703. };
  704. const result = feed.isBelowFrequencyCap(fakeImpressions, fakeSpoc);
  705. assert.isTrue(result);
  706. });
  707. it("should return true if there are no campaign caps", () => {
  708. const fakeImpressions = {
  709. "seen": [Date.now() - 1],
  710. };
  711. const fakeSpoc = {
  712. campaign_id: "seen",
  713. caps: {
  714. lifetime: 3,
  715. },
  716. };
  717. const result = feed.isBelowFrequencyCap(fakeImpressions, fakeSpoc);
  718. assert.isTrue(result);
  719. });
  720. it("should return false if lifetime cap is hit", () => {
  721. const fakeImpressions = {
  722. "seen": [Date.now() - 1],
  723. };
  724. const fakeSpoc = {
  725. campaign_id: "seen",
  726. caps: {
  727. lifetime: 1,
  728. campaign: {
  729. count: 3,
  730. period: 1,
  731. },
  732. },
  733. };
  734. const result = feed.isBelowFrequencyCap(fakeImpressions, fakeSpoc);
  735. assert.isFalse(result);
  736. });
  737. it("should return false if time based cap is hit", () => {
  738. const fakeImpressions = {
  739. "seen": [Date.now() - 1],
  740. };
  741. const fakeSpoc = {
  742. campaign_id: "seen",
  743. caps: {
  744. lifetime: 3,
  745. campaign: {
  746. count: 1,
  747. period: 1,
  748. },
  749. },
  750. };
  751. const result = feed.isBelowFrequencyCap(fakeImpressions, fakeSpoc);
  752. assert.isFalse(result);
  753. });
  754. });
  755. describe("#retryFeed", () => {
  756. it("should retry a feed fetch", async () => {
  757. sandbox.stub(feed, "getComponentFeed").returns(Promise.resolve({}));
  758. sandbox.stub(feed, "filterRecommendations").returns({});
  759. sandbox.spy(feed.store, "dispatch");
  760. await feed.retryFeed({url: "https://feed.com"});
  761. assert.calledOnce(feed.getComponentFeed);
  762. assert.calledOnce(feed.filterRecommendations);
  763. assert.calledOnce(feed.store.dispatch);
  764. assert.equal(feed.store.dispatch.firstCall.args[0].type, "DISCOVERY_STREAM_FEED_UPDATE");
  765. assert.deepEqual(feed.store.dispatch.firstCall.args[0].data, {
  766. feed: {},
  767. url: "https://feed.com",
  768. });
  769. });
  770. });
  771. describe("#recordCampaignImpression", () => {
  772. it("should return false if time based cap is hit", () => {
  773. sandbox.stub(feed, "readImpressionsPref").returns({});
  774. sandbox.stub(feed, "writeImpressionsPref").returns();
  775. feed.recordCampaignImpression("seen");
  776. assert.calledWith(feed.writeImpressionsPref, SPOC_IMPRESSION_TRACKING_PREF, {"seen": [0]});
  777. });
  778. });
  779. describe("#cleanUpCampaignImpressionPref", () => {
  780. it("should remove campaign-3 because it is no longer being used", async () => {
  781. const fakeSpocs = {
  782. spocs: [
  783. {
  784. campaign_id: "campaign-1",
  785. caps: {
  786. lifetime: 3,
  787. campaign: {
  788. count: 1,
  789. period: 1,
  790. },
  791. },
  792. },
  793. {
  794. campaign_id: "campaign-2",
  795. caps: {
  796. lifetime: 3,
  797. campaign: {
  798. count: 1,
  799. period: 1,
  800. },
  801. },
  802. },
  803. ],
  804. };
  805. const fakeImpressions = {
  806. "campaign-2": [Date.now() - 1],
  807. "campaign-3": [Date.now() - 1],
  808. };
  809. sandbox.stub(feed, "readImpressionsPref").returns(fakeImpressions);
  810. sandbox.stub(feed, "writeImpressionsPref").returns();
  811. feed.cleanUpCampaignImpressionPref(fakeSpocs);
  812. assert.calledWith(feed.writeImpressionsPref, SPOC_IMPRESSION_TRACKING_PREF, {"campaign-2": [-1]});
  813. });
  814. });
  815. describe("#recordTopRecImpressions", () => {
  816. it("should add a rec id to the rec impression pref", () => {
  817. sandbox.stub(feed, "readImpressionsPref").returns({});
  818. sandbox.stub(feed, "writeImpressionsPref");
  819. feed.recordTopRecImpressions("rec");
  820. assert.calledWith(feed.writeImpressionsPref, REC_IMPRESSION_TRACKING_PREF, {rec: 0});
  821. });
  822. it("should not add an impression if it already exists", () => {
  823. sandbox.stub(feed, "readImpressionsPref").returns({"rec": 4});
  824. sandbox.stub(feed, "writeImpressionsPref");
  825. feed.recordTopRecImpressions("rec");
  826. assert.notCalled(feed.writeImpressionsPref);
  827. });
  828. });
  829. describe("#cleanUpTopRecImpressionPref", () => {
  830. it("should remove recs no longer being used", () => {
  831. const newFeeds = {
  832. "https://foo.com": {
  833. data: {
  834. recommendations: [
  835. {
  836. id: "rec1",
  837. },
  838. {
  839. id: "rec2",
  840. },
  841. ],
  842. },
  843. },
  844. "https://bar.com": {
  845. data: {
  846. recommendations: [
  847. {
  848. id: "rec3",
  849. },
  850. {
  851. id: "rec4",
  852. },
  853. ],
  854. },
  855. },
  856. };
  857. const fakeImpressions = {
  858. "rec2": Date.now() - 1,
  859. "rec3": Date.now() - 1,
  860. "rec5": Date.now() - 1,
  861. };
  862. sandbox.stub(feed, "readImpressionsPref").returns(fakeImpressions);
  863. sandbox.stub(feed, "writeImpressionsPref").returns();
  864. feed.cleanUpTopRecImpressionPref(newFeeds);
  865. assert.calledWith(feed.writeImpressionsPref, REC_IMPRESSION_TRACKING_PREF, {rec2: -1, rec3: -1});
  866. });
  867. });
  868. describe("#writeImpressionsPref", () => {
  869. it("should call Services.prefs.setStringPref", () => {
  870. sandbox.spy(feed.store, "dispatch");
  871. const fakeImpressions = {
  872. "foo": [Date.now() - 1],
  873. "bar": [Date.now() - 1],
  874. };
  875. feed.writeImpressionsPref(SPOC_IMPRESSION_TRACKING_PREF, fakeImpressions);
  876. assert.calledWithMatch(feed.store.dispatch, {
  877. data: {
  878. name: SPOC_IMPRESSION_TRACKING_PREF,
  879. value: JSON.stringify(fakeImpressions),
  880. },
  881. type: at.SET_PREF,
  882. });
  883. });
  884. });
  885. describe("#readImpressionsPref", () => {
  886. it("should return what's in Services.prefs.getStringPref", () => {
  887. const fakeImpressions = {
  888. "foo": [Date.now() - 1],
  889. "bar": [Date.now() - 1],
  890. };
  891. setPref(SPOC_IMPRESSION_TRACKING_PREF, fakeImpressions);
  892. const result = feed.readImpressionsPref(SPOC_IMPRESSION_TRACKING_PREF);
  893. assert.deepEqual(result, fakeImpressions);
  894. });
  895. });
  896. describe("#onAction: DISCOVERY_STREAM_IMPRESSION_STATS", () => {
  897. it("should call recordTopRecImpressions from DISCOVERY_STREAM_IMPRESSION_STATS", async () => {
  898. sandbox.stub(feed, "recordTopRecImpressions").returns();
  899. await feed.onAction({type: at.DISCOVERY_STREAM_IMPRESSION_STATS, data: {tiles: [{id: "seen"}]}});
  900. assert.calledWith(feed.recordTopRecImpressions, "seen");
  901. });
  902. });
  903. describe("#onAction: DISCOVERY_STREAM_SPOC_IMPRESSION", () => {
  904. beforeEach(() => {
  905. const data = {
  906. spocs: [
  907. {
  908. id: 1,
  909. campaign_id: "seen",
  910. caps: {
  911. lifetime: 3,
  912. campaign: {
  913. count: 1,
  914. period: 1,
  915. },
  916. },
  917. },
  918. {
  919. id: 2,
  920. campaign_id: "not-seen",
  921. caps: {
  922. lifetime: 3,
  923. campaign: {
  924. count: 1,
  925. period: 1,
  926. },
  927. },
  928. },
  929. ],
  930. };
  931. sandbox.stub(feed.store, "getState").returns({
  932. DiscoveryStream: {
  933. spocs: {
  934. data,
  935. spocs_per_domain: 2,
  936. },
  937. },
  938. });
  939. });
  940. it("should call dispatch to ac.AlsoToPreloaded with filtered spoc data", async () => {
  941. Object.defineProperty(feed, "showSpocs", {get: () => true});
  942. const fakeImpressions = {
  943. "seen": [Date.now() - 1],
  944. };
  945. const result = {
  946. spocs: [
  947. {
  948. id: 2,
  949. campaign_id: "not-seen",
  950. caps: {
  951. lifetime: 3,
  952. campaign: {
  953. count: 1,
  954. period: 1,
  955. },
  956. },
  957. },
  958. ],
  959. };
  960. const spocFillResult = [{
  961. id: 1,
  962. reason: "frequency_cap",
  963. displayed: 0,
  964. full_recalc: 0,
  965. }];
  966. sandbox.stub(feed, "recordCampaignImpression").returns();
  967. sandbox.stub(feed, "readImpressionsPref").returns(fakeImpressions);
  968. sandbox.spy(feed.store, "dispatch");
  969. await feed.onAction({type: at.DISCOVERY_STREAM_SPOC_IMPRESSION, data: {campaign_id: "seen"}});
  970. assert.deepEqual(feed.store.dispatch.secondCall.args[0].data.spocs, result);
  971. assert.deepEqual(feed.store.dispatch.thirdCall.args[0].data.spoc_fills, spocFillResult);
  972. });
  973. it("should not call dispatch to ac.AlsoToPreloaded if spocs were not changed by frequency capping", async () => {
  974. Object.defineProperty(feed, "showSpocs", {get: () => true});
  975. const fakeImpressions = {};
  976. sandbox.stub(feed, "recordCampaignImpression").returns();
  977. sandbox.stub(feed, "readImpressionsPref").returns(fakeImpressions);
  978. sandbox.spy(feed.store, "dispatch");
  979. await feed.onAction({type: at.DISCOVERY_STREAM_SPOC_IMPRESSION, data: {campaign_id: "seen"}});
  980. assert.notCalled(feed.store.dispatch);
  981. });
  982. });
  983. describe("#onAction: PLACES_LINK_BLOCKED", () => {
  984. beforeEach(() => {
  985. const data = {
  986. spocs: [
  987. {
  988. id: 1,
  989. campaign_id: "foo",
  990. url: "foo.com",
  991. },
  992. {
  993. id: 2,
  994. campaign_id: "bar",
  995. url: "bar.com",
  996. },
  997. ],
  998. };
  999. sandbox.stub(feed.store, "getState").returns({
  1000. DiscoveryStream: {
  1001. spocs: {data},
  1002. },
  1003. });
  1004. });
  1005. it("should call dispatch with the SPOCS Fill if found a blocked spoc", async () => {
  1006. Object.defineProperty(feed, "showSpocs", {get: () => true});
  1007. const spocFillResult = [{
  1008. id: 1,
  1009. reason: "blocked_by_user",
  1010. displayed: 0,
  1011. full_recalc: 0,
  1012. }];
  1013. sandbox.spy(feed.store, "dispatch");
  1014. await feed.onAction({type: at.PLACES_LINK_BLOCKED, data: {url: "foo.com"}});
  1015. assert.deepEqual(feed.store.dispatch.firstCall.args[0].data.spoc_fills, spocFillResult);
  1016. assert.deepEqual(feed.store.dispatch.secondCall.args[0].data.url, "foo.com");
  1017. });
  1018. it("should not call dispatch with the SPOCS Fill if the blocked is not a SPOC", async () => {
  1019. Object.defineProperty(feed, "showSpocs", {get: () => true});
  1020. sandbox.spy(feed.store, "dispatch");
  1021. await feed.onAction({type: at.PLACES_LINK_BLOCKED, data: {url: "not_a_spoc.com"}});
  1022. assert.calledOnce(feed.store.dispatch);
  1023. assert.deepEqual(feed.store.dispatch.firstCall.args[0].data.url, "not_a_spoc.com");
  1024. });
  1025. });
  1026. describe("#onAction: INIT", () => {
  1027. it("should be .loaded=false before initialization", () => {
  1028. assert.isFalse(feed.loaded);
  1029. });
  1030. it("should load data and set .loaded=true if config.enabled is true", async () => {
  1031. sandbox.stub(feed.cache, "set").returns(Promise.resolve());
  1032. setPref(CONFIG_PREF_NAME, {enabled: true});
  1033. sandbox.stub(feed, "loadLayout").returns(Promise.resolve());
  1034. sandbox.stub(feed, "reportCacheAge").resolves();
  1035. sandbox.spy(feed, "reportRequestTime");
  1036. await feed.onAction({type: at.INIT});
  1037. assert.calledOnce(feed.loadLayout);
  1038. assert.calledOnce(feed.reportCacheAge);
  1039. assert.calledOnce(feed.reportRequestTime);
  1040. assert.isTrue(feed.loaded);
  1041. });
  1042. });
  1043. describe("#onAction: DISCOVERY_STREAM_CONFIG_SET_VALUE", async () => {
  1044. it("should add the new value to the pref without changing the existing values", async () => {
  1045. sandbox.spy(feed.store, "dispatch");
  1046. setPref(CONFIG_PREF_NAME, {enabled: true, other: "value"});
  1047. await feed.onAction({type: at.DISCOVERY_STREAM_CONFIG_SET_VALUE, data: {name: "layout_endpoint", value: "foo.com"}});
  1048. assert.calledWithMatch(feed.store.dispatch, {
  1049. data: {
  1050. name: CONFIG_PREF_NAME,
  1051. value: JSON.stringify({enabled: true, other: "value", layout_endpoint: "foo.com"}),
  1052. },
  1053. type: at.SET_PREF,
  1054. });
  1055. });
  1056. });
  1057. describe("#onAction: DISCOVERY_STREAM_RETRY_FEED", async () => {
  1058. it("should call retryFeed", async () => {
  1059. sandbox.spy(feed, "retryFeed");
  1060. feed.onAction({type: at.DISCOVERY_STREAM_RETRY_FEED, data: {feed: {url: "https://feed.com"}}});
  1061. assert.calledOnce(feed.retryFeed);
  1062. assert.calledWith(feed.retryFeed, {url: "https://feed.com"});
  1063. });
  1064. });
  1065. describe("#onAction: DISCOVERY_STREAM_CONFIG_CHANGE", () => {
  1066. it("should call this.loadLayout if config.enabled changes to true ", async () => {
  1067. sandbox.stub(feed.cache, "set").returns(Promise.resolve());
  1068. // First initialize
  1069. await feed.onAction({type: at.INIT});
  1070. assert.isFalse(feed.loaded);
  1071. // force clear cached pref value
  1072. feed._prefCache = {};
  1073. setPref(CONFIG_PREF_NAME, {enabled: true});
  1074. sandbox.stub(feed, "resetCache").returns(Promise.resolve());
  1075. sandbox.stub(feed, "loadLayout").returns(Promise.resolve());
  1076. await feed.onAction({type: at.DISCOVERY_STREAM_CONFIG_CHANGE});
  1077. assert.calledOnce(feed.loadLayout);
  1078. assert.calledOnce(feed.resetCache);
  1079. assert.isTrue(feed.loaded);
  1080. });
  1081. it("should clear the cache if a config change happens and config.enabled is true", async () => {
  1082. sandbox.stub(feed.cache, "set").returns(Promise.resolve());
  1083. // force clear cached pref value
  1084. feed._prefCache = {};
  1085. setPref(CONFIG_PREF_NAME, {enabled: true});
  1086. sandbox.stub(feed, "resetCache").returns(Promise.resolve());
  1087. await feed.onAction({type: at.DISCOVERY_STREAM_CONFIG_CHANGE});
  1088. assert.calledOnce(feed.resetCache);
  1089. });
  1090. it("should dispatch DISCOVERY_STREAM_LAYOUT_RESET from DISCOVERY_STREAM_CONFIG_CHANGE", async () => {
  1091. sandbox.stub(feed, "resetImpressionPrefs");
  1092. sandbox.stub(feed, "resetCache").resolves();
  1093. sandbox.stub(feed, "enable").resolves();
  1094. setPref(CONFIG_PREF_NAME, {enabled: true});
  1095. sandbox.spy(feed.store, "dispatch");
  1096. await feed.onAction({type: at.DISCOVERY_STREAM_CONFIG_CHANGE});
  1097. assert.calledWithMatch(feed.store.dispatch, {
  1098. type: at.DISCOVERY_STREAM_LAYOUT_RESET,
  1099. });
  1100. });
  1101. it("should not call this.loadLayout if config.enabled changes to false", async () => {
  1102. sandbox.stub(feed.cache, "set").returns(Promise.resolve());
  1103. // force clear cached pref value
  1104. feed._prefCache = {};
  1105. setPref(CONFIG_PREF_NAME, {enabled: true});
  1106. await feed.onAction({type: at.INIT});
  1107. assert.isTrue(feed.loaded);
  1108. feed._prefCache = {};
  1109. setPref(CONFIG_PREF_NAME, {enabled: false});
  1110. sandbox.stub(feed, "resetCache").returns(Promise.resolve());
  1111. sandbox.stub(feed, "loadLayout").returns(Promise.resolve());
  1112. await feed.onAction({type: at.DISCOVERY_STREAM_CONFIG_CHANGE});
  1113. assert.notCalled(feed.loadLayout);
  1114. assert.calledOnce(feed.resetCache);
  1115. assert.isFalse(feed.loaded);
  1116. });
  1117. });
  1118. describe("#onAction: UNINIT", () => {
  1119. it("should reset pref cache", async () => {
  1120. feed._prefCache = {cached: "value"};
  1121. await feed.onAction({type: at.UNINIT});
  1122. assert.deepEqual(feed._prefCache, {});
  1123. });
  1124. });
  1125. describe("#onAction: PREF_CHANGED", () => {
  1126. it("should update state.DiscoveryStream.config when the pref changes", async () => {
  1127. setPref(CONFIG_PREF_NAME, {enabled: true, show_spocs: false, layout_endpoint: "foo"});
  1128. assert.deepEqual(feed.store.getState().DiscoveryStream.config, {enabled: true, show_spocs: false, layout_endpoint: "foo"});
  1129. });
  1130. it("should fire loadSpocs is showSponsored pref changes", async () => {
  1131. sandbox.stub(feed, "loadSpocs").returns(Promise.resolve());
  1132. await feed.onAction({type: at.PREF_CHANGED, data: {name: "showSponsored"}});
  1133. assert.calledOnce(feed.loadSpocs);
  1134. });
  1135. });
  1136. describe("#onAction: SYSTEM_TICK", () => {
  1137. it("should not refresh if DiscoveryStream has not been loaded", async () => {
  1138. sandbox.stub(feed, "refreshAll").resolves();
  1139. setPref(CONFIG_PREF_NAME, {enabled: true});
  1140. await feed.onAction({type: at.SYSTEM_TICK});
  1141. assert.notCalled(feed.refreshAll);
  1142. });
  1143. it("should not refresh if no caches are expired", async () => {
  1144. sandbox.stub(feed.cache, "set").resolves();
  1145. setPref(CONFIG_PREF_NAME, {enabled: true});
  1146. await feed.onAction({type: at.INIT});
  1147. sandbox.stub(feed, "checkIfAnyCacheExpired").resolves(false);
  1148. sandbox.stub(feed, "refreshAll").resolves();
  1149. await feed.onAction({type: at.SYSTEM_TICK});
  1150. assert.notCalled(feed.refreshAll);
  1151. });
  1152. it("should refresh if DiscoveryStream has been loaded at least once and a cache has expired", async () => {
  1153. sandbox.stub(feed.cache, "set").resolves();
  1154. setPref(CONFIG_PREF_NAME, {enabled: true});
  1155. await feed.onAction({type: at.INIT});
  1156. sandbox.stub(feed, "checkIfAnyCacheExpired").resolves(true);
  1157. sandbox.stub(feed, "refreshAll").resolves();
  1158. await feed.onAction({type: at.SYSTEM_TICK});
  1159. assert.calledOnce(feed.refreshAll);
  1160. });
  1161. it("should refresh and not update open tabs if DiscoveryStream has been loaded at least once", async () => {
  1162. sandbox.stub(feed.cache, "set").resolves();
  1163. setPref(CONFIG_PREF_NAME, {enabled: true});
  1164. await feed.onAction({type: at.INIT});
  1165. sandbox.stub(feed, "checkIfAnyCacheExpired").resolves(true);
  1166. sandbox.stub(feed, "refreshAll").resolves();
  1167. await feed.onAction({type: at.SYSTEM_TICK});
  1168. assert.calledWith(feed.refreshAll, {updateOpenTabs: false});
  1169. });
  1170. });
  1171. describe("#onAction: PREF_SHOW_SPONSORED", () => {
  1172. it("should call loadSpocs when preference changes", async () => {
  1173. sandbox.stub(feed, "loadSpocs").resolves();
  1174. sandbox.stub(feed.store, "dispatch");
  1175. await feed.onAction({type: at.PREF_CHANGED, data: {name: "showSponsored"}});
  1176. assert.calledOnce(feed.loadSpocs);
  1177. const [dispatchFn] = feed.loadSpocs.firstCall.args;
  1178. dispatchFn({});
  1179. assert.calledWith(feed.store.dispatch, ac.BroadcastToContent({}));
  1180. });
  1181. });
  1182. describe("#isExpired", () => {
  1183. it("should throw if the key is not valid", () => {
  1184. assert.throws(() => {
  1185. feed.isExpired({}, "foo");
  1186. });
  1187. });
  1188. it("should return false for layout on startup for content under 1 week", () => {
  1189. const layout = {lastUpdated: Date.now()};
  1190. const result = feed.isExpired({cachedData: {layout}, key: "layout", isStartup: true});
  1191. assert.isFalse(result);
  1192. });
  1193. it("should return true for layout for isStartup=false after 30 mins", () => {
  1194. const layout = {lastUpdated: Date.now()};
  1195. clock.tick(THIRTY_MINUTES + 1);
  1196. const result = feed.isExpired({cachedData: {layout}, key: "layout"});
  1197. assert.isTrue(result);
  1198. });
  1199. it("should return true for layout on startup for content over 1 week", () => {
  1200. const layout = {lastUpdated: Date.now()};
  1201. clock.tick(ONE_WEEK + 1);
  1202. const result = feed.isExpired({cachedData: {layout}, key: "layout", isStartup: true});
  1203. assert.isTrue(result);
  1204. });
  1205. it("should return false for hardcoded layout on startup for content over 1 week", () => {
  1206. feed._prefCache.config = {
  1207. hardcoded_layout: true,
  1208. };
  1209. const layout = {lastUpdated: Date.now()};
  1210. clock.tick(ONE_WEEK + 1);
  1211. const result = feed.isExpired({cachedData: {layout}, key: "layout", isStartup: true});
  1212. assert.isFalse(result);
  1213. });
  1214. });
  1215. describe("#checkIfAnyCacheExpired", () => {
  1216. let cache;
  1217. beforeEach(() => {
  1218. cache = {
  1219. layout: {lastUpdated: Date.now()},
  1220. feeds: {"foo.com": {lastUpdated: Date.now()}},
  1221. spocs: {lastUpdated: Date.now()},
  1222. };
  1223. sandbox.stub(feed.cache, "get").resolves(cache);
  1224. });
  1225. it("should return false if nothing in the cache is expired", async () => {
  1226. const result = await feed.checkIfAnyCacheExpired();
  1227. assert.isFalse(result);
  1228. });
  1229. it("should return true if .layout is missing", async () => {
  1230. delete cache.layout;
  1231. assert.isTrue(await feed.checkIfAnyCacheExpired());
  1232. });
  1233. it("should return true if .layout is expired", async () => {
  1234. clock.tick(THIRTY_MINUTES + 1);
  1235. // Update other caches we aren't testing
  1236. cache.feeds["foo.com"].lastUpdate = Date.now();
  1237. cache.spocs.lastUpdate = Date.now();
  1238. assert.isTrue(await feed.checkIfAnyCacheExpired());
  1239. });
  1240. it("should return true if .spocs is missing", async () => {
  1241. delete cache.spocs;
  1242. assert.isTrue(await feed.checkIfAnyCacheExpired());
  1243. });
  1244. it("should return true if .spocs is expired", async () => {
  1245. clock.tick(THIRTY_MINUTES + 1);
  1246. // Update other caches we aren't testing
  1247. cache.layout.lastUpdated = Date.now();
  1248. cache.feeds["foo.com"].lastUpdate = Date.now();
  1249. assert.isTrue(await feed.checkIfAnyCacheExpired());
  1250. });
  1251. it("should return true if .feeds is missing", async () => {
  1252. delete cache.feeds;
  1253. assert.isTrue(await feed.checkIfAnyCacheExpired());
  1254. });
  1255. it("should return true if data for .feeds[url] is missing", async () => {
  1256. cache.feeds["foo.com"] = null;
  1257. assert.isTrue(await feed.checkIfAnyCacheExpired());
  1258. });
  1259. it("should return true if data for .feeds[url] is expired", async () => {
  1260. clock.tick(THIRTY_MINUTES + 1);
  1261. // Update other caches we aren't testing
  1262. cache.layout.lastUpdated = Date.now();
  1263. cache.spocs.lastUpdate = Date.now();
  1264. assert.isTrue(await feed.checkIfAnyCacheExpired());
  1265. });
  1266. });
  1267. describe("#refreshAll", () => {
  1268. beforeEach(() => {
  1269. sandbox.stub(feed, "loadLayout").resolves();
  1270. sandbox.stub(feed, "loadComponentFeeds").resolves();
  1271. sandbox.stub(feed, "loadSpocs").resolves();
  1272. sandbox.spy(feed.store, "dispatch");
  1273. Object.defineProperty(feed, "showSpocs", {get: () => true});
  1274. });
  1275. it("should call layout, component, spocs update and telemetry reporting functions", async () => {
  1276. await feed.refreshAll();
  1277. assert.calledOnce(feed.loadLayout);
  1278. assert.calledOnce(feed.loadComponentFeeds);
  1279. assert.calledOnce(feed.loadSpocs);
  1280. });
  1281. it("should pass in dispatch wrapped with broadcast if options.updateOpenTabs is true", async () => {
  1282. await feed.refreshAll({updateOpenTabs: true});
  1283. [feed.loadLayout, feed.loadComponentFeeds, feed.loadSpocs]
  1284. .forEach(fn => {
  1285. assert.calledOnce(fn);
  1286. const result = fn.firstCall.args[0]({type: "FOO"});
  1287. assert.isTrue(au.isBroadcastToContent(result));
  1288. });
  1289. });
  1290. it("should pass in dispatch with regular actions if options.updateOpenTabs is false", async () => {
  1291. await feed.refreshAll({updateOpenTabs: false});
  1292. [feed.loadLayout, feed.loadComponentFeeds, feed.loadSpocs]
  1293. .forEach(fn => {
  1294. assert.calledOnce(fn);
  1295. const result = fn.firstCall.args[0]({type: "FOO"});
  1296. assert.deepEqual(result, {type: "FOO"});
  1297. });
  1298. });
  1299. it("should set loaded to true if loadSpocs and loadComponentFeeds fails", async () => {
  1300. feed.loadComponentFeeds.rejects("loadComponentFeeds error");
  1301. feed.loadSpocs.rejects("loadSpocs error");
  1302. await feed.enable();
  1303. assert.isTrue(feed.loaded);
  1304. });
  1305. it("should call loadComponentFeeds and loadSpocs in Promise.all", async () => {
  1306. sandbox.stub(global.Promise, "all").resolves();
  1307. await feed.refreshAll();
  1308. assert.calledOnce(global.Promise.all);
  1309. const {args} = global.Promise.all.firstCall;
  1310. assert.equal(args[0].length, 2);
  1311. });
  1312. describe("test startup cache behaviour", () => {
  1313. beforeEach(() => {
  1314. feed._maybeUpdateCachedData.restore();
  1315. sandbox.stub(feed.cache, "set").resolves();
  1316. });
  1317. it("should refresh layout on startup if it was served from cache", async () => {
  1318. feed.loadLayout.restore();
  1319. sandbox.stub(feed.cache, "get").resolves({layout: {lastUpdated: Date.now(), layout: {}}});
  1320. sandbox.stub(feed, "fetchFromEndpoint").resolves({layout: {}});
  1321. clock.tick(THIRTY_MINUTES + 1);
  1322. await feed.refreshAll({isStartup: true});
  1323. assert.calledOnce(feed.fetchFromEndpoint);
  1324. // Once from cache, once to update the store
  1325. assert.calledTwice(feed.store.dispatch);
  1326. assert.equal(feed.store.dispatch.firstCall.args[0].type, at.DISCOVERY_STREAM_LAYOUT_UPDATE);
  1327. });
  1328. it("should not refresh layout on startup if it is under THIRTY_MINUTES", async () => {
  1329. feed.loadLayout.restore();
  1330. sandbox.stub(feed.cache, "get").resolves({layout: {lastUpdated: Date.now(), layout: {}}});
  1331. sandbox.stub(feed, "fetchFromEndpoint").resolves({layout: {}});
  1332. await feed.refreshAll({isStartup: true});
  1333. assert.notCalled(feed.fetchFromEndpoint);
  1334. });
  1335. it("should refresh spocs on startup if it was served from cache", async () => {
  1336. feed.loadSpocs.restore();
  1337. sandbox.stub(feed.cache, "get").resolves({spocs: {lastUpdated: Date.now()}});
  1338. sandbox.stub(feed, "fetchFromEndpoint").resolves("data");
  1339. clock.tick(THIRTY_MINUTES + 1);
  1340. await feed.refreshAll({isStartup: true});
  1341. assert.calledOnce(feed.fetchFromEndpoint);
  1342. // Once from cache, once to update the store
  1343. assert.calledTwice(feed.store.dispatch);
  1344. assert.equal(feed.store.dispatch.firstCall.args[0].type, at.DISCOVERY_STREAM_SPOCS_UPDATE);
  1345. });
  1346. it("should not refresh spocs on startup if it is under THIRTY_MINUTES", async () => {
  1347. feed.loadSpocs.restore();
  1348. sandbox.stub(feed.cache, "get").resolves({spocs: {lastUpdated: Date.now()}});
  1349. sandbox.stub(feed, "fetchFromEndpoint").resolves("data");
  1350. await feed.refreshAll({isStartup: true});
  1351. assert.notCalled(feed.fetchFromEndpoint);
  1352. });
  1353. it("should refresh feeds on startup if it was served from cache", async () => {
  1354. feed.loadComponentFeeds.restore();
  1355. const fakeComponents = {components: [{feed: {url: "foo.com"}}]};
  1356. const fakeLayout = [fakeComponents];
  1357. const fakeDiscoveryStream = {DiscoveryStream: {layout: fakeLayout}};
  1358. sandbox.stub(feed.store, "getState").returns(fakeDiscoveryStream);
  1359. sandbox.stub(feed, "rotate").callsFake(val => val);
  1360. sandbox.stub(feed, "scoreItems").callsFake(val => ({data: val, filtered: []}));
  1361. sandbox.stub(feed, "cleanUpTopRecImpressionPref").callsFake(val => val);
  1362. const fakeCache = {feeds: {"foo.com": {lastUpdated: Date.now(), data: "data"}}};
  1363. sandbox.stub(feed.cache, "get").resolves(fakeCache);
  1364. clock.tick(THIRTY_MINUTES + 1);
  1365. sandbox.stub(feed, "fetchFromEndpoint").resolves({
  1366. recommendations: "data",
  1367. settings: {
  1368. recsExpireTime: 1,
  1369. },
  1370. });
  1371. await feed.refreshAll({isStartup: true});
  1372. assert.calledOnce(feed.fetchFromEndpoint);
  1373. // Once from cache, once to update the feed, once to update that all feeds are done.
  1374. assert.calledThrice(feed.store.dispatch);
  1375. assert.equal(feed.store.dispatch.secondCall.args[0].type, at.DISCOVERY_STREAM_FEEDS_UPDATE);
  1376. });
  1377. });
  1378. });
  1379. describe("#reportCacheAge", () => {
  1380. let cache;
  1381. const cacheAge = 30;
  1382. beforeEach(() => {
  1383. cache = {
  1384. layout: {lastUpdated: Date.now() - 10 * 1000},
  1385. feeds: {"foo.com": {lastUpdated: Date.now() - cacheAge * 1000}},
  1386. spocs: {lastUpdated: Date.now() - 20 * 1000},
  1387. };
  1388. sandbox.stub(feed.cache, "get").resolves(cache);
  1389. });
  1390. it("should report the oldest lastUpdated date as the cache age", async () => {
  1391. sandbox.spy(feed.store, "dispatch");
  1392. feed.loaded = false;
  1393. await feed.reportCacheAge();
  1394. assert.calledOnce(feed.store.dispatch);
  1395. const [action] = feed.store.dispatch.firstCall.args;
  1396. assert.equal(action.type, at.TELEMETRY_PERFORMANCE_EVENT);
  1397. assert.equal(action.data.event, "DS_CACHE_AGE_IN_SEC");
  1398. assert.isAtLeast(action.data.value, cacheAge);
  1399. feed.loaded = true;
  1400. });
  1401. });
  1402. describe("#reportRequestTime", () => {
  1403. let cache;
  1404. const cacheAge = 30;
  1405. beforeEach(() => {
  1406. cache = {
  1407. layout: {lastUpdated: Date.now() - 10 * 1000},
  1408. feeds: {"foo.com": {lastUpdated: Date.now() - cacheAge * 1000}},
  1409. spocs: {lastUpdated: Date.now() - 20 * 1000},
  1410. };
  1411. sandbox.stub(feed.cache, "get").resolves(cache);
  1412. });
  1413. it("should report all the request times", async () => {
  1414. sandbox.spy(feed.store, "dispatch");
  1415. feed.loaded = false;
  1416. feed.layoutRequestTime = 1000;
  1417. feed.spocsRequestTime = 2000;
  1418. feed.componentFeedRequestTime = 3000;
  1419. feed.totalRequestTime = 5000;
  1420. feed.reportRequestTime();
  1421. assert.equal(feed.store.dispatch.callCount, 4);
  1422. let [action] = feed.store.dispatch.getCall(0).args;
  1423. assert.equal(action.type, at.TELEMETRY_PERFORMANCE_EVENT);
  1424. assert.equal(action.data.event, "LAYOUT_REQUEST_TIME");
  1425. assert.equal(action.data.value, 1000);
  1426. [action] = feed.store.dispatch.getCall(1).args;
  1427. assert.equal(action.type, at.TELEMETRY_PERFORMANCE_EVENT);
  1428. assert.equal(action.data.event, "SPOCS_REQUEST_TIME");
  1429. assert.equal(action.data.value, 2000);
  1430. [action] = feed.store.dispatch.getCall(2).args;
  1431. assert.equal(action.type, at.TELEMETRY_PERFORMANCE_EVENT);
  1432. assert.equal(action.data.event, "COMPONENT_FEED_REQUEST_TIME");
  1433. assert.equal(action.data.value, 3000);
  1434. [action] = feed.store.dispatch.getCall(3).args;
  1435. assert.equal(action.type, at.TELEMETRY_PERFORMANCE_EVENT);
  1436. assert.equal(action.data.event, "DS_FEED_TOTAL_REQUEST_TIME");
  1437. assert.equal(action.data.value, 5000);
  1438. feed.loaded = true;
  1439. });
  1440. });
  1441. describe("#loadAffinityScoresCache", () => {
  1442. it("should create an affinity provider from cached affinities", async () => {
  1443. feed._prefCache.config = {
  1444. personalized: true,
  1445. };
  1446. const fakeCache = {
  1447. affinities: {
  1448. scores: 123,
  1449. _timestamp: 456,
  1450. },
  1451. };
  1452. sandbox.stub(feed.cache, "get").returns(Promise.resolve(fakeCache));
  1453. await feed.loadAffinityScoresCache();
  1454. assert.equal(feed.domainAffinitiesLastUpdated, 456);
  1455. });
  1456. });
  1457. describe("#updateDomainAffinityScores", () => {
  1458. it("should update affinity provider on idle daily", async () => {
  1459. feed._prefCache.config = {
  1460. personalized: true,
  1461. };
  1462. feed.affinities = {
  1463. parameterSets: {
  1464. default: {},
  1465. },
  1466. maxHistoryQueryResults: 1000,
  1467. timeSegments: [],
  1468. version: "123",
  1469. };
  1470. feed.observe(null, "idle-daily");
  1471. assert.equal(feed.affinityProvider.version, "123");
  1472. });
  1473. it("should not update affinity provider on idle daily", async () => {
  1474. feed._prefCache.config = {
  1475. personalized: false,
  1476. };
  1477. feed.observe(null, "idle-daily");
  1478. assert.isTrue(!feed.affinityProvider);
  1479. });
  1480. });
  1481. describe("#scoreItems", () => {
  1482. it("should score items using item_score and min_score", () => {
  1483. const {data: result, filtered} = feed.scoreItems([
  1484. {item_score: 0.8, min_score: 0.1},
  1485. {item_score: 0.5, min_score: 0.6},
  1486. {item_score: 0.7, min_score: 0.1},
  1487. {item_score: 0.9, min_score: 0.1},
  1488. ]);
  1489. assert.deepEqual(result, [
  1490. {item_score: 0.9, score: 0.9, min_score: 0.1},
  1491. {item_score: 0.8, score: 0.8, min_score: 0.1},
  1492. {item_score: 0.7, score: 0.7, min_score: 0.1},
  1493. ]);
  1494. assert.deepEqual(filtered, [
  1495. {item_score: 0.5, min_score: 0.6, score: 0.5},
  1496. ]);
  1497. });
  1498. });
  1499. describe("#scoreItem", () => {
  1500. it("should use personalized score with affinity provider", () => {
  1501. const item = {};
  1502. feed._prefCache.config = {
  1503. personalized: true,
  1504. };
  1505. feed.affinityProvider = {
  1506. calculateItemRelevanceScore: () => 0.5,
  1507. };
  1508. const result = feed.scoreItem(item);
  1509. assert.equal(result.score, 0.5);
  1510. });
  1511. it("should use item_score score without affinity provider score", () => {
  1512. const item = {
  1513. item_score: 0.6,
  1514. };
  1515. feed._prefCache.config = {
  1516. personalized: true,
  1517. };
  1518. feed.affinityProvider = {
  1519. calculateItemRelevanceScore: () => {},
  1520. };
  1521. const result = feed.scoreItem(item);
  1522. assert.equal(result.score, 0.6);
  1523. });
  1524. it("should add min_score of 0 if undefined", () => {
  1525. const item = {};
  1526. feed._prefCache.config = {
  1527. personalized: true,
  1528. };
  1529. feed.affinityProvider = {
  1530. calculateItemRelevanceScore: () => 0.5,
  1531. };
  1532. const result = feed.scoreItem(item);
  1533. assert.equal(result.min_score, 0);
  1534. });
  1535. });
  1536. describe("#_sendSpocsFill", () => {
  1537. it("should send out all the SPOCS Fill pings", () => {
  1538. sandbox.spy(feed.store, "dispatch");
  1539. const expected = [
  1540. {id: 1, reason: "frequency_cap", displayed: 0, full_recalc: 1},
  1541. {id: 2, reason: "frequency_cap", displayed: 0, full_recalc: 1},
  1542. {id: 3, reason: "blocked_by_user", displayed: 0, full_recalc: 1},
  1543. {id: 4, reason: "blocked_by_user", displayed: 0, full_recalc: 1},
  1544. {id: 5, reason: "campaign_duplicate", displayed: 0, full_recalc: 1},
  1545. {id: 6, reason: "campaign_duplicate", displayed: 0, full_recalc: 1},
  1546. {id: 7, reason: "below_min_score", displayed: 0, full_recalc: 1},
  1547. {id: 8, reason: "below_min_score", displayed: 0, full_recalc: 1},
  1548. ];
  1549. const filtered = {
  1550. frequency_cap: [{id: 1, campaign_id: 1}, {id: 2, campaign_id: 2}],
  1551. blocked_by_user: [{id: 3, campaign_id: 3}, {id: 4, campaign_id: 4}],
  1552. campaign_duplicate: [{id: 5, campaign_id: 5}, {id: 6, campaign_id: 6}],
  1553. below_min_score: [{id: 7, campaign_id: 7}, {id: 8, campaign_id: 8}],
  1554. };
  1555. feed._sendSpocsFill(filtered, true);
  1556. assert.deepEqual(feed.store.dispatch.firstCall.args[0].data.spoc_fills, expected);
  1557. });
  1558. it("should send SPOCS Fill ping with the correct full_recalc", () => {
  1559. sandbox.spy(feed.store, "dispatch");
  1560. const expected = [
  1561. {id: 1, reason: "frequency_cap", displayed: 0, full_recalc: 0},
  1562. {id: 2, reason: "frequency_cap", displayed: 0, full_recalc: 0},
  1563. ];
  1564. const filtered = {
  1565. frequency_cap: [{id: 1, campaign_id: 1}, {id: 2, campaign_id: 2}],
  1566. };
  1567. feed._sendSpocsFill(filtered, false);
  1568. assert.deepEqual(feed.store.dispatch.firstCall.args[0].data.spoc_fills, expected);
  1569. });
  1570. it("should not send non-SPOCS Fill pings", () => {
  1571. sandbox.spy(feed.store, "dispatch");
  1572. const expected = [
  1573. {id: 1, reason: "frequency_cap", displayed: 0, full_recalc: 1},
  1574. {id: 3, reason: "blocked_by_user", displayed: 0, full_recalc: 1},
  1575. {id: 5, reason: "campaign_duplicate", displayed: 0, full_recalc: 1},
  1576. {id: 7, reason: "below_min_score", displayed: 0, full_recalc: 1},
  1577. ];
  1578. const filtered = {
  1579. frequency_cap: [{id: 1, campaign_id: 1}, {id: 2}],
  1580. blocked_by_user: [{id: 3, campaign_id: 3}, {id: 4}],
  1581. campaign_duplicate: [{id: 5, campaign_id: 5}, {id: 6}],
  1582. below_min_score: [{id: 7, campaign_id: 7}, {id: 8}],
  1583. };
  1584. feed._sendSpocsFill(filtered, true);
  1585. assert.deepEqual(feed.store.dispatch.firstCall.args[0].data.spoc_fills, expected);
  1586. });
  1587. });
  1588. });