text:
package gba

import (
	"encoding/binary"
	"errors"
	"fmt"
	"io"
	"log"
	"strings"
	"time"

	"github.com/howeyc/crc16"
)

type GBA struct {
	Port      io.ReadWriteCloser
	handshake byte
	lcgSeed   byte
	finalCRC  byte
}

func (g *GBA) Multiboot(data []byte) error {
	gamepak, err := newGamePak(data)
	if err != nil {
		return err
	}

	if err := g.discover(); err != nil {
		return err
	}

	if err := g.stabilizeConnection(); err != nil {
		return err
	}

	if err := g.sendFirstPrimaryReplica(); err != nil {
		return err
	}

	headers := gamepak.Headers()
	if err := g.sendHeaders(headers); err != nil {
		return err
	}

	if err := g.sendSecondPrimaryReplica(); err != nil {
		return err
	}

	if err := g.sendPaletteData(); err != nil {
		return err
	}

	if err := g.sendHandshake(); err != nil {
		return err
	}

	time.Sleep(62500 * time.Microsecond)

	lengthInfo := gamepak.Len()
	if err := g.sendLengthInfo(lengthInfo); err != nil {
		return err
	}

	mainData := gamepak.Data()
	if err := g.sendMainData(mainData); err != nil {
		return err
	}

	if err := g.prepareForCRC(); err != nil {
		return err
	}

	crc := gamepak.CRC()
	return g.sendCRC(crc)
}

func (g *GBA) discover() error {
	var gbaInReplicaMode bool
Loop:
	for {
		time.Sleep(62500 * time.Microsecond)
		r, err := g.xfer16(0x6200)
		if err != nil {
			return err
		}
		switch r {
		case 0xFFFF:
			gbaInReplicaMode = true
		case 0x0:
			if gbaInReplicaMode {
				break Loop
			}
			gbaInReplicaMode = true
		case 0x7202:
			break Loop
		}
	}
	log.Printf("Discovered...\n")
	return nil
}

// TODO: The lower 8 bits of the response here
// should not be assumed to be 02, but saved.
// That means comparing it to the last response
// for i > 0.
func (g *GBA) stabilizeConnection() error {
	var i int
	for i < 15 {
		r, err := g.xfer16(0x6200)
		if err != nil {
			return err
		}
		if r == 0x7202 {
			i++
		} else {
			time.Sleep(62500 * time.Microsecond)
			i = 0
		}
	}
	log.Printf("Stabilized...\n")
	return nil
}

func (g *GBA) sendFirstPrimaryReplica() error {
	if _, err := g.sendDemanding(0x6102, 0x7202, 0xffff); err != nil {
		return err
	}
	log.Printf("Exchanged primary/replica info...\n")
	return nil
}

func (g *GBA) sendSecondPrimaryReplica() error {
	_, err := g.sendDemanding(0x6202, 0x7202, 0xffff)
	return err
}

func (g *GBA) sendHeaders(headers [headerSize16]uint16) error {
	clientBit := uint16(0x02)
	for i, hb := range headers {
		framesRemaining := headerSize16 - uint16(i)
		response := (framesRemaining << 8) | clientBit
		if _, err := g.sendDemanding(hb, response, 0xffff); err != nil {
			return err
		}
	}
	if _, err := g.sendDemanding(0x6200, clientBit, 0xffff); err != nil {
		return err
	}
	log.Printf("Headers sent...\n")
	return nil
}

func (g *GBA) sendPaletteData() error {
	r, err := g.sendUntilResponse(0x63d1, 0x7300, 0xff00, 0)
	if err != nil {
		return err
	}
	g.lcgSeed = byte(r & 0xff)
	log.Printf("Palette data sent...\n")
	return nil
}

func (g *GBA) sendHandshake() error {
	g.handshake = (g.lcgSeed + 0xff + 0xff + 0x11) & 0xff
	handshake := 0x6400 | uint16(g.handshake)
	if _, err := g.sendDemanding(handshake, 0x7300, 0xff00); err != nil {
		return err
	}
	log.Printf("Handshake sent...\n")
	return nil
}

func (g *GBA) sendLengthInfo(length int) error {
	lengthInfo := uint16(length) - 0x34
	r, err := g.sendDemanding(lengthInfo, 0x7300, 0xff00)
	if err != nil {
		return err
	}
	g.finalCRC = byte(r & 0xff)
	log.Printf("Length info sent...\n")
	return nil
}

func (g *GBA) sendMainData(data []uint32) error {
	log.Printf("Sending main data...\n")
	iv := []byte{0xd1, g.lcgSeed, 0xff, 0xff}
	gc := NewGBACipher(binary.LittleEndian.Uint32(iv))
	for i, p := range data {
		c := gc.Encrypt(p)
		if _, err := g.xfer32(c); err != nil {
			return err
		}
		fmt.Printf("%s%3.1f%%...", strings.Repeat("\r", 50), 100.0*float32(i)/float32(len(data)))
	}
	log.Printf("Main data sent...\n")
	return nil
}

func (g *GBA) prepareForCRC() error {
	delay := 62500 * time.Microsecond
	if _, err := g.sendUntilResponse(0x65, 0x75, 0xff, delay); err != nil {
		return err
	}
	_, err := g.sendDemanding(0x66, 0x75, 0xff)
	return err
}

func (g *GBA) sendCRC(crc crc16.Hash16) error {
	final := []byte{g.handshake, g.finalCRC, 0xff, 0xff}
	crc.Write(final)
	_, err := g.sendDemanding(crc.Sum16(), crc.Sum16(), 0xffff)
	return err
}

func (g *GBA) sendUntilResponse(w, c, mask uint16, delay time.Duration) (uint16, error) {
	for {
		r, err := g.xfer16(w)
		if err != nil {
			return r, err
		}
		if (r & mask) == (c & mask) {
			return r, nil
		}
		time.Sleep(delay)
	}
}

func (g *GBA) sendDemanding(w, c, mask uint16) (uint16, error) {
	r, err := g.xfer16(w)
	if err != nil {
		return r, err
	}
	if (r & mask) != (c & mask) {
		return r, errors.New("unexpected response")
	}
	return r, nil
}

func (g *GBA) xfer16(w uint16) (uint16, error) {
	return g.xfer32(uint32(w))
}

func (g *GBA) xfer32(w uint32) (uint16, error) {
	var r uint32
	err := g.xfer(w, &r)
	return uint16(r >> 16), err
}

func (g *GBA) xfer(w interface{}, r interface{}) error {
	if err := binary.Write(g.Port, binary.BigEndian, w); err != nil {
		return err
	}
	if err := binary.Read(g.Port, binary.BigEndian, r); err != nil {
		return err
	}
	return nil
}

repository: bcgraham/polygolosh

repo_name: bcgraham/polygolosh


text:
package consuladapter_test

import (
	"time"

	"github.com/cloudfoundry-incubator/consuladapter"
	"github.com/cloudfoundry-incubator/consuladapter/fakes"
	"github.com/hashicorp/consul/api"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	"github.com/pivotal-golang/lager/lagertest"
)

// copied from consul to prevent unnecessary additional dependencies
const serfCheckID = "serfHealth"

var _ = Describe("Session", func() {
	BeforeEach(startCluster)
	AfterEach(stopCluster)

	var client *api.Client
	var sessionMgr *fakes.FakeSessionManager
	var session *consuladapter.Session
	var newSessionErr error
	var logger *lagertest.TestLogger
	var noChecks bool

	BeforeEach(func() {
		logger = lagertest.NewTestLogger("test")

		client = clusterRunner.NewClient()
		sessionMgr = newFakeSessionManager(client)
		noChecks = false
	})

	JustBeforeEach(func() {
		if noChecks {
			session, newSessionErr = consuladapter.NewSessionNoChecks("a-session", 20*time.Second, client, sessionMgr)
		} else {
			session, newSessionErr = consuladapter.NewSession("a-session", 20*time.Second, client, sessionMgr)
		}
	})

	AfterEach(func() {
		if session != nil {
			session.Destroy()
		}
	})

	Describe("NewSession", func() {
		Context("when consul is down", func() {
			BeforeEach(stopCluster)

			It("a session can be created", func() {
				Expect(newSessionErr).NotTo(HaveOccurred())
				Expect(session).NotTo(BeNil())
			})
		})

		It("creates a new session", func() {
			Expect(newSessionErr).NotTo(HaveOccurred())
			Expect(session).NotTo(BeNil())
		})

		Context("when a consul session is created", func() {
			JustBeforeEach(func() {
				err := session.AcquireLock("foo", []byte{})
				Expect(err).NotTo(HaveOccurred())
			})

			It("has checks", func() {
				entries, _, err := client.Session().List(nil)
				Expect(err).NotTo(HaveOccurred())
				session := findSession(session.ID(), entries)
				Expect(session.Checks).To(ConsistOf(serfCheckID))
			})

			Context("with no checks", func() {
				BeforeEach(func() {
					noChecks = true
				})

				It("has no checks", func() {
					entries, _, err := client.Session().List(nil)
					Expect(err).NotTo(HaveOccurred())
					session := findSession(session.ID(), entries)
					Expect(session.Checks).To(BeEmpty())
				})
			})
		})

		Describe("Session#Recreate", func() {
			var newSession *consuladapter.Session

			JustBeforeEach(func() {
				err := session.AcquireLock("foo", []byte{})
				Expect(err).NotTo(HaveOccurred())
			})

			Context("when the session exists", func() {
				JustBeforeEach(func() {
					var err error
					newSession, err = session.Recreate()
					Expect(err).NotTo(HaveOccurred())
				})

				It("destroys the current session", func() {
					Eventually(func() *api.SessionEntry {
						entries, _, err := client.Session().List(nil)
						Expect(err).NotTo(HaveOccurred())
						return findSession(session.ID(), entries)
					}).Should(BeNil())
				})

				It("has checks", func() {
					entries, _, err := client.Session().List(nil)
					Expect(err).NotTo(HaveOccurred())
					s := findSession(newSession.ID(), entries)
					Expect(s.Checks).To(ConsistOf(serfCheckID))
				})

				Context("with no checks", func() {
					BeforeEach(func() {
						noChecks = true
					})

					It("has no checks", func() {
						entries, _, err := client.Session().List(nil)
						Expect(err).NotTo(HaveOccurred())
						session := findSession(newSession.ID(), entries)
						Expect(session.Checks).To(BeEmpty())
					})
				})
			})

			Context("when the session does not exist", func() {
				var newSession *consuladapter.Session

				JustBeforeEach(func() {
					var err error
					session.Destroy()
					newSession, err = session.Recreate()
					Expect(err).NotTo(HaveOccurred())
				})

				It("has checks", func() {
					entries, _, err := client.Session().List(nil)
					Expect(err).NotTo(HaveOccurred())
					s := findSession(newSession.ID(), entries)
					Expect(s.Checks).To(ConsistOf(serfCheckID))
				})
			})
		})

		Describe("Session#Destroy", func() {
			JustBeforeEach(func() {
				err := session.AcquireLock("a-key", []byte("a-value"))
				Expect(err).NotTo(HaveOccurred())

				Eventually(func() []*api.SessionEntry {
					entries, _, err := client.Session().List(nil)
					Expect(err).NotTo(HaveOccurred())
					return entries
				}).Should(HaveLen(1))

				session.Destroy()
			})

			It("destroys the session", func() {
				Expect(sessionMgr.DestroyCallCount()).To(Equal(1))
				id, _ := sessionMgr.DestroyArgsForCall(0)
				Expect(id).To(Equal(session.ID()))
			})

			It("removes the session", func() {
				Eventually(func() *api.SessionEntry {
					entries, _, err := client.Session().List(nil)
					Expect(err).NotTo(HaveOccurred())
					return findSession(session.ID(), entries)
				}).Should(BeNil())
			})

			It("sends a nil error", func() {
				Eventually(session.Err()).Should(Receive(BeNil()))
			})

			It("can be called multiple times", func() {
				session.Destroy()
			})
		})
	})
})

func findSession(sessionID string, entries []*api.SessionEntry) *api.SessionEntry {
	for _, e := range entries {
		if e.ID == sessionID {
			return e
		}
	}

	return nil
}

repository: stefanschneider/consuladapter

license_type: permissive

repo_name: stefanschneider/consuladapter

branch_name: refs/heads/master

extension: go


text:
#======================================#
#           SUMMARY/LICENCE            #
#--------------------------------------#
SUMMARY = "Perl Compatible Regular Expressions"
HOMEPAGE = "http://www.pcre.org"

LICENSE = "BSD"
LIC_FILES_CHKSUM = "file://LICENCE;md5=60da32d84d067f53e22071c4ecb4384d"

#======================================#
#           REQUIRE/INHERIT            #
#--------------------------------------#
BINCONFIG = "${bindir}/pcre-config"

inherit autotools binconfig-disabled

#======================================#
#                SOURCE                #
#--------------------------------------#
SRC_URI = "ftp://ftp.csx.cam.ac.uk/pub/software/programming/pcre/pcre-${PV}.tar.bz2;name=source \
           file://pcre-cross.patch                                                              \
           file://fix-pcre-name-collision.patch                                                 \
           file://Makefile                                                                      \
           "

SRC_URI[source.md5sum] = "41a842bf7dcecd6634219336e2167d1d"
SRC_URI[source.sha256sum] = "00e27a29ead4267e3de8111fcaa59b132d0533cdfdbdddf4b0604279acbcf4f4"

S = "${WORKDIR}/pcre-${PV}"

#======================================#
#           DEPENDS/PROVIDES           #
#--------------------------------------#
PROVIDES_append = " pcre "
DEPENDS_append = " bzip2 zlib "

#======================================#
#         BUILD CONFIGURATIONS         #
#--------------------------------------#
EXTRA_OECONF = "                \
    --enable-newline-is-lf      \
    --enable-rebuild-chartables \
    --enable-utf                \
    --with-link-size=2          \
    --with-match-limit=10000000 \
    "

# Set LINK_SIZE in BUILD_CFLAGS given that the autotools bbclass use it to
# set CFLAGS_FOR_BUILD, required for the libpcre build.
BUILD_CFLAGS_prepend = " -DLINK_SIZE=2 -I${B} "
CFLAGS_append = " -D_REENTRANT "
CXXFLAGS_append_powerpc = " -lstdc++"

export CCLD_FOR_BUILD ="${BUILD_CCLD}"

#======================================#
#                TASKS                 #
#--------------------------------------#

#======================================#
#            PACKAGES/FILES            #
#--------------------------------------#
PACKAGECONFIG ??= "pcre8 unicode-properties"

