1/*
2 * file-serializer.test.ts
3 *
4 * Copyright (C) 2021 by RStudio, PBC
5 *
6 * Unless you have received this program directly from RStudio pursuant
7 * to the terms of a commercial license agreement with RStudio, then
8 * this program is licensed to you under the terms of version 3 of the
9 * GNU Affero General Public License. This program is distributed WITHOUT
10 * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
11 * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
12 * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
13 *
14 */
15
16import { describe } from 'mocha';
17import { assert } from 'chai';
18import path from 'path';
19import os from 'os';
20import fs from 'fs';
21
22import { randomString } from '../unit-utils';
23
24import { readStringArrayFromFile } from '../../../src/core/file-serializer';
25import { FilePath } from '../../../src/core/file-path';
26
27function writeTestFile(lineCount: number, includeBlanks: boolean): FilePath {
28  const file = new FilePath(path.join(os.tmpdir(), 'rstudio-temp-test-file-' + randomString()));
29  const blankLine = Buffer.from('  \t   \n', 'utf8');
30  const fd = fs.openSync(file.getAbsolutePath(), 'w');
31  for (let i = 0; i < lineCount; i++) {
32    // make every third line a blank (whitespace-only)
33    if (includeBlanks && i % 3 === 0) {
34      fs.writeSync(fd, blankLine);
35    } else {
36      fs.writeSync(fd, Buffer.from(`Line ${i}\n`, 'utf8'));
37    }
38  }
39  fs.closeSync(fd);
40  return file;
41}
42
43describe('file-serializer', () => {
44  it('readStringArrayFromFile reads a simple file including blank lines', async () => {
45    const tmpFile = writeTestFile(100, true);
46    const [result, error] = await readStringArrayFromFile(tmpFile, false);
47    assert.isNull(error);
48    assert.equal(100, result.length);
49    tmpFile.removeSync();
50  });
51  it('readStringArrayFromFile reads a simple file without any blank lines', async () => {
52    const tmpFile = writeTestFile(100, false);
53    const [result, error] = await readStringArrayFromFile(tmpFile, false);
54    assert.isNull(error);
55    assert.equal(100, result.length);
56    tmpFile.removeSync();
57  });
58  it('readStringArrayFromFile skips blank lines when requested', async () => {
59    const tmpFile = writeTestFile(100, true);
60    const [result, error] = await readStringArrayFromFile(tmpFile, true);
61    assert.isNull(error);
62    assert.equal(66, result.length);
63    for (const line in result) {
64      assert.isFalse(line.length === 0);
65    }
66    tmpFile.removeSync();
67  });
68  it('readStringArrayFromFile with skip set works when no blank lines', async () => {
69    const tmpFile = writeTestFile(100, false);
70    const [result, error] = await readStringArrayFromFile(tmpFile, true);
71    assert.isNull(error);
72    assert.equal(100, result.length);
73    tmpFile.removeSync();
74  });
75});
76