Repository: jhipster/generator-jhipster
Pull request #11789 (2020-05-15 13:36:54)

Fix bug getRecentForLiquibase always passing 1 day and move to utils
-   Please make sure the below checklist is followed for Pull Requests.

-   [ ] [All continuous integration tests](https://github.com/jhipster/generator-jhipster/actions) are green
-   [ ] Tests are added where necessary
-   [ ] Documentation is added/updated where necessary
-   [ ] Coding Rules & Commit Guidelines as per our [CONTRIBUTING.md document](https://github.com/jhipster/generator-jhipster/blob/master/CONTRIBUTING.md) are followed

<!--
Please also reference the issue number in a commit message to [automatically close the related Github issue](https://help.github.com/articles/closing-issues-via-commit-messages/)

Note: It is also possible to add `[skip ci]` or `[ci skip]` to your commit message to skip continuous integration tests
-->


MathieuAA: @mshima Thanks! One thing: should we create another utils file for liquibase-related stuff? I'd like to see the utils file split into content-related stuff
mshima: @MathieuAA utils-liquibase.js?
MathieuAA: @mshima yeah liquibase-utils sounds good!!
mshima: @MathieuAA keep inside generators folder or create utils folder at root?
Creating utils folder at root makes sense to me.
MathieuAA: @mshima Agreed, this makes more sense
mshima: @MathieuAA created utils/liquibase.js instead of utils/liquibase-utils.js.
MathieuAA: Good call. Can you do the same for tests? So as to be consistent with where the tests are kept
MathieuAA: Maybe you're right. You know what? Let's keep your version. I'm approving this
mshima: @MathieuAA thanks.
MathieuAA: I'm seeing one weird issue in the logs:
```
 AccountResourceIT > testRegisterDuplicateLogin() FAILED
    java.lang.IllegalStateException at DefaultCacheAwareContextLoaderDelegate.java:132
        Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException at ConstructorResolver.java:798
            Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException at ConstructorResolver.java:798
                Caused by: org.springframework.beans.factory.BeanCreationException at ConstructorResolver.java:656
                    Caused by: org.springframework.beans.BeanInstantiationException at SimpleInstantiationStrategy.java:185
                        Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException at ConstructorResolver.java:798
                            Caused by: org.springframework.beans.factory.BeanCreationException at ConstructorResolver.java:656
                                Caused by: org.springframework.beans.BeanInstantiationException at SimpleInstantiationStrategy.java:185
                                    Caused by: java.lang.IllegalArgumentException at RedisURI.java:42
```

Patch:
diff --git a/generators/entity-server/files.js b/generators/entity-server/files.js
index 3862f712f8..49d1c7af70 100644
--- a/generators/entity-server/files.js
+++ b/generators/entity-server/files.js
@@ -21,6 +21,7 @@ const chalk = require('chalk');
 const faker = require('faker');
 const fs = require('fs');
 const utils = require('../utils');
+const liquibaseUtils = require('../../utils/liquibase');
 const constants = require('../generator-constants');
 
 /* Use customized randexp */
@@ -33,41 +34,6 @@ const SERVER_MAIN_RES_DIR = constants.SERVER_MAIN_RES_DIR;
 const TEST_DIR = constants.TEST_DIR;
 const SERVER_TEST_SRC_DIR = constants.SERVER_TEST_SRC_DIR;
 
-/*
- * Current faker version is 4.1.0 and was release in 2017
- * It is outdated
- * https://github.com/Marak/faker.js/blob/10bfb9f467b0ac2b8912ffc15690b50ef3244f09/lib/date.js#L73-L96
- * Needed for reproducible builds
- */
-const getRecentDate = function (days, refDate) {
-    let date = new Date();
-    if (refDate !== undefined) {
-        date = new Date(Date.parse(refDate));
-    }
-
-    const range = {
-        min: 1000,
-        max: (days || 1) * 24 * 3600 * 1000,
-    };
-
-    let future = date.getTime();
-    future -= faker.random.number(range); // some time from now to N days ago, in milliseconds
-    date.setTime(future);
-
-    return date;
-};
-
-const getRecentForLiquibase = function (days, changelogDate) {
-    let formatedDate;
-    if (changelogDate !== undefined) {
-        formatedDate = `${changelogDate.substring(0, 4)}-${changelogDate.substring(4, 6)}-${changelogDate.substring(
-            6,
-            8
-        )}T${changelogDate.substring(8, 10)}:${changelogDate.substring(10, 12)}:${changelogDate.substring(12, 14)}+00:00`;
-    }
-    return getRecentDate(1, formatedDate);
-};
-
 /**
  * The default is to use a file path string. It implies use of the template method.
  * For any other config an object { file:.., method:.., template:.. } can be used
@@ -133,7 +99,7 @@ const serverFiles = {
                     options: {
                         interpolate: INTERPOLATE_REGEX,
                         context: {
-                            getRecentForLiquibase,
+                            getRecentForLiquibase: liquibaseUtils.getRecentDateForLiquibase,
                             faker,
                             randexp,
                         },
diff --git a/package.json b/package.json
index de81710a0b..a1afa43aee 100644
--- a/package.json
+++ b/package.json
@@ -4,7 +4,8 @@
     "description": "Spring Boot + Angular/React in one handy generator",
     "files": [
         "cli",
-        "generators"
+        "generators",
+        "utils"
     ],
     "keywords": [
         "yeoman-generator",
diff --git a/utils/liquibase.js b/utils/liquibase.js
new file mode 100644
index 0000000000..d7ae0269b7
--- /dev/null
+++ b/utils/liquibase.js
@@ -0,0 +1,59 @@
+/**
+ * Copyright 2013-2020 the original author or authors from the JHipster project.
+ *
+ * This file is part of the JHipster project, see https://www.jhipster.tech/
+ * for more information.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+const faker = require('faker');
+
+module.exports = { getRecentDateForLiquibase, parseLiquibaseChangelogDate };
+
+/*
+ * Current faker version is 4.1.0 and was release in 2017
+ * It is outdated
+ * https://github.com/Marak/faker.js/blob/10bfb9f467b0ac2b8912ffc15690b50ef3244f09/lib/date.js#L73-L96
+ * Needed for reproducible builds
+ */
+function getRecentDate(days = 1, date = new Date()) {
+    const range = {
+        min: 1000,
+        max: (days || 1) * 24 * 3600 * 1000,
+    };
+
+    let future = date.getTime();
+    future -= faker.random.number(range); // some time from now to N days ago, in milliseconds
+    date.setTime(future);
+
+    return date;
+}
+
+function parseLiquibaseChangelogDate(changelogDate) {
+    if (!changelogDate || changelogDate.length !== 14) {
+        throw new Error('A valid changelogDate is required to parse.');
+    }
+    const formatedDate = `${changelogDate.substring(0, 4)}-${changelogDate.substring(4, 6)}-${changelogDate.substring(
+        6,
+        8
+    )}T${changelogDate.substring(8, 10)}:${changelogDate.substring(10, 12)}:${changelogDate.substring(12, 14)}+00:00`;
+    return new Date(Date.parse(formatedDate));
+}
+
+function getRecentDateForLiquibase(days, changelogDate) {
+    let refDate;
+    if (changelogDate) {
+        refDate = parseLiquibaseChangelogDate(changelogDate);
+    }
+    return getRecentDate(days, refDate);
+}


Test patch:
diff --git a/test/liquibase-utils.spec.js b/test/liquibase-utils.spec.js
new file mode 100644
index 0000000000..3b45510f6e
--- /dev/null
+++ b/test/liquibase-utils.spec.js
@@ -0,0 +1,55 @@
+const expect = require('chai').expect;
+const faker = require('faker');
+const assert = require('yeoman-assert');
+const liquibaseUtils = require('../utils/liquibase');
+
+describe('Liquibase Utils', () => {
+    describe('::parseLiquibaseChangelogDate', () => {
+        describe('when not passing parameters', () => {
+            it('throws', () => {
+                expect(() => liquibaseUtils.parseLiquibaseChangelogDate()).to.throw(/^A valid changelogDate is required to parse\.$/);
+            });
+        });
+        describe('when passing an invalid changelogDate', () => {
+            it('throws', () => {
+                expect(() => liquibaseUtils.parseLiquibaseChangelogDate('1234')).to.throw(/^A valid changelogDate is required to parse\.$/);
+            });
+        });
+        describe('when passing a valid changelogDate', () => {
+            it('returns a date object', () => {
+                assert(liquibaseUtils.parseLiquibaseChangelogDate('20160208210114') instanceof Date);
+            });
+            it('returns the date', () => {
+                assert.equal(liquibaseUtils.parseLiquibaseChangelogDate('20160208210114').toISOString(), '2016-02-08T21:01:14.000Z');
+            });
+        });
+    });
+    describe('::getRecentDateForLiquibase', () => {
+        beforeEach(() => {
+            faker.seed(47);
+        });
+        describe('when not passing parameters', () => {
+            it('returns a date object', () => {
+                assert(liquibaseUtils.getRecentDateForLiquibase() instanceof Date);
+            });
+        });
+        describe('when passing 1 day', () => {
+            it('returns a date object', () => {
+                assert(liquibaseUtils.getRecentDateForLiquibase(1) instanceof Date);
+            });
+        });
+        describe('when passing 1 day with changelogDate', () => {
+            it('returns a date object', () => {
+                assert(liquibaseUtils.getRecentDateForLiquibase(1, '20160208210114') instanceof Date);
+            });
+            it('returns a recent reproducible date', () => {
+                assert.equal(liquibaseUtils.getRecentDateForLiquibase(1, '20160208210114').toISOString(), '2016-02-08T18:17:47.710Z');
+            });
+        });
+        describe('when passing 10 day with changelogDate', () => {
+            it('returns a recent reproducible date', () => {
+                assert.equal(liquibaseUtils.getRecentDateForLiquibase(10, '20160208210114').toISOString(), '2016-02-07T17:46:59.078Z');
+            });
+        });
+    });
+});