From c36cc4ca0628ba286115cc79ab23fb07543e0d08 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Frank=20Schr=C3=B6der?= Date: Fri, 14 Jan 2022 10:08:39 +0100 Subject: [PATCH] opcua: add FindNamespace and tests to client --- client.go | 15 ++++++++++++ uatest/namespace_test.go | 52 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 67 insertions(+) create mode 100644 uatest/namespace_test.go diff --git a/client.go b/client.go index 4bba08d0..dc18cef6 100644 --- a/client.go +++ b/client.go @@ -1084,6 +1084,21 @@ func (c *Client) NamespaceArray() ([]string, error) { return ns, nil } +// FindNamespace returns the id of the namespace with the given name. +func (c *Client) FindNamespace(name string) (uint16, error) { + stats.Client().Add("FindNamespace", 1) + nsa, err := c.NamespaceArray() + if err != nil { + return 0, err + } + for i, ns := range nsa { + if ns == name { + return uint16(i), nil + } + } + return 0, errors.Errorf("namespace not found. name=%s", name) +} + // UpdateNamespaces updates the list of cached namespaces from the server. func (c *Client) UpdateNamespaces() error { stats.Client().Add("UpdateNamespaces", 1) diff --git a/uatest/namespace_test.go b/uatest/namespace_test.go new file mode 100644 index 00000000..c97f67ed --- /dev/null +++ b/uatest/namespace_test.go @@ -0,0 +1,52 @@ +//go:build integration +// +build integration + +package uatest + +import ( + "context" + "testing" + + "github.com/pascaldekloe/goe/verify" + + "github.com/gopcua/opcua" +) + +func TestNamespace(t *testing.T) { + srv := NewServer("rw_server.py") + defer srv.Close() + + c := opcua.NewClient(srv.Endpoint, srv.Opts...) + if err := c.Connect(context.Background()); err != nil { + t.Fatal(err) + } + defer c.Close() + + t.Run("NamespaceArray", func(t *testing.T) { + got, err := c.NamespaceArray() + if err != nil { + t.Fatal(err) + } + want := []string{ + "http://opcfoundation.org/UA/", + "urn:freeopcua:python:server", + "http://gopcua.com/", + } + verify.Values(t, "", got, want) + }) + t.Run("FindNamespace", func(t *testing.T) { + ns, err := c.FindNamespace("http://gopcua.com/") + if err != nil { + t.Fatal(err) + } + if got, want := ns, uint16(2); got != want { + t.Fatalf("got namespace id %d want %d", got, want) + } + }) + t.Run("UpdateNamespaces", func(t *testing.T) { + err := c.UpdateNamespaces() + if err != nil { + t.Fatal(err) + } + }) +}