Files

110 lines
6.6 KiB
JavaScript

const test = require('node:test');
const assert = require('node:assert/strict');
const { createScraper, htmlProducts } = require('../server/scraper.cjs');
function response(url, value, status = 200, headers = {}) {
return { url, status, headers, body: Buffer.from(typeof value === 'string' ? value : JSON.stringify(value)) };
}
const wooItem = id => ({ id, name: 'Product ' + id, sku: 'SKU-' + id, prices: { price: String(id * 100), regular_price: String(id * 120), currency_code: 'BDT', currency_minor_unit: 2 } });
test('reads all advertised Woo pages using a discovered subdirectory REST root', async () => {
const calls = [];
const scrape = createScraper({ fetchPublic: async url => {
calls.push(url);
if (calls.length === 1) return response('https://www.catalog.fixture/shop/', '<link rel="https://api.w.org/" href="https://www.catalog.fixture/shop/wp-json/">');
const u = new URL(url);
assert.equal(u.pathname, '/shop/wp-json/wc/store/v1/products');
return response(url, u.searchParams.get('page') === '1' ? Array.from({ length: 100 }, (_, i) => wooItem(i)) : [wooItem(100)], 200, { 'x-wp-totalpages': '2' });
} });
const result = await scrape({ url: 'https://catalog.fixture/shop/', storeName: 'Own shop' });
assert.equal(result.count, 101);
assert.equal(result.domain, 'www.catalog.fixture');
assert.equal(result.products[0].rawPrice, 0);
assert.equal(result.products[100].rawPrice, 100);
assert.equal(calls.length, 3);
});
test('Shopify pagination preserves source currency and distinct variant records', async () => {
const calls = [];
const scrape = createScraper({ fetchPublic: async url => {
calls.push(url); const u = new URL(url);
if (u.pathname === '/') return response(url, '<html>Storefront</html>');
if (u.pathname.includes('wp-json')) return response(url, {}, 404);
const ids = u.searchParams.get('page') === '1' ? Array.from({ length: 250 }, (_, i) => i) : [250];
return response(url, { currency: 'USD', products: ids.map(id => ({ id, title: 'Item ' + id, variants: [{ id: 'v-' + id, sku: 'SKU-' + id, price: '1.25' }] })) });
} });
const result = await scrape({ url: 'https://catalog.fixture' });
assert.equal(result.count, 251);
assert.equal(result.products[0].currency, 'USD');
assert.equal(result.products[0].rawRegularPrice, null);
assert.equal(calls.length, 4);
});
test('failed later pages and repeated pages fail without claiming a complete import', async () => {
for (const repeated of [true, false]) {
const scrape = createScraper({ fetchPublic: async url => {
if (new URL(url).pathname === '/') return response(url, '<html>Shop</html>');
const second = new URL(url).searchParams.get('page') === '2';
return response(url, Array.from({ length: 100 }, (_, i) => wooItem(i)), second && !repeated ? 503 : 200, { 'x-wp-totalpages': '2' });
} });
await assert.rejects(scrape({ url: 'https://catalog.fixture' }), { code: repeated ? 'PAGINATION_UNSUPPORTED' : 'INCOMPLETE_CATALOG' });
}
});
test('HTML extraction uses actual sale markup and never invents a missing amount', () => {
const html = `<ul><li class="product"><a href="/item"><h2 class="woocommerce-loop-product__title">Own item</h2></a>
<span class="price"><del><span class="amount">৳ 270</span></del><ins><span class="amount">৳ 220</span></ins></span></li>
<li class="product"><h2 class="woocommerce-loop-product__title">Call for price</h2><span class="price">Contact us</span></li></ul>`;
const result = htmlProducts(Buffer.from(html), { url: 'https://catalog.fixture/', documentUrl: 'https://catalog.fixture/shop/', name: 'Shop', id: 'own', category: 'general' });
assert.equal(result.products[0].rawPrice, 220);
assert.equal(result.products[0].rawRegularPrice, 270);
assert.equal(result.products[1].rawPrice, null);
});
test('public HTML pagination is followed and its limited coverage is explicit', async () => {
const scrape = createScraper({ fetchPublic: async url => {
const u = new URL(url);
if (u.pathname.includes('wp-json') || u.pathname === '/products.json') return response(url, {}, 404);
const second = u.searchParams.get('page') === '2';
return response(url, `<script type="application/ld+json">${JSON.stringify({ '@type': 'Product', name: second ? 'Second' : 'First', sku: second ? 'B' : 'A', offers: { price: second ? 200 : 100, priceCurrency: 'BDT' } })}</script>${second ? '' : '<a rel="next" href="?page=2">Next</a>'}`);
} });
const result = await scrape({ url: 'https://catalog.fixture/catalog' });
assert.equal(result.count, 2);
assert.equal(result.sourceType, 'public-html-pages');
assert.match(result.coverage, /not a guarantee/);
});
test('request/product limits and private targets fail rather than saving a fabricated catalog', async () => {
const scrape = createScraper({ maxProducts: 1, fetchPublic: async url => new URL(url).pathname === '/' ? response(url, '<html>Shop</html>') : response(url, [wooItem(1), wooItem(2)]) });
await assert.rejects(scrape({ url: 'https://catalog.fixture' }), { code: 'IMPORT_LIMIT' });
let calls = 0;
const blocked = createScraper({ fetchPublic: async () => { calls++; throw Object.assign(new Error('blocked fixture'), { status: 400, code: 'NON_PUBLIC_SOURCE' }); } });
await assert.rejects(blocked({ url: 'http://127.0.0.1/' }), { code: 'NON_PUBLIC_SOURCE' });
assert.equal(calls, 1);
});
test('an empty authoritative public catalog does not fabricate products from unrelated home markup', async () => {
const scrape = createScraper({ fetchPublic: async url => new URL(url).pathname === '/' ? response(url, '<h1>Sale!</h1>') : response(url, []) });
await assert.rejects(scrape({ url: 'https://catalog.fixture' }), { code: 'NO_PUBLIC_PRODUCTS' });
});
test('an advertised second page is read even when the first page is shorter than the requested page size', async () => {
let pages = 0;
const scrape = createScraper({ pageDelayMs: 0, fetchPublic: async url => {
if (new URL(url).pathname === '/') return response(url, '<html>Shop</html>');
pages++;
return response(url, [wooItem(pages)], 200, { 'x-wp-totalpages': '2' });
} });
assert.equal((await scrape({ url: 'https://catalog.fixture/' })).count, 2);
assert.equal(pages, 2);
});
test('request pacing can be cancelled before the next website request', async () => {
let requests = 0;
const controller = new AbortController();
const scrape = createScraper({ pageDelayMs: 1000, fetchPublic: async url => { requests++; return response(url, '<html>Shop</html>'); } });
setTimeout(() => controller.abort(), 20);
await assert.rejects(scrape({ url: 'https://catalog.fixture/' }, { signal: controller.signal }), { code: 'IMPORT_TIMEOUT' });
assert.equal(requests, 1);
});