Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go test results in go: cannot find main module, but found .git/config in /Users/dp/Documents

Tags:

go

Im just getting started with Golang and am trying to run unit tests. When running go test, I end up getting the following output from the terminal

go: cannot find main module, but found .git/config in /Users/dp/Documents
    to create a module there, run:
    cd ../.. && go mod init

My file structure is fairly simple, as is as follows

├── CARDS
│   ├── .vscode
│   ├── main.go
│   ├── test.go
│   ├── deck_test.go
│   └── my_cards.txt

the contents of deck_test.go are

package main

import "testing"

func TestNewDeck(t *testing.T) {
    d := newDeck()

    if len(d) != 52 {
        t.Errorf("Length is not 52, got %v", len(d))
    }

    if d[0] != "A of D" {
        t.Errorf("First card is not A of D, got %v", d[0])
    }

    if d[len(d)-1] != "K of C" {
        t.Errorf("Last card is not K of C, got %v", d[len(d)-1])
    }

}

Any insights would be of help!

like image 378
DP12345 Avatar asked Apr 28 '21 19:04

DP12345


2 Answers

I am not using go modules (I know, I should). I got this error after upgrading from older Go versions to 1.16. From release notes:

Note that Go 1.16 requires use of Go modules by default, now that, according to our 2020 Go Developer Survey, 96% of Go developers have made the switch. We recently added official documentation for developing and publishing modules.

To still allow working as before, change it to as it was before. Add this in your .bashrc:

export GO111MODULE=auto
like image 168
subtleseeker Avatar answered Oct 17 '22 22:10

subtleseeker


Although not required, it's generally advisable to init when you're inside of a Git (or other VCS) repository so that modules can lean on your remotes information to determine the name of the module correctly, for example:

git init
git remote add origin https://github.com/syntaqx/dacode
go mod init

Allows go mod to understand my modules name is likely intended to be github.com/syntaqx/dacode.

Alternatively, and I often do this for sake of not needing to do things in any particular order, you can specify the module name:

go mod init dacode # valid, but..
go mod init github.com/syntaqx/dacode # is generally better, because it describes my remote

By specifying it, modules can just initialize in whatever directory I'm in without having to magic anything from the code.

Note: While you're starting out especially, I highly recommend naming your modules the same naming structure you would use for a repository. By doing so, you're allowing commands like:

go get github.com/syntaqx/dacode

To function correctly without having to do any of the internals yourself. As you learn more about how they work, you can decide if you want to keep that convention or go against the grain, but it's likely more sane to be consistent.

Hope this helped!

like image 25
syntaqx Avatar answered Oct 17 '22 22:10

syntaqx