Repository: webpack-contrib/compression-webpack-plugin
Pull request #195 (2020-09-14 14:56:41)

refactor: `filename` option
BREAKING CHANGE: filename` is changed, you need to return path with placholders

<!--
  HOLY CRAP a Pull Request. We ❤️ those!

  If you remove or skip this template, you'll make the 🐼 sad and the mighty god
  of Github will appear and pile-drive the close button from a great height
  while making animal noises.

  Please place an x (no spaces!) in all [ ] that apply
-->

This PR contains a:

- [ ] **bugfix**
- [ ] new **feature**
- [x] **code refactor**
- [x] **test update** <!-- if bug or feature is checked, this should be too -->
- [ ] **typo fix**
- [x] **metadata update**

### Motivation / Use-Case

to avoid problems with immutable files

### Breaking Changes

Yes:
- `filename: Function` should return filename with placeholders to avoid problems with immutable files
- the `[dir]` placeholder was replaced on the `[path]` placeholder
- added `[fragment]` and `[base]` placeholders
- 

### Additional Info

No

codecov[bot]: # [Codecov](https://codecov.io/gh/webpack-contrib/compression-webpack-plugin/pull/195?src=pr&el=h1) Report
> Merging [#195](https://codecov.io/gh/webpack-contrib/compression-webpack-plugin/pull/195?src=pr&el=desc) into [master](https://codecov.io/gh/webpack-contrib/compression-webpack-plugin/commit/9de2a88ccb7b16a84a4e1e08ae0889bc589a0089?el=desc) will **increase** coverage by `0.02%`.
> The diff coverage is `100.00%`.

[![Impacted file tree graph](https://codecov.io/gh/webpack-contrib/compression-webpack-plugin/pull/195/graphs/tree.svg?width=650&height=150&src=pr&token=wLGv0aBxEE)](https://codecov.io/gh/webpack-contrib/compression-webpack-plugin/pull/195?src=pr&el=tree)

```diff
@@            Coverage Diff             @@
##           master     #195      +/-   ##
==========================================
+ Coverage   98.75%   98.78%   +0.02%     
==========================================
  Files           4        4              
  Lines         161      164       +3     
  Branches       47       46       -1     
==========================================
+ Hits          159      162       +3     
  Misses          1        1              
  Partials        1        1              
```


| [Impacted Files](https://codecov.io/gh/webpack-contrib/compression-webpack-plugin/pull/195?src=pr&el=tree) | Coverage Δ | |
|---|---|---|
| [src/index.js](https://codecov.io/gh/webpack-contrib/compression-webpack-plugin/pull/195/diff?src=pr&el=tree#diff-c3JjL2luZGV4Lmpz) | `98.44% <100.00%> (+0.03%)` | :arrow_up: |

------

[Continue to review full report at Codecov](https://codecov.io/gh/webpack-contrib/compression-webpack-plugin/pull/195?src=pr&el=continue).
> **Legend** - [Click here to learn more](https://docs.codecov.io/docs/codecov-delta)
> `Δ = absolute <relative> (impact)`, `ø = not affected`, `? = missing data`
> Powered by [Codecov](https://codecov.io/gh/webpack-contrib/compression-webpack-plugin/pull/195?src=pr&el=footer). Last update [9de2a88...4b23274](https://codecov.io/gh/webpack-contrib/compression-webpack-plugin/pull/195?src=pr&el=lastupdated). Read the [comment docs](https://docs.codecov.io/docs/pull-request-comments).


Patch:
diff --git a/README.md b/README.md
index b269022..7f6e9ab 100644
--- a/README.md
+++ b/README.md
@@ -49,7 +49,7 @@ And run `webpack` via your preferred method.
 | **[`compressionOptions`](#compressionoptions)** |                `{Object}`                 | `{ level: 9 }` | Compression options for `algorithm`                                                                           |
 |          **[`threshold`](#threshold)**          |                `{Number}`                 |      `0`       | Only assets bigger than this size are processed (in bytes)                                                    |
 |           **[`minRatio`](#minratio)**           |                `{Number}`                 |     `0.8`      | Only assets that compress better than this ratio are processed (`minRatio = Compressed Size / Original Size`) |
-|           **[`filename`](#filename)**           |           `{String\|Function}`            |  `[path].gz`   | The target asset filename.                                                                                    |
+|           **[`filename`](#filename)**           |           `{String\|Function}`            |  `[base].gz`   | The target asset filename.                                                                                    |
 |              **[`cache`](#cache)**              |                `{Boolean}`                |     `true`     | Enable file caching                                                                                           |
 
 ### `test`
@@ -230,18 +230,27 @@ module.exports = {
 ### `filename`
 
 Type: `String|Function`
-Default: `[path].gz[query]`
+Default: `[path][base].gz`
 
 The target asset filename.
 
 #### `String`
 
-`[file]` is replaced with the original asset filename.
-`[path]` is replaced with the path of the original asset.
-`[dir]` is replaced with the directory of the original asset.
-`[name]` is replaced with the filename of the original asset.
-`[ext]` is replaced with the extension of the original asset.
-`[query]` is replaced with the query.
+For example we have `assets/images/image.png?foo=bar#hash`:
+
+`[path]` is replaced with the directories to the original asset, included trailing `/` (`assets/images/`).
+
+`[file]` is replaced with the path of original asset (`assets/images/image.png`).
+
+`[base]` is replaced with the base (`[name]` + `[ext]`) of the original asset (`image.png`).
+
+`[name]` is replaced with the name of the original asset (`image`).
+
+`[ext]` is replaced with the extension of the original asset, included `.` (`.png`).
+
+`[query]` is replaced with the query of the original asset, included `?` (`?foo=bar`).
+
+`[fragment]` is replaced with the fragment (in the concept of URL it is called `hash`) of the original asset (`#hash`).
 
 **webpack.config.js**
 
