π Get real-time stocks from TradingView
TypeScript backtestingbacktesting-trading-strategiesbitcoinchartscryptocryptocurrencyethereumrealtime-stocksstocksstocks-apistocks-pricestradingtradingviewtradingview-apitradingview-indicatortradingview-replaytradingview-scraper
Update redirect error message and add unit test
Caio Lins6f1e0762f24c
diff --git a/src/miscRequests.js b/src/miscRequests.jsindex ea2c5ba..a9707f2 100644--- a/src/miscRequests.js+++ b/src/miscRequests.js@@ -431,7 +431,7 @@ module.exports = {*/async getUser(session, signature = '', location = 'https://www.tradingview.com/', redirectCount = 0) {if (redirectCount > 5) {- throw new Error('Too many redirects - invalid session/signature');+ throw new Error('Too many redirects - possible WAF or geo-restriction');}const { data, headers } = await axios.get(location, {diff --git a/tests/getUser-redirect.test.ts b/tests/getUser-redirect.test.tsnew file mode 100644index 0000000..4d8faa5--- /dev/null+++ b/tests/getUser-redirect.test.ts@@ -0,0 +1,48 @@+import { describe, it, expect } from 'vitest';++describe('getUser redirect protection', () => {+ it('should not loop infinitely on repeated redirects', async () => {+ // Monkey-patch axios in the require cache to simulate redirect loop+ let callCount = 0;+ const axiosMock = {+ get: async (url: string) => {+ callCount++;+ const isA = url === 'https://www.tradingview.com/';+ return {+ data: '<html>no auth here</html>',+ headers: {+ location: isA+ ? 'https://www.tradingview.com/accounts/signin/'+ : 'https://www.tradingview.com/',+ },+ };+ },+ };++ const axiosPath = require.resolve('axios');+ const originalModule = require.cache[axiosPath];+ require.cache[axiosPath] = {+ id: axiosPath,+ filename: axiosPath,+ loaded: true,+ exports: axiosMock,+ } as any;++ const miscPath = require.resolve('../src/miscRequests');+ delete require.cache[miscPath];++ try {+ const misc = require('../src/miscRequests');+ await expect(+ misc.getUser('fake_session', 'fake_signature'),+ ).rejects.toThrow('Too many redirects');++ expect(callCount).toBeGreaterThan(0);+ expect(callCount).toBeLessThanOrEqual(10);+ } finally {+ if (originalModule) require.cache[axiosPath] = originalModule;+ else delete require.cache[axiosPath];+ delete require.cache[miscPath];+ }+ }, 5000);+});