PACKAGECONFIG[pcre8] = "--enable-pcre8, --disable-pcre8"
PACKAGECONFIG[pcre16] = "--enable-pcre16, --disable-pcre16"
PACKAGECONFIG[pcre32] = "--enable-pcre32, --disable-pcre32"
PACKAGECONFIG[pcretest-readline] = "--enable-pcretest-libreadline, --disable-pcretest-libreadline, readline"
PACKAGECONFIG[unicode-properties] = "--enable-unicode-properties, --disable-unicode-properties"

PACKAGES_prepend = " libpcrecpp libpcreposix pcregrep pcregrep-doc pcretest pcretest-doc "

FILES_libpcrecpp = "${libdir}/libpcrecpp.so.*"
FILES_libpcreposix = "${libdir}/libpcreposix.so.*"
FILES_pcregrep = "${bindir}/pcregrep"
FILES_pcregrep-doc = "${mandir}/man1/pcregrep.1"
FILES_pcretest = "${bindir}/pcretest"
FILES_pcretest-doc = "${mandir}/man1/pcretest.1"

#======================================#
#            INSTALL SCRIPT            #
#--------------------------------------#

#======================================#
#             ALTERNATIVES             #
#--------------------------------------#

#======================================#
#           USERADD/SYSTEMD            #
#--------------------------------------#

#======================================#
#                 TEST                 #
#--------------------------------------#

license: MIT

extension: bb


text:
DESCRIPTION = "Google C++ Testing Framework"
SECTION = "libs"
DEPENDS = ""
LICENSE = "Apache-2.0"
LIC_FILES_CHKSUM = "file://include/gtest/gtest.h;endline=28;md5=c6443e2c0a211d2ccec9fe856fced5fc"
HOMEPAGE = "http://code.google.com/p/googletest/"
PR = "r0"

SRC_URI = "http://googletest.googlecode.com/files/gtest-${PV}.zip"

SRC_URI[md5sum] = "4577b49f2973c90bf9ba69aa8166b786"
SRC_URI[sha256sum] = "5ec97df8e75b4ee796604e74716d1b50582beba22c5502edd055a7e67a3965d8"

S = "${WORKDIR}/gtest-${PV}"

inherit autotools

BBCLASSEXTEND = "native"