@@ -263,11 +272,14 @@ module.exports = {
 module.exports = {
   plugins: [
     new CompressionPlugin({
-      filename(info) {
-        // info.file is the original asset filename
-        // info.path is the path of the original asset
-        // info.query is the query
-        return `${info.path}.gz${info.query}`;
+      filename(pathData) {
+        // The `pathData` argument contains all placeholders - `path`/`name`/`ext`/etc
+        // Available properties described above, for the `String` notation
+        if (/\.svg$/.test(pathData.file)) {
+          return 'assets/svg/[path][base].gz';
+        }
+
+        return 'assets/js/[path][base].gz';
       },
     }),
   ],
diff --git a/src/index.js b/src/index.js
index de40b37..1df37bb 100644
--- a/src/index.js
+++ b/src/index.js
@@ -4,7 +4,6 @@
 */
 
 import crypto from 'crypto';
-import url from 'url';
 import path from 'path';
 
 import webpack, {
@@ -33,7 +32,7 @@ class CompressionPlugin {
       cache = true,
       algorithm = 'gzip',
       compressionOptions = {},
-      filename = '[path].gz',
+      filename = '[base].gz',
       threshold = 0,
       minRatio = 0.8,
       deleteOriginalAssets = false,
@@ -74,27 +73,6 @@ class CompressionPlugin {
     }
   }
 
-  static interpolateName(originalFilename, filename) {
-    const parse = url.parse(originalFilename);
-    const { pathname } = parse;
-    const { dir, name, ext } = path.parse(pathname);
-    const info = {
-      file: originalFilename,
-      path: pathname,
-      dir: dir ? `${dir}/` : '',
-      name,
-      ext,
-      query: parse.query ? `?${parse.query}` : '',
-    };
-
-    return typeof filename === 'function'
-      ? filename(info)
-      : filename.replace(
-          /\[(file|path|query|dir|name|ext)]/g,
-          (p0, p1) => info[p1]
-        );
-  }
-
   // eslint-disable-next-line consistent-return
   static getAsset(compilation, name) {
     // New API
@@ -254,23 +232,48 @@ class CompressionPlugin {
             return;
           }
 
-          const newAssetName = CompressionPlugin.interpolateName(
-            name,
-            this.options.filename
+          const match = /^([^?#]*)(\?[^#]*)?(#.*)?$/.exec(name);
+          const [, replacerFile] = match;
+          const replacerQuery = match[2] || '';
+          const replacerFragment = match[3] || '';
+          const replacerExt = path.extname(replacerFile);
+          const replacerBase = path.basename(replacerFile);
+          const replacerName = replacerBase.slice(
+            0,
+            replacerBase.length - replacerExt.length
+          );
+          const replacerPath = replacerFile.slice(
+            0,
+            replacerFile.length - replacerBase.length
+          );
+          const pathData = {
+            file: replacerFile,
+            query: replacerQuery,
+            fragment: replacerFragment,
+            path: replacerPath,
+            base: replacerBase,
+            name: replacerName,
+            ext: replacerExt || '',
+          };
+
+          let newFilename = this.options.filename;
+
+          if (typeof newFilename === 'function') {
+            newFilename = newFilename(pathData);
+          }
+
+          const newName = newFilename.replace(
+            /\[(file|query|fragment|path|base|name|ext)]/g,
+            (p0, p1) => pathData[p1]
           );
 
           const newInfo = { compressed: true };
 
-          if (info.immutable) {
+          if (info.immutable && /(\[name]|\[base]|\[file])/.test(newFilename)) {
             newInfo.immutable = true;
           }
 
-          CompressionPlugin.emitAsset(
-            compilation,
-            newAssetName,
-            output,
-            newInfo
-          );
+          CompressionPlugin.emitAsset(compilation, newName, output, newInfo);
 
           if (this.options.deleteOriginalAssets) {
             // eslint-disable-next-line no-param-reassign
@@ -279,7 +282,7 @@ class CompressionPlugin {
             // TODO `...` required only for webpack@4
             const newOriginalInfo = {
               ...info,
-              related: { [relatedName]: newAssetName },
+              related: { [relatedName]: newName },
             };
 
             CompressionPlugin.updateAsset(


Test patch:
diff --git a/test/CompressionPlugin.test.js b/test/CompressionPlugin.test.js
index b1d9c93..dd909fa 100644
--- a/test/CompressionPlugin.test.js
+++ b/test/CompressionPlugin.test.js
@@ -2,7 +2,10 @@ import zlib from 'zlib';
 import path from 'path';
 
 import webpack from 'webpack';
+import findCacheDir from 'find-cache-dir';
+import cacache from 'cacache';
 
+import Webpack4Cache from '../src/Webpack4Cache';
 import CompressionPlugin from '../src/index';
 
 import {
@@ -17,9 +20,18 @@ import {
   removeCache,
 } from './helpers/index';
 
+const cacheDir1 = findCacheDir({ name: 'compression-webpack-plugin-cache-1' });
+const cacheDir2 = findCacheDir({ name: 'compression-webpack-plugin-cache-2' });
+const cacheDir3 = findCacheDir({ name: 'compression-webpack-plugin-cache-3' });
+
 describe('CompressionPlugin', () => {
-  beforeEach(() => {
-    return removeCache();
+  beforeAll(() => {
+    return Promise.all([
+      removeCache(),
+      cacache.rm.all(cacheDir1),
+      cacache.rm.all(cacheDir2),
+      cacache.rm.all(cacheDir3),
+    ]);
   });
 
   it('should work', async () => {
@@ -148,23 +160,23 @@ describe('CompressionPlugin', () => {
 
     new CompressionPlugin({
       algorithm: 'gzip',
-      filename: '[path].gz',
+      filename: '[path][base].gz',
     }).apply(compiler);
     new CompressionPlugin({
       algorithm: 'brotliCompress',
-      filename: '[path].br',
+      filename: '[path][base].br',
     }).apply(compiler);
     new CompressionPlugin({
       algorithm: (input, options, callback) => {
         return callback(input);
       },
-      filename: '[path].compress',
+      filename: '[path][base].compress',
     }).apply(compiler);
     new CompressionPlugin({
       algorithm: (input, options, callback) => {
         return callback(input);
       },
-      filename: '[path].custom?foo=bar#hash',
+      filename: '[path][base].custom?foo=bar#hash',
     }).apply(compiler);
 
     const stats = await compile(compiler);
@@ -230,6 +242,12 @@ describe('CompressionPlugin', () => {
   });
 
   it('should work and use memory cache without options in the "development" mode', async () => {
+    const getCacheDirectorySpy = jest
+      .spyOn(Webpack4Cache, 'getCacheDirectory')
+      .mockImplementation(() => {
+        return cacheDir1;
+      });
+
     const compiler = getCompiler('./entry.js', {}, { mode: 'development' });
 
     new CompressionPlugin().apply(compiler);
@@ -267,11 +285,19 @@ describe('CompressionPlugin', () => {
       expect(getWarnings(newStats)).toMatchSnapshot('errors');
       expect(getErrors(newStats)).toMatchSnapshot('warnings');
 
+      getCacheDirectorySpy.mockRestore();
+
       resolve();
     });
   });
 
   it('should work and use memory cache when the "cache" option is "true"', async () => {
+    const getCacheDirectorySpy = jest
+      .spyOn(Webpack4Cache, 'getCacheDirectory')
+      .mockImplementation(() => {
+        return cacheDir2;
+      });
+
     const compiler = getCompiler(
       './entry.js',
       {},
@@ -320,11 +346,19 @@ describe('CompressionPlugin', () => {
       expect(getWarnings(newStats)).toMatchSnapshot('errors');
       expect(getErrors(newStats)).toMatchSnapshot('warnings');
 
+      getCacheDirectorySpy.mockRestore();
+
       resolve();
     });
   });
 
   it('should work and use memory cache when the "cache" option is "true" and the asset has been changed', async () => {
+    const getCacheDirectorySpy = jest
+      .spyOn(Webpack4Cache, 'getCacheDirectory')
+      .mockImplementation(() => {
+        return cacheDir3;
+      });
+
     const compiler = getCompiler(
       './entry.js',
       {},
@@ -375,6 +409,8 @@ describe('CompressionPlugin', () => {
       expect(getWarnings(newStats)).toMatchSnapshot('errors');
       expect(getErrors(newStats)).toMatchSnapshot('warnings');
 
+      getCacheDirectorySpy.mockRestore();
+
       resolve();
     });
   });
diff --git a/test/__snapshots__/filename-option.test.js.snap.webpack4 b/test/__snapshots__/filename-option.test.js.snap.webpack4
index 995a2a1..700c7c4 100644
--- a/test/__snapshots__/filename-option.test.js.snap.webpack4
+++ b/test/__snapshots__/filename-option.test.js.snap.webpack4
@@ -1,17 +1,17 @@
 // Jest Snapshot v1, https://goo.gl/fbAQLP
 
-exports[`"filename" option matches snapshot for \`[dir][name].super-compressed.gz[ext][query]\` value ({String}): assets 1`] = `
+exports[`"filename" option matches snapshot for \`[name][ext].super-compressed.gz[query]\` value ({String}): assets 1`] = `
 Array [
   Array [
     "09a1a1112c577c2794359715edfcb5ac.png",
     78117,
   ],
   Array [
-    "09a1a1112c577c2794359715edfcb5ac.super-compressed.gz.png",
+    "09a1a1112c577c2794359715edfcb5ac.super-compressed.png.gz",
     73160,
   ],
   Array [
-    "23fc1d3ac606d117e05a140e0de79806.super-compressed.gz.svg",
+    "23fc1d3ac606d117e05a140e0de79806.super-compressed.svg.gz",
     393,
   ],
   Array [
@@ -23,7 +23,7 @@ Array [
     249,
   ],
   Array [
-    "async.async.super-compressed.gz.js?ver=dc74724f7b13a2de5a20",
+    "async.async.super-compressed.js.gz?ver=dc74724f7b13a2de5a20",
     171,
   ],
   Array [
@@ -31,17 +31,17 @@ Array [
     11630,
   ],
   Array [
-    "main.super-compressed.gz.js?var=dc74724f7b13a2de5a20",
+    "main.super-compressed.js.gz?var=dc74724f7b13a2de5a20",
     3002,
   ],
 ]
 `;
 
-exports[`"filename" option matches snapshot for \`[dir][name].super-compressed.gz[ext][query]\` value ({String}): errors 1`] = `Array []`;
+exports[`"filename" option matches snapshot for \`[name][ext].super-compressed.gz[query]\` value ({String}): errors 1`] = `Array []`;
 
-exports[`"filename" option matches snapshot for \`[dir][name].super-compressed.gz[ext][query]\` value ({String}): warnings 1`] = `Array []`;
+exports[`"filename" option matches snapshot for \`[name][ext].super-compressed.gz[query]\` value ({String}): warnings 1`] = `Array []`;
 
-exports[`"filename" option matches snapshot for \`[path].super-compressed.gz[query]\` value ({String}): assets 1`] = `
+exports[`"filename" option matches snapshot for \`[path][base].super-compressed.gz[query][fragment]\` value ({String}): assets 1`] = `
 Array [
   Array [
     "09a1a1112c577c2794359715edfcb5ac.png",
@@ -60,27 +60,27 @@ Array [
     393,
   ],
   Array [
-    "async.async.js.super-compressed.gz?ver=dc74724f7b13a2de5a20",
+    "assets/js/async.async.js.super-compressed.gz?ver=6532e4640290c0b395f3#hash",
     171,
   ],
   Array [
-    "async.async.js?ver=dc74724f7b13a2de5a20",
+    "assets/js/async.async.js?ver=6532e4640290c0b395f3#hash",
     249,
   ],
   Array [
-    "main.js.super-compressed.gz?var=dc74724f7b13a2de5a20",
-    3002,
+    "assets/js/main.js.super-compressed.gz?var=6532e4640290c0b395f3#hash",
+    3015,
   ],
   Array [
-    "main.js?var=dc74724f7b13a2de5a20",
-    11630,
+    "assets/js/main.js?var=6532e4640290c0b395f3#hash",
+    11645,
   ],
 ]
 `;
 
-exports[`"filename" option matches snapshot for \`[path].super-compressed.gz[query]\` value ({String}): errors 1`] = `Array []`;
+exports[`"filename" option matches snapshot for \`[path][base].super-compressed.gz[query][fragment]\` value ({String}): errors 1`] = `Array []`;
 
-exports[`"filename" option matches snapshot for \`[path].super-compressed.gz[query]\` value ({String}): warnings 1`] = `Array []`;
+exports[`"filename" option matches snapshot for \`[path][base].super-compressed.gz[query][fragment]\` value ({String}): warnings 1`] = `Array []`;
 
 exports[`"filename" option matches snapshot for custom function ({Function}): assets 1`] = `
 Array [
@@ -101,20 +101,20 @@ Array [
     393,
   ],
   Array [
-    "async.async.js.gz?ver=dc74724f7b13a2de5a20",
+    "async.async.js.gz?ver=56cecc99721c0a179d38",
     171,
   ],
   Array [
-    "async.async.js?ver=dc74724f7b13a2de5a20",
+    "async.async.js?ver=56cecc99721c0a179d38#hash",
     249,
   ],
   Array [
-    "main.js.gz?var=dc74724f7b13a2de5a20",
-    3002,
+    "main.js.gz?var=56cecc99721c0a179d38",
+    3007,
   ],
   Array [
-    "main.js?var=dc74724f7b13a2de5a20",
-    11630,
+    "main.js?var=56cecc99721c0a179d38#hash",
+    11635,
   ],
 ]
 `;
diff --git a/test/__snapshots__/filename-option.test.js.snap.webpack5 b/test/__snapshots__/filename-option.test.js.snap.webpack5
index d4405c5..d613919 100644
--- a/test/__snapshots__/filename-option.test.js.snap.webpack5
+++ b/test/__snapshots__/filename-option.test.js.snap.webpack5
@@ -1,17 +1,17 @@
 // Jest Snapshot v1, https://goo.gl/fbAQLP
 
-exports[`"filename" option matches snapshot for \`[dir][name].super-compressed.gz[ext][query]\` value ({String}): assets 1`] = `
+exports[`"filename" option matches snapshot for \`[name][ext].super-compressed.gz[query]\` value ({String}): assets 1`] = `
 Array [
   Array [
     "09a1a1112c577c2794359715edfcb5ac.png",
     78117,
   ],
   Array [
-    "09a1a1112c577c2794359715edfcb5ac.super-compressed.gz.png",
+    "09a1a1112c577c2794359715edfcb5ac.super-compressed.png.gz",
     73160,
   ],
   Array [
-    "23fc1d3ac606d117e05a140e0de79806.super-compressed.gz.svg",
+    "23fc1d3ac606d117e05a140e0de79806.super-compressed.svg.gz",
     393,
   ],
   Array [
@@ -23,7 +23,7 @@ Array [
     265,
   ],
   Array [
-    "async.async.super-compressed.gz.js?ver=bbf6508f271a84a2c39d",
+    "async.async.super-compressed.js.gz?ver=bbf6508f271a84a2c39d",
     179,
   ],
   Array [
@@ -31,17 +31,17 @@ Array [
     15236,
   ],
   Array [
-    "main.super-compressed.gz.js?var=bbf6508f271a84a2c39d",
+    "main.super-compressed.js.gz?var=bbf6508f271a84a2c39d",
     3567,
   ],
 ]
 `;
 
-exports[`"filename" option matches snapshot for \`[dir][name].super-compressed.gz[ext][query]\` value ({String}): errors 1`] = `Array []`;
+exports[`"filename" option matches snapshot for \`[name][ext].super-compressed.gz[query]\` value ({String}): errors 1`] = `Array []`;
 
-exports[`"filename" option matches snapshot for \`[dir][name].super-compressed.gz[ext][query]\` value ({String}): warnings 1`] = `Array []`;
+exports[`"filename" option matches snapshot for \`[name][ext].super-compressed.gz[query]\` value ({String}): warnings 1`] = `Array []`;
 
-exports[`"filename" option matches snapshot for \`[path].super-compressed.gz[query]\` value ({String}): assets 1`] = `
+exports[`"filename" option matches snapshot for \`[path][base].super-compressed.gz[query][fragment]\` value ({String}): assets 1`] = `
 Array [
   Array [
     "09a1a1112c577c2794359715edfcb5ac.png",
@@ -60,27 +60,27 @@ Array [
     393,
   ],
   Array [
-    "async.async.js.super-compressed.gz?ver=bbf6508f271a84a2c39d",
+    "assets/js/async.async.js.super-compressed.gz?ver=d31d295ee8d5ebdf41b4#hash",
     179,
   ],
   Array [
-    "async.async.js?ver=bbf6508f271a84a2c39d",
+    "assets/js/async.async.js?ver=d31d295ee8d5ebdf41b4#hash",
     265,
   ],
   Array [
-    "main.js.super-compressed.gz?var=bbf6508f271a84a2c39d",
-    3567,
+    "assets/js/main.js.super-compressed.gz?var=d31d295ee8d5ebdf41b4#hash",
+    3578,
   ],
   Array [
-    "main.js?var=bbf6508f271a84a2c39d",
-    15236,
+    "assets/js/main.js?var=d31d295ee8d5ebdf41b4#hash",
+    15251,
   ],
 ]
 `;
 
-exports[`"filename" option matches snapshot for \`[path].super-compressed.gz[query]\` value ({String}): errors 1`] = `Array []`;
+exports[`"filename" option matches snapshot for \`[path][base].super-compressed.gz[query][fragment]\` value ({String}): errors 1`] = `Array []`;
 
-exports[`"filename" option matches snapshot for \`[path].super-compressed.gz[query]\` value ({String}): warnings 1`] = `Array []`;
+exports[`"filename" option matches snapshot for \`[path][base].super-compressed.gz[query][fragment]\` value ({String}): warnings 1`] = `Array []`;
 
 exports[`"filename" option matches snapshot for custom function ({Function}): assets 1`] = `
 Array [
@@ -101,20 +101,20 @@ Array [
     393,
   ],
   Array [
-    "async.async.js.gz?ver=bbf6508f271a84a2c39d",
+    "async.async.js.gz?ver=e0cd056ace173b6df0d1",
     179,
   ],
   Array [
-    "async.async.js?ver=bbf6508f271a84a2c39d",
+    "async.async.js?ver=e0cd056ace173b6df0d1#hash",
     265,
   ],
   Array [
-    "main.js.gz?var=bbf6508f271a84a2c39d",
-    3567,
+    "main.js.gz?var=e0cd056ace173b6df0d1",
+    3568,
   ],
   Array [
-    "main.js?var=bbf6508f271a84a2c39d",
-    15236,
+    "main.js?var=e0cd056ace173b6df0d1#hash",
+    15241,
   ],
 ]
 `;
diff --git a/test/cache-option.test.js b/test/cache-option.test.js
index 408d6f1..c047d27 100644
--- a/test/cache-option.test.js
+++ b/test/cache-option.test.js
@@ -26,17 +26,7 @@ const uniqueCacheDirectory = findCacheDir({ name: 'unique-cache-directory' });
 
 if (getCompiler.isWebpack4()) {
   describe('"cache" option', () => {
-    beforeEach(() => {
-      return Promise.all([
-        cacache.rm.all(falseCacheDirectory),
-        cacache.rm.all(cacheDir),
-        cacache.rm.all(otherCacheDir),
-        cacache.rm.all(uniqueCacheDirectory),
-        cacache.rm.all(otherOtherCacheDir),
-      ]);
-    });
-
-    afterAll(() => {
+    beforeAll(() => {
       return Promise.all([
         cacache.rm.all(falseCacheDirectory),
         cacache.rm.all(cacheDir),
diff --git a/test/filename-option.test.js b/test/filename-option.test.js
index f1d72f1..3d714f5 100644
--- a/test/filename-option.test.js
+++ b/test/filename-option.test.js
@@ -1,3 +1,5 @@
+import path from 'path';
+
 import CompressionPlugin from '../src/index';
 
 import {
@@ -13,25 +15,25 @@ describe('"filename" option', () => {
   let compiler;
 
   beforeEach(() => {
+    return removeCache();
+  });
+
+  it('matches snapshot for `[path][base].super-compressed.gz[query][fragment]` value ({String})', async () => {
     compiler = getCompiler(
       './entry.js',
       {},
       {
         output: {
-          path: `${__dirname}/dist`,
-          filename: '[name].js?var=[hash]',
-          chunkFilename: '[id].[name].js?ver=[hash]',
+          path: path.resolve(__dirname, './outputs'),
+          filename: 'assets/js/[name].js?var=[hash]#hash',
+          chunkFilename: 'assets/js/[id].[name].js?ver=[hash]#hash',
         },
       }
     );
 
-    return removeCache();
-  });
-
-  it('matches snapshot for `[path].super-compressed.gz[query]` value ({String})', async () => {
     new CompressionPlugin({
       minRatio: 1,
-      filename: '[path].super-compressed.gz[query]',
+      filename: '[path][base].super-compressed.gz[query][fragment]',
     }).apply(compiler);
 
     const stats = await compile(compiler);
@@ -41,10 +43,22 @@ describe('"filename" option', () => {
     expect(getErrors(stats)).toMatchSnapshot('warnings');
   });
 
-  it('matches snapshot for `[dir][name].super-compressed.gz[ext][query]` value ({String})', async () => {
+  it('matches snapshot for `[name][ext].super-compressed.gz[query]` value ({String})', async () => {
+    compiler = getCompiler(
+      './entry.js',
+      {},
+      {
+        output: {
+          path: path.resolve(__dirname, './outputs'),
+          filename: '[name].js?var=[hash]',
+          chunkFilename: '[id].[name].js?ver=[hash]',
+        },
+      }
+    );
+
     new CompressionPlugin({
       minRatio: 1,
-      filename: '[dir][name].super-compressed.gz[ext][query]',
+      filename: '[name].super-compressed[ext].gz[query]',
     }).apply(compiler);
 
     const stats = await compile(compiler);
@@ -55,10 +69,22 @@ describe('"filename" option', () => {
   });
 
   it('matches snapshot for custom function ({Function})', async () => {
+    compiler = getCompiler(
+      './entry.js',
+      {},
+      {
+        output: {
+          path: path.resolve(__dirname, './outputs'),
+          filename: '[name].js?var=[hash]#hash',
+          chunkFilename: '[id].[name].js?ver=[hash]#hash',
+        },
+      }
+    );
+
     new CompressionPlugin({
       minRatio: 1,
       filename(info) {
-        return `${info.path}.gz${info.query}`;
+        return `[name][ext].gz${info.query}`;
       },
     }).apply(compiler);