├── .github ├── FUNDING.yml └── workflows │ ├── build.yml │ └── publish.yml ├── .gitignore ├── .vscode ├── copyright.code-snippets ├── settings.json └── tasks.json ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── example_test.go ├── go.mod ├── go.sum ├── postgrestest.go └── postgrestest_test.go /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | github: zombiezen 2 | -------------------------------------------------------------------------------- /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | # Copyright 2020 Ross Light 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # https://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | # 15 | # SPDX-License-Identifier: Apache-2.0 16 | 17 | name: Build 18 | on: push 19 | jobs: 20 | linux: 21 | name: Linux 22 | runs-on: ubuntu-latest 23 | steps: 24 | - name: Check out code 25 | uses: actions/checkout@v3 26 | 27 | - name: Set up Go 28 | uses: actions/setup-go@v4 29 | with: 30 | # Run on the latest minor release of Go 1.23: 31 | go-version: ^1.23 32 | 33 | - name: Run tests 34 | run: go test -race -v ./... 35 | 36 | windows: 37 | name: Windows 38 | runs-on: windows-latest 39 | steps: 40 | - name: Check out code 41 | uses: actions/checkout@v3 42 | 43 | - name: Set up Go 44 | uses: actions/setup-go@v4 45 | with: 46 | # Run on the latest minor release of Go 1.23: 47 | go-version: ^1.23 48 | 49 | - name: Run tests 50 | run: go test -race -v ./... 51 | 52 | macos: 53 | name: macOS 54 | runs-on: macos-latest 55 | steps: 56 | - name: Check out code 57 | uses: actions/checkout@v3 58 | 59 | - name: Set up Go 60 | uses: actions/setup-go@v4 61 | with: 62 | # Run on the latest minor release of Go 1.23: 63 | go-version: ^1.23 64 | 65 | - name: Install PostgreSQL 66 | run: | 67 | brew install postgresql 68 | brew link postgresql 69 | 70 | - name: Run tests 71 | run: go test -race -v ./... 72 | -------------------------------------------------------------------------------- /.github/workflows/publish.yml: -------------------------------------------------------------------------------- 1 | # Copyright 2020 Ross Light 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # https://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | # 15 | # SPDX-License-Identifier: Apache-2.0 16 | 17 | name: Publish 18 | on: 19 | release: 20 | types: [published] 21 | jobs: 22 | go-get: 23 | name: go get 24 | runs-on: ubuntu-latest 25 | steps: 26 | - name: Set up Go 27 | uses: actions/setup-go@v4 28 | with: 29 | # Run on the latest minor release of Go 1.23: 30 | go-version: ^1.23 31 | 32 | - name: Fetch release from proxy 33 | run: go get -d github.com/stapelberg/postgrestest@"$(echo "$GITHUB_REF" | sed -e 's:^refs/tags/::')" 34 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Binaries for programs and plugins 2 | *.exe 3 | *.exe~ 4 | *.dll 5 | *.so 6 | *.dylib 7 | 8 | # Test binary, built with `go test -c` 9 | *.test 10 | 11 | # Output of the go coverage tool, specifically when used with LiteIDE 12 | *.out 13 | 14 | # IDEA dot files 15 | # We could also do the same for .vscode 16 | .idea 17 | -------------------------------------------------------------------------------- /.vscode/copyright.code-snippets: -------------------------------------------------------------------------------- 1 | { 2 | "Copyright": { 3 | "prefix": "copyright", 4 | "body": [ 5 | "$LINE_COMMENT Copyright $CURRENT_YEAR Ross Light", 6 | "$LINE_COMMENT", 7 | "$LINE_COMMENT Licensed under the Apache License, Version 2.0 (the \"License\");", 8 | "$LINE_COMMENT you may not use this file except in compliance with the License.", 9 | "$LINE_COMMENT You may obtain a copy of the License at", 10 | "$LINE_COMMENT", 11 | "$LINE_COMMENT https://www.apache.org/licenses/LICENSE-2.0", 12 | "$LINE_COMMENT", 13 | "$LINE_COMMENT Unless required by applicable law or agreed to in writing, software", 14 | "$LINE_COMMENT distributed under the License is distributed on an \"AS IS\" BASIS,", 15 | "$LINE_COMMENT WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", 16 | "$LINE_COMMENT See the License for the specific language governing permissions and", 17 | "$LINE_COMMENT limitations under the License.", 18 | "$LINE_COMMENT", 19 | "$LINE_COMMENT SPDX-License-Identifier: Apache-2.0", 20 | ], 21 | "description": "Apache license header" 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "[markdown]": { 3 | "editor.insertSpaces": true, 4 | "editor.tabSize": 3, 5 | "editor.detectIndentation": false 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /.vscode/tasks.json: -------------------------------------------------------------------------------- 1 | { 2 | // See https://go.microsoft.com/fwlink/?LinkId=733558 3 | // for the documentation about the tasks.json format 4 | "version": "2.0.0", 5 | "tasks": [ 6 | { 7 | "label": "go test", 8 | "type": "process", 9 | "command": "go", 10 | "args": ["test", "./..."], 11 | "group": { 12 | "kind": "test", 13 | "isDefault": true 14 | }, 15 | "presentation": { 16 | "clear": true 17 | }, 18 | "problemMatcher": ["$go"] 19 | } 20 | ] 21 | } 22 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | We as members, contributors, and leaders pledge to make participation in our 6 | community a harassment-free experience for everyone, regardless of age, body 7 | size, visible or invisible disability, ethnicity, sex characteristics, gender 8 | identity and expression, level of experience, education, socio-economic status, 9 | nationality, personal appearance, race, religion, or sexual identity 10 | and orientation. 11 | 12 | We pledge to act and interact in ways that contribute to an open, welcoming, 13 | diverse, inclusive, and healthy community. 14 | 15 | ## Our Standards 16 | 17 | Examples of behavior that contributes to a positive environment for our 18 | community include: 19 | 20 | * Demonstrating empathy and kindness toward other people 21 | * Being respectful of differing opinions, viewpoints, and experiences 22 | * Giving and gracefully accepting constructive feedback 23 | * Accepting responsibility and apologizing to those affected by our mistakes, 24 | and learning from the experience 25 | * Focusing on what is best not just for us as individuals, but for the 26 | overall community 27 | 28 | Examples of unacceptable behavior include: 29 | 30 | * The use of sexualized language or imagery, and sexual attention or 31 | advances of any kind 32 | * Trolling, insulting or derogatory comments, and personal or political attacks 33 | * Public or private harassment 34 | * Publishing others' private information, such as a physical or email 35 | address, without their explicit permission 36 | * Other conduct which could reasonably be considered inappropriate in a 37 | professional setting 38 | 39 | ## Enforcement Responsibilities 40 | 41 | Community leaders are responsible for clarifying and enforcing our standards of 42 | acceptable behavior and will take appropriate and fair corrective action in 43 | response to any behavior that they deem inappropriate, threatening, offensive, 44 | or harmful. 45 | 46 | Community leaders have the right and responsibility to remove, edit, or reject 47 | comments, commits, code, wiki edits, issues, and other contributions that are 48 | not aligned to this Code of Conduct, and will communicate reasons for moderation 49 | decisions when appropriate. 50 | 51 | ## Scope 52 | 53 | This Code of Conduct applies within all community spaces, and also applies when 54 | an individual is officially representing the community in public spaces. 55 | Examples of representing our community include using an official e-mail address, 56 | posting via an official social media account, or acting as an appointed 57 | representative at an online or offline event. 58 | 59 | ## Enforcement 60 | 61 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 62 | reported to the community leaders responsible for enforcement at ross@zombiezen.com. 63 | All complaints will be reviewed and investigated promptly and fairly. 64 | 65 | All community leaders are obligated to respect the privacy and security of the 66 | reporter of any incident. 67 | 68 | ## Enforcement Guidelines 69 | 70 | Community leaders will follow these Community Impact Guidelines in determining 71 | the consequences for any action they deem in violation of this Code of Conduct: 72 | 73 | ### 1. Correction 74 | 75 | **Community Impact**: Use of inappropriate language or other behavior deemed 76 | unprofessional or unwelcome in the community. 77 | 78 | **Consequence**: A private, written warning from community leaders, providing 79 | clarity around the nature of the violation and an explanation of why the 80 | behavior was inappropriate. A public apology may be requested. 81 | 82 | ### 2. Warning 83 | 84 | **Community Impact**: A violation through a single incident or series 85 | of actions. 86 | 87 | **Consequence**: A warning with consequences for continued behavior. No 88 | interaction with the people involved, including unsolicited interaction with 89 | those enforcing the Code of Conduct, for a specified period of time. This 90 | includes avoiding interactions in community spaces as well as external channels 91 | like social media. Violating these terms may lead to a temporary or 92 | permanent ban. 93 | 94 | ### 3. Temporary Ban 95 | 96 | **Community Impact**: A serious violation of community standards, including 97 | sustained inappropriate behavior. 98 | 99 | **Consequence**: A temporary ban from any sort of interaction or public 100 | communication with the community for a specified period of time. No public or 101 | private interaction with the people involved, including unsolicited interaction 102 | with those enforcing the Code of Conduct, is allowed during this period. 103 | Violating these terms may lead to a permanent ban. 104 | 105 | ### 4. Permanent Ban 106 | 107 | **Community Impact**: Demonstrating a pattern of violation of community 108 | standards, including sustained inappropriate behavior, harassment of an 109 | individual, or aggression toward or disparagement of classes of individuals. 110 | 111 | **Consequence**: A permanent ban from any sort of public interaction within 112 | the community. 113 | 114 | ## Attribution 115 | 116 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], 117 | version 2.0, available at 118 | https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. 119 | 120 | Community Impact Guidelines were inspired by [Mozilla's code of conduct 121 | enforcement ladder](https://github.com/mozilla/diversity). 122 | 123 | [homepage]: https://www.contributor-covenant.org 124 | 125 | For answers to common questions about this code of conduct, see the FAQ at 126 | https://www.contributor-covenant.org/faq. Translations are available at 127 | https://www.contributor-covenant.org/translations. 128 | 129 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # `postgrestest` Contributor's Guide 2 | 3 | `postgrestest` is intentionally a very small package, so in general I will not 4 | accept feature requests. However, I am happy to accept bug fixes and support for 5 | more environments. 6 | 7 | File a bug on the [issue tracker][] or [open a pull request][]. Please follow 8 | the [Code of Conduct][] for all interactions. If applicable, add unit tests for 9 | your change before sending out for review. 10 | 11 | [Code of Conduct]: CODE_OF_CONDUCT.md 12 | [issue tracker]: https://github.com/zombiezen/postgrestest/issues/new 13 | [open a pull request]: https://github.com/zombiezen/postgrestest/compare 14 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # `zombiezen.com/go/postgrestest` 2 | 3 | [![Reference](https://pkg.go.dev/badge/zombiezen.com/go/postgrestest?tab=doc)](https://pkg.go.dev/zombiezen.com/go/postgrestest?tab=doc) 4 | [![Contributor Covenant](https://img.shields.io/badge/Contributor%20Covenant-v2.0%20adopted-ff69b4.svg)](CODE_OF_CONDUCT.md) 5 | 6 | Package `postgrestest` provides a test harness that starts an ephemeral 7 | [PostgreSQL][] server. It is tested on macOS, Linux, and Windows. It can cut 8 | down the overhead of PostgreSQL in tests up to 90% compared to spinning up a 9 | `postgres` Docker container: starting a server with this package takes 10 | roughly 650 milliseconds and creating a database takes roughly 20 milliseconds. 11 | 12 | [PostgreSQL]: https://www.postgresql.org/ 13 | 14 | ## Example 15 | 16 | ```go 17 | func TestApp(t *testing.T) { 18 | // Start up the PostgreSQL server. This can take a few seconds, so better to 19 | // do it once per test run. 20 | ctx := context.Background() 21 | srv, err := postgrestest.Start(ctx) 22 | if err != nil { 23 | t.Fatal(err) 24 | } 25 | t.Cleanup(srv.Cleanup) 26 | 27 | // Each of your subtests can have their own database: 28 | t.Run("Test1", func(t *testing.T) { 29 | db, err := srv.NewDatabase(ctx) 30 | if err != nil { 31 | t.Fatal(err) 32 | } 33 | if _, err := db.Exec(`CREATE TABLE foo (id SERIAL PRIMARY KEY);`); err != nil { 34 | t.Fatal(err) 35 | } 36 | // ... 37 | }) 38 | 39 | t.Run("Test2", func(t *testing.T) { 40 | db, err := srv.NewDatabase(ctx) 41 | if err != nil { 42 | t.Fatal(err) 43 | } 44 | if _, err := db.Exec(`CREATE TABLE foo (id SERIAL PRIMARY KEY);`); err != nil { 45 | t.Fatal(err) 46 | } 47 | // ... 48 | }) 49 | } 50 | ``` 51 | 52 | ## Installation 53 | 54 | PostgreSQL must be installed locally for this package to work. See the 55 | [PostgreSQL Downloads page][] for instructions on how to obtain PostgreSQL for 56 | your operating system. 57 | 58 | To install the package: 59 | 60 | ``` 61 | go get zombiezen.com/go/postgrestest 62 | ``` 63 | 64 | [PostgreSQL Downloads page]: https://www.postgresql.org/download/ 65 | 66 | ## License 67 | 68 | [Apache 2.0](LICENSE) 69 | -------------------------------------------------------------------------------- /example_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2020 Ross Light 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // https://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | // 15 | // SPDX-License-Identifier: Apache-2.0 16 | 17 | package postgrestest_test 18 | 19 | import ( 20 | "context" 21 | "testing" 22 | 23 | "zombiezen.com/go/postgrestest" 24 | ) 25 | 26 | func Example() { 27 | var t *testing.T // passed into your testing function 28 | 29 | // Start up the PostgreSQL server. This can take a few seconds, so better to 30 | // do it once per test run. 31 | ctx := context.Background() 32 | srv, err := postgrestest.Start(ctx) 33 | if err != nil { 34 | t.Fatal(err) 35 | } 36 | t.Cleanup(srv.Cleanup) 37 | 38 | // Each of your subtests can have their own database: 39 | t.Run("Test1", func(t *testing.T) { 40 | db, err := srv.NewDatabase(ctx) 41 | if err != nil { 42 | t.Fatal(err) 43 | } 44 | if _, err := db.Exec(`CREATE TABLE foo (id SERIAL PRIMARY KEY);`); err != nil { 45 | t.Fatal(err) 46 | } 47 | // ... 48 | }) 49 | 50 | t.Run("Test2", func(t *testing.T) { 51 | db, err := srv.NewDatabase(ctx) 52 | if err != nil { 53 | t.Fatal(err) 54 | } 55 | if _, err := db.Exec(`CREATE TABLE foo (id SERIAL PRIMARY KEY);`); err != nil { 56 | t.Fatal(err) 57 | } 58 | // ... 59 | }) 60 | } 61 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | // Copyright 2020 Ross Light 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // https://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | // 15 | // SPDX-License-Identifier: Apache-2.0 16 | 17 | module zombiezen.com/go/postgrestest 18 | 19 | go 1.14 20 | 21 | require github.com/lib/pq v1.10.10-0.20241116184759-b7ffbd3b47da 22 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/lib/pq v1.10.10-0.20241116184759-b7ffbd3b47da h1:b0x2DrMfYi9f0dIn36/xrX3ztyam/fByaN14MO48G7s= 2 | github.com/lib/pq v1.10.10-0.20241116184759-b7ffbd3b47da/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= 3 | -------------------------------------------------------------------------------- /postgrestest.go: -------------------------------------------------------------------------------- 1 | // Copyright 2020 Ross Light 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // https://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | // 15 | // SPDX-License-Identifier: Apache-2.0 16 | 17 | // Package postgrestest provides a test harness that starts an ephemeral 18 | // PostgreSQL server. PostgreSQL must be installed locally for this package to 19 | // work. 20 | package postgrestest 21 | 22 | import ( 23 | "context" 24 | "crypto/rand" 25 | "database/sql" 26 | "encoding/base64" 27 | "errors" 28 | "fmt" 29 | "io/ioutil" 30 | "net/url" 31 | "os" 32 | "os/exec" 33 | "path/filepath" 34 | "runtime" 35 | "strconv" 36 | "strings" 37 | "sync" 38 | 39 | _ "github.com/lib/pq" 40 | ) 41 | 42 | const superuserName = "postgres" 43 | 44 | // A Server represents a running PostgreSQL server. 45 | type Server struct { 46 | dir string 47 | baseURL *url.URL 48 | conn *sql.DB 49 | 50 | exited <-chan struct{} 51 | waitErr error 52 | } 53 | 54 | // Start starts a PostgreSQL server with an empty database and waits for it to 55 | // accept connections. 56 | // 57 | // Start looks for the programs "pg_ctl" and "initdb" in PATH. If these are not 58 | // found, then Start searches for them in /usr/lib/postgresql/*/bin, preferring 59 | // the highest version found. 60 | func Start(ctx context.Context) (_ *Server, err error) { 61 | // Prepare data directory. 62 | dir, err := ioutil.TempDir("", "postgrestest") 63 | if err != nil { 64 | return nil, fmt.Errorf("start postgres: %w", err) 65 | } 66 | defer func() { 67 | if err != nil { 68 | os.RemoveAll(dir) 69 | } 70 | }() 71 | dataDir := filepath.Join(dir, "data") 72 | err = runCommand("initdb", 73 | "--no-sync", 74 | "--username="+superuserName, 75 | "-D", dataDir) 76 | if err != nil { 77 | return nil, fmt.Errorf("start postgres: %w", err) 78 | } 79 | const configFormat = "" + 80 | "listen_addresses = ''\n" + 81 | "unix_socket_directories = '%s'\n" + 82 | "fsync = off\n" + 83 | "synchronous_commit = off\n" + 84 | "full_page_writes = off\n" 85 | err = ioutil.WriteFile( 86 | filepath.Join(dataDir, "postgresql.conf"), 87 | []byte(fmt.Sprintf(configFormat, filepath.ToSlash(dir))), 88 | 0666) 89 | if err != nil { 90 | return nil, fmt.Errorf("start postgres: %w", err) 91 | } 92 | 93 | // Start server process. 94 | // On Unix systems, pg_ctl runs as a daemon. 95 | // On Windows systems, pg_ctl runs in the foreground (not well-documented) and 96 | // drops privileges as needed. 97 | logFile := filepath.Join(dir, "log.txt") 98 | proc, err := command("pg_ctl", "start", "--no-wait", "--pgdata="+dataDir, "--log="+logFile) 99 | if err != nil { 100 | return nil, fmt.Errorf("start postgres: %w", err) 101 | } 102 | if err := proc.Start(); err != nil { 103 | return nil, fmt.Errorf("start postgres: %w", err) 104 | } 105 | exited := make(chan struct{}) 106 | srv := &Server{ 107 | dir: dir, 108 | baseURL: &url.URL{ 109 | Scheme: "postgres", 110 | Host: "localhost", 111 | User: url.UserPassword(superuserName, ""), 112 | Path: "/", 113 | RawQuery: (&url.Values{ 114 | "host": []string{dir}, 115 | "sslmode": []string{"disable"}, 116 | }).Encode(), 117 | }, 118 | exited: exited, 119 | } 120 | go func() { 121 | defer close(exited) 122 | srv.waitErr = proc.Wait() 123 | }() 124 | 125 | // Wait for server to come up healthy. 126 | srv.conn, err = sql.Open("postgres", srv.DefaultDatabase()) 127 | if err != nil { 128 | // Failure to open means the DSN is invalid. Connections aren't created 129 | // until we ping. 130 | srv.stop() 131 | return nil, fmt.Errorf("start postgres: %w", err) 132 | } 133 | defer func() { 134 | if err != nil { 135 | srv.conn.Close() 136 | } 137 | }() 138 | srv.conn.SetMaxOpenConns(1) 139 | for { 140 | select { 141 | case <-ctx.Done(): 142 | srv.stop() 143 | logOutput, _ := ioutil.ReadFile(logFile) 144 | if len(logOutput) == 0 { 145 | return nil, fmt.Errorf("start postgres: %w", ctx.Err()) 146 | } 147 | return nil, fmt.Errorf("start postgres: %w\n%s", ctx.Err(), logOutput) 148 | default: 149 | if err := srv.conn.PingContext(ctx); err == nil { 150 | return srv, nil 151 | } 152 | } 153 | } 154 | } 155 | 156 | // DefaultDatabase returns the data source name of the default "postgres" database. 157 | func (srv *Server) DefaultDatabase() string { 158 | return srv.dsn("postgres") 159 | } 160 | 161 | func dsnString(u *url.URL) string { 162 | dsn := u.String() 163 | // We need to set a non-empty Host, otherwise the / separating hostname and 164 | // path will be missing from the String() representation. Hence, we replace 165 | // the first 'localhost' Host with the empty string textually: 166 | dsn = strings.Replace(dsn, "localhost", "", 1) 167 | return dsn 168 | } 169 | 170 | func (srv *Server) dsn(dbName string) string { 171 | u := *srv.baseURL 172 | u.Path = dbName 173 | return dsnString(&u) 174 | } 175 | 176 | // NewDatabase opens a connection to a freshly created database on the server. 177 | func (srv *Server) NewDatabase(ctx context.Context) (*sql.DB, error) { 178 | dsn, err := srv.CreateDatabase(ctx) 179 | if err != nil { 180 | return nil, err 181 | } 182 | return sql.Open("postgres", dsn) 183 | } 184 | 185 | // CreateDatabase creates a new database on the server and returns its 186 | // data source name. 187 | func (srv *Server) CreateDatabase(ctx context.Context) (string, error) { 188 | dbName, err := randomString(16) 189 | if err != nil { 190 | return "", fmt.Errorf("new database: %w", err) 191 | } 192 | _, err = srv.conn.ExecContext(ctx, "CREATE DATABASE \""+dbName+"\";") 193 | if err != nil { 194 | return "", fmt.Errorf("new database: %w", err) 195 | } 196 | return srv.dsn(dbName), nil 197 | } 198 | 199 | // Cleanup shuts down the server and deletes any on-disk files the server used. 200 | func (srv *Server) Cleanup() { 201 | if srv.conn != nil { 202 | srv.conn.Close() 203 | } 204 | srv.stop() 205 | os.RemoveAll(srv.dir) 206 | } 207 | 208 | func (srv *Server) stop() { 209 | // Use Immediate Shutdown mode. We don't care about data corruption. 210 | // https://www.postgresql.org/docs/current/server-shutdown.html 211 | // 212 | // TODO(someday): What happens if this fails? 213 | runCommand("pg_ctl", "stop", 214 | "--pgdata="+filepath.Join(srv.dir, "data"), 215 | "--mode=immediate", 216 | "--wait") 217 | <-srv.exited 218 | } 219 | 220 | // command creates an *exec.Cmd for the given PostgreSQL program. If it it 221 | // cannot find the program on the PATH, then it searches some well-known 222 | // PostgreSQL installation paths. 223 | func command(name string, args ...string) (*exec.Cmd, error) { 224 | if runtime.GOOS == "windows" { 225 | name += ".exe" 226 | } 227 | p, lookErr := exec.LookPath(name) 228 | if lookErr == nil { 229 | return exec.Command(p, args...), nil 230 | } 231 | // Find PostgreSQL installation path. If this doesn't work, return the 232 | // original LookPath error, since the runner of the test should add the binary 233 | // to their PATH if it can't be found. 234 | postgresBin.init.Do(findPostgresBin) 235 | if postgresBin.dir == "" { 236 | return nil, lookErr 237 | } 238 | p = filepath.Join(postgresBin.dir, name) 239 | if _, err := os.Stat(p); err != nil { 240 | return nil, lookErr 241 | } 242 | return exec.Command(p, args...), nil 243 | } 244 | 245 | func findPostgresBin() { 246 | dir := "/usr/lib/postgresql" 247 | if runtime.GOOS == "windows" { 248 | dir = `C:\Program Files\PostgreSQL` 249 | } 250 | listing, err := ioutil.ReadDir(dir) 251 | if err != nil { 252 | return 253 | } 254 | maxVersion := -1 255 | for _, ent := range listing { 256 | v, err := strconv.ParseInt(ent.Name(), 10, 0) 257 | if err != nil || v <= 0 { 258 | continue 259 | } 260 | if int(v) > maxVersion { 261 | maxVersion = int(v) 262 | } 263 | } 264 | if maxVersion < 0 { 265 | return 266 | } 267 | postgresBin.dir = filepath.Join(dir, strconv.Itoa(maxVersion), "bin") 268 | } 269 | 270 | var postgresBin struct { 271 | init sync.Once 272 | dir string 273 | } 274 | 275 | func runCommand(name string, args ...string) error { 276 | c, err := command(name, args...) 277 | if err != nil { 278 | return fmt.Errorf("%s: %w", name, err) 279 | } 280 | out, err := c.CombinedOutput() 281 | if errors.As(err, new(*exec.ExitError)) { 282 | return fmt.Errorf("%s: %s", name, out) 283 | } 284 | if err != nil { 285 | return fmt.Errorf("%s: %w", name, err) 286 | } 287 | return nil 288 | } 289 | 290 | func randomString(n int) (string, error) { 291 | enc := base64.RawURLEncoding 292 | bits := make([]byte, enc.DecodedLen(n)) 293 | if _, err := rand.Read(bits); err != nil { 294 | return "", fmt.Errorf("generate random string: %w", err) 295 | } 296 | return enc.EncodeToString(bits), nil 297 | } 298 | -------------------------------------------------------------------------------- /postgrestest_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2020 Ross Light 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // https://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | // 15 | // SPDX-License-Identifier: Apache-2.0 16 | 17 | package postgrestest 18 | 19 | import ( 20 | "bytes" 21 | "context" 22 | "database/sql" 23 | "fmt" 24 | "net" 25 | "os/exec" 26 | "strings" 27 | "testing" 28 | "time" 29 | ) 30 | 31 | const singleTestTime = 30 * time.Second 32 | 33 | func TestStart(t *testing.T) { 34 | ctx, cancel := context.WithTimeout(context.Background(), singleTestTime) 35 | defer cancel() 36 | srv, err := Start(ctx) 37 | if err != nil { 38 | t.Fatal(err) 39 | } 40 | t.Cleanup(srv.Cleanup) 41 | db, err := sql.Open("postgres", srv.DefaultDatabase()) 42 | if err != nil { 43 | t.Fatal(err) 44 | } 45 | defer db.Close() 46 | db.SetMaxOpenConns(1) 47 | var result int 48 | if err := db.QueryRowContext(ctx, "SELECT 1;").Scan(&result); err != nil { 49 | t.Fatal("Test query:", err) 50 | } 51 | if result != 1 { 52 | t.Errorf("Query returned %d; want 1", result) 53 | } 54 | } 55 | 56 | func TestNewDatabase(t *testing.T) { 57 | ctx, cancel := context.WithTimeout(context.Background(), singleTestTime) 58 | defer cancel() 59 | srv, err := Start(ctx) 60 | if err != nil { 61 | t.Fatal(err) 62 | } 63 | t.Cleanup(srv.Cleanup) 64 | 65 | const createTableStmt = `CREATE TABLE foo (id SERIAL PRIMARY KEY);` 66 | db1, err := srv.NewDatabase(ctx) 67 | if err != nil { 68 | t.Fatal(err) 69 | } 70 | defer db1.Close() 71 | _, err = db1.ExecContext(ctx, createTableStmt) 72 | if err != nil { 73 | t.Fatal("CREATE TABLE in database #1:", err) 74 | } 75 | 76 | db2, err := srv.NewDatabase(ctx) 77 | if err != nil { 78 | t.Fatal(err) 79 | } 80 | defer db2.Close() 81 | // If this fails, it likely means that the server is returning the same database. 82 | _, err = db2.ExecContext(ctx, createTableStmt) 83 | if err != nil { 84 | t.Fatal("CREATE TABLE in database #2:", err) 85 | } 86 | } 87 | 88 | func BenchmarkStart(b *testing.B) { 89 | ctx := context.Background() 90 | for i := 0; i < b.N; i++ { 91 | srv, err := Start(ctx) 92 | if err != nil { 93 | b.Fatal(err) 94 | } 95 | b.Cleanup(srv.Cleanup) 96 | } 97 | } 98 | 99 | func BenchmarkCreateDatabase(b *testing.B) { 100 | ctx := context.Background() 101 | srv, err := Start(ctx) 102 | if err != nil { 103 | b.Fatal(err) 104 | } 105 | b.Cleanup(srv.Cleanup) 106 | b.ResetTimer() 107 | 108 | for i := 0; i < b.N; i++ { 109 | _, err := srv.CreateDatabase(ctx) 110 | if err != nil { 111 | b.Fatal(err) 112 | } 113 | } 114 | } 115 | 116 | func BenchmarkDocker(b *testing.B) { 117 | dockerExe, err := exec.LookPath("docker") 118 | if err != nil { 119 | b.Skip("Could not find Docker:", err) 120 | } 121 | pullCmd := exec.Command(dockerExe, "pull", "postgres") 122 | pullOutput := new(bytes.Buffer) 123 | pullCmd.Stdout = pullOutput 124 | pullCmd.Stderr = pullOutput 125 | err = pullCmd.Run() 126 | b.Log(pullOutput) 127 | if err != nil { 128 | b.Fatal("docker pull:", err) 129 | } 130 | 131 | b.Run("Start", func(b *testing.B) { 132 | for i := 0; i < b.N; i++ { 133 | db, cleanup, err := startDocker(b, dockerExe) 134 | if err != nil { 135 | b.Fatal(err) 136 | } 137 | b.Cleanup(cleanup) 138 | db.Close() 139 | } 140 | }) 141 | 142 | b.Run("CreateDatabase", func(b *testing.B) { 143 | db, cleanup, err := startDocker(b, dockerExe) 144 | if err != nil { 145 | b.Fatal(err) 146 | } 147 | b.Cleanup(cleanup) 148 | defer db.Close() 149 | b.ResetTimer() 150 | 151 | for i := 0; i < b.N; i++ { 152 | dbName, err := randomString(16) 153 | if err != nil { 154 | b.Fatal(err) 155 | } 156 | _, err = db.Exec("CREATE DATABASE \"" + dbName + "\";") 157 | if err != nil { 158 | b.Fatal(err) 159 | } 160 | } 161 | }) 162 | } 163 | 164 | type logger interface { 165 | Log(...interface{}) 166 | } 167 | 168 | func findUnusedTCPPort() (int, error) { 169 | l, err := net.ListenTCP("tcp", &net.TCPAddr{ 170 | IP: net.IPv4(127, 0, 0, 1), 171 | }) 172 | if err != nil { 173 | return 0, fmt.Errorf("find unused tcp port: %w", err) 174 | } 175 | port := l.Addr().(*net.TCPAddr).Port 176 | if err := l.Close(); err != nil { 177 | return 0, fmt.Errorf("find unused tcp port: %w", err) 178 | } 179 | return port, nil 180 | } 181 | 182 | func startDocker(l logger, dockerExe string) (db *sql.DB, cleanup func(), _ error) { 183 | port, err := findUnusedTCPPort() 184 | if err != nil { 185 | return nil, nil, err 186 | } 187 | c := exec.Command(dockerExe, "run", 188 | "--rm", 189 | "--detach", 190 | fmt.Sprintf("--publish=127.0.0.1:%d:5432", port), 191 | "--env=POSTGRES_PASSWORD=xyzzy", 192 | "postgres") 193 | imageID := new(strings.Builder) 194 | c.Stdout = imageID 195 | runLog := new(bytes.Buffer) 196 | c.Stderr = runLog 197 | if err := c.Run(); err != nil { 198 | l.Log(runLog) 199 | return nil, nil, err 200 | } 201 | cleanup = func() { 202 | stopLog := new(bytes.Buffer) 203 | c := exec.Command("docker", "stop", "--", strings.TrimSpace(imageID.String())) 204 | c.Stdout = stopLog 205 | c.Stderr = stopLog 206 | if err := c.Run(); err != nil { 207 | l.Log(err) 208 | l.Log("docker stop:", err) 209 | } 210 | } 211 | dsn := fmt.Sprintf("postgres://postgres:xyzzy@localhost:%d/postgres?sslmode=disable", port) 212 | db, err = sql.Open("postgres", dsn) 213 | if err != nil { 214 | cleanup() 215 | return nil, nil, err 216 | } 217 | db.SetMaxOpenConns(1) 218 | for { 219 | if err := db.Ping(); err == nil { 220 | return db, cleanup, nil 221 | } 222 | } 223 | } 224 | --------------------------------------------------------------------------------