do_install () {
	install -d ${D}${includedir}/gtest/
	install -m 0644 include/gtest/*.h ${D}${includedir}/gtest/
	install -d ${D}${includedir}/gtest/internal/
	install -m 0644 include/gtest/internal/*.h ${D}${includedir}/gtest/internal
}


text:
package main

import (
	"encoding/json"
	"flag"
	"fmt"
	"io"
	"io/ioutil"
	"strings"
	"testing"

	"github.com/hyperledger/fabric/core/chaincode/shim"
	peer "github.com/hyperledger/fabric/protos/peer"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)

const objectiveDescriptionHash = "5c1d9cd1c2c1082dde0921b56d11030c81f62fbb51932758b58ac2569dd0b379"
const objectiveDescriptionStorageAddress = "https://toto/objective/222/description"
const objectiveMetricsHash = "4a1d9cd1c2c1082dde0921b56d11030c81f62fbb51932758b58ac2569dd0b379"
const objectiveMetricsStorageAddress = "https://toto/objective/222/metrics"
const dataManagerOpenerHash = "da1bb7c31f62244c0f3a761cc168804227115793d01c270021fe3f7935482dcc"
const trainDataSampleHash1 = "aa1bb7c31f62244c0f3a761cc168804227115793d01c270021fe3f7935482dcc"
const trainDataSampleHash2 = "aa2bb7c31f62244c0f3a761cc168804227115793d01c270021fe3f7935482dcc"
const testDataSampleHash1 = "bb1bb7c31f62244c0f3a761cc168804227115793d01c270021fe3f7935482dcc"
const testDataSampleHash2 = "bb2bb7c31f62244c0f3a761cc168804227115793d01c270021fe3f7935482dcc"
const algoHash = "fd1bb7c31f62244c0f3a761cc168804227115793d01c270021fe3f7935482dcc"
const algoStorageAddress = "https://toto/algo/222/algo"
const algoName = "hog + svm"
const modelHash = "eedbb7c31f62244c0f3a761cc168804227115793d01c270021fe3f7935482eed"
const modelAddress = "https://substrabac/model/toto"
const worker = "bbd157aa8e85eb985aeedb79361cd45739c92494dce44d351fd2dbd6190e27f0"
const traintupleKey = "8e29bacef1250f8c3bd6ccc72455f764b74ef7e66b9157fd6cd2b0cecef1c687"

var (
	pipeline = flag.Bool("pipeline", false, "Print out the pipeline test output")
	readme   = flag.String("readme", "../README.md", "Pass the path to the README and compare it to the output")
	update   = flag.Bool("update", false, "Update the README.md file")
)

func TestInit(t *testing.T) {
	scc := new(SubstraChaincode)
	mockStub := shim.NewMockStub("substra", scc)

	// resp := mockStub.MockInit("42", [][]byte{[]byte("init")})
	resp := mockStub.MockInit("42", [][]byte{[]byte("init")})
	assert.EqualValuesf(t, 200, resp.Status, "init failed with status %d and message %s", resp.Status, resp.Message)
}

func printArgs(buf io.Writer, args [][]byte, command string) {
	s := "```\npeer chaincode " + command + " -n mycc -c '{\"Args\":["
	for i, arg := range args {
		s += "\"" + string(arg) + "\""
		if i+1 < len(args) {
			s += ","
		}
	}
	s += "]}' -C myc\n```"
	fmt.Fprintln(buf, s)
}
func printArgsNames(buf io.Writer, fnName string, argsNames []string) {
	s := "Smart contract: `" + fnName + "`  \n Inputs: `" + strings.Join(argsNames, "`, `") + "`"
	fmt.Fprintln(buf, s)
}

func (dataManager *inputDataManager) createSample() [][]byte {
	if dataManager.Name == "" {
		dataManager.Name = "liver slide"
	}
	if dataManager.OpenerHash == "" {
		dataManager.OpenerHash = dataManagerOpenerHash
	}
	if dataManager.OpenerStorageAddress == "" {
		dataManager.OpenerStorageAddress = "https://toto/dataManager/42234/opener"
	}
	if dataManager.Type == "" {
		dataManager.Type = "images"
	}
	if dataManager.DescriptionHash == "" {
		dataManager.DescriptionHash = "8d4bb7c31f62244c0f3a761cc168804227115793d01c270021fe3f7935482eee"
	}
	if dataManager.DescriptionStorageAddress == "" {
		dataManager.DescriptionStorageAddress = "https://toto/dataManager/42234/description"
	}
	dataManager.Permissions = "all"
	args, _ := inputStructToBytes(dataManager)
	args = append([][]byte{[]byte("registerDataManager")}, args...)
	return args
}

func (dataSample *inputDataSample) createSample() [][]byte {
	if dataSample.Hashes == "" {
		dataSample.Hashes = trainDataSampleHash1 + ", " + trainDataSampleHash2
	}
	if dataSample.DataManagerKeys == "" {
		dataSample.DataManagerKeys = dataManagerOpenerHash
	}
	if dataSample.TestOnly == "" {
		dataSample.TestOnly = "false"
	}
	args, _ := inputStructToBytes(dataSample)
	args = append([][]byte{[]byte("registerDataSample")}, args...)
	return args
}

func (objective *inputObjective) createSample() [][]byte {
	if objective.Name == "" {
		objective.Name = "MSI classification"
	}
	if objective.DescriptionHash == "" {
		objective.DescriptionHash = objectiveDescriptionHash
	}
	if objective.DescriptionStorageAddress == "" {
		objective.DescriptionStorageAddress = "https://toto/objective/222/description"
	}
	if objective.MetricsName == "" {
		objective.MetricsName = "accuracy"
	}
	if objective.MetricsHash == "" {
		objective.MetricsHash = objectiveMetricsHash
	}
	if objective.MetricsStorageAddress == "" {
		objective.MetricsStorageAddress = objectiveMetricsStorageAddress
	}
	if objective.TestDataset == "" {
		objective.TestDataset = dataManagerOpenerHash + ":" + testDataSampleHash1 + ", " + testDataSampleHash2
	}
	objective.Permissions = "all"
	args, _ := inputStructToBytes(objective)
	args = append([][]byte{[]byte("registerObjective")}, args...)
	return args
}

func (algo *inputAlgo) createSample() [][]byte {
	if algo.Name == "" {
		algo.Name = algoName
	}
	if algo.Hash == "" {
		algo.Hash = algoHash
	}
	if algo.StorageAddress == "" {
		algo.StorageAddress = algoStorageAddress
	}
	if algo.DescriptionHash == "" {
		algo.DescriptionHash = "e2dbb7c31f62244c0f3a761cc168804227115793d01c270021fe3f7935482dca"
	}
	if algo.DescriptionStorageAddress == "" {
		algo.DescriptionStorageAddress = "https://toto/algo/222/description"
	}
	algo.Permissions = "all"
	args, _ := inputStructToBytes(algo)
	args = append([][]byte{[]byte("registerAlgo")}, args...)
	return args
}

func (traintuple *inputTraintuple) createSample() [][]byte {
	if traintuple.AlgoKey == "" {
		traintuple.AlgoKey = algoHash
	}
	if traintuple.InModels == "" {
		traintuple.InModels = ""
	}
	if traintuple.ObjectiveKey == "" {
		traintuple.ObjectiveKey = objectiveDescriptionHash
	}
	if traintuple.DataManagerKey == "" {
		traintuple.DataManagerKey = dataManagerOpenerHash
	}
	if traintuple.DataSampleKeys == "" {
		traintuple.DataSampleKeys = trainDataSampleHash1 + ", " + trainDataSampleHash2
	}
	args, _ := inputStructToBytes(traintuple)
	args = append([][]byte{[]byte("createTraintuple")}, args...)
	return args
}

func (testtuple *inputTesttuple) createSample() [][]byte {
	if testtuple.TraintupleKey == "" {
		testtuple.TraintupleKey = traintupleKey
	}
	args, _ := inputStructToBytes(testtuple)
	args = append([][]byte{[]byte("createTesttuple")}, args...)
	return args
}

func registerItem(t *testing.T, mockStub shim.MockStub, itemType string) (peer.Response, interface{}) {
	// 1. add dataManager
	inpDataManager := inputDataManager{}
	args := inpDataManager.createSample()
	resp := mockStub.MockInvoke("42", args)
	require.EqualValuesf(t, 200, resp.Status, "when adding dataManager with status %d and message %s", resp.Status, resp.Message)
	if itemType == "dataManager" {
		return resp, inpDataManager
	}
	// 2. add test dataSample
	inpDataSample := inputDataSample{
		Hashes:          testDataSampleHash1 + ", " + testDataSampleHash2,
		DataManagerKeys: dataManagerOpenerHash,
		TestOnly:        "true",
	}
	args = inpDataSample.createSample()
	resp = mockStub.MockInvoke("42", args)
	require.EqualValuesf(t, 200, resp.Status, "when adding test dataSample with status %d and message %s", resp.Status, resp.Message)
	if itemType == "testDataset" {
		return resp, inpDataSample
	}
	// 3. add objective
	inpObjective := inputObjective{}
	args = inpObjective.createSample()
	resp = mockStub.MockInvoke("42", args)
	require.EqualValuesf(t, 200, resp.Status, "when adding objective with status %d and message %s", resp.Status, resp.Message)
	if itemType == "objective" {
		return resp, inpObjective
	}
	// 4. Add train dataSample
	inpDataSample = inputDataSample{}
	args = inpDataSample.createSample()
	resp = mockStub.MockInvoke("42", args)
	require.EqualValuesf(t, 200, resp.Status, "when adding train dataSample with status %d and message %s", resp.Status, resp.Message)
	if itemType == "trainDataset" {
		return resp, inpDataSample
	}
	// 5. Add algo
	inpAlgo := inputAlgo{}
	args = inpAlgo.createSample()
	resp = mockStub.MockInvoke("42", args)
	require.EqualValuesf(t, 200, resp.Status, "when adding algo with status %d and message %s", resp.Status, resp.Message)
	if itemType == "algo" {
		return resp, inpAlgo
	}
	// 6. Add traintuple
	inpTraintuple := inputTraintuple{}
	args = inpTraintuple.createSample()
	resp = mockStub.MockInvoke("42", args)
	require.EqualValuesf(t, 200, resp.Status, "when adding traintuple with status %d and message %s", resp.Status, resp.Message)
	return resp, inpTraintuple
}

func TestPipeline(t *testing.T) {
	scc := new(SubstraChaincode)
	mockStub := shim.NewMockStub("substra", scc)
	var out strings.Builder

	fmt.Fprintln(&out, "#### ------------ Add DataManager ------------")
	inpDataManager := inputDataManager{}
	printArgsNames(&out, "registerDataManager", getFieldNames(&inpDataManager))
	args := inpDataManager.createSample()
	printArgs(&out, args, "invoke")
	resp := mockStub.MockInvoke("42", args)
	assert.EqualValuesf(t, 200, resp.Status, "when adding dataManager with status %d and message %s", resp.Status, resp.Message)
	fmt.Fprintf(&out, ">  %s \n\n", string(resp.Payload))
	// Get dataManager key from Payload
	res := map[string]string{}
	err := json.Unmarshal(resp.Payload, &res)
	assert.NoError(t, err, "should unmarshal without problem")
	assert.Contains(t, res, "key")
	dataManagerKey := res["key"]

	fmt.Fprintln(&out, "#### ------------ Query DataManager From key ------------")
	printArgsNames(&out, "queryDataManager", []string{"elementKey"})
	args = [][]byte{[]byte("queryDataManager"), []byte(dataManagerKey)}
	printArgs(&out, args, "queryDataManager")
	resp = mockStub.MockInvoke("42", args)
	assert.EqualValuesf(t, 200, resp.Status, "when querying a dataManager with status %d and message %s", resp.Status, resp.Message)
	fmt.Fprintf(&out, ">  %s \n\n", string(resp.Payload))

	fmt.Fprintln(&out, "#### ------------ Add test DataSample ------------")
	inpDataSample := inputDataSample{
		Hashes:   testDataSampleHash1 + ", " + testDataSampleHash2,
		TestOnly: "true",
	}
	printArgsNames(&out, "registerDataSample", getFieldNames(&inpDataSample))
	args = inpDataSample.createSample()
	printArgs(&out, args, "invoke")
	resp = mockStub.MockInvoke("42", args)
	assert.EqualValuesf(t, 200, resp.Status, "when adding test dataSample with status %d and message %s", resp.Status, resp.Message)
	fmt.Fprintf(&out, ">  %s \n\n", string(resp.Payload))

	fmt.Fprintln(&out, "#### ------------ Add Objective ------------")
	inpObjective := inputObjective{}
	printArgsNames(&out, "registerObjective", getFieldNames(&inpObjective))
	args = inpObjective.createSample()
	printArgs(&out, args, "invoke")
	resp = mockStub.MockInvoke("42", args)
	assert.EqualValuesf(t, 200, resp.Status, "when adding objective with status %d and message %s", resp.Status, resp.Message)
	fmt.Fprintf(&out, ">  %s \n\n", string(resp.Payload))

	fmt.Fprintln(&out, "#### ------------ Add Algo ------------")
	inpAlgo := inputAlgo{}
	printArgsNames(&out, "registerAlgo", getFieldNames(&inpAlgo))
	args = inpAlgo.createSample()
	printArgs(&out, args, "invoke")
	resp = mockStub.MockInvoke("42", args)
	assert.EqualValuesf(t, 200, resp.Status, "when adding algo with status %d and message %s", resp.Status, resp.Message)
	fmt.Fprintf(&out, ">  %s \n\n", string(resp.Payload))

	fmt.Fprintln(&out, "#### ------------ Add Train DataSample ------------")
	inpDataSample = inputDataSample{}
	printArgsNames(&out, "registerDataSample", getFieldNames(&inpDataSample))
	args = inpDataSample.createSample()
	printArgs(&out, args, "invoke")
	resp = mockStub.MockInvoke("42", args)
	assert.EqualValuesf(t, 200, resp.Status, "when adding train dataSample with status %d and message %s", resp.Status, resp.Message)
	fmt.Fprintf(&out, ">  %s \n\n", string(resp.Payload))

	fmt.Fprintln(&out, "#### ------------ Query DataManagers ------------")
	args = [][]byte{[]byte("queryDataManagers")}
	printArgs(&out, args, "query")
	resp = mockStub.MockInvoke("42", args)
	assert.EqualValuesf(t, 200, resp.Status, "when querying dataManager with status %d and message %s", resp.Status, resp.Message)
	fmt.Fprintf(&out, ">  %s \n\n", string(resp.Payload))

	fmt.Fprintln(&out, "#### ------------ Query Objectives ------------")
	args = [][]byte{[]byte("queryObjectives")}
	printArgs(&out, args, "query")
	resp = mockStub.MockInvoke("42", args)
	assert.EqualValuesf(t, 200, resp.Status, "when querying objective with status %d and message %s", resp.Status, resp.Message)
	fmt.Fprintf(&out, ">  %s \n\n", string(resp.Payload))

	fmt.Fprintln(&out, "#### ------------ Add Traintuple ------------")
	inpTraintuple := inputTraintuple{}
	printArgsNames(&out, "createTraintuple", getFieldNames(&inpTraintuple))
	args = inpTraintuple.createSample()
	printArgs(&out, args, "invoke")
	resp = mockStub.MockInvoke("42", args)
	assert.EqualValuesf(t, 200, resp.Status, "when adding traintuple with status %d and message %s", resp.Status, resp.Message)
	fmt.Fprintf(&out, ">  %s \n\n", string(resp.Payload))
	// Get traintuple key from Payload
	res = map[string]string{}
	err = json.Unmarshal(resp.Payload, &res)
	assert.NoError(t, err, "should unmarshal without problem")
	assert.Contains(t, res, "key")
	traintupleKey := []byte(res["key"])
	// check not possible to create same traintuple
	resp = mockStub.MockInvoke("42", args)
	assert.EqualValuesf(t, 500, resp.Status, "when adding same traintuple with status %d and message %s", resp.Status, resp.Message)
	// Get owner of the traintuple
	args = [][]byte{[]byte("queryTraintuple"), traintupleKey}
	resp = mockStub.MockInvoke("42", args)
	assert.EqualValuesf(t, 200, resp.Status, "when adding traintuple with status %d and message %s", resp.Status, resp.Message)
	traintuple := outputTraintuple{}
	respTraintuple := resp.Payload
	if err := bytesToStruct(respTraintuple, &traintuple); err != nil {
		t.Errorf("when unmarshalling queried traintuple with error %s", err)
	}
	trainWorker := traintuple.Dataset.Worker

	fmt.Fprintln(&out, "#### ------------ Add Traintuple with inModel from previous traintuple ------------")
	inpTraintuple = inputTraintuple{
		InModels: string(traintupleKey),
	}
	printArgsNames(&out, "createTraintuple", getFieldNames(&inpTraintuple))
	args = inpTraintuple.createSample()
	printArgs(&out, args, "invoke")
	resp = mockStub.MockInvoke("42", args)
	assert.EqualValuesf(t, 200, resp.Status, "when adding traintuple with status %d and message %s", resp.Status, resp.Message)
	fmt.Fprintf(&out, ">  %s \n\n", string(resp.Payload))
	res = map[string]string{}
	err = json.Unmarshal(resp.Payload, &res)
	assert.NoError(t, err, "should unmarshal without problem")
	assert.Contains(t, res, "key")
	todoTraintupleKey := res["key"]

	fmt.Fprintln(&out, "#### ------------ Query Traintuples of worker with todo status ------------")
	args = [][]byte{[]byte("queryFilter"), []byte("traintuple~worker~status"), []byte(trainWorker + ", todo")}
	printArgs(&out, args, "invoke")
	resp = mockStub.MockInvoke("42", args)
	assert.EqualValuesf(t, 200, resp.Status, "when querying traintuple of worker with todo status - with status %d and message %s", resp.Status, resp.Message)
	fmt.Fprintf(&out, ">  %s \n\n", string(resp.Payload))

	fmt.Fprintln(&out, "#### ------------ Log Start Training ------------")
	args = [][]byte{[]byte("logStartTrain"), traintupleKey}
	printArgs(&out, args, "invoke")
	resp = mockStub.MockInvoke("42", args)
	assert.EqualValuesf(t, 200, resp.Status, "when logging start training with status %d and message %s", resp.Status, resp.Message)
	fmt.Fprintf(&out, ">  %s \n\n", string(resp.Payload))

	fmt.Fprintln(&out, "#### ------------ Log Success Training ------------")
	perf := "0.9"
	log := "no error, ah ah ah"
	args = [][]byte{[]byte("logSuccessTrain"), traintupleKey, []byte(modelHash + ", " + modelAddress),
		[]byte(perf), []byte(log)}
	printArgs(&out, args, "invoke")
	resp = mockStub.MockInvoke("42", args)
	assert.EqualValuesf(t, 200, resp.Status, "when logging successful training with status %d and message %s", resp.Status, resp.Message)
	fmt.Fprintf(&out, ">  %s \n\n", string(resp.Payload))

	fmt.Fprintln(&out, "#### ------------ Query Traintuple From key ------------")
	args = [][]byte{[]byte("queryTraintuple"), traintupleKey}
	printArgs(&out, args, "queryTraintuple")
	resp = mockStub.MockInvoke("42", args)
	assert.EqualValuesf(t, 200, resp.Status, "when querying traintuple with status %d and message %s", resp.Status, resp.Message)
	fmt.Fprintf(&out, ">  %s \n\n", string(resp.Payload))

	fmt.Fprintln(&out, "#### ------------ Add Non-Certified Testtuple ------------")
	inpTesttuple := inputTesttuple{
		DataManagerKey: dataManagerOpenerHash,
		DataSampleKeys: trainDataSampleHash1 + ", " + trainDataSampleHash2,
	}
	printArgsNames(&out, "createTesttuple", getFieldNames(&inpTesttuple))
	args = inpTesttuple.createSample()
	printArgs(&out, args, "invoke")
	resp = mockStub.MockInvoke("42", args)
	assert.EqualValuesf(t, 200, resp.Status, "when adding testtuple with status %d and message %s", resp.Status, resp.Message)
	fmt.Fprintf(&out, ">  %s \n\n", string(resp.Payload))

	fmt.Fprintln(&out, "#### ------------ Add Certified Testtuple ------------")
	inpTesttuple = inputTesttuple{}
	printArgsNames(&out, "createTesttuple", getFieldNames(&inpTesttuple))
	args = inpTesttuple.createSample()
	printArgs(&out, args, "invoke")
	resp = mockStub.MockInvoke("42", args)
	assert.EqualValuesf(t, 200, resp.Status, "when adding testtuple with status %d and message %s", resp.Status, resp.Message)
	fmt.Fprintf(&out, ">  %s \n\n", string(resp.Payload))
	// Get testtuple key from Payload
	res = map[string]string{}
	err = json.Unmarshal(resp.Payload, &res)
	assert.NoError(t, err, "should unmarshal without problem")
	assert.Contains(t, res, "key")
	testtupleKey := []byte(res["key"])
	// check not possible to create same testtuple
	resp = mockStub.MockInvoke("42", args)
	assert.EqualValuesf(t, 500, resp.Status, "when adding same testtuple with status %d and message %s", resp.Status, resp.Message)
	// Get owner of the testtuple
	args = [][]byte{[]byte("queryTesttuple"), testtupleKey}
	resp = mockStub.MockInvoke("42", args)
	respTesttuple := resp.Payload
	testtuple := Testtuple{}
	if err := bytesToStruct(respTesttuple, &testtuple); err != nil {
		t.Errorf("when unmarshalling queried testtuple with error %s", err)
	}
	testWorker := testtuple.Dataset.Worker

	fmt.Fprintln(&out, "#### ------------ Add Testtuple with not done traintuple ------------")
	inpTesttuple = inputTesttuple{
		TraintupleKey: todoTraintupleKey,
	}
	printArgsNames(&out, "createTesttuple", getFieldNames(&inpTesttuple))
	args = inpTesttuple.createSample()
	printArgs(&out, args, "invoke")
	resp = mockStub.MockInvoke("42", args)
	assert.EqualValuesf(t, 200, resp.Status, "when adding testtuple with status %d and message %s", resp.Status, resp.Message)
	fmt.Fprintf(&out, ">  %s \n\n", string(resp.Payload))

	fmt.Fprintln(&out, "#### ------------ Query Testtuples of worker with todo status ------------")
	args = [][]byte{[]byte("queryFilter"), []byte("testtuple~worker~status"), []byte(testWorker + ", todo")}
	printArgs(&out, args, "invoke")
	resp = mockStub.MockInvoke("42", args)
	assert.EqualValuesf(t, 200, resp.Status, "when querying testtuple of worker with todo status - with status %d and message %s", resp.Status, resp.Message)
	fmt.Fprintf(&out, ">  %s \n\n", string(resp.Payload))

	fmt.Fprintln(&out, "#### ------------ Log Start Testing ------------")
	args = [][]byte{[]byte("logStartTest"), testtupleKey}
	printArgs(&out, args, "invoke")
	resp = mockStub.MockInvoke("42", args)
	assert.EqualValuesf(t, 200, resp.Status, "when logging start testing with status %d and message %s", resp.Status, resp.Message)
	fmt.Fprintf(&out, ">  %s \n\n", string(resp.Payload))

	fmt.Fprintln(&out, "#### ------------ Log Success Testing ------------")
	perf = "0.89"
	log = "still no error, suprah ah ah"
	args = [][]byte{[]byte("logSuccessTest"), testtupleKey, []byte(perf), []byte(log)}
	printArgs(&out, args, "invoke")
	resp = mockStub.MockInvoke("42", args)
	assert.EqualValuesf(t, 200, resp.Status, "when logging successful training with status %d and message %s", resp.Status, resp.Message)
	fmt.Fprintf(&out, ">  %s \n\n", string(resp.Payload))

	fmt.Fprintln(&out, "#### ------------ Query Testtuple from its key ------------")
	args = [][]byte{[]byte("queryTesttuple"), testtupleKey}
	printArgs(&out, args, "queryTesttuple")
	resp = mockStub.MockInvoke("42", args)
	assert.EqualValuesf(t, 200, resp.Status, "when querying testtuple with status %d and message %s", resp.Status, resp.Message)
	fmt.Fprintf(&out, ">  %s \n\n", string(resp.Payload))

	fmt.Fprintln(&out, "#### ------------ Query all Testtuples ------------")
	args = [][]byte{[]byte("queryTesttuples")}
	printArgs(&out, args, "queryTesttuples")
	resp = mockStub.MockInvoke("42", args)
	assert.EqualValuesf(t, 200, resp.Status, "when querying testtuple with status %d and message %s", resp.Status, resp.Message)
	fmt.Fprintf(&out, ">  %s \n\n", string(resp.Payload))

	fmt.Fprintln(&out, "#### ------------ Query details about a model ------------")
	args = [][]byte{[]byte("queryModelDetails"), []byte(traintupleKey)}
	printArgs(&out, args, "query")
	resp = mockStub.MockInvoke("42", args)
	assert.EqualValuesf(t, 200, resp.Status, "when querying model details with status %d and message %s", resp.Status, resp.Message)
	fmt.Fprintf(&out, ">  %s \n\n", string(resp.Payload))

	fmt.Fprintln(&out, "#### ------------ Query all models ------------")
	args = [][]byte{[]byte("queryModels")}
	printArgs(&out, args, "query")
	resp = mockStub.MockInvoke("42", args)
	assert.EqualValuesf(t, 200, resp.Status, "when querying model tuples with status %d and message %s", resp.Status, resp.Message)
	fmt.Fprintf(&out, ">  %s \n\n", string(resp.Payload))

	fmt.Fprintln(&out, "#### ------------ Query Dataset ------------")
	args = [][]byte{[]byte("queryDataset"), []byte(dataManagerOpenerHash)}
	printArgs(&out, args, "query")
	resp = mockStub.MockInvoke("42", args)
	assert.EqualValuesf(t, 200, resp.Status, "when querying dataset with status %d and message %s", resp.Status, resp.Message)
	fmt.Fprintf(&out, ">  %s \n\n", string(resp.Payload))

	// Use the output to check the README file and if asked update it
	doc := out.String()
	fromFile, err := ioutil.ReadFile(*readme)
	require.NoErrorf(t, err, "can not read the readme file at the path %s", *readme)
	actualReadme := string(fromFile)
	exampleTitle := "### Examples\n\n"
	index := strings.Index(actualReadme, exampleTitle)
	require.NotEqual(t, -1, index, "README file does not include a Examples section")
	if *update {
		err = ioutil.WriteFile(*readme, []byte(actualReadme[:index+len(exampleTitle)]+doc), 0644)
		assert.NoError(t, err)
	} else {
		testUsage := "The Readme examples are not up to date with the tests"
		testUsage += "\n`-pipeline` to see the output"
		testUsage += "\n`-update` to update the README"
		testUsage += "\n`-readme` to set a different path for the README"
		assert.True(t, strings.Contains(actualReadme, doc), testUsage)
	}
	if *pipeline {
		fmt.Println(doc, index)
	}
}

repository: samlesu/substra-chaincode

repo_name: samlesu/substra-chaincode


text:
package parser

const (
	_ int = iota
	LOWEST
	EQUALS      // ==
	LESSGREATER // > or <
	SUM         // +
	PRODUCT     // *
	PREFIX      // -X or !X
	CALL        // myFunction(X)
	INDEX       // array[index]
)


text:
@article{Hu-2019-Phosphorothioate,
    title = "Phosphorothioate DNA Mediated Sequence-Insensitive Etching and Ripening of Silver Nanoparticles",
    author = "Hu, Shengqiang  and
      Huang, Po-Jung Jimmy  and
      Wang, Jianxiu  and
      Liu, Juewen",
    journal = "Frontiers in Chemistry, Volume 7",
    volume = "7",
    year = "2019",
    publisher = "Frontiers Media SA",
    url = "https://aclanthology.org/G19-73001",
    doi = "10.3389/fchem.2019.00198",
    abstract = "Many DNA-functionalized nanomaterials and biosensors have been reported, but most have ignored the influence of DNA on the stability of nanoparticles. We observed that cytosine-rich DNA oligonucleotides can etch silver nanoparticles (AgNPs). In this work, we showed that phosphorothioate (PS)-modified DNA (PS-DNA) can etch AgNPs independently of DNA sequence, suggesting that the thio-modifications are playing the major role in etching. Compared to unmodified DNA (e.g., poly-cytosine DNA), the concentration of required PS DNA decreases sharply, and the reaction rate increases. Furthermore, etching by PS-DNA occurs quite independent of pH, which is also different from unmodified DNA. The PS-DNA mediated etching could also be controlled well by varying DNA length and conformation, and the number and location of PS modifications. With a higher activity of PS-DNA, the process of etching, ripening, and further etching was taken place sequentially. The etching ability is inhibited by forming duplex DNA and thus etching can be used to measure the concentration of complementary DNA.",
}

repository: gwf-uwaterloo/gwf-publications

repo_name: gwf-uwaterloo/gwf-publications

branch_name: refs/heads/main

gha_language: Python

extension: bib


text:
DESCRIPTION = "Qml clock for new year celebration."

LICENSE = "GPL-3.0"
LIC_FILES_CHKSUM = "file://LICENSE;md5=1ebbd3e34237af26da5dc08a4e440464"

inherit cmake_qt5

SRCREV = "b0ebf4409c6561433af67b29437bee594dcf0cec"
SRC_URI = "gitsm://github.com/dev-0x7C6/new-year-clock.git;protocol=https;branch=master;user=git"

S = "${WORKDIR}/git"

DEPENDS += "qtbase qtmultimedia qtdeclarative"


text:
package app

import (
	"database/sql"
	"errors"
	"fmt"
	"os"

	"github.com/AndrewMobbs/appdb"
)

type appDB struct {
	db      *sql.DB
	Path    string
	AppName string
}

const schemaVersion uint8 = 1

// schema returns the database schema. Golang doesn't provide const arrays/slices.
func schema() []string {
	return []string{
		`CREATE TABLE id(
			id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
		`,
	}
}

func NewAppDB(path string, appName string) *appDB {
	return &appDB{
		Path:    path,
		AppName: appName,
	}
}

// Open() opens the app database.
func (s *appDB) Open() error {
	var err error
	if s.Path == "" {
		return fmt.Errorf("database not configured, run init command")
	}
	if s.db == nil {
		s.db, err = appdb.Open(s.Path, s.AppName, schemaVersion)
	}
	return err
}

// Initialize the database, deploying the schema
func (s *appDB) Initialize() error {
	db, err := appdb.InitAppDB(s.Path, s.AppName, schemaVersion, schema())
	if err == nil {
		db.Close()
	}
	return err
}

func (s *appDB) Close() error {
	if s.db != nil {
		return s.db.Close()
	}
	return nil
}

func (a *App) checkDBExists() bool {
	a.Logger.Trace("App.checkDBExists()")
	filestat, err := os.Stat(a.DatabasePath)
	exists := true
	if err != nil {
		if errors.Is(err, os.ErrNotExist) {
			exists = false
		} else {
			a.Logger.Fatal("Error statting Database file: ", err)
		}
	} else {
		if !filestat.Mode().IsRegular() {
			a.Logger.Fatal("Database file exists but isn't regular file.")
		}
	}
	return exists
}

repository: AndrewMobbs/boilerplate-golang-cli

repo_name: AndrewMobbs/boilerplate-golang-cli


text:
package dhcp6opts

import (
	"bytes"
	"encoding"
	"encoding/binary"
	"io"
	"net"
	"net/url"
	"reflect"
	"testing"
	"time"

	"github.com/oiooj/dhcp6d"
)

// TestOptionsAddBinaryMarshaler verifies that dhcp6.Options.Add correctly creates or
// appends OptionCode keys with BinaryMarshaler bytes values to an dhcp6.Options map.
//
// TODO: This should just be atest for each of the binary marshalers.
func TestOptionsAddBinaryMarshaler(t *testing.T) {
	var tests = []struct {
		desc    string
		code    dhcp6.OptionCode
		bin     encoding.BinaryMarshaler
		options dhcp6.Options
	}{
		{
			desc: "DUID-LLT",
			code: dhcp6.OptionClientID,
			bin: &DUIDLLT{
				Type:         DUIDTypeLLT,
				HardwareType: 1,
				Time:         duidLLTTime.Add(1 * time.Minute).Sub(duidLLTTime),
				HardwareAddr: net.HardwareAddr([]byte{0, 1, 0, 1, 0, 1}),
			},
			options: dhcp6.Options{
				dhcp6.OptionClientID: [][]byte{{
					0, 1,
					0, 1,
					0, 0, 0, 60,
					0, 1, 0, 1, 0, 1,
				}},
			},
		},
		{
			desc: "DUID-EN",
			code: dhcp6.OptionClientID,
			bin: &DUIDEN{
				Type:             DUIDTypeEN,
				EnterpriseNumber: 100,
				Identifier:       []byte{0, 1, 2, 3, 4},
			},
			options: dhcp6.Options{
				dhcp6.OptionClientID: [][]byte{{
					0, 2,
					0, 0, 0, 100,
					0, 1, 2, 3, 4,
				}},
			},
		},
		{
			desc: "DUID-LL",
			code: dhcp6.OptionClientID,
			bin: &DUIDLL{
				Type:         DUIDTypeLL,
				HardwareType: 1,
				HardwareAddr: net.HardwareAddr([]byte{0, 1, 0, 1, 0, 1}),
			},
			options: dhcp6.Options{
				dhcp6.OptionClientID: [][]byte{{
					0, 3,
					0, 1,
					0, 1, 0, 1, 0, 1,
				}},
			},
		},
		{
			desc: "DUID-UUID",
			code: dhcp6.OptionClientID,
			bin: &DUIDUUID{
				Type: DUIDTypeUUID,
				UUID: [16]byte{
					1, 1, 1, 1,
					2, 2, 2, 2,
					3, 3, 3, 3,
					4, 4, 4, 4,
				},
			},
			options: dhcp6.Options{
				dhcp6.OptionClientID: [][]byte{{
					0, 4,
					1, 1, 1, 1,
					2, 2, 2, 2,
					3, 3, 3, 3,
					4, 4, 4, 4,
				}},
			},
		},
		{
			desc: "IA_NA",
			code: dhcp6.OptionIANA,
			bin: &IANA{
				IAID: [4]byte{0, 1, 2, 3},
				T1:   30 * time.Second,
				T2:   60 * time.Second,
			},
			options: dhcp6.Options{
				dhcp6.OptionIANA: [][]byte{{
					0, 1, 2, 3,
					0, 0, 0, 30,
					0, 0, 0, 60,
				}},
			},
		},
		{
			desc: "IA_TA",
			code: dhcp6.OptionIATA,
			bin: &IATA{
				IAID: [4]byte{0, 1, 2, 3},
			},
			options: dhcp6.Options{
				dhcp6.OptionIATA: [][]byte{{
					0, 1, 2, 3,
				}},
			},
		},
		{
			desc: "IAAddr",
			code: dhcp6.OptionIAAddr,
			bin: &IAAddr{
				IP:                net.IPv6loopback,
				PreferredLifetime: 30 * time.Second,
				ValidLifetime:     60 * time.Second,
			},
			options: dhcp6.Options{
				dhcp6.OptionIAAddr: [][]byte{{
					0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
					0, 0, 0, 30,
					0, 0, 0, 60,
				}},
			},
		},
		{
			desc: "Preference",
			code: dhcp6.OptionPreference,
			bin:  Preference(255),
			options: dhcp6.Options{
				dhcp6.OptionPreference: [][]byte{{255}},
			},
		},
		{
			desc: "ElapsedTime",
			code: dhcp6.OptionElapsedTime,
			bin:  ElapsedTime(60 * time.Second),
			options: dhcp6.Options{
				dhcp6.OptionElapsedTime: [][]byte{{23, 112}},
			},
		},
		{
			desc: "Unicast IP",
			code: dhcp6.OptionUnicast,
			bin:  IP(net.IPv6loopback),
			options: dhcp6.Options{
				dhcp6.OptionUnicast: [][]byte{{
					0, 0, 0, 0, 0, 0, 0, 0,
					0, 0, 0, 0, 0, 0, 0, 1,
				}},
			},
		},
		{
			desc: "StatusCode",
			code: dhcp6.OptionStatusCode,
			bin: &StatusCode{
				Code:    dhcp6.StatusSuccess,
				Message: "hello world",
			},
			options: dhcp6.Options{
				dhcp6.OptionStatusCode: [][]byte{{
					0, 0,
					'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd',
				}},
			},
		},
		{
			desc: "RapidCommit",
			code: dhcp6.OptionRapidCommit,
			bin:  nil,
			options: dhcp6.Options{
				dhcp6.OptionRapidCommit: [][]byte{nil},
			},
		},
		{
			desc: "Data (UserClass, VendorClass, BootFileParam)",
			code: dhcp6.OptionUserClass,
			bin: Data{
				[]byte{0},
				[]byte{0, 1},
				[]byte{0, 1, 2},
			},
			options: dhcp6.Options{
				dhcp6.OptionUserClass: [][]byte{{
					0, 1, 0,
					0, 2, 0, 1,
					0, 3, 0, 1, 2,
				}},
			},
		},
		{
			desc: "IA_PD",
			code: dhcp6.OptionIAPD,
			bin: &IAPD{
				IAID: [4]byte{0, 1, 2, 3},
				T1:   30 * time.Second,
				T2:   60 * time.Second,
			},
			options: dhcp6.Options{
				dhcp6.OptionIAPD: [][]byte{{
					0, 1, 2, 3,
					0, 0, 0, 30,
					0, 0, 0, 60,
				}},
			},
		},
		{
			desc: "IAPrefix",
			code: dhcp6.OptionIAPrefix,
			bin: &IAPrefix{
				PreferredLifetime: 30 * time.Second,
				ValidLifetime:     60 * time.Second,
				PrefixLength:      64,
				Prefix: net.IP{
					1, 1, 1, 1, 1, 1, 1, 1,
					0, 0, 0, 0, 0, 0, 0, 0,
				},
			},
			options: dhcp6.Options{
				dhcp6.OptionIAPrefix: [][]byte{{
					0, 0, 0, 30,
					0, 0, 0, 60,
					64,
					1, 1, 1, 1, 1, 1, 1, 1,
					0, 0, 0, 0, 0, 0, 0, 0,
				}},
			},
		},
		{
			desc: "URL",
			code: dhcp6.OptionBootFileURL,
			bin: &URL{
				Scheme: "tftp",
				Host:   "192.168.1.1:69",
			},
			options: dhcp6.Options{
				dhcp6.OptionBootFileURL: [][]byte{[]byte("tftp://192.168.1.1:69")},
			},
		},
		{
			desc: "ArchTypes",
			code: dhcp6.OptionClientArchType,
			bin: ArchTypes{
				ArchTypeEFIx8664,
				ArchTypeIntelx86PC,
				ArchTypeIntelLeanClient,
			},
			options: dhcp6.Options{
				dhcp6.OptionClientArchType: [][]byte{{0, 9, 0, 0, 0, 5}},
			},
		},
		{
			desc: "NII",
			code: dhcp6.OptionNII,
			bin: &NII{
				Type:  1,
				Major: 2,
				Minor: 3,
			},
			options: dhcp6.Options{
				dhcp6.OptionNII: [][]byte{{1, 2, 3}},
			},
		},
	}

	for i, tt := range tests {
		o := make(dhcp6.Options)
		if err := o.Add(tt.code, tt.bin); err != nil {
			t.Fatal(err)
		}

		if want, got := tt.options, o; !reflect.DeepEqual(want, got) {
			t.Errorf("[%02d] test %q, unexpected dhcp6.Options map:\n- want: %v\n-  got: %v",
				i, tt.desc, want, got)
		}
	}
}

// TestGetClientID verifies that dhcp6.Options.ClientID properly parses and returns
// a DUID value, if one is available with OptionClientID.
func TestGetClientID(t *testing.T) {
	var tests = []struct {
		desc    string
		options dhcp6.Options
		duid    DUID
		err     error
	}{
		{
			desc: "OptionClientID not present in dhcp6.Options map",
			err:  dhcp6.ErrOptionNotPresent,
		},
		{
			desc: "OptionClientID present in dhcp6.Options map",
			options: dhcp6.Options{
				dhcp6.OptionClientID: [][]byte{{
					0, 3,
					0, 1,
					0, 1, 0, 1, 0, 1,
				}},
			},
			duid: &DUIDLL{
				Type:         DUIDTypeLL,
				HardwareType: 1,
				HardwareAddr: []byte{0, 1, 0, 1, 0, 1},
			},
		},
	}

	for i, tt := range tests {
		// DUID parsing is tested elsewhere, so errors should automatically fail
		// test here
		duid, err := GetClientID(tt.options)
		if err != nil {
			if want, got := tt.err, err; want != got {
				t.Errorf("[%02d] test %q, unexpected err for dhcp6.Options.ClientID(): %v != %v",
					i, tt.desc, want, got)
			}
			continue
		}

		if want, got := tt.duid, duid; !reflect.DeepEqual(want, got) {
			t.Errorf("[%02d] test %q, unexpected value for dhcp6.Options.ClientID():\n- want: %v\n-  got: %v",
				i, tt.desc, want, got)
		}
	}
}

// TestGetServerID verifies that dhcp6.Options.ServerID properly parses and returns
// a DUID value, if one is available with OptionServerID.
func TestGetServerID(t *testing.T) {
	var tests = []struct {
		desc    string
		options dhcp6.Options
		duid    DUID
		err     error
	}{
		{
			desc: "OptionServerID not present in dhcp6.Options map",
			err:  dhcp6.ErrOptionNotPresent,
		},
		{
			desc: "OptionServerID present in dhcp6.Options map",
			options: dhcp6.Options{
				dhcp6.OptionServerID: [][]byte{{
					0, 3,
					0, 1,
					0, 1, 0, 1, 0, 1,
				}},
			},
			duid: &DUIDLL{
				Type:         DUIDTypeLL,
				HardwareType: 1,
				HardwareAddr: []byte{0, 1, 0, 1, 0, 1},
			},
		},
	}

	for i, tt := range tests {
		// DUID parsing is tested elsewhere, so errors should automatically fail
		// test here
		duid, err := GetServerID(tt.options)
		if err != nil {
			if want, got := tt.err, err; want != got {
				t.Errorf("[%02d] test %q, unexpected err for dhcp6.Options.ServerID(): %v != %v",
					i, tt.desc, want, got)
			}
			continue
		}

		if want, got := tt.duid, duid; !reflect.DeepEqual(want, got) {
			t.Errorf("[%02d] test %q, unexpected value for dhcp6.Options.ServerID():\n- want: %v\n-  got: %v",
				i, tt.desc, want, got)
		}
	}
}

// TestGetIANA verifies that dhcp6.Options.IANA properly parses and
// returns multiple IANA values, if one or more are available with OptionIANA.
func TestGetIANA(t *testing.T) {
	var tests = []struct {
		desc    string
		options dhcp6.Options
		iana    []*IANA
		err     error
	}{
		{
			desc: "OptionIANA not present in dhcp6.Options map",
			err:  dhcp6.ErrOptionNotPresent,
		},
		{
			desc: "OptionIANA present in dhcp6.Options map, but too short",
			options: dhcp6.Options{
				dhcp6.OptionIANA: [][]byte{bytes.Repeat([]byte{0}, 11)},
			},
			err: io.ErrUnexpectedEOF,
		},
		{
			desc: "one OptionIANA present in dhcp6.Options map",
			options: dhcp6.Options{
				dhcp6.OptionIANA: [][]byte{{
					1, 2, 3, 4,
					0, 0, 0, 30,
					0, 0, 0, 60,
				}},
			},
			iana: []*IANA{
				{
					IAID: [4]byte{1, 2, 3, 4},
					T1:   30 * time.Second,
					T2:   60 * time.Second,
				},
			},
		},
		{
			desc: "two OptionIANA present in dhcp6.Options map",
			options: dhcp6.Options{
				dhcp6.OptionIANA: [][]byte{
					append(bytes.Repeat([]byte{0}, 12), []byte{0, 1, 0, 1, 1}...),
					append(bytes.Repeat([]byte{0}, 12), []byte{0, 2, 0, 1, 2}...),
				},
			},
			iana: []*IANA{
				{
					Options: dhcp6.Options{
						dhcp6.OptionClientID: [][]byte{{1}},
					},
				},
				{
					Options: dhcp6.Options{
						dhcp6.OptionServerID: [][]byte{{2}},
					},
				},
			},
		},
	}

	for i, tt := range tests {
		iana, err := GetIANA(tt.options)
		if err != nil {
			if want, got := tt.err, err; want != got {
				t.Errorf("[%02d] test %q, unexpected error for dhcp6.Options.IANA: %v != %v",
					i, tt.desc, want, got)
			}
			continue
		}

		for j := range tt.iana {
			want, err := tt.iana[j].MarshalBinary()
			if err != nil {
				t.Fatal(err)
			}
			got, err := iana[j].MarshalBinary()
			if err != nil {
				t.Fatal(err)
			}

			if !bytes.Equal(want, got) {
				t.Errorf("[%02d:%02d] test %q, unexpected value for dhcp6.Options.IANA():\n- want: %v\n-  got: %v",
					i, j, tt.desc, want, got)
			}
		}
	}
}

// TestGetIATA verifies that dhcp6.Options.IATA properly parses and
// returns multiple IATA values, if one or more are available with OptionIATA.
func TestGetIATA(t *testing.T) {
	var tests = []struct {
		desc    string
		options dhcp6.Options
		iata    []*IATA
		err     error
	}{
		{
			desc: "OptionIATA not present in dhcp6.Options map",
			err:  dhcp6.ErrOptionNotPresent,
		},
		{
			desc: "OptionIATA present in dhcp6.Options map, but too short",
			options: dhcp6.Options{
				dhcp6.OptionIATA: [][]byte{{0, 0, 0}},
			},
			err: io.ErrUnexpectedEOF,
		},
		{
			desc: "one OptionIATA present in dhcp6.Options map",
			options: dhcp6.Options{
				dhcp6.OptionIATA: [][]byte{{
					1, 2, 3, 4,
				}},
			},
			iata: []*IATA{
				{
					IAID: [4]byte{1, 2, 3, 4},
				},
			},
		},
		{
			desc: "two OptionIATA present in dhcp6.Options map",
			options: dhcp6.Options{
				dhcp6.OptionIATA: [][]byte{
					{0, 1, 2, 3, 0, 1, 0, 1, 1},
					{4, 5, 6, 7, 0, 2, 0, 1, 2},
				},
			},
			iata: []*IATA{
				{
					IAID: [4]byte{0, 1, 2, 3},
					Options: dhcp6.Options{
						dhcp6.OptionClientID: [][]byte{{1}},
					},
				},
				{
					IAID: [4]byte{4, 5, 6, 7},
					Options: dhcp6.Options{
						dhcp6.OptionServerID: [][]byte{{2}},
					},
				},
			},
		},
	}

	for i, tt := range tests {
		iata, err := GetIATA(tt.options)
		if err != nil {
			if want, got := tt.err, err; want != got {
				t.Errorf("[%02d] test %q, unexpected error for dhcp6.Options.IATA: %v != %v",
					i, tt.desc, want, got)
			}
			continue
		}

		for j := range tt.iata {
			want, err := tt.iata[j].MarshalBinary()
			if err != nil {
				t.Fatal(err)
			}
			got, err := iata[j].MarshalBinary()
			if err != nil {
				t.Fatal(err)
			}

			if !bytes.Equal(want, got) {
				t.Errorf("[%02d:%02d] test %q, unexpected value for dhcp6.Options.IATA():\n- want: %v\n-  got: %v",
					i, j, tt.desc, want, got)
			}
		}
	}
}

// TestGetIAAddr verifies that dhcp6.Options.IAAddr properly parses and
// returns multiple IAAddr values, if one or more are available with
// OptionIAAddr.
func TestGetIAAddr(t *testing.T) {
	var tests = []struct {
		desc    string
		options dhcp6.Options
		iaaddr  []*IAAddr
		err     error
	}{
		{
			desc: "OptionIAAddr not present in dhcp6.Options map",
			err:  dhcp6.ErrOptionNotPresent,
		},
		{
			desc: "OptionIAAddr present in dhcp6.Options map, but too short",
			options: dhcp6.Options{
				dhcp6.OptionIAAddr: [][]byte{bytes.Repeat([]byte{0}, 23)},
			},
			err: io.ErrUnexpectedEOF,
		},
		{
			desc: "one OptionIAAddr present in dhcp6.Options map",
			options: dhcp6.Options{
				dhcp6.OptionIAAddr: [][]byte{{
					0, 0, 0, 0,
					1, 1, 1, 1,
					2, 2, 2, 2,
					3, 3, 3, 3,
					0, 0, 0, 30,
					0, 0, 0, 60,
				}},
			},
			iaaddr: []*IAAddr{
				{
					IP: net.IP{
						0, 0, 0, 0,
						1, 1, 1, 1,
						2, 2, 2, 2,
						3, 3, 3, 3,
					},
					PreferredLifetime: 30 * time.Second,
					ValidLifetime:     60 * time.Second,
				},
			},
		},
		{
			desc: "two OptionIAAddr present in dhcp6.Options map",
			options: dhcp6.Options{
				dhcp6.OptionIAAddr: [][]byte{
					bytes.Repeat([]byte{0}, 24),
					bytes.Repeat([]byte{0}, 24),
				},
			},
			iaaddr: []*IAAddr{
				{
					IP: net.IPv6zero,
				},
				{
					IP: net.IPv6zero,
				},
			},
		},
	}

	for i, tt := range tests {
		iaaddr, err := GetIAAddr(tt.options)
		if err != nil {
			if want, got := tt.err, err; want != got {
				t.Errorf("[%02d] test %q, unexpected error for dhcp6.Options.IAAddr: %v != %v",
					i, tt.desc, want, got)
			}
			continue
		}

		for j := range tt.iaaddr {
			want, err := tt.iaaddr[j].MarshalBinary()
			if err != nil {
				t.Fatal(err)
			}
			got, err := iaaddr[j].MarshalBinary()
			if err != nil {
				t.Fatal(err)
			}

			if !bytes.Equal(want, got) {
				t.Errorf("[%02d:%02d] test %q, unexpected value for dhcp6.Options.IAAddr():\n- want: %v\n-  got: %v",
					i, j, tt.desc, want, got)
			}
		}
	}
}

// TestGetOptionRequest verifies that dhcp6.Options.OptionRequest properly parses
// and returns a slice of OptionCode values, if they are available with
// OptionORO.
func TestGetOptionRequest(t *testing.T) {
	var tests = []struct {
		desc    string
		options dhcp6.Options
		codes   OptionRequestOption
		err     error
	}{
		{
			desc: "OptionORO not present in dhcp6.Options map",
			err:  dhcp6.ErrOptionNotPresent,
		},
		{
			desc: "OptionORO present in dhcp6.Options map, but not even length",
			options: dhcp6.Options{
				dhcp6.OptionORO: [][]byte{{0}},
			},
			err: io.ErrUnexpectedEOF,
		},
		{
			desc: "OptionORO present in dhcp6.Options map",
			options: dhcp6.Options{
				dhcp6.OptionORO: [][]byte{{0, 1}},
			},
			codes: []dhcp6.OptionCode{1},
		},
		{
			desc: "OptionORO present in dhcp6.Options map, with multiple values",
			options: dhcp6.Options{
				dhcp6.OptionORO: [][]byte{{0, 1, 0, 2, 0, 3}},
			},
			codes: []dhcp6.OptionCode{1, 2, 3},
		},
	}

	for i, tt := range tests {
		codes, err := GetOptionRequest(tt.options)
		if err != nil {
			if want, got := tt.err, err; want != got {
				t.Errorf("[%02d] test %q, unexpected error for dhcp6.Options.OptionRequest(): %v != %v",
					i, tt.desc, want, got)
			}
			continue
		}

		if want, got := tt.codes, codes; !reflect.DeepEqual(want, got) {
			t.Errorf("[%02d] test %q, unexpected value for dhcp6.Options.OptionRequest():\n- want: %v\n-  got: %v",
				i, tt.desc, want, got)
		}
	}
}

// TestGetPreference verifies that dhcp6.Options.Preference properly parses
// and returns an integer value, if it is available with OptionPreference.
func TestGetPreference(t *testing.T) {
	var tests = []struct {
		desc       string
		options    dhcp6.Options
		preference Preference
		err        error
	}{
		{
			desc: "OptionPreference not present in dhcp6.Options map",
			err:  dhcp6.ErrOptionNotPresent,
		},
		{
			desc: "OptionPreference present in dhcp6.Options map, but too short length",
			options: dhcp6.Options{
				dhcp6.OptionPreference: [][]byte{{}},
			},
			err: io.ErrUnexpectedEOF,
		},
		{
			desc: "OptionPreference present in dhcp6.Options map, but too long length",
			options: dhcp6.Options{
				dhcp6.OptionPreference: [][]byte{{0, 1}},
			},
			err: io.ErrUnexpectedEOF,
		},
		{
			desc: "OptionPreference present in dhcp6.Options map",
			options: dhcp6.Options{
				dhcp6.OptionPreference: [][]byte{{255}},
			},
			preference: 255,
		},
	}

	for i, tt := range tests {
		preference, err := GetPreference(tt.options)
		if err != nil {
			if want, got := tt.err, err; want != got {
				t.Errorf("[%02d] test %q, unexpected error for dhcp6.Options.Preference(): %v != %v",
					i, tt.desc, want, got)
			}
			continue
		}

		if want, got := tt.preference, preference; want != got {
			t.Errorf("[%02d] test %q, unexpected value for dhcp6.Options.Preference(): %v != %v",
				i, tt.desc, want, got)
		}
	}
}

// TestGetUnicast verifies that dhcp6.Options.Unicast properly parses
// and returns an IPv6 address or an error, if available with OptionUnicast.
func TestGetUnicast(t *testing.T) {
	var tests = []struct {
		desc    string
		options dhcp6.Options
		ip      IP
		err     error
	}{
		{
			desc: "OptionUnicast not present in dhcp6.Options map",
			err:  dhcp6.ErrOptionNotPresent,
		},
		{
			desc: "OptionUnicast present in dhcp6.Options map, but too short length",
			options: dhcp6.Options{
				dhcp6.OptionUnicast: [][]byte{bytes.Repeat([]byte{0}, 15)},
			},
			err: io.ErrUnexpectedEOF,
		},
		{
			desc: "OptionUnicast present in dhcp6.Options map, but too long length",
			options: dhcp6.Options{
				dhcp6.OptionUnicast: [][]byte{bytes.Repeat([]byte{0}, 17)},
			},
			err: io.ErrUnexpectedEOF,
		},
		{
			desc: "OptionUnicast present in dhcp6.Options map with IPv4 address",
			options: dhcp6.Options{
				dhcp6.OptionUnicast: [][]byte{net.IPv4(192, 168, 1, 1)},
			},
			err: io.ErrUnexpectedEOF,
		},
		{
			desc: "OptionUnicast present in dhcp6.Options map with IPv6 address",
			options: dhcp6.Options{
				dhcp6.OptionUnicast: [][]byte{net.IPv6loopback},
			},
			ip: IP(net.IPv6loopback),
		},
	}

	for i, tt := range tests {
		ip, err := GetUnicast(tt.options)
		if err != nil {
			if want, got := tt.err, err; want != got {
				t.Errorf("[%02d] test %q, unexpected error for dhcp6.Options.Unicast(): %v != %v",
					i, tt.desc, want, got)
			}
			continue
		}

		if want, got := tt.ip, ip; !bytes.Equal(want, got) {
			t.Errorf("[%02d] test %q, unexpected value for dhcp6.Options.Unicast():\n- want: %v\n-  got: %v",
				i, tt.desc, want, got)
		}
	}
}

// TestGetStatusCode verifies that dhcp6.Options.StatusCode properly parses
// and returns a StatusCode value, if it is available with OptionStatusCode.
func TestGetStatusCode(t *testing.T) {
	var tests = []struct {
		desc    string
		options dhcp6.Options
		sc      *StatusCode
		err     error
	}{
		{
			desc: "OptionStatusCode not present in dhcp6.Options map",
			err:  dhcp6.ErrOptionNotPresent,
		},
		{
			desc: "OptionStatusCode present in dhcp6.Options map, but too short length",
			options: dhcp6.Options{
				dhcp6.OptionStatusCode: [][]byte{{}},
			},
			err: io.ErrUnexpectedEOF,
		},
		{
			desc: "OptionStatusCode present in dhcp6.Options map, no message",
			options: dhcp6.Options{
				dhcp6.OptionStatusCode: [][]byte{{0, 0}},
			},
			sc: &StatusCode{
				Code: dhcp6.StatusSuccess,
			},
		},
		{
			desc: "OptionStatusCode present in dhcp6.Options map, with message",
			options: dhcp6.Options{
				dhcp6.OptionStatusCode: [][]byte{append([]byte{0, 0}, []byte("deadbeef")...)},
			},
			sc: &StatusCode{
				Code:    dhcp6.StatusSuccess,
				Message: "deadbeef",
			},
		},
	}

	for i, tt := range tests {
		sc, err := GetStatusCode(tt.options)
		if err != nil {
			if want, got := tt.err, err; want != got {
				t.Errorf("[%02d] test %q, unexpected error for dhcp6.Options.StatusCode(): %v != %v",
					i, tt.desc, want, got)
			}
			continue
		}

		if want, got := tt.sc, sc; !reflect.DeepEqual(want, got) {
			t.Errorf("[%02d] test %q, unexpected value for dhcp6.Options.StatusCode():\n- want: %v\n-  got: %v",
				i, tt.desc, want, got)
		}
	}
}

// TestGetElapsedTime verifies that dhcp6.Options.ElapsedTime properly parses and
// returns a time.Duration value, if one is available with OptionElapsedTime.
func TestGetElapsedTime(t *testing.T) {
	var tests = []struct {
		desc     string
		options  dhcp6.Options
		duration ElapsedTime
		err      error
	}{
		{
			desc: "OptionElapsedTime not present in dhcp6.Options map",
			err:  dhcp6.ErrOptionNotPresent,
		},
		{
			desc: "OptionElapsedTime present in dhcp6.Options map, but too short",
			options: dhcp6.Options{
				dhcp6.OptionElapsedTime: [][]byte{{1}},
			},
			err: io.ErrUnexpectedEOF,
		},
		{
			desc: "OptionElapsedTime present in dhcp6.Options map, but too long",
			options: dhcp6.Options{
				dhcp6.OptionElapsedTime: [][]byte{{1, 2, 3}},
			},
			err: io.ErrUnexpectedEOF,
		},
		{
			desc: "OptionElapsedTime present in dhcp6.Options map",
			options: dhcp6.Options{
				dhcp6.OptionElapsedTime: [][]byte{{1, 1}},
			},
			duration: ElapsedTime(2570 * time.Millisecond),
		},
	}

	for i, tt := range tests {
		duration, err := GetElapsedTime(tt.options)
		if err != nil {
			if want, got := tt.err, err; want != got {
				t.Errorf("[%02d] test %q, unexpected error for dhcp6.Options.ElapsedTime: %v != %v",
					i, tt.desc, want, got)
			}
			continue
		}

		if want, got := tt.duration, duration; want != got {
			t.Errorf("[%02d] test %q, unexpected value for dhcp6.Options.ElapsedTime(): %v != %v",
				i, tt.desc, want, got)
		}
	}
}

// TestElapsedTimeMarshalBinary verifies that dhcp6.Options.ElapsedTime properly
// marsharls into bytes array.
func TestElapsedTimeMarshalBinary(t *testing.T) {
	var tests = []struct {
		desc        string
		elapsedTime ElapsedTime
		buf         []byte
		err         error
	}{
		{
			desc: "OptionElapsedTime elapsed-time = 0",
			buf:  []byte{0, 0},
		},
		{
			desc:        "OptionElapsedTime elapsed-time = 65534 hundredths of a second",
			elapsedTime: ElapsedTime(655340 * time.Millisecond),
			buf:         []byte{0xff, 0xfe},
		},
		{
			desc:        "OptionElapsedTime elapsed-time = 65535 hundredths of a second",
			elapsedTime: ElapsedTime(655350 * time.Millisecond),
			buf:         []byte{0xff, 0xff},
		},
		{
			desc:        "OptionElapsedTime elapsed-time = 65537 hundredths of a second",
			elapsedTime: ElapsedTime(655370 * time.Millisecond),
			buf:         []byte{0xff, 0xff},
		},
	}

	for i, tt := range tests {
		buf, err := tt.elapsedTime.MarshalBinary()
		if want, got := tt.err, err; want != got {
			t.Errorf("[%02d] test %q, unexpected error for dhcp6.Options.ElapsedTime\n- want: %v\n-  got: %v",
				i, tt.desc, want, got)
		}

		if tt.err != nil {
			continue
		}

		if want, got := tt.buf, buf; !bytes.Equal(want, got) {
			t.Errorf("[%02d] test %q, unexpected error for dhcp6.Options.ElapsedTime\n- want: %v\n-  got: %v",
				i, tt.desc, want, got)
		}
	}
}

// TestGetRelayMessage verifies that dhcp6.Options.RelayMessageOption properly parses and
// returns an relay message option value, if one is available with RelayMessageOption.
func TestGetRelayMessage(t *testing.T) {
	var tests = []struct {
		desc           string
		options        dhcp6.Options
		authentication RelayMessageOption
		err            error
	}{
		{
			desc: "RelayMessageOption not present in dhcp6.Options map",
			err:  dhcp6.ErrOptionNotPresent,
		},
		{
			desc: "RelayMessageOption present in dhcp6.Options map",
			options: dhcp6.Options{
				dhcp6.OptionRelayMsg: [][]byte{{1, 1, 2, 3}},
			},
			authentication: []byte{1, 1, 2, 3},
		},
	}

	for i, tt := range tests {
		relayMsg, err := GetRelayMessageOption(tt.options)
		if want, got := tt.err, err; want != got {
			t.Errorf("[%02d] test %q, unexpected error for dhcp6.Options.RelayMessageOption\n- want: %v\n-  got: %v", i, tt.desc, want, got)
		}

		if tt.err != nil {
			continue
		}

		if want, got := tt.authentication, relayMsg; !reflect.DeepEqual(want, got) {
			t.Errorf("[%02d] test %q, unexpected value for dhcp6.Options.RelayMessageOption()\n- want: %v\n-  got: %v", i, tt.desc, want, got)
		}

		if want, got := tt.err, err; want != got {
			t.Errorf("[%02d] test %q, unexpected err for dhcp6.Options.RelayMessageOption(): %v != %v", i, tt.desc, want, got)
		}
	}
}

// TestAuthentication verifies that dhcp6.Options.Authentication properly parses and
// returns an authentication value, if one is available with Authentication.
func TestAuthentication(t *testing.T) {
	var tests = []struct {
		desc           string
		options        dhcp6.Options
		authentication *Authentication
		err            error
	}{
		{
			desc: "Authentication not present in dhcp6.Options map",
			err:  dhcp6.ErrOptionNotPresent,
		},
		{
			desc: "Authentication present in dhcp6.Options map, but too short",
			options: dhcp6.Options{
				dhcp6.OptionAuth: [][]byte{bytes.Repeat([]byte{0}, 10)},
			},
			err: io.ErrUnexpectedEOF,
		},
		{
			desc: "Authentication present in dhcp6.Options map",
			options: dhcp6.Options{
				dhcp6.OptionAuth: [][]byte{{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf}},
			},
			authentication: &Authentication{
				Protocol:                  0,
				Algorithm:                 1,
				RDM:                       2,
				ReplayDetection:           binary.BigEndian.Uint64([]byte{3, 4, 5, 6, 7, 8, 9, 0xa}),
				AuthenticationInformation: []byte{0xb, 0xc, 0xd, 0xe, 0xf},
			},
		},
	}

	for i, tt := range tests {
		authentication, err := GetAuthentication(tt.options)
		if want, got := tt.err, err; want != got {
			t.Errorf("[%02d] test %q, unexpected error for dhcp6.Options.Authentication\n- want: %v\n-  got: %v", i, tt.desc, want, got)
		}

		if tt.err != nil {
			continue
		}

		if want, got := tt.authentication, authentication; !reflect.DeepEqual(want, got) {
			t.Errorf("[%02d] test %q, unexpected value for dhcp6.Options.Authentication()\n- want: %v\n-  got: %v", i, tt.desc, want, got)
		}

		if want, got := tt.err, err; want != got {
			t.Errorf("[%02d] test %q, unexpected err for dhcp6.Options.Authentication(): %v != %v", i, tt.desc, want, got)
		}
	}
}

// TestGetRapidCommit verifies that dhcp6.Options.RapidCommit properly indicates
// if OptionRapidCommit was present in dhcp6.Options.
func TestGetRapidCommit(t *testing.T) {
	var tests = []struct {
		desc    string
		options dhcp6.Options
		err     error
	}{
		{
			desc: "OptionRapidCommit not present in dhcp6.Options map",
			err:  dhcp6.ErrOptionNotPresent,
		},
		{
			desc: "OptionRapidCommit present in dhcp6.Options map, but non-empty",
			options: dhcp6.Options{
				dhcp6.OptionRapidCommit: [][]byte{{1}},
			},
			err: dhcp6.ErrInvalidPacket,
		},
		{
			desc: "OptionRapidCommit present in dhcp6.Options map, empty",
			options: dhcp6.Options{
				dhcp6.OptionRapidCommit: [][]byte{},
			},
		},
	}

	for i, tt := range tests {
		err := GetRapidCommit(tt.options)
		if want, got := tt.err, err; want != got {
			t.Errorf("[%02d] test %q, unexpected error for dhcp6.Options.RapidCommit: %v != %v",
				i, tt.desc, want, got)
		}
	}
}

// TestGetUserClass verifies that dhcp6.Options.UserClass properly parses
// and returns raw user class data, if it is available with OptionUserClass.
func TestGetUserClass(t *testing.T) {
	var tests = []struct {
		desc    string
		options dhcp6.Options
		classes [][]byte
		err     error
	}{
		{
			desc: "OptionUserClass not present in dhcp6.Options map",
			err:  dhcp6.ErrOptionNotPresent,
		},
		{
			desc: "OptionUserClass present in dhcp6.Options map, but empty",
			options: dhcp6.Options{
				dhcp6.OptionUserClass: [][]byte{{}},
			},
			err: io.ErrUnexpectedEOF,
		},
		{
			desc: "OptionUserClass present in dhcp6.Options map, one item, zero length",
			options: dhcp6.Options{
				dhcp6.OptionUserClass: [][]byte{{
					0, 0,
				}},
			},
			classes: [][]byte{{}},
		},
		{
			desc: "OptionUserClass present in dhcp6.Options map, one item, extra byte",
			options: dhcp6.Options{
				dhcp6.OptionUserClass: [][]byte{{
					0, 1, 1, 255,
				}},
			},
			err: io.ErrUnexpectedEOF,
		},
		{
			desc: "OptionUserClass present in dhcp6.Options map, one item",
			options: dhcp6.Options{
				dhcp6.OptionUserClass: [][]byte{{
					0, 1, 1,
				}},
			},
			classes: [][]byte{{1}},
		},
		{
			desc: "OptionUserClass present in dhcp6.Options map, three items",
			options: dhcp6.Options{
				dhcp6.OptionUserClass: [][]byte{{
					0, 1, 1,
					0, 2, 2, 2,
					0, 3, 3, 3, 3,
				}},
			},
			classes: [][]byte{{1}, {2, 2}, {3, 3, 3}},
		},
	}

	for i, tt := range tests {
		classes, err := GetUserClass(tt.options)
		if err != nil {
			if want, got := tt.err, err; want != got {
				t.Errorf("[%02d] test %q, unexpected error for dhcp6.Options.UserClass: %v != %v",
					i, tt.desc, want, got)
			}
			continue
		}

		if want, got := len(tt.classes), len(classes); want != got {
			t.Errorf("[%02d] test %q, unexpected classes slice length: %v != %v",
				i, tt.desc, want, got)

		}

		for j := range classes {
			if want, got := tt.classes[j], classes[j]; !bytes.Equal(want, got) {
				t.Errorf("[%02d:%02d] test %q, unexpected value for dhcp6.Options.UserClass()\n- want: %v\n-  got: %v",
					i, j, tt.desc, want, got)
			}
		}
	}
}

// TestGetVendorClass verifies that dhcp6.Options.VendorClass properly parses
// and returns raw vendor class data, if it is available with OptionVendorClass.
func TestGetVendorClass(t *testing.T) {
	var tests = []struct {
		desc    string
		options dhcp6.Options
		classes [][]byte
		err     error
	}{
		{
			desc: "OptionVendorClass not present in dhcp6.Options map",
			err:  dhcp6.ErrOptionNotPresent,
		},
		{
			desc: "OptionVendorClass present in dhcp6.Options map, but empty",
			options: dhcp6.Options{
				dhcp6.OptionVendorClass: [][]byte{{}},
			},
			err: io.ErrUnexpectedEOF,
		},
		{
			desc: "OptionVendorClass present in dhcp6.Options map, zero item",
			options: dhcp6.Options{
				dhcp6.OptionVendorClass: [][]byte{{
					0, 0, 5, 0x58,
				}},
			},
			err: io.ErrUnexpectedEOF,
		},
		{
			desc: "OptionVendorClass present in dhcp6.Options map, one item, zero length",
			options: dhcp6.Options{
				dhcp6.OptionVendorClass: [][]byte{{
					0, 0, 5, 0x58,
					0, 0,
				}},
			},
			classes: [][]byte{{}},
		},
		{
			desc: "OptionVendorClass present in dhcp6.Options map, one item, extra byte",
			options: dhcp6.Options{
				dhcp6.OptionVendorClass: [][]byte{{
					0, 0, 5, 0x58,
					0, 1, 1, 255,
				}},
			},
			err: io.ErrUnexpectedEOF,
		},
		{
			desc: "OptionVendorClass present in dhcp6.Options map, one item",
			options: dhcp6.Options{
				dhcp6.OptionVendorClass: [][]byte{{
					0, 0, 5, 0x58,
					0, 1, 1,
				}},
			},
			classes: [][]byte{{1}},
		},
		{
			desc: "OptionVendorClass present in dhcp6.Options map, three items",
			options: dhcp6.Options{
				dhcp6.OptionVendorClass: [][]byte{{
					0, 0, 5, 0x58,
					0, 1, 1,
					0, 2, 2, 2,
					0, 3, 3, 3, 3,
				}},
			},
			classes: [][]byte{{1}, {2, 2}, {3, 3, 3}},
		},
	}

	for i, tt := range tests {
		classes, err := GetVendorClass(tt.options)
		if err != nil {
			if want, got := tt.err, err; want != got {
				t.Errorf("[%02d] test %q, unexpected error for dhcp6.Options.VendorClass: %v != %v",
					i, tt.desc, want, got)
			}
			continue
		}

		if want, got := len(tt.classes), len(classes.VendorClassData); want != got {
			t.Errorf("[%02d] test %q, unexpected classes slice length: %v != %v",
				i, tt.desc, want, got)

		}

		for j := range classes.VendorClassData {
			if want, got := tt.classes[j], classes.VendorClassData[j]; !bytes.Equal(want, got) {
				t.Errorf("[%02d:%02d] test %q, unexpected value for dhcp6.Options.VendorClass()\n- want: %v\n-  got: %v",
					i, j, tt.desc, want, got)
			}
		}
	}
}

// TestInterfaceID verifies that dhcp6.Options.InterfaceID properly parses
// and returns raw interface-id data, if it is available with InterfaceID.
func TestInterfaceID(t *testing.T) {
	var tests = []struct {
		desc        string
		options     dhcp6.Options
		interfaceID InterfaceID
		err         error
	}{
		{
			desc: "InterfaceID not present in dhcp6.Options map",
			err:  dhcp6.ErrOptionNotPresent,
		},
		{
			desc: "InterfaceID present in dhcp6.Options map, one item",
			options: dhcp6.Options{
				dhcp6.OptionInterfaceID: [][]byte{{
					0, 1, 1,
				}},
			},
			interfaceID: []byte{0, 1, 1},
		},
		{
			desc: "InterfaceID present in dhcp6.Options map with no interface-id data",
			options: dhcp6.Options{
				dhcp6.OptionInterfaceID: [][]byte{{}},
			},
			interfaceID: []byte{},
		},
	}

	for i, tt := range tests {
		interfaceID, err := GetInterfaceID(tt.options)
		if err != nil {
			if want, got := tt.err, err; want != got {
				t.Errorf("[%02d] test %q, unexpected error for dhcp6.Options.InterfaceID: %v != %v",
					i, tt.desc, want, got)
			}
			continue
		}

		if want, got := tt.interfaceID, interfaceID; !bytes.Equal(want, got) {
			t.Errorf("[%02d] test %q, unexpected value for dhcp6.Options.InterfaceID()\n- want: %v\n-  got: %v",
				i, tt.desc, want, got)
		}
	}
}

// TestGetIAPD verifies that dhcp6.Options.IAPD properly parses and
// returns multiple IAPD values, if one or more are available with OptionIAPD.
func TestGetIAPD(t *testing.T) {
	var tests = []struct {
		desc    string
		options dhcp6.Options
		iapd    []*IAPD
		err     error
	}{
		{
			desc: "OptionIAPD not present in dhcp6.Options map",
			err:  dhcp6.ErrOptionNotPresent,
		},
		{
			desc: "OptionIAPD present in dhcp6.Options map, but too short",
			options: dhcp6.Options{
				dhcp6.OptionIAPD: [][]byte{bytes.Repeat([]byte{0}, 11)},
			},
			err: io.ErrUnexpectedEOF,
		},
		{
			desc: "one OptionIAPD present in dhcp6.Options map",
			options: dhcp6.Options{
				dhcp6.OptionIAPD: [][]byte{{
					1, 2, 3, 4,
					0, 0, 0, 30,
					0, 0, 0, 60,
				}},
			},
			iapd: []*IAPD{
				{
					IAID: [4]byte{1, 2, 3, 4},
					T1:   30 * time.Second,
					T2:   60 * time.Second,
				},
			},
		},
		{
			desc: "two OptionIAPD present in dhcp6.Options map",
			options: dhcp6.Options{
				dhcp6.OptionIAPD: [][]byte{
					append(bytes.Repeat([]byte{0}, 12), []byte{0, 1, 0, 1, 1}...),
					append(bytes.Repeat([]byte{0}, 12), []byte{0, 2, 0, 1, 2}...),
				},
			},
			iapd: []*IAPD{
				{
					Options: dhcp6.Options{
						dhcp6.OptionClientID: [][]byte{{1}},
					},
				},
				{
					Options: dhcp6.Options{
						dhcp6.OptionServerID: [][]byte{{2}},
					},
				},
			},
		},
	}

	for i, tt := range tests {
		iapd, err := GetIAPD(tt.options)
		if err != nil {
			if want, got := tt.err, err; want != got {
				t.Errorf("[%02d] test %q, unexpected error for dhcp6.Options.IAPD: %v != %v",
					i, tt.desc, want, got)
			}
			continue
		}

		for j := range tt.iapd {
			want, err := tt.iapd[j].MarshalBinary()
			if err != nil {
				t.Fatal(err)
			}
			got, err := iapd[j].MarshalBinary()
			if err != nil {
				t.Fatal(err)
			}

			if !bytes.Equal(want, got) {
				t.Errorf("[%02d:%02d] test %q, unexpected value for dhcp6.Options.IAPD():\n- want: %v\n-  got: %v",
					i, j, tt.desc, want, got)
			}
		}
	}
}

// TestGetIAPrefix verifies that dhcp6.Options.IAPrefix properly parses and
// returns multiple IAPrefix values, if one or more are available with
// OptionIAPrefix.
func TestGetIAPrefix(t *testing.T) {
	var tests = []struct {
		desc     string
		options  dhcp6.Options
		iaprefix []*IAPrefix
		err      error
	}{
		{
			desc: "OptionIAPrefix not present in dhcp6.Options map",
			err:  dhcp6.ErrOptionNotPresent,
		},
		{
			desc: "OptionIAPrefix present in dhcp6.Options map, but too short",
			options: dhcp6.Options{
				dhcp6.OptionIAPrefix: [][]byte{bytes.Repeat([]byte{0}, 24)},
			},
			err: io.ErrUnexpectedEOF,
		},
		{
			desc: "one OptionIAPrefix present in dhcp6.Options map",
			options: dhcp6.Options{
				dhcp6.OptionIAPrefix: [][]byte{{
					0, 0, 0, 30,
					0, 0, 0, 60,
					32,
					32, 1, 13, 184, 0, 0, 0, 0,
					0, 0, 0, 0, 0, 0, 0, 0,
				}},
			},
			iaprefix: []*IAPrefix{
				{
					PreferredLifetime: 30 * time.Second,
					ValidLifetime:     60 * time.Second,
					PrefixLength:      32,
					Prefix: net.IP{
						32, 1, 13, 184, 0, 0, 0, 0,
						0, 0, 0, 0, 0, 0, 0, 0,
					},
				},
			},
		},
		{
			desc: "two OptionIAPrefix present in dhcp6.Options map",
			options: dhcp6.Options{
				dhcp6.OptionIAPrefix: [][]byte{
					bytes.Repeat([]byte{0}, 25),
					bytes.Repeat([]byte{0}, 25),
				},
			},
			iaprefix: []*IAPrefix{
				{
					Prefix: net.IPv6zero,
				},
				{
					Prefix: net.IPv6zero,
				},
			},
		},
	}

	for i, tt := range tests {
		iaprefix, err := GetIAPrefix(tt.options)
		if err != nil {
			if want, got := tt.err, err; want != got {
				t.Errorf("[%02d] test %q, unexpected error for dhcp6.Options.IAPrefix: %v != %v",
					i, tt.desc, want, got)
			}
			continue
		}

		for j := range tt.iaprefix {
			want, err := tt.iaprefix[j].MarshalBinary()
			if err != nil {
				t.Fatal(err)
			}
			got, err := iaprefix[j].MarshalBinary()
			if err != nil {
				t.Fatal(err)
			}

			if !bytes.Equal(want, got) {
				t.Errorf("[%02d:%02d] test %q, unexpected value for dhcp6.Options.IAPrefix():\n- want: %v\n-  got: %v",
					i, j, tt.desc, want, got)
			}
		}
	}
}

// TestRemoteIdentifier verifies that dhcp6.Options.RemoteIdentifier properly parses
// and returns a RemoteIdentifier, if it is available with dhcp6.OptionsRemoteIdentifier.
func TestGetRemoteIdentifier(t *testing.T) {
	var tests = []struct {
		desc             string
		options          dhcp6.Options
		remoteIdentifier *RemoteIdentifier
		err              error
	}{
		{
			desc: "OptionsRemoteIdentifier not present in dhcp6.Options map",
			err:  dhcp6.ErrOptionNotPresent,
		},
		{
			desc: "OptionsRemoteIdentifier present in dhcp6.Options map, but too short",
			options: dhcp6.Options{
				dhcp6.OptionRemoteIdentifier: [][]byte{{
					0, 0, 5, 0x58,
				}},
			},
			err: io.ErrUnexpectedEOF,
		},
		{
			desc: "OptionsRemoteIdentifier present in dhcp6.Options map",
			options: dhcp6.Options{
				dhcp6.OptionRemoteIdentifier: [][]byte{{
					0, 0, 5, 0x58,
					0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0xa, 0xb, 0xc, 0xe, 0xf,
				}},
			},
			remoteIdentifier: &RemoteIdentifier{
				EnterpriseNumber: 1368,
				RemoteID:         []byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0xa, 0xb, 0xc, 0xe, 0xf},
			},
		},
	}
	for i, tt := range tests {
		remoteIdentifier, err := GetRemoteIdentifier(tt.options)
		if want, got := tt.err, err; want != got {
			t.Errorf("[%02d] test %q, unexpected error for dhcp6.Options.RemoteIdentifier\n- want: %v\n-  got: %v", i, tt.desc, want, got)
		}

		if tt.err != nil {
			continue
		}

		if want, got := tt.remoteIdentifier, remoteIdentifier; !reflect.DeepEqual(want, got) {
			t.Errorf("[%02d] test %q, unexpected value for dhcp6.Options.RemoteIdentifier()\n- want: %v\n-  got: %v", i, tt.desc, want, got)
		}

		if want, got := tt.err, err; want != got {
			t.Errorf("[%02d] test %q, unexpected err for dhcp6.Options.RemoteIdentifier(): %v != %v", i, tt.desc, want, got)
		}
	}
}

// TestGetBootFileURL verifies that dhcp6.Options.BootFileURL properly parses
// and returns a URL, if it is available with OptionBootFileURL.
func TestGetBootFileURL(t *testing.T) {
	var tests = []struct {
		desc    string
		options dhcp6.Options
		u       *url.URL
		err     error
	}{
		{
			desc: "OptionBootFileURL not present in dhcp6.Options map",
			err:  dhcp6.ErrOptionNotPresent,
		},
		{
			desc: "OptionBootFileURL present in dhcp6.Options map",
			options: dhcp6.Options{
				dhcp6.OptionBootFileURL: [][]byte{[]byte("tftp://192.168.1.1:69")},
			},
			u: &url.URL{
				Scheme: "tftp",
				Host:   "192.168.1.1:69",
			},
		},
	}

	for i, tt := range tests {
		u, err := GetBootFileURL(tt.options)
		if err != nil {
			if want, got := tt.err, err; want != got {
				t.Errorf("[%02d] test %q, unexpected err for dhcp6.Options.BootFileURL(): %v != %v",
					i, tt.desc, want, got)
			}
			continue
		}

		ttuu := url.URL(*tt.u)
		uu := url.URL(*u)
		if want, got := ttuu.String(), uu.String(); want != got {
			t.Errorf("[%02d] test %q, unexpected value for dhcp6.Options.BootFileURL(): %v != %v",
				i, tt.desc, want, got)
		}
	}
}

// TestGetBootFileParam verifies that dhcp6.Options.BootFileParam properly parses
// and returns boot file parameter data, if it is available with
// OptionBootFileParam.
func TestGetBootFileParam(t *testing.T) {
	var tests = []struct {
		desc    string
		options dhcp6.Options
		param   BootFileParam
		err     error
	}{
		{
			desc: "OptionBootFileParam not present in dhcp6.Options map",
			err:  dhcp6.ErrOptionNotPresent,
		},
		{
			desc: "OptionBootFileParam present in dhcp6.Options map, but empty",
			options: dhcp6.Options{
				dhcp6.OptionBootFileParam: [][]byte{{}},
			},
			err: io.ErrUnexpectedEOF,
		},
		{
			desc: "OptionBootFileParam present in dhcp6.Options map, one item, zero length",
			options: dhcp6.Options{
				dhcp6.OptionBootFileParam: [][]byte{{
					0, 0,
				}},
			},
			param: []string{""},
		},
		{
			desc: "OptionBootFileParam present in dhcp6.Options map, one item, extra byte",
			options: dhcp6.Options{
				dhcp6.OptionBootFileParam: [][]byte{{
					0, 1, 1, 255,
				}},
			},
			err: io.ErrUnexpectedEOF,
		},
		{
			desc: "OptionBootFileParam present in dhcp6.Options map, one item",
			options: dhcp6.Options{
				dhcp6.OptionBootFileParam: [][]byte{{
					0, 3, 'f', 'o', 'o',
				}},
			},
			param: []string{"foo"},
		},
		{
			desc: "OptionBootFileParam present in dhcp6.Options map, three items",
			options: dhcp6.Options{
				dhcp6.OptionBootFileParam: [][]byte{{
					0, 1, 'a',
					0, 2, 'a', 'b',
					0, 3, 'a', 'b', 'c',
				}},
			},
			param: []string{"a", "ab", "abc"},
		},
	}

	for i, tt := range tests {
		param, err := GetBootFileParam(tt.options)
		if err != nil {
			if want, got := tt.err, err; want != got {
				t.Errorf("[%02d] test %q, unexpected error for dhcp6.Options.BootFileParam: %v != %v",
					i, tt.desc, want, got)
			}
			continue
		}

		if want, got := len(tt.param), len(param); want != got {
			t.Errorf("[%02d] test %q, unexpected param slice length: %v != %v",
				i, tt.desc, want, got)

		}

		for j := range param {
			if want, got := tt.param[j], param[j]; want != got {
				t.Errorf("[%02d:%02d] test %q, unexpected value for dhcp6.Options.BootFileParam()\n- want: %v\n-  got: %v",
					i, j, tt.desc, want, got)
			}
		}
	}
}

// TestGetClientArchType verifies that dhcp6.Options.ClientArchType properly parses
// and returns client architecture type data, if it is available with
// OptionClientArchType.
func TestGetClientArchType(t *testing.T) {
	var tests = []struct {
		desc    string
		options dhcp6.Options
		arch    ArchTypes
		err     error
	}{
		{
			desc: "OptionClientArchType not present in dhcp6.Options map",
			err:  dhcp6.ErrOptionNotPresent,
		},
		{
			desc: "OptionClientArchType present in dhcp6.Options map, but empty",
			options: dhcp6.Options{
				dhcp6.OptionClientArchType: [][]byte{{}},
			},
			err: io.ErrUnexpectedEOF,
		},
		{
			desc: "OptionClientArchType present in dhcp6.Options map, but not divisible by 2",
			options: dhcp6.Options{
				dhcp6.OptionClientArchType: [][]byte{{0, 0, 0}},
			},
			err: io.ErrUnexpectedEOF,
		},
		{
			desc: "OptionClientArchType present in dhcp6.Options map, one architecture",
			options: dhcp6.Options{
				dhcp6.OptionClientArchType: [][]byte{{0, 9}},
			},
			arch: ArchTypes{ArchTypeEFIx8664},
		},
		{
			desc: "OptionClientArchType present in dhcp6.Options map, three architectures",
			options: dhcp6.Options{
				dhcp6.OptionClientArchType: [][]byte{{0, 5, 0, 9, 0, 0}},
			},
			arch: ArchTypes{
				ArchTypeIntelLeanClient,
				ArchTypeEFIx8664,
				ArchTypeIntelx86PC,
			},
		},
	}

	for i, tt := range tests {
		arch, err := GetClientArchType(tt.options)
		if err != nil {
			if want, got := tt.err, err; want != got {
				t.Errorf("[%02d] test %q, unexpected error for dhcp6.Options.ClientArchType: %v != %v",
					i, tt.desc, want, got)
			}
			continue
		}

		if want, got := len(tt.arch), len(arch); want != got {
			t.Errorf("[%02d] test %q, unexpected arch slice length: %v != %v",
				i, tt.desc, want, got)
		}

		for j := range arch {
			if want, got := tt.arch[j], arch[j]; !reflect.DeepEqual(want, got) {
				t.Errorf("[%02d:%02d] test %q, unexpected value for dhcp6.Options.ClientArchType()\n- want: %v\n-  got: %v",
					i, j, tt.desc, want, got)
			}
		}
	}
}

// TestGetNII verifies that dhcp6.Options.NII properly parses and returns a
// Network Interface Identifier value, if it is available with OptionNII.
func TestGetNII(t *testing.T) {
	var tests = []struct {
		desc    string
		options dhcp6.Options
		nii     *NII
		err     error
	}{
		{
			desc: "OptionNII not present in dhcp6.Options map",
			err:  dhcp6.ErrOptionNotPresent,
		},
		{
			desc: "OptionNII present in dhcp6.Options map, but too short length",
			options: dhcp6.Options{
				dhcp6.OptionNII: [][]byte{{1, 2}},
			},
			err: io.ErrUnexpectedEOF,
		},
		{
			desc: "OptionNII present in dhcp6.Options map, but too long length",
			options: dhcp6.Options{
				dhcp6.OptionNII: [][]byte{{1, 2, 3, 4}},
			},
			err: io.ErrUnexpectedEOF,
		},
		{
			desc: "OptionNII present in dhcp6.Options map",
			options: dhcp6.Options{
				dhcp6.OptionNII: [][]byte{{1, 2, 3}},
			},
			nii: &NII{
				Type:  1,
				Major: 2,
				Minor: 3,
			},
		},
	}

	for i, tt := range tests {
		nii, err := GetNII(tt.options)
		if err != nil {
			if want, got := tt.err, err; want != got {
				t.Errorf("[%02d] test %q, unexpected error for dhcp6.Options.NII(): %v != %v",
					i, tt.desc, want, got)
			}
			continue
		}

		if want, got := tt.nii, nii; !reflect.DeepEqual(want, got) {
			t.Errorf("[%02d] test %q, unexpected value for dhcp6.Options.NII(): %v != %v",
				i, tt.desc, want, got)
		}
	}
}

// TestGetDNSServers verifies that dhcp6opts.GetDNSServers properly parses and
// returns a list of net.IPs, if it is available with OptionDNSServers.
func TestGetDNSServers(t *testing.T) {
	var tests = []struct {
		desc    string
		options dhcp6.Options
		dns     IPs
		err     error
	}{
		{
			desc: "OptionDNSServers not present in dhcp6.Options map",
			err:  dhcp6.ErrOptionNotPresent,
		},
		{
			desc: "OptionDNSServers present in dhcp6.Options map, but too short length",
			options: dhcp6.Options{
				dhcp6.OptionDNSServers: [][]byte{{255, 255, 255}},
			},
			err: io.ErrUnexpectedEOF,
		},
		{
			desc: "OptionDNSServers present in dhcp6.Options map, but too long length",
			options: dhcp6.Options{
				dhcp6.OptionDNSServers: [][]byte{bytes.Repeat([]byte{0xff}, 17)},
			},
			err: io.ErrUnexpectedEOF,
		},
		{
			desc: "One OptionDNSServers present in dhcp6.Options map",
			options: dhcp6.Options{
				dhcp6.OptionDNSServers: [][]byte{bytes.Repeat([]byte{0xfe}, 16)},
			},
			dns: IPs{
				net.IP(bytes.Repeat([]byte{0xfe}, 16)),
			},
		},
		{
			desc: "Two OptionDNSServers present in dhcp6.Options map",
			options: dhcp6.Options{
				dhcp6.OptionDNSServers: [][]byte{append(bytes.Repeat([]byte{0xfd}, 16), bytes.Repeat([]byte{0xfc}, 16)...)},
			},
			dns: IPs{
				net.IP(bytes.Repeat([]byte{0xfd}, 16)),
				net.IP(bytes.Repeat([]byte{0xfc}, 16)),
			},
		},
	}

	for i, tt := range tests {
		dns, err := GetDNSServers(tt.options)
		if err != nil {
			if want, got := tt.err, err; want != got {
				t.Errorf("[%02d] test %q, unexpected error for GetDNSServers(dhcp6.Options): %v != %v",
					i, tt.desc, want, got)
			}
			continue
		}

		if want, got := tt.dns, dns; !reflect.DeepEqual(want, got) {
			t.Errorf("[%02d] test %q, unexpected value for GetDNSServers(dhcp6.Options): %v != %v",
				i, tt.desc, want, got)
		}
	}
}


text:
DESCRIPTION = "netifaces"
SECTION = "devel/python"
LICENSE = "MIT"
LIC_FILES_CHKSUM = "file://PKG-INFO;beginline=8;endline=8;md5=a53cbc7cb75660694e138ba973c148df"
HOMEPAGE = "http://alastairs-place.net/projects/netifaces/"
DEPENDS = "python"

SRC_URI = "http://alastairs-place.net/projects/netifaces/netifaces-0.8.tar.gz"
SRC_URI[md5sum] = "e57e5983f4c286fac5f8068fbfc5c873"
SRC_URI[sha256sum] = "53a711038db3d6e5cf7129d6f751185fd052f830f12f271fbfe17bd2671ab1ec"

inherit setuptools


text:
//go:build integ
// +build integ

// Copyright Red Hat, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package smmr

import (
	"testing"
	"time"

	"istio.io/istio/pkg/test/framework"
	"istio.io/istio/pkg/test/framework/components/istio"
	"istio.io/istio/tests/integration/servicemesh"
)

var i istio.Instance

func TestMain(m *testing.M) {
	framework.
		NewSuite(m).
		RequireSingleCluster().
		Setup(istio.Setup(&i, nil)).
		Setup(EnableMultiTenancy).
		Run()
}

func TestSMMR(t *testing.T) {
	framework.NewTest(t).
		Run(func(ctx framework.TestContext) {
			cluster := ctx.Clusters().Default()
			gatewayNamespace := servicemesh.CreateNamespace(ctx, cluster, "gateway")
			httpbinNamespace := servicemesh.CreateNamespace(ctx, cluster, "httpbin")
			sleepNamespace := servicemesh.CreateNamespace(ctx, cluster, "sleep")
			CreateServiceMeshMemberRoll(ctx, cluster, gatewayNamespace, httpbinNamespace)
			applyGateway(ctx, cluster, gatewayNamespace)
			applyVirtualService(ctx, cluster, httpbinNamespace, gatewayNamespace, "httpbin")
			applyVirtualService(ctx, cluster, sleepNamespace, gatewayNamespace, "sleep")
			time.Sleep(5 * time.Second)
			checkIfIngressHasConfiguredRouteWithVirtualHost(ctx, cluster, 1, "httpbin")
			checkIfIngressHasConfiguredRouteWithoutVirtualHost(ctx, cluster, "sleep")
			addNamespaceToServiceMeshMemberRoll(ctx, cluster, sleepNamespace)
			time.Sleep(5 * time.Second)
			checkIfIngressHasConfiguredRouteWithVirtualHost(ctx, cluster, 2, "httpbin")
			checkIfIngressHasConfiguredRouteWithVirtualHost(ctx, cluster, 2, "sleep")
		})
}

repository: bartoszmajsak/istio

repo_name: bartoszmajsak/istio

gha_language: Go


text:
@book{box2015time,
  title={Time series analysis: forecasting and control},
  author={Box, George EP and Jenkins, Gwilym M and Reinsel, Gregory C and Ljung, Greta M},
  year={2015},
  publisher={John Wiley \& Sons}
}

@inproceedings{sandgren2012moving,
  title={On moving average parameter estimation},
  author={Sandgren, Niclas and Stoica, Petre and Babu, Prabhu},
  booktitle={Signal Processing Conference (EUSIPCO), 2012 Proceedings of the 20th European},
  pages={2348--2351},
  year={2012},
  organization={IEEE}
}

@misc{baillie2017maximum,
  title={Maximum Likelihood Estimation of Time Series Models},
  author={Baillie, Richard},
  year={2017}
}

@book{gagniuc2017markov,
  title={Markov Chains: From Theory to Implementation and Experimentation},
  author={Gagniuc, Paul A},
  year={2017},
  publisher={John Wiley \& Sons}
}

@article{zhou2007novel,
  title={A novel model for photovoltaic array performance prediction},
  author={Zhou, Wei and Yang, Hongxing and Fang, Zhaohong},
  journal={Applied energy},
  volume={84},
  number={12},
  pages={1187--1198},
  year={2007},
  publisher={Elsevier}
}


text:
// Copyright 2020 ETH Zurich, Anapaya Systems
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package colibri_mgmt

import (
	"strings"

	"github.com/scionproto/scion/go/proto"
)

type Response struct {
	// TODO(juagargi)
}

type ColibriRequestPayload struct {
	Which    proto.ColibriRequestPayload_Which
	Request  *Request
	Response *Response
}

var _ proto.Cerealizable = (*ColibriRequestPayload)(nil)

func (p *ColibriRequestPayload) ProtoId() proto.ProtoIdType {
	return proto.ColibriRequestPayload_TypeID
}

func (p *ColibriRequestPayload) String() string {
	strs := make([]string, 1, 2)
	strs[0] = "ColibriRequestPayload:"
	switch p.Which {
	case proto.ColibriRequestPayload_Which_request:
		strs = append(strs, "Request")
	case proto.ColibriRequestPayload_Which_response:
		strs = append(strs, "Response")
	default:
		strs = append(strs, "Unknown subtype")
	}
	return strings.Join(strs, " ")
}

func (p *ColibriRequestPayload) PackRoot() ([]byte, error) {
	return proto.PackRoot(p)
}

func NewFromRaw(b []byte) (*ColibriRequestPayload, error) {
	pld := &ColibriRequestPayload{}
	err := proto.ParseFromRaw(pld, b)
	if err != nil {
		return nil, err
	}
	return pld, nil
}

repository: xingyang-liu/scion

repo_name: xingyang-liu/scion


text:
/*
 * Copyright 2012-2019 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package atomic

import (
	"math"
	"sync/atomic"

	"github.com/go-spring/spring-base/json"
)

// A Float32 is an atomic float32 value.
type Float32 struct {
	_ nocopy
	v uint32
}

// Add atomically adds delta to x and returns the new value.
func (x *Float32) Add(delta float32) (new float32) {
	return math.Float32frombits(atomic.AddUint32(&x.v, math.Float32bits(delta)))
}

// Load atomically loads and returns the value stored in x.
func (x *Float32) Load() (val float32) {
	return math.Float32frombits(atomic.LoadUint32(&x.v))
}

// Store atomically stores val into x.
func (x *Float32) Store(val float32) {
	atomic.StoreUint32(&x.v, math.Float32bits(val))
}

// Swap atomically stores new into x and returns the old value.
func (x *Float32) Swap(new float32) (old float32) {
	return math.Float32frombits(atomic.SwapUint32(&x.v, math.Float32bits(new)))
}

// CompareAndSwap executes the compare-and-swap operation for x.
func (x *Float32) CompareAndSwap(old, new float32) (swapped bool) {
	return atomic.CompareAndSwapUint32(&x.v, math.Float32bits(old), math.Float32bits(new))
}

// MarshalJSON returns the JSON encoding of x.
func (x *Float32) MarshalJSON() ([]byte, error) {
	return json.Marshal(x.Load())
}

repository: go-spring/go-spring

repo_name: go-spring/go-spring