1

How do I write a unit test for my code that clones a repo using git-go

Below is a sample of the function I have created. I am cloning multiple repos and reading a particular file that is in that repo, I am unsure how to unit test this function.

func cloneRepository(repository string) (repo beans.Repo) {

    dir, err := os.MkdirTemp("./", "temp") //To create a temp folder to clone repo in
    if err != nil...
    
    _, err := git.PlainClone(dir, false, &git.CloneOptions{
               URL: repository,
               Depth: 1,
              })

    var repo beans.Repo
    if err = util.ParseYmlFile("filename.yml", &repo) // Custom util function to parse a file in the repository

    if err = os.RemoveAll(dir); err != nil{...}

   return repo

}
rustyx
  • 80,671
  • 25
  • 200
  • 267
Danial Ang
  • 107
  • 1
  • 7
  • Take a look at the FS abstraction, part of go git repo itself - https://github.com/go-git/go-billy, tests in the go-git repo use the former for abstraction - https://github.com/go-git/go-git/blob/master/example_test.go – Inian Jan 13 '22 at 07:18

2 Answers2

3

You can mock the git.PlainClone() function so it returns a custom file for your tests.

Take a look into spf13's lib, that provides a filesystem mocking solution!

Leonardo Lima
  • 373
  • 2
  • 10
0

What we did in the past was create a bare git repository with some predefined content, put it under e.g. testdata/myrepo.git and use it during unit-testing.

Commit the repo normally as part of your project.

rustyx
  • 80,671
  • 25
  • 200
  • 267
  • Hmm, won't this defeat the purpose of unit-testing? I was under the assumption that unit tests should not hit any "live" external dependencies – Danial Ang Jan 18 '22 at 18:21
  • It's not an external dependency, just store it together with your code. Yes you're going to be exercising go-kit code as part of your unit test. That's actually an advantage, since you depend on that code anyway, so it's good to include it. – rustyx Jan 19 '22 at 16:49