Skip to content

Commit

Permalink
fix: add better error logging and cache handling for tests
Browse files Browse the repository at this point in the history
  • Loading branch information
seansica committed Oct 14, 2024
1 parent 9261950 commit 1d1492e
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 10 deletions.
3 changes: 3 additions & 0 deletions .github/workflows/npm-publish.yml
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,9 @@ jobs:
- name: Install dependencies
run: npm install

- name: Clear cache
run: rm -rf .cached_stix_data

- name: Run tests
run: npm test

Expand Down
27 changes: 17 additions & 10 deletions test/utils/attack-data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,27 +42,34 @@ async function fetchAttackData(domain: AttackDomain, version?: string): Promise<
* @returns A Promise that resolves to a StixBundle.
*/
async function getCachedOrFetchAttackData(domain: AttackDomain, version?: string): Promise<StixBundle> {
// Create a file path for the cached data
const fileName = version ? `${domain}-${version}.json` : `${domain}.json`;
const filePath = path.join(CACHE_DIR, fileName);

// Check if the file already exists locally
if (await fileExists(filePath)) {
// If file exists, read it from disk
try {
if (await fileExists(filePath)) {
const data = await readFile(filePath, 'utf8');
return JSON.parse(data) as StixBundle;
} else {
// If file does not exist, fetch the data from the remote server
console.log(`Successfully read cached file: ${filePath}`);
try {
return JSON.parse(data) as StixBundle;
} catch (parseError) {
console.error(`Error parsing JSON from cached file: ${filePath}`, parseError);
throw parseError;
}
} else {
console.log(`Fetching data for ${domain} from remote server`);
const stixData = await fetchAttackData(domain, version);

// Ensure the cache directory exists
if (!await fileExists(CACHE_DIR)) {
fs.mkdirSync(CACHE_DIR, { recursive: true });
await fs.promises.mkdir(CACHE_DIR, { recursive: true });
}

// Cache the fetched data locally
await writeFile(filePath, JSON.stringify(stixData, null, 2), 'utf8');
console.log(`Successfully cached data for ${domain} at ${filePath}`);
return stixData;
}
} catch (error) {
console.error(`Error in getCachedOrFetchAttackData for ${domain}:`, error);
throw error;
}
}

Expand Down

0 comments on commit 1d1492e

Please sign in to comment.