-
Notifications
You must be signed in to change notification settings - Fork 0
/
driver.go
80 lines (69 loc) · 1.74 KB
/
driver.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package juniper_els
import (
"fmt"
"github.com/Juniper/go-netconf/netconf"
"os"
"path/filepath"
"regexp"
"strings"
)
type JuniperDriver interface {
Exec(methods ...netconf.RPCMethod) (*netconf.RPCReply, error)
Close() error
}
type MockDriver struct {
mockBasePath string
}
func NewMockDriver() *JuniperELS {
directory, err := os.Getwd()
if err != nil {
panic(err)
}
_, err = os.Stat(directory + "/testdata")
for os.IsNotExist(err) {
directory, _ = filepath.Abs(directory + "/..")
_, err = os.Stat(directory + "/testdata")
}
return &JuniperELS{
session: &MockDriver{
mockBasePath: directory + "/testdata/juniper-els/",
},
}
}
func (j *MockDriver) Exec(methods ...netconf.RPCMethod) (*netconf.RPCReply, error) {
if len(methods) != 1 {
return nil, fmt.Errorf("mock driver does not support multiple RPC methods")
}
method, ok := methods[0].(netconf.RawMethod)
if !ok {
return nil, fmt.Errorf("mock driver only supports raw RPC methods")
}
mockFileRegex := regexp.MustCompile(`<([^>]+)>`)
match := mockFileRegex.FindStringSubmatch(strings.Replace(string(method), "/", "", 1))
if len(match) != 2 {
return nil, fmt.Errorf("could not find mock file for RPC method")
}
reply := &netconf.RPCReply{}
absPath, err := filepath.Abs(fmt.Sprintf("%s/%s.xml", j.mockBasePath, match[1]))
if err != nil {
return nil, err
}
data, err := os.ReadFile(absPath)
if err != nil {
return nil, err
}
reply.RawReply = string(data)
return reply, nil
}
func (j *MockDriver) Close() error {
return nil
}
type LiveDriver struct {
session *netconf.Session
}
func (j *LiveDriver) Exec(methods ...netconf.RPCMethod) (*netconf.RPCReply, error) {
return j.session.Exec(methods...)
}
func (j *LiveDriver) Close() error {
return j.session.Close()
}