Files
go-libp2p/proto_test.go
Josh Klopfenstein 0fb7daca4a Fix proto import paths (#2920)
* Add failing proto test

* Add a new proto compilation script

A proto file's *import path* is relative to one of the `--proto-path`s.

Previously, the proto files were compiled separately. Some invocations
used different values for the `--proto_path`, which led to inconsistent
import paths in proto file descriptors.

Typically, this wouldn't be a problem. However, if a downstream project
uses `protoregistry.GlobalFiles` to inspect proto dependencies, it will fail
to find a dependency's file descriptor when the dependency was compiled
with a different `--proto_path`.

By using a single script to generate all protobuf files, we can ensure
the `--proto_path` is always set to the same sane value (the root of the
project, as suggested in the [official documentation]).

[official documentation]: https://protobuf.dev/programming-guides/proto2/#importing

* Add go_package options so scripts/gen-proto.sh succeeds

* Remove undesirable `go:generate protoc` directives

* Run `go generate ./...`

* Script uses arrays, I think we need bash

---------

Co-authored-by: Marco Munizaga <git@marcopolo.io>
2024-08-19 10:32:20 -07:00

39 lines
1.4 KiB
Go

package libp2p_test
import (
"testing"
// Import all protobuf packages to ensure their `init` functions run.
// This may not be strictly necessary if they are imported in the `libp2p` package, but
// we do it here in case the imports in non-test files change.
_ "github.com/libp2p/go-libp2p/core/crypto/pb"
_ "github.com/libp2p/go-libp2p/core/peer/pb"
_ "github.com/libp2p/go-libp2p/core/record/pb"
_ "github.com/libp2p/go-libp2p/core/sec/insecure/pb"
_ "github.com/libp2p/go-libp2p/p2p/host/autonat/pb"
_ "github.com/libp2p/go-libp2p/p2p/host/peerstore/pstoreds/pb"
_ "github.com/libp2p/go-libp2p/p2p/protocol/autonatv2/pb"
_ "github.com/libp2p/go-libp2p/p2p/protocol/circuitv2/pb"
_ "github.com/libp2p/go-libp2p/p2p/protocol/holepunch/pb"
_ "github.com/libp2p/go-libp2p/p2p/protocol/identify/pb"
_ "github.com/libp2p/go-libp2p/p2p/security/noise/pb"
_ "github.com/libp2p/go-libp2p/p2p/transport/webrtc/pb"
"google.golang.org/protobuf/reflect/protoreflect"
"google.golang.org/protobuf/reflect/protoregistry"
)
//go:generate scripts/gen-proto.sh .
func TestProtoImportsAndPathsAreConsistent(t *testing.T) {
protoregistry.GlobalFiles.RangeFiles(func(fd protoreflect.FileDescriptor) bool {
imports := fd.Imports()
for i := 0; i < imports.Len(); i++ {
path := imports.Get(i).Path()
if _, err := protoregistry.GlobalFiles.FindFileByPath(path); err != nil {
t.Fatalf("find dependency %s: %v", path, err)
}
}
return true
})
}