Add tests and rename middleware to plugin

This commit is contained in:
Miek Gieben 2018-01-26 18:43:28 +00:00
parent 06a23f27f8
commit d9282030ca
4 changed files with 59 additions and 7 deletions

View File

@ -1,7 +1,7 @@
# example
The example middleware prints "example" on every query received. It can be used as documentation for
writing external middleware and to test if external middleware compiles with CoreDNS.
writing external plugins and to test if external plugins compile with CoreDNS.
## Syntax
@ -11,7 +11,7 @@ example
## Examples
```
``` corefile
example.com {
file example.com.db {
upstream 8.8.8.8

View File

@ -1,23 +1,25 @@
// The example middleware prints example to stdout on every packet received.
// The example plugin prints example to stdout on every packet received.
package example
import (
"fmt"
"io"
"os"
"github.com/coredns/coredns/plugin"
"github.com/miekg/dns"
"golang.org/x/net/context"
)
// Example is an example middleware to ...
// Example is an example plugin to show how to write a plugin.
type Example struct {
Next plugin.Handler
}
// ServeDNS implements the middleware.Handler interface.
// ServeDNS implements the plugin.Handler interface.
func (e Example) ServeDNS(ctx context.Context, w dns.ResponseWriter, r *dns.Msg) (int, error) {
// Somewhat convoluted, as we could have printed "example" here and just call
// the next middleware - but as an example, show how to wrap a ResponseWriter might be
// the next plugin - but as an example, show how to wrap a ResponseWriter might be
// educational.
pw := NewResponsePrinter(w)
return plugin.NextOrFailure(e.Name(), e.Next, ctx, pw, r)
@ -37,6 +39,8 @@ func NewResponsePrinter(w dns.ResponseWriter) *ResponsePrinter {
// WriteMsg records the status code and calls the underlying ResponseWriter's WriteMsg method.
func (r *ResponsePrinter) WriteMsg(res *dns.Msg) error {
fmt.Println("example")
fmt.Fprintf(out, "example")
return r.ResponseWriter.WriteMsg(res)
}
var out io.Writer = os.Stdout

29
example_test.go Normal file
View File

@ -0,0 +1,29 @@
package example
import (
"bytes"
"testing"
"github.com/coredns/coredns/plugin/pkg/dnstest"
"github.com/coredns/coredns/plugin/test"
"github.com/miekg/dns"
"golang.org/x/net/context"
)
func TestExample(t *testing.T) {
ex := Example{Next: test.ErrorHandler()}
b := &bytes.Buffer{}
out = b
ctx := context.TODO()
r := new(dns.Msg)
r.SetQuestion("example.org.", dns.TypeA)
rec := dnstest.NewRecorder(&test.ResponseWriter{})
ex.ServeDNS(ctx, rec, r)
if x := b.String(); x != "example" {
t.Errorf("Failed to print 'example', got %s", x)
}
}

19
setup_test.go Normal file
View File

@ -0,0 +1,19 @@
package example
import (
"testing"
"github.com/mholt/caddy"
)
func TestSetupWhoami(t *testing.T) {
c := caddy.NewTestController("dns", `example`)
if err := setup(c); err != nil {
t.Fatalf("Expected no errors, but got: %v", err)
}
c = caddy.NewTestController("dns", `example more`)
if err := setup(c); err == nil {
t.Fatalf("Expected errors, but got: %v", err)
}
}