├── .codecov.yml ├── .gitignore ├── .mergify.yml ├── .travis.yml ├── LICENSE ├── README.md ├── build.sbt ├── js └── src │ ├── main │ └── scala │ │ └── com │ │ └── danielasfregola │ │ └── randomdatagenerator │ │ ├── RandomDataGenerator.scala │ │ └── utils │ │ └── SeedVariable.scala │ └── test │ └── scala │ └── com │ └── danielasfregola │ └── randomdatagenerator │ └── JSRandomDataGeneratorSpec.scala ├── jvm └── src │ ├── main │ └── scala │ │ └── com │ │ └── danielasfregola │ │ └── randomdatagenerator │ │ ├── RandomDataGenerator.scala │ │ └── utils │ │ └── SeedVariable.scala │ └── test │ └── scala │ └── com │ └── danielasfregola │ └── randomdatagenerator │ └── JVMRandomDataGeneratorSpec.scala ├── project ├── build.properties └── plugins.sbt ├── shared └── src │ ├── main │ └── scala │ │ └── com │ │ └── danielasfregola │ │ └── randomdatagenerator │ │ ├── RandomDataException.scala │ │ └── utils │ │ ├── PrettyPrinter.scala │ │ ├── SeedDetector.scala │ │ └── ShapelessLike.scala │ └── test │ └── scala │ └── com │ └── danielasfregola │ └── randomdatagenerator │ ├── RandomDataGeneratorSpec.scala │ └── utils │ ├── PrettyPrinterSpec.scala │ └── SeedDetectorSpec.scala ├── sonatype.sbt └── travis └── setNodeVersion.sh /.codecov.yml: -------------------------------------------------------------------------------- 1 | coverage: 2 | status: 3 | project: 4 | default: off 5 | js: 6 | flags: js 7 | jvm: 8 | flags: jvm 9 | 10 | flags: 11 | jvm: 12 | paths: 13 | - jvm/ 14 | js: 15 | paths: 16 | - js/ 17 | tests: 18 | paths: 19 | - js/src/test/ 20 | - jvm/src/test/ 21 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Created by .ignore support plugin (hsz.mobi) 2 | ### SBT template 3 | # Simple Build Tool 4 | # http://www.scala-sbt.org/release/docs/Getting-Started/Directories.html#configuring-version-control 5 | 6 | target/ 7 | lib_managed/ 8 | src_managed/ 9 | project/boot/ 10 | .history 11 | .cache 12 | 13 | 14 | ### Scala template 15 | *.class 16 | *.log 17 | 18 | # sbt specific 19 | .cache 20 | .history 21 | .lib/ 22 | dist/* 23 | target/ 24 | lib_managed/ 25 | src_managed/ 26 | project/boot/ 27 | project/plugins/project/ 28 | 29 | # Scala-IDE specific 30 | .scala_dependencies 31 | .worksheet 32 | .idea 33 | -------------------------------------------------------------------------------- /.mergify.yml: -------------------------------------------------------------------------------- 1 | pull_request_rules: 2 | - name: automatically merge scala-steward's PRs 3 | conditions: 4 | - author=scala-steward 5 | - status-success=Travis CI - Pull Request 6 | actions: 7 | merge: 8 | method: merge 9 | comment: 10 | message: "Thank you Scala Steward! :heart:" 11 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: scala 2 | 3 | os: linux 4 | 5 | dist: xenial 6 | 7 | cache: 8 | directories: 9 | - $HOME/.ivy2/cache 10 | - $HOME/.sbt/boot/ 11 | 12 | before_cache: 13 | - find $HOME/.ivy2 -name "ivydata-*.properties" -delete 14 | - find $HOME/.sbt -name "*.lock" -delete 15 | 16 | script: 17 | - sbt clean rootJVM/test rootJS/test 18 | 19 | after_success: 20 | - bash <(curl -s https://codecov.io/bash) 21 | 22 | scala: 23 | - 2.13.0 24 | - 2.12.8 25 | 26 | env: 27 | - SBT_OPTS="-XX:+UseConcMarkSweepGC -XX:+CMSClassUnloadingEnabled -XX:PermSize=256M -XX:MaxPermSize=512M" 28 | 29 | install: 30 | - source travis/setNodeVersion.sh 31 | 32 | # whitelist 33 | branches: 34 | only: 35 | - master 36 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | random-data-generator 2 | ===================== 3 | 4 | [![Build Status](https://travis-ci.org/DanielaSfregola/random-data-generator.svg?branch=master)](https://travis-ci.org/DanielaSfregola/random-data-generator) [![License](http://img.shields.io/:license-Apache%202-red.svg)](http://www.apache.org/licenses/LICENSE-2.0.txt) [![Scala Steward badge](https://img.shields.io/badge/Scala_Steward-helping-brightgreen.svg?style=flat&logo=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA4AAAAQCAMAAAARSr4IAAAAVFBMVEUAAACHjojlOy5NWlrKzcYRKjGFjIbp293YycuLa3pYY2LSqql4f3pCUFTgSjNodYRmcXUsPD/NTTbjRS+2jomhgnzNc223cGvZS0HaSD0XLjbaSjElhIr+AAAAAXRSTlMAQObYZgAAAHlJREFUCNdNyosOwyAIhWHAQS1Vt7a77/3fcxxdmv0xwmckutAR1nkm4ggbyEcg/wWmlGLDAA3oL50xi6fk5ffZ3E2E3QfZDCcCN2YtbEWZt+Drc6u6rlqv7Uk0LdKqqr5rk2UCRXOk0vmQKGfc94nOJyQjouF9H/wCc9gECEYfONoAAAAASUVORK5CYII=)](https://scala-steward.org) [![Chat](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/random-data-generator/Lobby) 5 | 6 | 7 | A library to generate random data for test purposes, using [ScalaCheck](https://github.com/rickynils/scalacheck) and [scalacheck-shapeless](https://github.com/alexarchambault/scalacheck-shapeless). 8 | 9 | This library has been presented at Scalar 2017: have a look at the [slides](https://speakerdeck.com/danielasfregola/random-data-generation-with-scalacheck-scalar-2017) and the [video](https://www.youtube.com/watch?v=Yx64dgTkX5k&list=PL8NC5lCgGs6Pd7RCawHK4XN0oq23oRe7U&index=11) of the presentation. 10 | 11 | Setup 12 | ----- 13 | Supported Scala versions: 2.12+ 14 | 15 | Scala JS is also supported! 16 | 17 | If you don't have it already, make sure you add the Maven Central as resolver in your SBT settings: 18 | ```scala 19 | resolvers += Resolver.sonatypeRepo("releases") 20 | ``` 21 | 22 | Also, you need to include the library as your dependency: 23 | ```scala 24 | libraryDependencies += "com.danielasfregola" %% "random-data-generator" % "2.9" 25 | ``` 26 | 27 | Usage 28 | ----- 29 | Extends the trait [`RandomDataGenerator`](https://github.com/DanielaSfregola/random-data-generator/blob/master/js/src/main/scala/com/danielasfregola/randomdatagenerator/RandomDataGenerator.scala) to add the function `random` to your scope. 30 | Once the trait has been extended, you can just use the random function as following: 31 | 32 | ```scala 33 | import com.danielasfregola.randomdatagenerator.RandomDataGenerator 34 | 35 | object MyApp extends RandomDataGenerator { 36 | 37 | case class Example(text: String, n: Int) 38 | 39 | val example: Example = random[Example] 40 | // Example(ਈ䈦㈾钜㔪旅ꪔ墛炝푰⡨䌆ᵅ퍧咪, 73967257) 41 | } 42 | ``` 43 | 44 | Alternatively, you can import [`RandomDataGenerator`](https://github.com/DanielaSfregola/random-data-generator/blob/master/js/src/main/scala/com/danielasfregola/randomdatagenerator/RandomDataGenerator.scala) as object: 45 | 46 | ```scala 47 | import com.danielasfregola.randomdatagenerator.RandomDataGenerator._ 48 | 49 | case class Example(text: String, n: Int) 50 | 51 | val example: Example = random[Example] 52 | // Example(巵腉밞鵾Վ뎠꿷덊,2147483647) 53 | 54 | 55 | ``` 56 | 57 | Have a look at the [tests](/shared/src/test/scala/com/danielasfregola/randomdatagenerator/RandomDataGeneratorSpec.scala) for more examples on how to use the library and on how to generate manual instances of `Arbitrary[T]` when needed. 58 | 59 | Seed Selection 60 | -------------- 61 | At the beginning of each test session, a seed is selected and used across all the tests. 62 | The select seed is communicated in the logs. The log message looks something like the following: 63 | ```bash 64 | [info] [RandomDataGenerator] Generating random data using seed 6260565278463862333 65 | ``` 66 | 67 | Fix your Seed 68 | ------------- 69 | When investigating bugs or test failures, it can be useful to reproduce the same generated data of a specific session. 70 | 71 | For every session, a seed is selected and communicated in the logs. The log message will look similar to the following: 72 | ```bash 73 | [info] [RandomDataGenerator] Generating random data using seed 6260565278463862333 74 | [info] [RandomDataGenerator] Replicate this session by setting RANDOM_DATA_GENERATOR_SEED=6260565278463862333 75 | 76 | ``` 77 | 78 | To generate the same data again, all you need to do is specify an environment variable indicating the seed number to use: 79 | ```bash 80 | export RANDOM_DATA_GENERATOR_SEED=6260565278463862333 81 | ``` 82 | 83 | Once you are done, remember to remove the environment variable: 84 | ```bash 85 | unset RANDOM_DATA_GENERATOR_SEED 86 | ``` 87 | 88 | When a fix seed variable is detected, in the logs you will see something similar to the following: 89 | ```bash 90 | [info] [RandomDataGenerator] Variable RANDOM_DATA_GENERATOR_SEED detected: setting 6260565278463862333 as seed 91 | ``` 92 | otherwise, the following message will appear: 93 | ```bash 94 | [info] [RandomDataGenerator] No variable RANDOM_DATA_GENERATOR_SEED detected: setting seed to random number 95 | ``` 96 | 97 | Multiple Random Instances 98 | ------------------------- 99 | Fixing the seed at the beginning of each session has an important side effect: when calling the function `random[T]`, we always get the same instance back. 100 | However, sometimes we do need multiple instances of the same case class within the same test. 101 | 102 | To generate multiple instances of the same case class use the `random[T](n: Int)` function as following: 103 | ```scala 104 | import com.danielasfregola.randomdatagenerator.RandomDataGenerator._ 105 | 106 | val examples: Seq[Example] = random[Example](2) 107 | // List(Example(ਈ䈦㈾钜㔪旅ꪔ墛炝푰⡨䌆ᵅ퍧咪, 73967257), Example(᭞㩵᭟뛎Ժ䌑讵蓐ꍊꎼꙐ涌㰑袽,1736119865)) 108 | ``` 109 | 110 | Improve the Compilation Time 111 | ---------------------------- 112 | [random-data-generator](https://github.com/DanielaSfregola/random-data-generator) heavily uses [Shapeless](https://github.com/milessabin/shapeless), so its compilation time can be slow at times -- but think of all the magic that the compiler is doing for you! 113 | 114 | To improve the compilation time, you can cache your implicit `Arbitrary` instances using `shapeless.cachedImplicit`: 115 | 116 | ```scala 117 | import shapeless._ 118 | 119 | object CachedArbitraries { 120 | implicit val arbA: Arbitrary[A] = cachedImplicit 121 | implicit val arbB: Arbitrary[B] = cachedImplicit 122 | } 123 | ``` 124 | For more information on what it is and on how to use it have a look [here](http://stackoverflow.com/a/34401558). 125 | 126 | Snapshot Versions 127 | ----------------- 128 | To use a snapshot version of this library, make sure you have the resolver for maven central (snapshot repositories) in your SBT settings: 129 | ```scala 130 | resolvers += Resolver.sonatypeRepo("snapshots") 131 | ``` 132 | 133 | Then, add the library as your dependency: 134 | ```scala 135 | libraryDependencies += "com.danielasfregola" %% "random-data-generator" % "2.10-SNAPSHOT" 136 | ``` 137 | -------------------------------------------------------------------------------- /build.sbt: -------------------------------------------------------------------------------- 1 | import com.typesafe.sbt.SbtGit.GitKeys._ 2 | import sbtcrossproject.CrossPlugin.autoImport.{crossProject, CrossType} 3 | 4 | lazy val standardSettings = Seq( 5 | organization := "com.danielasfregola", 6 | version := "2.10-SNAPSHOT", 7 | scalaVersion := "2.13.8", 8 | crossScalaVersions := Seq("2.13.8", "2.12.8"), 9 | scalacOptions in Test ++= Seq("-Yrangepos"), 10 | licenses += ("Apache-2.0", url("http://www.apache.org/licenses/LICENSE-2.0.html")), 11 | homepage := Some(url("https://github.com/DanielaSfregola/random-data-generator")), 12 | scmInfo := Some( 13 | ScmInfo(url("https://github.com/DanielaSfregola/random-data-generator"), 14 | "scm:git:git@github.com:DanielaSfregola/random-data-generator.git")), 15 | apiURL := None, // TBD scaladoc needed? 16 | pomExtra := ( 17 | 18 | 19 | DanielaSfregola 20 | Daniela Sfregola 21 | http://danielasfregola.com/ 22 | 23 | 24 | ), 25 | publishMavenStyle := true, 26 | publishTo in ThisBuild := { 27 | if (version.value.trim.endsWith("SNAPSHOT")) Some(Opts.resolver.sonatypeSnapshots) 28 | else Some(Opts.resolver.sonatypeStaging) 29 | }, 30 | gitRemoteRepo := "git@github.com:DanielaSfregola/random-data-generator.git", 31 | scalacOptions ++= Seq("-encoding", 32 | "UTF-8", 33 | "-deprecation", 34 | "-Xfatal-warnings", 35 | "-feature", 36 | "-language:postfixOps", 37 | "-unchecked"), 38 | scalacOptions in (Compile, doc) ++= Seq("-sourcepath", baseDirectory.value.getAbsolutePath), 39 | autoAPIMappings := true, 40 | apiURL := None, 41 | scalacOptions in (Compile, doc) ++= { 42 | val branch = if (version.value.trim.endsWith("SNAPSHOT")) "master" else version.value 43 | Seq( 44 | "-doc-source-url", 45 | "https://github.com/DanielaSfregola/random-data-generator/tree/" + branch + "€{FILE_PATH}.scala" 46 | ) 47 | } 48 | ) 49 | 50 | lazy val root = 51 | crossProject(JSPlatform, JVMPlatform) 52 | .crossType(CrossType.Full) 53 | .in(file(".")) 54 | .settings(standardSettings) 55 | .settings( 56 | name := "random-data-generator", 57 | libraryDependencies ++= { 58 | val ScalacheckShapeless = "1.3.0" 59 | val Spec2 = "4.10.3" 60 | 61 | Seq( 62 | "com.github.alexarchambault" %%% "scalacheck-shapeless_1.15" % ScalacheckShapeless, 63 | "org.scala-lang" % "scala-reflect" % scalaVersion.value % "provided", 64 | "org.specs2" %%% "specs2-core" % Spec2 % "test" 65 | ) 66 | } 67 | ) 68 | 69 | lazy val rootJS = root.js 70 | lazy val rootJVM = root.jvm 71 | -------------------------------------------------------------------------------- /js/src/main/scala/com/danielasfregola/randomdatagenerator/RandomDataGenerator.scala: -------------------------------------------------------------------------------- 1 | package com.danielasfregola.randomdatagenerator 2 | 3 | import com.danielasfregola.randomdatagenerator.utils.{SeedDetector, ShapelessLike} 4 | import org.scalacheck._ 5 | 6 | import scala.reflect.ClassTag 7 | import scala.util.{Success, Try} 8 | 9 | object RandomDataGenerator extends RandomDataGenerator 10 | 11 | trait RandomDataGenerator extends ShapelessLike { 12 | 13 | protected[randomdatagenerator] val seed = SeedDetector.seed 14 | 15 | def random[T: Arbitrary: ClassTag]: T = { 16 | val arbitrary = implicitly[Arbitrary[T]] 17 | val ct = implicitly[ClassTag[T]] 18 | random(1)(arbitrary, ct).head 19 | } 20 | 21 | def random[T: Arbitrary: ClassTag](n: Int): Seq[T] = { 22 | val gen = Gen.infiniteStream(implicitly[Arbitrary[T]].arbitrary) 23 | Try(gen.apply(Gen.Parameters.default, seed)) match { 24 | case Success(Some(v)) => v.take(n) 25 | case _ => explode[T] 26 | } 27 | } 28 | 29 | private def explode[T: ClassTag]() = { 30 | val classTag = implicitly[ClassTag[T]] 31 | val msg = 32 | s"""Could not generate a random value for $classTag. 33 | |Please, make use that the Arbitrary instance for type $classTag is not too restrictive""".stripMargin 34 | throw new RandomDataException(msg) 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /js/src/main/scala/com/danielasfregola/randomdatagenerator/utils/SeedVariable.scala: -------------------------------------------------------------------------------- 1 | package com.danielasfregola.randomdatagenerator.utils 2 | 3 | import scala.util.Try 4 | import scala.scalajs.js 5 | 6 | protected[utils] object SeedVariable { 7 | 8 | lazy val name = "RANDOM_DATA_GENERATOR_SEED" 9 | 10 | lazy val value = Try { 11 | val fromEnv = js.Dynamic.global.process.env.selectDynamic(name) 12 | if (js.isUndefined(fromEnv)) { 13 | throw new Exception("Seed not defined by user") 14 | } else { 15 | fromEnv.toString 16 | } 17 | }.toOption 18 | 19 | } 20 | -------------------------------------------------------------------------------- /js/src/test/scala/com/danielasfregola/randomdatagenerator/JSRandomDataGeneratorSpec.scala: -------------------------------------------------------------------------------- 1 | package com.danielasfregola.randomdatagenerator 2 | 3 | import org.scalacheck._ 4 | import org.specs2.mutable._ 5 | 6 | class JSRandomDataGeneratorSpec extends RandomDataGenerator with SpecificationLike { 7 | 8 | "RandomDataGenerator" should { 9 | 10 | "throw an exception when the arbitrary is too restrictive" in { 11 | case class Example(text: String, n: Int) 12 | 13 | implicit val restrictive = Arbitrary(Gen.chooseNum(1, 100).suchThat(_ > 200)) 14 | random[Example] must throwA[RandomDataException] 15 | } 16 | 17 | } 18 | 19 | } 20 | -------------------------------------------------------------------------------- /jvm/src/main/scala/com/danielasfregola/randomdatagenerator/RandomDataGenerator.scala: -------------------------------------------------------------------------------- 1 | package com.danielasfregola.randomdatagenerator 2 | 3 | import com.danielasfregola.randomdatagenerator.utils.{SeedDetector, ShapelessLike} 4 | import org.scalacheck._ 5 | 6 | import scala.reflect.runtime.universe._ 7 | import scala.util.{Success, Try} 8 | 9 | object RandomDataGenerator extends RandomDataGenerator 10 | 11 | trait RandomDataGenerator extends ShapelessLike { 12 | 13 | protected[randomdatagenerator] val seed = SeedDetector.seed 14 | 15 | def random[T: WeakTypeTag: Arbitrary]: T = random(1).head 16 | 17 | def random[T: WeakTypeTag: Arbitrary](n: Int): Seq[T] = { 18 | val gen = Gen.infiniteStream(implicitly[Arbitrary[T]].arbitrary) 19 | Try(gen.apply(Gen.Parameters.default, seed)) match { 20 | case Success(Some(v)) => v.take(n) 21 | case _ => explode[T] 22 | } 23 | } 24 | 25 | private def explode[T: WeakTypeTag]() = { 26 | val tpe = implicitly[WeakTypeTag[T]].tpe 27 | val msg = 28 | s"""Could not generate a random value for $tpe. 29 | |Please, make use that the Arbitrary instance for type $tpe is not too restrictive""".stripMargin 30 | throw new RandomDataException(msg) 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /jvm/src/main/scala/com/danielasfregola/randomdatagenerator/utils/SeedVariable.scala: -------------------------------------------------------------------------------- 1 | package com.danielasfregola.randomdatagenerator.utils 2 | 3 | import scala.util.Properties 4 | 5 | protected[utils] object SeedVariable { 6 | 7 | lazy val name = "RANDOM_DATA_GENERATOR_SEED" 8 | 9 | lazy val value = Properties.envOrNone(name) 10 | 11 | } 12 | -------------------------------------------------------------------------------- /jvm/src/test/scala/com/danielasfregola/randomdatagenerator/JVMRandomDataGeneratorSpec.scala: -------------------------------------------------------------------------------- 1 | package com.danielasfregola.randomdatagenerator 2 | 3 | import java.util.Currency 4 | 5 | import org.scalacheck._ 6 | import org.specs2.mutable._ 7 | 8 | class JVMRandomDataGeneratorSpec extends RandomDataGenerator with SpecificationLike { 9 | 10 | "RandomDataGenerator" should { 11 | 12 | "generate a random instance of a non-predefined type" in { 13 | 14 | implicit val arbitraryCurrency: Arbitrary[Currency] = Arbitrary { 15 | Gen.oneOf(Currency.getInstance("USD"), Currency.getInstance("GBP"), Currency.getInstance("EUR")) 16 | } 17 | 18 | val instance = random[Currency] 19 | 20 | instance should beAnInstanceOf[Currency] 21 | } 22 | 23 | "throw an exception when the arbitrary is too restrictive" in { 24 | case class Example(text: String, n: Int) 25 | 26 | implicit val restrictive = Arbitrary(Gen.chooseNum(1, 100).suchThat(_ > 200)) 27 | val expectedException = new RandomDataException( 28 | """Could not generate a random value for Example. 29 | |Please, make use that the Arbitrary instance for type Example is not too restrictive""".stripMargin) 30 | random[Example] must throwA(expectedException) 31 | } 32 | 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /project/build.properties: -------------------------------------------------------------------------------- 1 | sbt.version = 1.4.7 2 | -------------------------------------------------------------------------------- /project/plugins.sbt: -------------------------------------------------------------------------------- 1 | addSbtPlugin("com.typesafe.sbt" % "sbt-site" % "1.4.1") 2 | 3 | addSbtPlugin("com.typesafe.sbt" % "sbt-ghpages" % "0.6.3") 4 | 5 | addSbtPlugin("com.github.sbt" % "sbt-unidoc" % "0.5.0") 6 | 7 | resolvers += Classpaths.sbtPluginReleases 8 | 9 | addSbtPlugin("org.scoverage" % "sbt-coveralls" % "1.3.1") 10 | 11 | addSbtPlugin("org.xerial.sbt" % "sbt-sonatype" % "3.9.12") 12 | 13 | addSbtPlugin("com.github.sbt" % "sbt-pgp" % "2.1.2") 14 | 15 | // cross-compiling 16 | addSbtPlugin("org.portable-scala" % "sbt-scalajs-crossproject" % "1.1.0") 17 | addSbtPlugin("org.scala-js" % "sbt-scalajs" % "1.9.0") -------------------------------------------------------------------------------- /shared/src/main/scala/com/danielasfregola/randomdatagenerator/RandomDataException.scala: -------------------------------------------------------------------------------- 1 | package com.danielasfregola.randomdatagenerator 2 | 3 | final case class RandomDataException(msg: String) extends Exception(msg) 4 | -------------------------------------------------------------------------------- /shared/src/main/scala/com/danielasfregola/randomdatagenerator/utils/PrettyPrinter.scala: -------------------------------------------------------------------------------- 1 | package com.danielasfregola.randomdatagenerator.utils 2 | 3 | private[randomdatagenerator] class PrettyPrinter(printF: String => Unit = println) { 4 | 5 | def info(msg: String) = prettyPrint("info", msg) 6 | def warning(msg: String) = prettyPrint("warn", msg) 7 | def error(msg: String) = prettyPrint("error", msg) 8 | def debug(msg: String) = prettyPrint("debug", msg) 9 | 10 | private def prettyPrint(level: String, msg: String) = 11 | printF(s"[$level] [RandomDataGenerator] $msg") 12 | } 13 | -------------------------------------------------------------------------------- /shared/src/main/scala/com/danielasfregola/randomdatagenerator/utils/SeedDetector.scala: -------------------------------------------------------------------------------- 1 | package com.danielasfregola.randomdatagenerator.utils 2 | 3 | import org.scalacheck.rng.Seed 4 | 5 | import scala.util.{Failure, Success, Try} 6 | 7 | private[randomdatagenerator] object SeedDetector extends SeedDetector 8 | 9 | private[randomdatagenerator] trait SeedDetector { 10 | 11 | protected lazy val logger = new PrettyPrinter() 12 | 13 | 14 | lazy val seed: Seed = createSeedObj(seedValue) 15 | 16 | private def createSeedObj(seedValue: Long): Seed = { 17 | logger.info(s"Generating random data using seed $seedValue") 18 | logger.info(s"Replicate this session by setting ${SeedVariable.name}=$seedValue") 19 | Seed(seedValue) 20 | } 21 | 22 | private lazy val seedValue: Long = optLongVariable match { 23 | case Some(preSelectedSeed) => 24 | logger.info(s"Variable ${SeedVariable.name} detected: setting $preSelectedSeed as seed") 25 | preSelectedSeed 26 | case None => 27 | logger.info(s"No variable ${SeedVariable.name} detected: setting random seed") 28 | randomLong 29 | } 30 | 31 | private lazy val optLongVariable: Option[Long] = envVariable.map { value => 32 | Try(value.toLong) match { 33 | case Success(l) => l 34 | case Failure(ex) => throw new RuntimeException(s"Please, provide a numeric value for ${SeedVariable.name}", ex) 35 | } 36 | } 37 | 38 | protected lazy val envVariable: Option[String] = SeedVariable.value 39 | protected def randomLong = scala.util.Random.nextLong 40 | } 41 | -------------------------------------------------------------------------------- /shared/src/main/scala/com/danielasfregola/randomdatagenerator/utils/ShapelessLike.scala: -------------------------------------------------------------------------------- 1 | package com.danielasfregola.randomdatagenerator.utils 2 | 3 | import org.scalacheck.derive._ 4 | 5 | private[randomdatagenerator] trait ShapelessLike 6 | extends SingletonInstances 7 | with HListInstances 8 | with CoproductInstances 9 | with DerivedInstances 10 | with FieldTypeInstances 11 | -------------------------------------------------------------------------------- /shared/src/test/scala/com/danielasfregola/randomdatagenerator/RandomDataGeneratorSpec.scala: -------------------------------------------------------------------------------- 1 | package com.danielasfregola.randomdatagenerator 2 | 3 | import org.scalacheck._ 4 | import org.specs2.mutable._ 5 | 6 | class RandomDataGeneratorSpec extends RandomDataGenerator with SpecificationLike { 7 | 8 | "RandomDataGenerator" should { 9 | 10 | "generate a random instance of a simple case class" in { 11 | case class Example(text: String, n: Int) 12 | 13 | val instance = random[Example] 14 | 15 | instance should beAnInstanceOf[Example] 16 | } 17 | 18 | "generate multiple instances of a simple case class" in { 19 | case class Example(text: String, n: Int) 20 | 21 | val size = 3 22 | val instances = random[Example](size) 23 | 24 | instances.distinct.size === size 25 | instances should beAnInstanceOf[Seq[Example]] 26 | } 27 | 28 | "generate a random instance by using a custom generator" in { 29 | case class Person(name: String, age: Int) 30 | 31 | implicit val arbitraryPerson: Arbitrary[Person] = Arbitrary { 32 | for { 33 | name <- Gen.oneOf("Daniela", "John", "Martin", "Marco") 34 | age <- Gen.choose(0, 100) 35 | } yield Person(name, age) 36 | } 37 | 38 | val instance = random[Person] 39 | 40 | instance should beAnInstanceOf[Person] 41 | Seq("Daniela", "John", "Martin", "Marco").contains(instance.name) should beTrue 42 | (0 to 100).contains(instance.age) should beTrue 43 | } 44 | 45 | "generate a random instance by using a overridden generator of a predefined type" in { 46 | case class AlphaStrExample(text: String) 47 | 48 | implicit val arbitraryString: Arbitrary[String] = Arbitrary(Gen.alphaStr) 49 | 50 | val instance = random[AlphaStrExample] 51 | 52 | instance should beAnInstanceOf[AlphaStrExample] 53 | instance.text.forall(_.isLetter) should beTrue 54 | } 55 | 56 | "generate a random instance of a case class with more than 22 fields" in { 57 | case class BigExample(f1: String, f2: Int, f3: Long, f4: Char, f5: String, 58 | f6: String, f7: Int, f8: Long, f9: Char, f10: String, 59 | f11: String, f12: Int, f13: Long, f14: Char, f15: String, 60 | f16: String, f17: Int, f18: Long, f19: Char, f20: String, 61 | f21: String, f22: Int, f23: Long, f24: Char, f25: String, 62 | f26: String, f27: Int, f28: Long, f29: Char, f30: String) 63 | 64 | 65 | val instance = random[BigExample] 66 | 67 | instance should beAnInstanceOf[BigExample] 68 | } 69 | 70 | } 71 | 72 | } 73 | -------------------------------------------------------------------------------- /shared/src/test/scala/com/danielasfregola/randomdatagenerator/utils/PrettyPrinterSpec.scala: -------------------------------------------------------------------------------- 1 | package com.danielasfregola.randomdatagenerator.utils 2 | 3 | import org.specs2.mutable._ 4 | import org.specs2.specification.Scope 5 | import scala.collection.mutable.ListBuffer 6 | 7 | class PrettyPrinterSpec extends SpecificationLike { 8 | 9 | abstract class PrettyPrinterSpecContext extends Scope { 10 | val logs: ListBuffer[String] = new ListBuffer 11 | private def append(log: String): Unit = synchronized { logs += log; () } 12 | 13 | val printer = { 14 | val mockPrintF = (log: String) => append(log) 15 | new PrettyPrinter(mockPrintF) 16 | } 17 | } 18 | 19 | "PrettyPrinter" should { 20 | 21 | "print an info message" in new PrettyPrinterSpecContext { 22 | val msg = "This is my info message" 23 | printer.info(msg) 24 | logs must haveSize(1) 25 | logs must_== ListBuffer(s"[info] [RandomDataGenerator] $msg") 26 | } 27 | 28 | "print an warning message" in new PrettyPrinterSpecContext { 29 | val msg = "This is my warning message" 30 | printer.warning(msg) 31 | logs must haveSize(1) 32 | logs must_== ListBuffer(s"[warn] [RandomDataGenerator] $msg") 33 | } 34 | 35 | "print an error message" in new PrettyPrinterSpecContext { 36 | val msg = "This is my error message" 37 | printer.error(msg) 38 | logs must haveSize(1) 39 | logs must_== ListBuffer(s"[error] [RandomDataGenerator] $msg") 40 | } 41 | 42 | "print an debug message" in new PrettyPrinterSpecContext { 43 | val msg = "This is my debug message" 44 | printer.debug(msg) 45 | logs must haveSize(1) 46 | logs must_== ListBuffer(s"[debug] [RandomDataGenerator] $msg") 47 | } 48 | } 49 | 50 | } 51 | -------------------------------------------------------------------------------- /shared/src/test/scala/com/danielasfregola/randomdatagenerator/utils/SeedDetectorSpec.scala: -------------------------------------------------------------------------------- 1 | package com.danielasfregola.randomdatagenerator.utils 2 | 3 | import org.scalacheck.rng.Seed 4 | import org.specs2.mutable._ 5 | import org.specs2.specification.Scope 6 | 7 | class SeedDetectorSpec extends SpecificationLike { 8 | 9 | abstract class SeedDetectorSpecContext extends Scope { 10 | val myRandomLong = scala.util.Random.nextLong 11 | 12 | def buildSeedDetector(myEnvVariable: Option[String]) = new SeedDetector { 13 | override protected lazy val envVariable = myEnvVariable 14 | override protected def randomLong = myRandomLong 15 | } 16 | } 17 | 18 | "SeedDetector" should { 19 | 20 | "when RANDOM_DATA_GENERATOR_SEED is not defined" should { 21 | "randomly select a seed value" in new SeedDetectorSpecContext { 22 | val seedDetector = buildSeedDetector(myEnvVariable = None) 23 | seedDetector.seed === Seed(myRandomLong) 24 | } 25 | } 26 | 27 | "when RANDOM_DATA_GENERATOR_SEED is defined" should { 28 | "set seed to the variable value" in new SeedDetectorSpecContext { 29 | val mySeed = "1234567" 30 | val seedDetector = buildSeedDetector(myEnvVariable = Some(mySeed)) 31 | seedDetector.seed === Seed(mySeed.toLong) 32 | } 33 | 34 | "throw exception if the variable value is not numeric" in new SeedDetectorSpecContext { 35 | val mySeed = "not-a-valid-value" 36 | val seedDetector = buildSeedDetector(myEnvVariable = Some(mySeed)) 37 | seedDetector.seed should throwA[RuntimeException] 38 | } 39 | } 40 | } 41 | 42 | } 43 | -------------------------------------------------------------------------------- /sonatype.sbt: -------------------------------------------------------------------------------- 1 | sonatypeProfileName := "com.danielasfregola" 2 | 3 | pomExtra in Global := { 4 | http://danielasfregola.github.io/random-data-generator 5 | 6 | 7 | Apache 2 8 | http://www.apache.org/licenses/LICENSE-2.0.html 9 | 10 | 11 | 12 | scm:git:github.com/DanielaSfregola/random-data-generator 13 | scm:git:git@github.com:DanielaSfregola/random-data-generator 14 | github.com/DanielaSfregola/random-data-generator 15 | 16 | 17 | 18 | DanielaSfregola 19 | Daniela Sfregola 20 | http://danielasfregola.com/ 21 | 22 | 23 | } 24 | -------------------------------------------------------------------------------- /travis/setNodeVersion.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | TRAVIS_NODE_VERSION=8.12.0 4 | if [ ! -z "$TRAVIS_NODE_VERSION" ]; then 5 | rm -rf ~/.nvm 6 | git clone https://github.com/creationix/nvm.git ~/.nvm 7 | (cd ~/.nvm && git checkout `git describe --abbrev=0 --tags`) 8 | source ~/.nvm/nvm.sh 9 | nvm install $TRAVIS_NODE_VERSION 10 | npm install 11 | fi; 12 | --------------------------------------------------------------------------------