text stringlengths 11 4.05M |
|---|
package views
import (
"fmt"
"strings"
"github.com/jenkins-x/jx-logging/v3/pkg/log"
v1 "github.com/jenkins-x/jx-api/v4/pkg/apis/jenkins.io/v1"
"github.com/jenkins-x/octant-jx/pkg/common/viewhelpers"
"github.com/jenkins-x/octant-jx/pkg/plugin"
"github.com/vmware-tanzu/octant/pkg/view/component"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
)
const (
indentation = " "
)
type PipelineStepRenderer struct {
Writer strings.Builder
PipelineActivity *v1.PipelineActivity
Pod *unstructured.Unstructured
}
// ToStepsView renders a markdown description of the pipeline
func ToStepsView(pa *v1.PipelineActivity, pod *unstructured.Unstructured) *component.Text {
r := &PipelineStepRenderer{
PipelineActivity: pa,
Pod: pod,
}
w := &r.Writer
if pa != nil {
steps := pa.Spec.Steps
for k := range steps {
if addStepRow(r, &steps[k], "") {
break
}
}
}
text := w.String()
return viewhelpers.NewMarkdownText(text)
}
func addStepRow(w *PipelineStepRenderer, parent *v1.PipelineActivityStep, indent string) bool {
stage := parent.Stage
preview := parent.Preview
promote := parent.Promote
pending := false
if stage != nil {
if addStageRow(w, stage, indent) {
pending = true
}
} else if preview != nil {
if addPreviewRow(w, stage, preview, indent) {
pending = true
}
} else if promote != nil {
if addPromoteRow(w, stage, promote, indent) {
pending = true
}
} else {
log.Logger().Infof("Unknown step kind %#v", parent)
}
return pending
}
func addStageRow(w *PipelineStepRenderer, stage *v1.StageActivityStep, indent string) bool {
name := "Stage"
if stage.Name != "" {
name = ""
}
pending := addStepRowItem(w, stage, &stage.CoreActivityStep, indent, name, "")
indent += indentation
steps := stage.Steps
for k := range steps {
if addStepRowItem(w, stage, &steps[k], indent, "", "") {
pending = true
break
}
}
return pending
}
func addPreviewRow(w *PipelineStepRenderer, stage *v1.StageActivityStep, parent *v1.PreviewActivityStep, indent string) bool {
pullRequestURL := parent.PullRequestURL
if pullRequestURL == "" {
pullRequestURL = parent.Environment
}
pending := addStepRowItem(w, stage, &parent.CoreActivityStep, indent, "Preview", colorInfo(pullRequestURL))
indent += indentation
appURL := parent.ApplicationURL
if appURL != "" {
if addStepRowItem(w, stage, &parent.CoreActivityStep, indent, "Preview Application", colorInfo(appURL)) {
pending = true
}
}
return pending
}
func addPromoteRow(w *PipelineStepRenderer, stage *v1.StageActivityStep, parent *v1.PromoteActivityStep, indent string) bool {
pending := addStepRowItem(w, stage, &parent.CoreActivityStep, indent, "Promote: "+parent.Environment, "")
indent += indentation
pullRequest := parent.PullRequest
update := parent.Update
if pullRequest != nil {
if addStepRowItem(w, stage, &pullRequest.CoreActivityStep, indent, "PullRequest", describePromotePullRequest(pullRequest)) {
pending = true
}
}
if update != nil {
if addStepRowItem(w, stage, &update.CoreActivityStep, indent, "Update", describePromoteUpdate(update)) {
pending = true
}
}
appURL := parent.ApplicationURL
if appURL != "" {
if addStepRowItem(w, stage, &update.CoreActivityStep, indent, "Promoted", " Application is at: "+colorInfo(appURL)) {
pending = true
}
}
return pending
}
func addStepRowItem(w *PipelineStepRenderer, stage *v1.StageActivityStep, step *v1.CoreActivityStep, indent, name, description string) bool {
textName := step.Name
if textName == "" {
textName = name
} else if name != "" {
textName = name + ":" + textName
}
icon := ToPipelineStatusMarkup(step.Status)
status := ""
durationText := durationMarkup(step.StartedTimestamp, step.CompletedTimestamp)
if durationText != "" {
status = " : " + durationText
}
podName := ""
if w.Pod != nil {
podName = w.Pod.GetName()
}
containerName := FindContainerName(step, w.Pod)
if containerName != "" {
paName := w.PipelineActivity.Name
ns := w.PipelineActivity.Namespace
if podName != "" {
status += fmt.Sprintf(` <a href="%s" title="View Step details"><clr-icon shape="details"></clr-icon></a>`, plugin.GetPipelineContainerLink(ns, paName, podName, containerName))
}
w.Writer.WriteString(fmt.Sprintf("%s* %s [%s](%s) %s\n", indent, icon, textName, plugin.GetPipelineContainerLogLink(paName, containerName), status))
} else {
log.Logger().Infof("failed to find container name for step %s and pod %s", step.Name, podName)
w.Writer.WriteString(fmt.Sprintf("%s* %s %s %s\n", indent, icon, textName, status))
}
return step.Status == v1.ActivityStatusTypePending
}
func durationMarkup(start, end *metav1.Time) string {
if start == nil || end == nil {
return ""
}
return end.Sub(start.Time).String()
}
func FindContainerName(step *v1.CoreActivityStep, u *unstructured.Unstructured) string {
if u != nil && step != nil {
pod, err := viewhelpers.ToPod(u)
if err != nil {
log.Logger().Info(fmt.Sprintf("failed to convert to Pod: %s", err.Error()))
return ""
}
names := []string{step.Name}
return FindContainerNameForStepName(pod, names)
}
return ""
}
func FindContainerNameForStepName(pod *corev1.Pod, pipelineActivityStepNames []string) string {
name := "step-" + strings.ToLower(strings.Join(pipelineActivityStepNames, "-"))
name = strings.ReplaceAll(name, " ", "-")
name2 := "step-" + name
containers := pod.Spec.Containers
for k := range containers {
c := containers[k]
if c.Name == name || c.Name == name2 {
return c.Name
}
}
return ""
}
func ToPipelineStatus(pa *v1.PipelineActivity) component.Component {
if pa == nil || pa.Spec.Status == v1.ActivityStatusTypeNone {
return component.NewText("")
}
return viewhelpers.NewMarkdownText(ToPipelineStatusMarkup(pa.Spec.Status))
}
func ToPipelineStatusMarkup(statusType v1.ActivityStatusType) string {
text := statusType.String()
switch statusType {
case v1.ActivityStatusTypeFailed, v1.ActivityStatusTypeError:
return `<clr-icon shape="warning-standard" class="is-solid is-danger" title="Failed"></clr-icon>`
case v1.ActivityStatusTypeSucceeded:
return `<clr-icon shape="check-circle" class="is-solid is-success" title="Succeeded"></clr-icon>`
case v1.ActivityStatusTypePending:
return `<clr-icon shape="clock" title="Pending"></clr-icon>`
case v1.ActivityStatusTypeRunning:
return `<span class="spinner spinner-inline" title="Running"></span>`
}
return text
}
func describePromotePullRequest(promote *v1.PromotePullRequestStep) string {
description := ""
if promote.PullRequestURL != "" {
description += " PullRequest: " + colorInfo(promote.PullRequestURL)
}
if promote.MergeCommitSHA != "" {
description += " Merge SHA: " + colorInfo(promote.MergeCommitSHA)
}
return description
}
func describePromoteUpdate(promote *v1.PromoteUpdateStep) string {
description := ""
for _, status := range promote.Statuses {
url := status.URL
state := status.Status
if url != "" && state != "" {
description += " Status: " + pullRequestStatusString(state) + " at: " + colorInfo(url)
}
}
return description
}
func colorInfo(text string) string {
return text
}
func colorError(text string) string {
return text
}
func pullRequestStatusString(text string) string {
title := strings.Title(text)
switch text {
case "success":
return colorInfo(title)
case "error", "failed":
return colorError(title)
default:
return text
}
}
|
// Copyright 2020 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Package fileutil provides utilities for operating files in remote wifi tests.
package fileutil
import (
"context"
"os"
"path"
"strings"
"chromiumos/tast/errors"
"chromiumos/tast/ssh"
"chromiumos/tast/ssh/linuxssh"
"chromiumos/tast/testing"
)
// WriteTmp writes the content to a temp file created by "mktemp $pattern" on host.
func WriteTmp(ctx context.Context, host *ssh.Conn, pattern string, content []byte) (string, error) {
out, err := host.CommandContext(ctx, "mktemp", pattern).Output()
if err != nil {
return "", errors.Wrap(err, "failed to create temp file on host")
}
filepath := strings.TrimSpace(string(out))
if err := linuxssh.WriteFile(ctx, host, filepath, content, 0644); err != nil {
return "", err
}
return filepath, nil
}
// PrepareOutDirFile prepares the base directory of the path under OutDir and opens the file.
func PrepareOutDirFile(ctx context.Context, filename string) (*os.File, error) {
outdir, ok := testing.ContextOutDir(ctx)
if !ok {
return nil, errors.New("failed to get OutDir")
}
filepath := path.Join(outdir, filename)
if err := os.MkdirAll(path.Dir(filepath), 0755); err != nil {
return nil, errors.Wrapf(err, "failed to create basedir for %q", filepath)
}
f, err := os.OpenFile(filepath, os.O_WRONLY|os.O_CREATE, 0644)
if err != nil {
return nil, errors.Wrapf(err, "cannot open file %q", filepath)
}
return f, nil
}
|
package uisession
import (
"context"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/types"
"sigs.k8s.io/controller-runtime/pkg/cache"
ctrlclient "sigs.k8s.io/controller-runtime/pkg/client"
"github.com/tilt-dev/tilt/internal/controllers/apicmp"
"github.com/tilt-dev/tilt/internal/hud/webview"
"github.com/tilt-dev/tilt/internal/store"
"github.com/tilt-dev/tilt/pkg/apis/core/v1alpha1"
)
type Subscriber struct {
client ctrlclient.Client
}
func NewSubscriber(client ctrlclient.Client) *Subscriber {
return &Subscriber{client: client}
}
func (s *Subscriber) OnChange(ctx context.Context, st store.RStore, summary store.ChangeSummary) error {
if summary.IsLogOnly() {
return nil
}
state := st.RLockState()
session := webview.ToUISession(state)
st.RUnlockState()
stored := &v1alpha1.UISession{}
err := s.client.Get(ctx, types.NamespacedName{Name: session.Name}, stored)
if apierrors.IsNotFound(err) {
// If nothing is stored, create it.
err := s.client.Create(ctx, session)
if err != nil {
return err
}
return nil
} else if err != nil {
// If the cache hasn't started yet, that's OK.
// We'll get it on the next OnChange()
if _, ok := err.(*cache.ErrCacheNotStarted); ok {
return nil
}
return err
}
if !apicmp.DeepEqual(session.Status, stored.Status) {
// If the current version is different than what's stored, update it.
update := &v1alpha1.UISession{
ObjectMeta: *stored.ObjectMeta.DeepCopy(),
Spec: *stored.Spec.DeepCopy(),
Status: *session.Status.DeepCopy(),
}
err = s.client.Status().Update(ctx, update)
if err != nil {
return err
}
}
return nil
}
var _ store.Subscriber = &Subscriber{}
|
package main
import (
"fmt"
"log"
"net/http"
"runtime"
"time"
)
// 这是一个recommend server
// Recommendation Service
func main() {
logGoroutines()
http.HandleFunc("/recommendations", recoHandler)
log.Fatal(http.ListenAndServe(":9090", nil))
}
func logGoroutines() {
ticker := time.NewTicker(500 * time.Millisecond)
done := make(chan bool)
go func() {
for {
select {
case <-done:
return
case t := <-ticker.C:
fmt.Printf("\n%v - %v", t, runtime.NumGoroutine())
}
}
}()
}
func recoHandler(w http.ResponseWriter, r *http.Request) {
a := `{"movies": ["Few Angry Men", "Pride & Prejudice"]}`
w.Write([]byte(a))
}
|
package v3
import (
"bytes"
"fmt"
"sort"
"go/constant"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
"github.com/cockroachdb/cockroach/pkg/sql/sem/types"
"github.com/gogo/protobuf/sortkeys"
)
type bucket struct {
// The number of values in the bucket equal to upperBound.
numEq int64
// The number of values in the bucket, excluding those that are
// equal to upperBound.
numRange int64
// The upper boundary of the bucket. The column values for the upper bound
// are encoded using the ascending key encoding.
upperBound tree.Datum
}
// A histogram struct stores statistics for a table column, as well as
// buckets representing the distribution of non-NULL values.
//
// The statistics calculated on the base table will be 100% accurate
// at the time of collection (except for distinctCount, which is an estimate).
// Statistics become stale quickly, however, if the table is updated
// frequently. This struct does not currently include any estimate of
// the error due to staleness.
//
// For histograms representing intermediate states in the query tree,
// there is an additional source of error due to lack of information
// about the distribution of values within each histogram bucket at
// the base of the query tree. For example, when a bucket is split,
// we calculate the size of the new buckets by assuming that values are
// uniformly distributed across the original bucket. The histogram struct does
// not currently include any estimate of the error due to data distribution
// within buckets.
type histogram struct {
// The total number of rows in the table.
rowCount int64
// The estimated cardinality (distinct values) for the column.
distinctCount int64
// The number of NULL values for the column.
nullCount int64
// The histogram buckets which describe the distribution of non-NULL
// values. The buckets are sorted by bucket.upperBound.
// The first bucket must have numRange = 0, so the upperBound
// of the bucket indicates the lower bound of the histogram.
buckets []bucket
}
func (h *histogram) String() string {
var buf bytes.Buffer
fmt.Fprintf(&buf, "rows: %d\n", h.rowCount)
fmt.Fprintf(&buf, "distinct: %d\n", h.distinctCount)
fmt.Fprintf(&buf, "nulls: %d\n", h.nullCount)
fmt.Fprintf(&buf, "buckets: ")
if len(h.buckets) == 0 {
fmt.Fprintf(&buf, " none")
}
for _, b := range h.buckets {
fmt.Fprintf(&buf, " %s:%d,%d", b.upperBound, b.numRange, b.numEq)
}
buf.WriteString("\n")
return buf.String()
}
// Create a histogram from an INSERT clause. The rows are expected to be a
// VALUES clause containing pairs of (upper-bound, count). Currently only INT
// or NULL constants are valid for upper-bound, and only INT constants are
// valid for count.
//
// Row, distinct and null counts can be specified by using the strings 'rows',
// 'distinct' and 'nulls' respectively for the upper-bound. For example:
//
// VALUES ('rows', 1000), ('distinct', 100), ('nulls', 10)
//
// This creates a histogram with rowCount=1000, distinctCount=100, nullCount=10
// and no buckets.
func createHistogram(
catalog map[tableName]*table,
tblName tableName, colName columnName,
rows *tree.Select,
) *histogram {
values, ok := rows.Select.(*tree.ValuesClause)
if !ok {
fatalf("unsupported rows: %s", rows)
}
tab, ok := catalog[tblName]
if !ok {
fatalf("unable to find table %s", tblName)
}
colIdx, ok := tab.colMap[colName]
if !ok {
fatalf("unable to find %s.%s", tblName, colName)
}
col := &tab.columns[colIdx]
col.hist = &histogram{}
for _, v := range values.Tuples {
if len(v.Exprs) != 2 && len(v.Exprs) != 3 {
fatalf("malformed histogram bucket: %s", v)
}
val, err := v.Exprs[1].(*tree.NumVal).AsInt64()
if err != nil {
fatalf("malformed histogram bucket: %s: %v", v, err)
}
switch t := v.Exprs[0].(type) {
case *tree.NumVal:
upperBound, err := t.ResolveAsType(nil, types.Int)
if err != nil {
fatalf("malformed histogram bucket: %s: %v", v, err)
}
// Buckets have 3 values.
if len(v.Exprs) != 3 {
fatalf("malformed histogram bucket: %s", v)
}
numEq, err := v.Exprs[2].(*tree.NumVal).AsInt64()
if err != nil {
fatalf("malformed histogram bucket: %s: %v", v, err)
}
col.hist.buckets = append(col.hist.buckets, bucket{
numEq: numEq,
numRange: val,
upperBound: upperBound,
})
case *tree.StrVal:
switch t.RawString() {
case "rows":
col.hist.rowCount = val
case "distinct":
col.hist.distinctCount = val
case "nulls":
col.hist.nullCount = val
}
default:
unimplemented("histogram bucket: %T", v.Exprs[0])
}
}
sort.Slice(col.hist.buckets, func(i, j int) bool {
bi := &col.hist.buckets[i]
bj := &col.hist.buckets[j]
return bi.upperBound.Compare(nil, bj.upperBound) < 0
})
checkBucketsValid(col.hist.buckets)
return col.hist
}
// filterHistogram filters a histogram based on the WHERE clause in the given select
// statement, and returns the histogram. It expects a statement of the form:
// SELECT * from histogram.table.column WHERE ...
func filterHistogram(catalog map[tableName]*table, stmt *tree.Select) *histogram {
sel, ok := stmt.Select.(*tree.SelectClause)
if !ok {
unimplemented("%s", stmt)
}
// Get the histogram name.
name, ok := sel.From.Tables[0].(*tree.AliasedTableExpr).Expr.(*tree.NormalizableTableName)
if !ok {
unimplemented("%s", stmt)
}
tname, err := name.Normalize()
if err != nil {
fatalf("unable to normalize: %v", err)
}
if tname.PrefixName != "histogram" {
unimplemented("%s", stmt)
}
// Get the histogram from the catalog.
tblName, colName := tableName(tname.DatabaseName), columnName(tname.TableName)
tab, ok := catalog[tblName]
if !ok {
fatalf("unable to find table %s", tblName)
}
colIdx, ok := tab.colMap[colName]
if !ok {
fatalf("unable to find %s.%s", tblName, colName)
}
hist := tab.columns[colIdx].hist
// Filter the histogram.
return hist.filterHistogram(sel.Where.Expr)
}
func (h *histogram) filterHistogram(expr tree.Expr) *histogram {
switch e := expr.(type) {
case *tree.ComparisonExpr:
op := comparisonOpMap[e.Operator]
var val int64
var vals []int64
var err error
switch v := e.Right.(type) {
case *tree.NumVal:
val, err = v.AsInt64()
if err != nil {
fatalf("unable to cast datum to int64: %v", err)
}
vals = []int64{val}
case *tree.Tuple:
for _, elem := range v.Exprs {
numVal, ok := elem.(*tree.NumVal)
if !ok {
unimplemented("%s", expr)
}
val, err = numVal.AsInt64()
if err != nil {
fatalf("unable to cast datum to int64: %v", err)
}
vals = append(vals, val)
}
default:
unimplemented("%T", v)
}
switch op {
case ltOp, leOp:
return h.filterHistogramLtOpLeOp(op, val)
case gtOp, geOp:
return h.filterHistogramGtOpGeOp(op, val)
case eqOp, inOp:
return h.filterHistogramEqOpInOp(vals)
case neOp, notInOp:
return h.filterHistogramNeOpNotInOp(vals)
default:
unimplemented("%s", expr)
}
case *tree.AndExpr:
left := h.filterHistogram(e.Left)
right := h.filterHistogram(e.Right)
return left.andHistograms(right)
case *tree.OrExpr:
left := h.filterHistogram(e.Left)
right := h.filterHistogram(e.Right)
return left.orHistograms(right)
default:
unimplemented("%s", expr)
}
return nil
}
func makeDatum(val int64) tree.Datum {
v := &tree.NumVal{Value: constant.MakeInt64(val)}
datum, err := v.ResolveAsType(nil, types.Int)
if err != nil {
fatalf("could not create Datum: %s: %v", v, err)
}
return datum
}
func newBucket(upperBound, numRange, numEq int64) bucket {
return bucket{
numEq: numEq,
numRange: numRange,
upperBound: makeDatum(upperBound),
}
}
// splitBucket splits a bucket into two buckets at the given split point.
// The lower bucket contains the values less than or equal to splitPoint, and the
// upper bucket contains the values greater than splitPoint. The count of values
// in numRange is split between the two buckets assuming a uniform distribution.
//
// lowerBound is an exclusive lower bound on the bucket (it's equal to one less
// than the minimum value).
func (b bucket) splitBucket(splitPoint, lowerBound int64) (bucket, bucket) {
upperBound := (int64)(*b.upperBound.(*tree.DInt))
// The bucket size calculation has a -1 because numRange does not
// include values equal to upperBound.
bucketSize := upperBound - lowerBound - 1
if bucketSize <= 0 {
panic("empty bucket should have been skipped")
}
if splitPoint >= upperBound || splitPoint <= lowerBound {
panic(fmt.Sprintf("splitPoint (%d) must be between upperBound (%d) and lowerBound (%d)",
splitPoint, upperBound, lowerBound))
}
// Make the lower bucket.
lowerMatchSize := splitPoint - lowerBound - 1
lowerNumRange := (int64)(float64(b.numRange) * float64(lowerMatchSize) / float64(bucketSize))
lowerNumEq := (int64)(float64(b.numRange) / float64(bucketSize))
bucLower := newBucket(splitPoint, lowerNumRange, lowerNumEq)
// Make the upper bucket.
upperMatchSize := upperBound - splitPoint - 1
bucUpper := b
bucUpper.numRange = (int64)(float64(b.numRange) * float64(upperMatchSize) / float64(bucketSize))
return bucLower, bucUpper
}
// checkBucketsValid checks that the given buckets
// are valid histogram buckets, and panics if they are not valid.
func checkBucketsValid(buckets []bucket) {
if len(buckets) == 0 {
return
}
if buckets[0].numRange != 0 {
panic("First bucket must have numRange = 0")
}
prev := buckets[0].upperBound
for i := 1; i < len(buckets); i++ {
cur := buckets[i].upperBound
if prev.Compare(nil /* ctx */, cur) >= 0 {
panic("Buckets must be disjoint and ordered by upperBound")
}
prev = cur
}
}
// getLowerBound gets the exclusive lower bound on the
// histogram. i.e., it returns one less than the minimum value
// in the histogram.
//
// It panics if the histogram is empty or if numRange is not
// zero in the first bucket.
func (h *histogram) getLowerBound() int64 {
if len(h.buckets) == 0 {
panic("Called getLowerBound on empty histogram")
}
if h.buckets[0].numRange != 0 {
panic("First bucket must have numRange = 0")
}
return (int64)(*h.buckets[0].upperBound.(*tree.DInt)) - 1
}
// getUpperBound gets the inclusive upper bound on the
// histogram. i.e., it returns the maximum value
// in the histogram.
//
// It panics if the histogram is empty.
func (h *histogram) getUpperBound() int64 {
if len(h.buckets) == 0 {
panic("Called getUpperBound on empty histogram")
}
return (int64)(*h.buckets[len(h.buckets)-1].upperBound.(*tree.DInt))
}
// newHistogram creates a new histogram given new buckets which represent
// a filtered version of the existing histogram h.
func (h *histogram) newHistogram(newBuckets []bucket) *histogram {
checkBucketsValid(newBuckets)
total := int64(0)
for _, b := range newBuckets {
total += b.numEq + b.numRange
}
if total == 0 {
return &histogram{}
}
selectivity := float64(total) / float64(h.rowCount)
// Estimate the new distinctCount based on the selectivity of this filter.
// todo(rytaft): this could be more precise if we take into account the
// null count of the original histogram.
distinctCount := int64(float64(h.distinctCount) * selectivity)
if distinctCount == 0 {
// There must be at least one distinct value since rowCount > 0.
distinctCount++
}
return &histogram{
rowCount: total,
distinctCount: distinctCount,
// All the returned rows will be non-null for this column.
nullCount: 0,
buckets: newBuckets,
}
}
// filterHistogramLtOpLeOp applies a filter to the histogram that compares
// the histogram column value to a constant value with a ltOp or leOp (e.g., x < 4).
// Returns an updated histogram including only the values that satisfy the predicate.
//
// Currently only works for integer valued columns. This will need to be altered
// for floating point columns and other types.
func (h *histogram) filterHistogramLtOpLeOp(op operator, val int64) *histogram {
if op != ltOp && op != leOp {
panic("filterHistogramLtOpLeOp called with operator " + op.String())
}
if len(h.buckets) == 0 {
return h
}
lowerBound := h.getLowerBound()
var newBuckets []bucket
for _, b := range h.buckets {
if val <= lowerBound {
break
}
upperBound := (int64)(*b.upperBound.(*tree.DInt))
if val <= upperBound {
var buc bucket
if val < upperBound {
buc, _ = b.splitBucket(val, lowerBound)
} else {
buc = b
}
if op == ltOp {
buc.numEq = 0
}
newBuckets = append(newBuckets, buc)
break
}
newBuckets = append(newBuckets, b)
lowerBound = upperBound
}
return h.newHistogram(newBuckets)
}
// filterHistogramGtOpGeOp applies a filter to the histogram that compares
// the histogram column value to a constant value with a gtOp or geOp (e.g., x > 4).
// Returns an updated histogram including only the values that satisfy the predicate.
//
// Currently only works for integer valued columns. This will need to be altered
// for floating point columns and other types.
func (h *histogram) filterHistogramGtOpGeOp(op operator, val int64) *histogram {
if op != gtOp && op != geOp {
panic("filterHistogramGtOpGeOp called with operator " + op.String())
}
if len(h.buckets) == 0 {
return h
}
upperBound := h.getUpperBound()
var newBuckets []bucket
newLowerBound := val
if op == geOp {
newLowerBound -= 1
}
// Iterate backwards through the buckets to avoid scanning buckets
// that don't satisfy the predicate.
for i := len(h.buckets) - 1; i >= 0; i-- {
b := h.buckets[i]
if val >= upperBound {
if val == upperBound && op == geOp {
buc := b
buc.numRange = 0
newBuckets = append(newBuckets, buc)
}
break
}
var lowerBound int64
if i == 0 {
lowerBound = upperBound - 1
} else {
lowerBound = (int64)(*h.buckets[i-1].upperBound.(*tree.DInt))
}
if val > lowerBound {
_, buc := b.splitBucket(newLowerBound, lowerBound)
newBuckets = append(newBuckets, buc)
break
}
newBuckets = append(newBuckets, b)
upperBound = lowerBound
}
// Add a dummy bucket for the lower bound if needed.
if len(newBuckets) > 0 && newBuckets[len(newBuckets)-1].numRange != 0 {
buc := newBucket(newLowerBound, 0 /* numRange */, 0 /* numEq */)
newBuckets = append(newBuckets, buc)
}
// Reverse the buckets so they are sorted in ascending order.
for i, j := 0, len(newBuckets)-1; i < j; i, j = i+1, j-1 {
newBuckets[i], newBuckets[j] = newBuckets[j], newBuckets[i]
}
return h.newHistogram(newBuckets)
}
// filterHistogramEqOpInOp applies a filter to the histogram that compares
// the histogram column value to a constant value or set of values with an
// eqOp (e.g., x == 4) or an inOp (e.g., x in (4, 5, 6)).
// Returns an updated histogram including only the values that satisfy the predicate.
//
// Currently only works for integer valued columns. This will need to be altered
// for floating point columns and other types.
func (h *histogram) filterHistogramEqOpInOp(vals []int64) *histogram {
if len(vals) == 0 {
return &histogram{}
}
if len(h.buckets) == 0 {
return h
}
sortkeys.Int64s(vals)
valIdx := 0
lowerBound := h.getLowerBound()
var newBuckets []bucket
for _, b := range h.buckets {
if valIdx >= len(vals) {
break
}
for valIdx < len(vals) && vals[valIdx] <= lowerBound {
valIdx++
}
upperBound := (int64)(*b.upperBound.(*tree.DInt))
bucketSize := upperBound - lowerBound - 1
for valIdx < len(vals) && vals[valIdx] < upperBound && bucketSize > 0 {
// Assuming a uniform distribution.
numEq := (int64)(float64(b.numRange) / float64(bucketSize))
buc := newBucket(vals[valIdx], 0 /* numRange */, numEq)
newBuckets = append(newBuckets, buc)
valIdx++
}
for valIdx < len(vals) && vals[valIdx] == upperBound {
buc := b
buc.numRange = 0
newBuckets = append(newBuckets, buc)
valIdx++
}
lowerBound = upperBound
}
hist := h.newHistogram(newBuckets)
// The distinct count cannot be more than the number of values in vals.
if hist.distinctCount > int64(len(vals)) {
hist.distinctCount = int64(len(vals))
}
return hist
}
// filterHistogramNeOpNotInOp applies a filter to the histogram that compares
// the histogram column value to a constant value or set of values with a
// neOp (e.g., x != 4) or notInOp (e.g., x not in (4, 5, 6)).
// Returns an updated histogram including only the values that satisfy the predicate.
//
// Currently only works for integer valued columns. This will need to be altered
// for floating point columns and other types.
func (h *histogram) filterHistogramNeOpNotInOp(vals []int64) *histogram {
if len(vals) == 0 || len(h.buckets) == 0 {
return h
}
sortkeys.Int64s(vals)
valIdx := 0
lowerBound := h.getLowerBound()
var newBuckets []bucket
for _, b := range h.buckets {
for valIdx < len(vals) && vals[valIdx] <= lowerBound {
valIdx++
}
buc := b
upperBound := (int64)(*b.upperBound.(*tree.DInt))
for valIdx < len(vals) && vals[valIdx] > lowerBound && vals[valIdx] < upperBound {
var bucLower bucket
// Upper bucket will either be split again or added once this inner
// loop terminates.
bucLower, buc = buc.splitBucket(vals[valIdx], lowerBound)
bucLower.numEq = 0
newBuckets = append(newBuckets, bucLower)
lowerBound = vals[valIdx]
valIdx++
}
for valIdx < len(vals) && vals[valIdx] == upperBound {
buc.numEq = 0
valIdx++
}
newBuckets = append(newBuckets, buc)
lowerBound = upperBound
}
hist := h.newHistogram(newBuckets)
// The distinct count cannot have decreased by more than the number of values in vals.
if hist.distinctCount < h.distinctCount - int64(len(vals)) {
hist.distinctCount = h.distinctCount - int64(len(vals))
}
return hist
}
func max(x, y int64) int64 {
if x > y {
return x
}
return y
}
func min(x, y int64) int64 {
if x < y {
return x
}
return y
}
// histogramIter is an iterator for stepping through the buckets
// in a histogram. It holds useful metadata including the upper and lower
// bounds of the current histogram bucket.
type histogramIter struct {
h *histogram
// Current histogram bucket.
b bucket
// Current histogram bucket index.
idx int
// Upper bound of the current bucket.
ub int64
// Lower bound of the current bucket.
lb int64
done bool
}
// newHistogramIter returns a new histogramIter for histogram
// h, initialized at the first bucket.
func newHistogramIter(h *histogram) *histogramIter {
if len(h.buckets) == 0 {
return &histogramIter{done: true}
}
buc := h.buckets[0]
return &histogramIter{
h: h,
idx: 0,
b: buc,
lb: h.getLowerBound(),
ub: (int64)(*buc.upperBound.(*tree.DInt)),
done: false,
}
}
// next causes w to move to the next histogram bucket if there are any
// remaining buckets. Otherwise, it sets w.done = true.
func (w *histogramIter) next() {
if w.done {
return
}
if w.idx+1 >= len(w.h.buckets) {
w.done = true
return
}
w.idx++
w.b = w.h.buckets[w.idx]
w.lb = w.ub
w.ub = (int64)(*w.b.upperBound.(*tree.DInt))
}
// getOverlappingBuckets finds the overlapping buckets of the histogramIters
// w and other, merges them using the provided mergeBuckets function, and
// returns the merged buckets. Buckets may only be merged if they have the same
// upper and lower bound, so some of the overlapping buckets may need to be
// split.
//
// For example, consider the following two sets of buckets:
// |____|_______|___|______|__|
// |___|_____|______|__|
//
// The merged buckets will have the following form:
// |___||____|__|___|__|
//
// The function assumes that both histogramIters initially point to buckets
// which have the same lower bound.
func (w *histogramIter) getOverlappingBuckets(
other *histogramIter,
mergeBuckets func(bucket, bucket, int64) bucket,
) []bucket {
var buckets []bucket
splitAndMergeBuckets := func(wA, wB *histogramIter) {
var newBuc bucket
newBuc, wA.b = wA.b.splitBucket(wB.ub, wA.lb)
newBuc = mergeBuckets(newBuc, wB.b, wB.ub)
buckets = append(buckets, newBuc)
wA.lb = wB.ub
wB.next()
}
for !w.done && !other.done {
if other.ub < w.ub {
splitAndMergeBuckets(w, other)
} else if w.ub < other.ub {
splitAndMergeBuckets(other, w)
} else { // wThis.ub == wOther.ub
newBuc := mergeBuckets(w.b, other.b, w.ub)
buckets = append(buckets, newBuc)
w.next()
other.next()
}
}
return buckets
}
// orHistograms combines two histograms using an orOp (e.g., x < 3 OR x > 5).
// Returns an updated histogram including all the values that satisfy the predicate.
//
// Currently only works for integer valued columns. This will need to be altered
// for floating point columns and other types.
func (h *histogram) orHistograms(other *histogram) *histogram {
var buckets []bucket
wThis := newHistogramIter(h)
wOther := newHistogramIter(other)
// If one histogram has lower buckets than the other, add those buckets first.
addLeadingBuckets := func(wA, wB *histogramIter) {
for wA.lb < wB.lb && !wA.done {
if wB.lb < wA.ub {
var newBuc bucket
newBuc, wA.b = wA.b.splitBucket(wB.lb, wA.lb)
buckets = append(buckets, newBuc)
wA.lb = wB.lb
} else {
buckets = append(buckets, wA.b)
wA.next()
}
}
}
addLeadingBuckets(wThis, wOther)
addLeadingBuckets(wOther, wThis)
// Add the buckets from the two histograms that overlap each other.
mergeBuckets := func(bucA, bucB bucket, upperBound int64) bucket {
// When merging buckets, we take the maximum of the two bucket counts
// for the OR operator.
return newBucket(upperBound, max(bucA.numRange, bucB.numRange), max(bucA.numEq, bucB.numEq))
}
buckets = append(buckets, wThis.getOverlappingBuckets(wOther, mergeBuckets) ...)
// Add any remaining non-overlapping buckets.
addTrailingBuckets := func(w *histogramIter) {
for !w.done {
buckets = append(buckets, w.b)
w.next()
}
}
addTrailingBuckets(wThis)
addTrailingBuckets(wOther)
hist := h.newHistogram(buckets)
// Calculate the distinct count. If the original two histograms are
// completely disjoint, the combined distinct count is equal to the sum
// of the original distinct counts. Otherwise, the distinct count is
// scaled by the amount of overlap.
selectivity := float64(hist.rowCount) / float64(h.rowCount+other.rowCount)
hist.distinctCount = int64(float64(h.distinctCount+other.distinctCount) * selectivity)
if hist.distinctCount == 0 && hist.rowCount > 0 {
// There must be at least one distinct value since rowCount > 0.
hist.distinctCount++
}
return hist
}
// andHistograms combines two histograms using an andOp (e.g., x > 3 AND x < 5).
// Returns an updated histogram including all the values that satisfy the predicate.
//
// Currently only works for integer valued columns. This will need to be altered
// for floating point columns and other types.
func (h *histogram) andHistograms(other *histogram) *histogram {
var buckets []bucket
wThis := newHistogramIter(h)
wOther := newHistogramIter(other)
// If one histogram has lower buckets than the other, skip those buckets.
skipLeadingBuckets := func(wA, wB *histogramIter) {
for wA.lb < wB.lb && !wA.done {
if wB.lb < wA.ub {
_, wA.b = wA.b.splitBucket(wB.lb, wA.lb)
wA.lb = wB.lb
} else {
wA.next()
}
}
}
skipLeadingBuckets(wThis, wOther)
skipLeadingBuckets(wOther, wThis)
// Add the buckets from the two histograms that overlap each other.
mergeBuckets := func(bucA, bucB bucket, upperBound int64) bucket {
// When merging buckets, we take the minimum of the two bucket counts
// for the AND operator.
return newBucket(upperBound, min(bucA.numRange, bucB.numRange), min(bucA.numEq, bucB.numEq))
}
buckets = append(buckets, wThis.getOverlappingBuckets(wOther, mergeBuckets) ...)
hist := h.newHistogram(buckets)
// Calculate the distinct count. If one of the original histograms
// completely contains the other, the combined distinct count is equal to
// the minimum of the original distinct counts. Otherwise, the distinct
// count is scaled by the amount of overlap.
selectivity := float64(hist.rowCount) / float64(min(h.rowCount, other.rowCount))
hist.distinctCount = int64(float64(min(h.distinctCount, other.distinctCount)) * selectivity)
if hist.distinctCount == 0 && hist.rowCount > 0 {
// There must be at least one distinct value since rowCount > 0.
hist.distinctCount++
}
return hist
}
|
package parser_test
import (
"github.com/bytesparadise/libasciidoc/pkg/types"
. "github.com/bytesparadise/libasciidoc/testsupport"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var _ = Describe("passthrough blocks", func() {
Context("in raw documents", func() {
Context("paragraph with attribute", func() {
It("2-line paragraph followed by another paragraph", func() {
source := `[pass]
_foo_
*bar*
another paragraph`
expected := []types.DocumentFragment{
{
Position: types.Position{
Start: 0,
End: 19,
},
Elements: []interface{}{
&types.Paragraph{
Attributes: types.Attributes{
types.AttrStyle: types.Passthrough,
},
Elements: []interface{}{
&types.RawLine{
Content: "_foo_\n",
},
&types.RawLine{
Content: "*bar*",
},
},
},
},
},
{
Position: types.Position{
Start: 19,
End: 20,
},
Elements: []interface{}{
&types.BlankLine{},
},
},
{
Position: types.Position{
Start: 20,
End: 37,
},
Elements: []interface{}{
&types.Paragraph{
Elements: []interface{}{
&types.RawLine{
Content: "another paragraph",
},
},
},
},
},
}
Expect(ParseDocumentFragments(source)).To(MatchDocumentFragments(expected))
})
})
})
Context("in final documents", func() {
Context("as delimited blocks", func() {
It("with title", func() {
source := `.a title
++++
_foo_
*bar*
++++`
expected := &types.Document{
Elements: []interface{}{
&types.DelimitedBlock{
Kind: types.Passthrough,
Attributes: types.Attributes{
types.AttrTitle: "a title",
},
Elements: []interface{}{
&types.StringElement{
Content: "_foo_\n\n*bar*",
},
},
},
},
}
result, err := ParseDocument(source)
Expect(err).NotTo(HaveOccurred())
Expect(result).To(MatchDocument(expected))
})
It("with special characters", func() {
source := `++++
<input>
<input>
++++`
expected := &types.Document{
Elements: []interface{}{
&types.DelimitedBlock{
Kind: types.Passthrough,
Elements: []interface{}{
&types.StringElement{
Content: "<input>\n\n<input>",
},
},
},
},
}
Expect(ParseDocument(source)).To(MatchDocument(expected))
})
It("with inline link", func() {
source := `++++
https://example.com[]
++++`
expected := &types.Document{
Elements: []interface{}{
&types.DelimitedBlock{
Kind: types.Passthrough,
Elements: []interface{}{
&types.StringElement{
Content: "https://example.com[]",
},
},
},
},
}
Expect(ParseDocument(source)).To(MatchDocument(expected))
})
It("with inline pass", func() {
source := `++++
pass:[foo]
++++`
expected := &types.Document{
Elements: []interface{}{
&types.DelimitedBlock{
Kind: types.Passthrough,
Elements: []interface{}{
&types.StringElement{
Content: "pass:[foo]",
},
},
},
},
}
Expect(ParseDocument(source)).To(MatchDocument(expected))
})
Context("with variable delimiter length", func() {
It("with 5 chars", func() {
source := `+++++
some *passthrough* content
+++++`
expected := &types.Document{
Elements: []interface{}{
&types.DelimitedBlock{
Kind: types.Passthrough,
Elements: []interface{}{
&types.StringElement{
Content: "some *passthrough* content",
},
},
},
},
}
Expect(ParseDocument(source)).To(MatchDocument(expected))
})
It("with 5 chars with nested with 4 chars", func() {
source := `+++++
++++
some *passthrough* content
++++
+++++`
expected := &types.Document{
Elements: []interface{}{
&types.DelimitedBlock{
Kind: types.Passthrough,
Elements: []interface{}{
&types.StringElement{
Content: "++++\nsome *passthrough* content\n++++",
},
},
},
},
}
Expect(ParseDocument(source)).To(MatchDocument(expected))
})
})
})
Context("paragraph with attribute", func() {
It("2-line paragraph followed by another paragraph", func() {
source := `[pass]
_foo_
*bar*
another paragraph`
expected := &types.Document{
Elements: []interface{}{
&types.Paragraph{
Attributes: types.Attributes{
types.AttrStyle: types.Passthrough,
},
Elements: []interface{}{
&types.StringElement{
Content: "_foo_\n*bar*",
},
},
},
&types.Paragraph{
Elements: []interface{}{
&types.StringElement{
Content: "another paragraph",
},
},
},
},
}
Expect(ParseDocument(source)).To(MatchDocument(expected))
})
})
})
})
|
package common
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
var _ = Describe("ResourceMatches", func() {
It("doesn't match", func() {
Expect(ResourceMatches("my-resource-name", "not-my-resource", false)).To(BeFalse())
})
It("does match", func() {
Expect(ResourceMatches("my-resource-name", "my-res", false)).To(BeTrue())
})
It("matches for empty filter", func() {
Expect(ResourceMatches("my-resource-name", "", false)).To(BeTrue())
})
Context("interpreting filter as regex", func() {
It("doesn't match", func() {
Expect(ResourceMatches("my-resource-name", "not-.*-resource", true)).To(BeFalse())
})
It("does match", func() {
Expect(ResourceMatches("my-resource-name", "my-res.*-name", true)).To(BeTrue())
})
It("matches for empty filter", func() {
Expect(ResourceMatches("my-resource-name", "", true)).To(BeTrue())
})
})
Context("handling extended regex", func() {
filter := `^(?=.*pull-1611)(?!.*iless-).*`
Context("given a bosh deployed vm resource", func() {
It("filters in the positive case", func() {
name := "vm-ca9e5f2d-7ae9-40b8-66b3-22fc49318a75 (pull-1611-pcf-network, cf-8bf3da062289a6c57468, cf-8bf3da062289a6c57468-compute, compute, p-bosh, p-bosh-cf-8bf3da062289a6c57468, p-bosh-cf-8bf3da062289a6c57468-compute, pull-1611-vms)"
Expect(ResourceMatches(name, filter, true)).To(BeTrue())
})
It("filters in the negative case", func() {
name := "vm-b60ce906-54d3-46d2-771c-7a9c8aad53bb (iless-pull-1611-pcf-network, cf-13d3260375a79e249520, cf-13d3260375a79e249520-router, iless-pull-1611-vms, p-bosh, p-bosh-cf-13d3260375a79e249520, p-bosh-cf-13d3260375a79e249520-router, router)"
Expect(ResourceMatches(name, filter, true)).To(BeFalse())
})
})
Context("given a terraform deployed vm resource", func() {
It("filters in the positive case", func() {
name := "pull-1611-infrastructure-subnet"
Expect(ResourceMatches(name, filter, true)).To(BeTrue())
})
It("filters in the negative case", func() {
name := "iless-pull-1611-infrastructure-subnet"
Expect(ResourceMatches(name, filter, true)).To(BeFalse())
})
})
})
})
|
package Palindrome_Partitioning
func partition(s string) [][]string {
if len(s) == 0 {
return [][]string{}
}
results := make([][]string, 0)
backTracking(s, &results, []string{}, 0)
return results
}
func backTracking(s string, result *[][]string, subset []string, index int) {
if index == len(s) {
*result = append(*result, append([]string{}, subset...))
return
}
for i := 1; index+i <= len(s); i++ {
if !isPalindrome(s[index : index+i]) {
continue
}
backTracking(s, result, append(subset, s[index:index+i]), index+i)
}
}
func partition2(s string) [][]string {
if len(s) == 1 {
return [][]string{{s}}
}
results := make([][]string, 0)
for i := 0; i < len(s); i++ {
if !isPalindrome(s[:i+1]) {
continue
}
before := s[:i+1]
after := partition(s[i+1:])
if len(after) == 0 {
results = append(results, []string{before})
continue
}
for _, v := range after {
result := append([]string{}, before)
result = append(result, v...)
results = append(results, result)
}
}
return results
}
func isPalindrome(subset string) bool {
if len(subset) == 0 {
return false
}
if len(subset) == 1 {
return true
}
left, right := 0, len(subset)-1
for left <= right {
if subset[left] != subset[right] {
return false
}
left++
right--
}
return true
}
|
package server
import (
"encoding/json"
"errors"
"2C_vehicle_ms/pkg"
"log"
"net/http"
"strconv"
"github.com/gorilla/mux"
)
type favrouteRouter struct {
favrouteService root.FavrouteService
}
func NewFavrouteRouter(v root.FavrouteService, router *mux.Router) *mux.Router {
favrouteRouter := favrouteRouter{v}
router.HandleFunc("/fav_routes/", favrouteRouter.createFavrouteHandler).Methods("POST")
router.HandleFunc("/fav_routes/", favrouteRouter.getAllFavrouteHandler).Methods("GET")
router.HandleFunc("/fav_routes/{id}/", favrouteRouter.getFavrouteByIdHandler).Methods("GET")
router.HandleFunc("/fav_routes/my_favRoutes/{user_id}/", favrouteRouter.getFavrouteByUserIdHandler).Methods("GET")
router.HandleFunc("/fav_routes/{id}/", favrouteRouter.deleteFavrouteHandler).Methods("DELETE")
router.HandleFunc("/fav_routes/{id}/", favrouteRouter.updateFavrouteHandler).Methods("PUT")
return router
}
func (vr *favrouteRouter) createFavrouteHandler(w http.ResponseWriter, r *http.Request) {
favroute, err := decodeFavroute(r)
if err != nil {
Error(w, http.StatusBadRequest, "Invalid request payload")
return
}
salida, err := vr.favrouteService.CreateFavroute(&favroute)
if err != nil {
Error(w, http.StatusInternalServerError, err.Error())
return
}
Json(w, http.StatusOK, salida)
}
func (vr *favrouteRouter) deleteFavrouteHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
log.Println(vars)
favrouteId, err := strconv.Atoi(vars["id"])
err = vr.favrouteService.DeleteById(favrouteId)
if err != nil {
Error(w, http.StatusNotFound, err.Error())
return
}
Json(w, http.StatusOK, err)
}
func (vr *favrouteRouter) getFavrouteByIdHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
favrouteId, err := strconv.Atoi(vars["id"])
favroute, err := vr.favrouteService.GetById(favrouteId)
if err != nil {
Error(w, http.StatusNotFound, err.Error())
return
}
Json(w, http.StatusOK, favroute)
}
func (vr *favrouteRouter) updateFavrouteHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
favrouteId, err := strconv.Atoi(vars["id"])
favroute, err := decodeFavroute(r)
favrouteUp, err := vr.favrouteService.UpdateById(favrouteId, &favroute)
if err != nil {
Error(w, http.StatusNotFound, err.Error())
return
}
Json(w, http.StatusOK, favrouteUp)
}
func (vr *favrouteRouter) getAllFavrouteHandler(w http.ResponseWriter, r *http.Request) {
favroutes, err := vr.favrouteService.GetAll()
if err != nil {
Error(w, http.StatusNotFound, err.Error())
return
}
Json(w, http.StatusOK, favroutes)
}
func (vr *favrouteRouter) getFavrouteByUserIdHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
favrouteId, err := strconv.Atoi(vars["user_id"])
favroute, err := vr.favrouteService.GetByUserId(favrouteId)
if err != nil {
Error(w, http.StatusNotFound, err.Error())
return
}
Json(w, http.StatusOK, favroute)
}
func decodeFavroute(r *http.Request) (root.Favroute, error) {
var v root.Favroute
if r.Body == nil {
return v, errors.New("no request body")
}
decoder := json.NewDecoder(r.Body)
err := decoder.Decode(&v)
return v, err
}
|
package update
import (
"encoding/json"
"fmt"
"net/http"
"os"
"github.com/ocoscope/face/db"
"github.com/ocoscope/face/utils"
"github.com/ocoscope/face/utils/answer"
)
func User(w http.ResponseWriter, r *http.Request) {
type tbody struct {
CompanyID, UserID uint
AccessToken, FirstName, LastName, PatronymicName, Email, Position, Number, Password string
}
var body tbody
err := json.NewDecoder(r.Body).Decode(&body)
if err != nil {
utils.Message(w, answer.WRONG_DATA, 400)
return
}
database, err := db.CopmanyDB(int64(body.CompanyID))
if err != nil {
utils.Message(w, answer.NOT_FOUND_COMPANY, 400)
return
}
defer database.Close()
err = db.CheckUserAccessToken(database, int64(body.UserID), body.AccessToken)
if err != nil {
utils.Message(w, answer.UNAUTHORIZED, 401)
return
}
user := db.TUpdateUser{
FirstName: body.FirstName,
LastName: body.LastName,
PatronymicName: body.PatronymicName,
Number: body.Number,
Position: body.Position,
UserID: int64(body.UserID),
}
_, err = db.UpdateUser(database, user)
if err != nil {
fmt.Println(err)
utils.Message(w, answer.FR, 400)
return
}
// если есть email то меняем его
if result := utils.VEmail(&body.Email); len(result) == 0 || len(body.Password) == 0 {
utils.Message(w, result, 400)
return
}
userPassword, err := db.GetPasswordByUserID(database, body.UserID)
if err != nil {
utils.Message(w, answer.F_USER_AUTH_DATA, 400)
return
}
boolean := utils.CheckHashPassword(body.Password, userPassword)
if !boolean {
utils.Message(w, answer.F_USER_AUTH_DATA, 400)
return
}
access, err := db.GetAccessToken(database, int64(body.UserID))
if err != nil {
fmt.Println(err)
utils.Message(w, answer.FR, 400)
return
}
subj := "Подтверждение нового email"
url := `
Ссылка для изменение email:
`+os.Getenv("FRONT_URL") + "/confirm/email/" + utils.IntToStr(int64(body.CompanyID)) + "/"+ utils.IntToStr(int64(body.UserID)) + "/" + access
err = utils.MessageSmtp(body.Email, subj, url)
if err != nil {
fmt.Println(err)
utils.Message(w, answer.FR, 400)
return
}
utils.Message(w, answer.UPDATE_USER_PROFILE, 200)
}
|
// Copyright 2017 Google Inc. All Rights Reserved.
//
// 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 inventory scans the current inventory (patches and package installed and available)
// and writes them to Guest Attributes.
package inventory
import (
"context"
"time"
"github.com/GoogleCloudPlatform/osconfig/agentconfig"
"github.com/GoogleCloudPlatform/osconfig/clog"
"github.com/GoogleCloudPlatform/osconfig/osinfo"
"github.com/GoogleCloudPlatform/osconfig/packages"
)
// InstanceInventory is an instances inventory data.
type InstanceInventory struct {
Hostname string
LongName string
ShortName string
Version string
Architecture string
KernelVersion string
KernelRelease string
OSConfigAgentVersion string
InstalledPackages *packages.Packages
PackageUpdates *packages.Packages
LastUpdated string
}
// Get generates inventory data.
func Get(ctx context.Context) *InstanceInventory {
clog.Debugf(ctx, "Gathering instance inventory.")
hs := &InstanceInventory{}
installedPackages, err := packages.GetInstalledPackages(ctx)
if err != nil {
clog.Errorf(ctx, "packages.GetInstalledPackages() error: %v", err)
}
packageUpdates, err := packages.GetPackageUpdates(ctx)
if err != nil {
clog.Errorf(ctx, "packages.GetPackageUpdates() error: %v", err)
}
oi, err := osinfo.Get()
if err != nil {
clog.Errorf(ctx, "osinfo.Get() error: %v", err)
}
hs.Hostname = oi.Hostname
hs.LongName = oi.LongName
hs.ShortName = oi.ShortName
hs.Version = oi.Version
hs.KernelVersion = oi.KernelVersion
hs.KernelRelease = oi.KernelRelease
hs.Architecture = oi.Architecture
hs.OSConfigAgentVersion = agentconfig.Version()
hs.InstalledPackages = installedPackages
hs.PackageUpdates = packageUpdates
hs.LastUpdated = time.Now().UTC().Format(time.RFC3339)
return hs
}
|
package main
import (
"encoding/json"
)
// layer 1 => CommandFrame
type CommandFrame struct {
/*
Kind 1 => Payload = SessionMessage, Body = empty
Kind 2 => Payload = empty, Body = CommandFrame
Kind 4 => Payload = empty, Body = RoomMsg
*/
Kind int `json:"kind"`
Payload string `json:"payload"`
Signature string `json:"signature"`
Body string `json:"body"`
}
// kind: 4
// layer: 2
type RoomMsg struct {
Occupancy int `json:"occupancy"`
Room string `json:"room"`
TotalParticipants int `json:"total_participants"`
}
type SenderT struct {
UserId string `json:"user_id"`
ParticipantIndex int `json:"participant_index"`
}
// kind: 1
// layer: 2
type SessionMessage struct {
Body string `json:"body"`
Bt int `json:"bt"` //Body Type
Oa bool `json:"oa"` //OAuth ???
Room string `json:"room"`
Sender SenderT `json:"sender"`
Ssid string `json:"ssid"`
St int `json:"st"`//Always 0 ?
Timestamp int `json:"timestamp"`
}
/*
type 1: Chat msg
Username,DisplayName,Body
type 2:
type 3:
type 4: Geoloc frame
Heading, Lat, Lng,
*/
type PeriMessage struct {
Type int `json:"type"`
Body string `json:"body"`
DisplayName string `json:"displayName"`
Heading float64 `json:"heading"`
Initials string `json:"initials"`
JuryDuration int `json:"jury_duration"`
Lat float64 `json:"lat"`
Lng float64 `json:"lng"`
Ntpforbroadcasterframe int `json:"ntpForBroadcasterFrame"`
Ntpforliveframe int `json:"ntpForLiveFrame"`
ParticipantIndex int `json:"participant_index"`
Profileimageurl string `json:"profileImageURL"`
Remoteid string `json:"remoteID"`
ReportType int `json:"report_type"`
SentenceDuration int `json:"sentence_duration"`
SentenceType int `json:"sentence_type"`
Timestamp int `json:"timestamp"`
Username string `json:"username"`
Uuid string `json:"uuid"`
Verdict int `json:"verdict"`
V int `json:"v"`
}
func FrameFilter(frame []byte) (PeriMessage, error) {
var cf CommandFrame
var sm SessionMessage
var pm PeriMessage
err := json.Unmarshal(frame, &cf)
if err != nil {
return pm, err
}
if cf.Kind == 1 {
err = json.Unmarshal([]byte(cf.Payload), &sm)
if err != nil {
return pm, err
}
if sm.Bt == 1 {
err = json.Unmarshal([]byte(sm.Body), &pm)
return pm, nil
}
}
return pm, nil
}
|
// Copyright 2020 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package wilco
import (
"context"
"chromiumos/tast/local/bundles/cros/wilco/pre"
"chromiumos/tast/local/wilco"
"chromiumos/tast/testing"
dtcpb "chromiumos/wilco_dtc"
)
func init() {
testing.AddTest(&testing.Test{
Func: APIPerformWebRequestError,
Desc: "Test sending PerformWebRequest gRPC request from Wilco DTC VM to the Wilco DTC Support Daemon when not enrolled",
Contacts: []string{
"chromeos-oem-services@google.com", // Use team email for tickets.
"bkersting@google.com",
"lamzin@google.com",
},
Attr: []string{"group:mainline"},
SoftwareDeps: []string{"vm_host", "wilco"},
Pre: pre.WilcoDtcSupportdAPI,
})
}
func APIPerformWebRequestError(ctx context.Context, s *testing.State) {
request := dtcpb.PerformWebRequestParameter{
HttpMethod: dtcpb.PerformWebRequestParameter_HTTP_METHOD_GET,
Url: "https://localhost/test",
}
response := dtcpb.PerformWebRequestResponse{}
if err := wilco.DPSLSendMessage(ctx, "PerformWebRequest", &request, &response); err != nil {
s.Fatal("Unable to get configuration data: ", err)
}
// Error conditions defined by the proto definition.
if response.Status != dtcpb.PerformWebRequestResponse_STATUS_INTERNAL_ERROR {
s.Errorf("Unexpected Status; got %s, want STATUS_INTERNAL_ERROR", response.Status)
}
if len(response.ResponseBody) > 0 {
s.Errorf("Unexpected ResponseBody; got %v, want an empty response", response.ResponseBody)
}
}
|
package routes
import (
"context"
"github.com/ONSdigital/dp-hello-world-controller/config"
"github.com/ONSdigital/dp-hello-world-controller/handlers"
health "github.com/ONSdigital/dp-healthcheck/healthcheck"
"github.com/ONSdigital/log.go/log"
"github.com/gorilla/mux"
)
// Setup registers routes for the service
func Setup(ctx context.Context, r *mux.Router, cfg *config.Config, hc health.HealthCheck) {
log.Event(ctx, "adding routes")
r.StrictSlash(true).Path("/health").HandlerFunc(hc.Handler)
r.StrictSlash(true).Path("/helloworld").Methods("GET").HandlerFunc(handlers.HelloWorld(*cfg))
}
|
package main
import "fmt"
func main() { // 0 1 2 3 4 5 6 7 8 9
req := []int{5, 7, 9, 10, 11, 12, 13, 14, 28, 42}
seq := []int{}
// tag := 0
for i := 1; i < len(req); i++ {
seq = append(seq, req[i]-req[i-1])
}
fmt.Println(seq)
type Set struct {
begin int
end int
}
result := []Set{}
for i := 0; i < len(seq)-1; i++ {
j := i + 1
if seq[i] == seq[j] {
tmp := Set{
begin: i,
end: j + 1,
}
result = append(result, tmp)
}
}
for i := 0; i < len(seq)-1; i++ {
count := 0
for j := i + 1; j < len(seq); j++ {
if seq[i] == seq[j] {
count++
} else {
break
}
if count >= 2 {
tmp := Set{
begin: i,
end: j + 1,
}
result = append(result, tmp)
}
}
}
fmt.Println(result)
}
|
package models
import "github.com/jinzhu/gorm"
// Tip for tip model
type Tip struct {
gorm.Model
Content string `json:"content"`
}
|
package jsonutils
import (
"encoding/json"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/joshprzybyszewski/cribbage/model"
)
func TestUnmarshalPlayerAction(t *testing.T) {
testCases := []struct {
msg string
pa model.PlayerAction
}{{
msg: `deal`,
pa: model.PlayerAction{
GameID: model.GameID(42),
ID: model.PlayerID(`alice`),
Overcomes: model.DealCards,
Action: model.DealAction{
NumShuffles: 543,
},
},
}, {
msg: `crib`,
pa: model.PlayerAction{
GameID: model.GameID(45),
ID: model.PlayerID(`bob`),
Overcomes: model.CribCard,
Action: model.BuildCribAction{
Cards: []model.Card{
model.NewCardFromString(`jh`),
model.NewCardFromString(`5d`),
},
},
},
}, {
msg: `cut`,
pa: model.PlayerAction{
GameID: model.GameID(312),
ID: model.PlayerID(`charlie`),
Overcomes: model.CutCard,
Action: model.CutDeckAction{
Percentage: 0.12345,
},
},
}, {
msg: `peg`,
pa: model.PlayerAction{
GameID: model.GameID(999),
ID: model.PlayerID(`diane`),
Overcomes: model.PegCard,
Action: model.PegAction{
Card: model.NewCardFromString(`jh`),
},
},
}, {
msg: `peg saygo`,
pa: model.PlayerAction{
GameID: model.GameID(1),
ID: model.PlayerID(`edward`),
Overcomes: model.PegCard,
Action: model.PegAction{
SayGo: true,
},
},
}, {
msg: `count hand`,
pa: model.PlayerAction{
GameID: model.GameID(54),
ID: model.PlayerID(`frances`),
Overcomes: model.CountHand,
Action: model.CountHandAction{
Pts: 29,
},
},
}, {
msg: `count crib`,
pa: model.PlayerAction{
GameID: model.GameID(3),
ID: model.PlayerID(`george`),
Overcomes: model.CountCrib,
Action: model.CountCribAction{
Pts: 12,
},
},
}}
for _, tc := range testCases {
tc.pa.SetTimeStamp(time.Now())
paCopy := tc.pa
b, err := json.Marshal(tc.pa)
require.NoError(t, err, tc.msg)
actPA, err := UnmarshalPlayerAction(b)
require.NoError(t, err, tc.msg)
assert.Equal(t, paCopy, actPA, tc.msg)
}
}
|
package openstack
import (
"fmt"
"github.com/gophercloud/gophercloud/openstack/compute/v2/servers"
"github.com/gophercloud/gophercloud/pagination"
)
//go:generate faux --interface ComputeInstanceAPI --output fakes/compute_instance_api.go
type ComputeInstanceAPI interface {
GetComputeInstancePager() pagination.Pager
PagerToPage(pagination.Pager) (pagination.Page, error)
PageToServers(pagination.Page) ([]servers.Server, error)
Delete(instanceID string) error
}
type ComputeInstanceClient struct {
api ComputeInstanceAPI
}
func NewComputeInstanceClient(api ComputeInstanceAPI) ComputeInstanceClient {
return ComputeInstanceClient{
api: api,
}
}
func (client ComputeInstanceClient) List() ([]servers.Server, error) {
pager := client.api.GetComputeInstancePager()
page, err := client.api.PagerToPage(pager)
if err != nil {
return nil, fmt.Errorf("pager to page: %s", err)
}
servers, err := client.api.PageToServers(page)
if err != nil {
return nil, fmt.Errorf("page to servers: %s", err)
}
return servers, nil
}
func (client ComputeInstanceClient) Delete(instanceID string) error {
return client.api.Delete(instanceID)
}
|
package main
import (
"bufio"
"os"
"sync"
)
var channels = map[string]*Log{}
func GetLog(channel string) (*Log, error) {
log, ok := channels[channel]
if !ok {
var err error
log, err = NewLog(channel)
if err != nil {
return nil, err
}
channels[channel] = log
}
return log, nil
}
type Log struct {
fileLock sync.Mutex
channel string
}
func NewLog(channel string) (*Log, error) {
log := Log{
channel: channel,
}
_, err := os.Stat(log.filePath())
if err != nil {
_, createErr := os.Create(log.filePath())
if createErr != nil {
return nil, createErr
}
}
return &log, nil
}
func (l *Log) Load() ([]string, error) {
var logArr []string
fp, err := os.Open(l.filePath())
defer fp.Close()
if err != nil {
return nil, err
}
scanner := bufio.NewScanner(fp)
for scanner.Scan() {
log := scanner.Text()
logArr = append(logArr, log)
}
return logArr, nil
}
func (l *Log) Write(message string) error {
l.fileLock.Lock()
defer l.fileLock.Unlock()
fp, err := os.OpenFile(l.filePath(), os.O_APPEND|os.O_WRONLY, 0600)
defer fp.Close()
if err != nil {
return err
}
_, err = fp.WriteString(message + "\n")
if err != nil {
return err
}
return nil
}
func (l *Log) filePath() string {
return "./log/" + l.channel + ".log"
}
|
// Copyright 2020 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package firmware
import (
"reflect"
"testing"
pb "chromiumos/tast/services/cros/firmware"
)
// flags converts a list of ints to a slice of pb.GBBFlags.
func flags(f ...int) []pb.GBBFlag {
var fs []pb.GBBFlag
for _, i := range f {
fs = append(fs, pb.GBBFlag(i))
}
return fs
}
// state constructs a GBBFlagsState.
func state(clear, set []pb.GBBFlag) *pb.GBBFlagsState {
return &pb.GBBFlagsState{Clear: clear, Set: set}
}
func TestCanonicalGBBFlagState(t *testing.T) {
states := []struct {
a *pb.GBBFlagsState
c *pb.GBBFlagsState
}{
{state(flags(), flags()), state(flags(), flags())},
{state(flags(0), flags()), state(flags(0), flags())},
{state(flags(), flags(0)), state(flags(), flags(0))},
{state(flags(1, 2, 3), flags(4, 5, 6)), state(flags(1, 2, 3), flags(4, 5, 6))},
{state(flags(3, 2, 1), flags(6, 5, 4)), state(flags(1, 2, 3), flags(4, 5, 6))},
}
for _, s := range states {
cA := canonicalGBBFlagsState(s.a)
if !reflect.DeepEqual(cA.Clear, s.c.Clear) {
t.Errorf("Clear incorrect for canonical %v: \ngot\n%v\nwant\n%v\n\n", s.a.Clear, cA.Clear, s.c.Clear)
}
if !reflect.DeepEqual(cA.Set, s.c.Set) {
t.Errorf("Set incorrect for canonical %v: \ngot\n%v\nwant\n%v\n\n", s.a.Set, cA.Set, s.c.Set)
}
}
}
func TestGBBFlagsStatesEqual(t *testing.T) {
states := []struct {
a *pb.GBBFlagsState
b *pb.GBBFlagsState
want bool
}{
{state(flags(), flags()), state(flags(), flags()), true},
{state(flags(0), flags()), state(flags(0), flags()), true},
{state(flags(), flags(0)), state(flags(), flags(0)), true},
{state(flags(1, 2, 3), flags(4, 5, 6)), state(flags(1, 2, 3), flags(4, 5, 6)), true},
{state(flags(3, 2, 1), flags(6, 5, 4)), state(flags(1, 2, 3), flags(4, 5, 6)), true},
{state(flags(3, 2, 1), flags(6, 5, 4)), state(flags(3, 2, 1), flags(6, 5, 4)), true},
{state(flags(), flags()), state(flags(0), flags()), false},
{state(flags(0), flags()), state(flags(), flags(0)), false},
{state(flags(0), flags(0)), state(flags(0), flags(1)), false},
{state(flags(0), flags(0)), state(flags(1), flags(0)), false},
{state(flags(0, 1), flags(0, 1)), state(flags(0, 1), flags(0, 2)), false},
}
for _, s := range states {
got := GBBFlagsStatesEqual(s.a, s.b)
if got != s.want {
t.Errorf("Comparing\n%+v\nand\n%+v\ngot %v, want %v", s.a, s.b, got, s.want)
}
}
}
func TestGBBFlagsChanged(t *testing.T) {
states := []struct {
a *pb.GBBFlagsState
b *pb.GBBFlagsState
f []pb.GBBFlag
want bool
}{
{state(flags(), flags()), state(flags(), flags()), flags(0), false},
{state(flags(0), flags(1)), state(flags(1), flags(0)), flags(2), false},
{state(flags(0), flags()), state(flags(0), flags()), flags(0), false},
{state(flags(), flags(0)), state(flags(), flags(0)), flags(0), false},
{state(flags(), flags(0)), state(flags(), flags(0)), flags(0), false},
{state(flags(0), flags()), state(flags(1), flags()), flags(0), false},
{state(flags(0), flags()), state(flags(), flags(0)), flags(0), true},
{state(flags(), flags(0)), state(flags(0), flags()), flags(0), true},
{state(flags(), flags(0)), state(flags(0), flags()), flags(0), true},
{state(flags(0, 1), flags(0, 1, 2)), state(flags(0, 2), flags()), flags(0), true},
}
for _, s := range states {
got := GBBFlagsChanged(s.a, s.b, s.f)
if got != s.want {
t.Errorf("Flags %v changed from\n%v\nto%v\ngot %v, want %v", s.f, s.a, s.b, got, s.want)
}
}
}
func TestAllGBBFlags(t *testing.T) {
var all []int
for i := 0; i < len(pb.GBBFlag_value); i++ {
all = append(all, i)
}
want := flags(all...)
got := AllGBBFlags()
if !reflect.DeepEqual(got, want) {
t.Errorf("All flags\ngot\n%v\nwant\n%v", got, want)
}
}
|
package summary_test
import (
"bytes"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/go-task/task/v3/internal/logger"
"github.com/go-task/task/v3/internal/summary"
"github.com/go-task/task/v3/taskfile"
)
func TestPrintsDependenciesIfPresent(t *testing.T) {
buffer, l := createDummyLogger()
task := &taskfile.Task{
Deps: []*taskfile.Dep{
{Task: "dep1"},
{Task: "dep2"},
{Task: "dep3"},
},
}
summary.PrintTask(&l, task)
assert.Contains(t, buffer.String(), "\ndependencies:\n - dep1\n - dep2\n - dep3\n")
}
func createDummyLogger() (*bytes.Buffer, logger.Logger) {
buffer := &bytes.Buffer{}
l := logger.Logger{
Stderr: buffer,
Stdout: buffer,
Verbose: false,
}
return buffer, l
}
func TestDoesNotPrintDependenciesIfMissing(t *testing.T) {
buffer, l := createDummyLogger()
task := &taskfile.Task{
Deps: []*taskfile.Dep{},
}
summary.PrintTask(&l, task)
assert.NotContains(t, buffer.String(), "dependencies:")
}
func TestPrintTaskName(t *testing.T) {
buffer, l := createDummyLogger()
task := &taskfile.Task{
Task: "my-task-name",
}
summary.PrintTask(&l, task)
assert.Contains(t, buffer.String(), "task: my-task-name\n")
}
func TestPrintTaskCommandsIfPresent(t *testing.T) {
buffer, l := createDummyLogger()
task := &taskfile.Task{
Cmds: []*taskfile.Cmd{
{Cmd: "command-1"},
{Cmd: "command-2"},
{Task: "task-1"},
},
}
summary.PrintTask(&l, task)
assert.Contains(t, buffer.String(), "\ncommands:\n")
assert.Contains(t, buffer.String(), "\n - command-1\n")
assert.Contains(t, buffer.String(), "\n - command-2\n")
assert.Contains(t, buffer.String(), "\n - Task: task-1\n")
}
func TestDoesNotPrintCommandIfMissing(t *testing.T) {
buffer, l := createDummyLogger()
task := &taskfile.Task{
Cmds: []*taskfile.Cmd{},
}
summary.PrintTask(&l, task)
assert.NotContains(t, buffer.String(), "commands")
}
func TestLayout(t *testing.T) {
buffer, l := createDummyLogger()
task := &taskfile.Task{
Task: "sample-task",
Summary: "line1\nline2\nline3\n",
Deps: []*taskfile.Dep{
{Task: "dependency"},
},
Cmds: []*taskfile.Cmd{
{Cmd: "command"},
},
}
summary.PrintTask(&l, task)
assert.Equal(t, expectedOutput(), buffer.String())
}
func expectedOutput() string {
expected := `task: sample-task
line1
line2
line3
dependencies:
- dependency
commands:
- command
`
return expected
}
func TestPrintDescriptionAsFallback(t *testing.T) {
buffer, l := createDummyLogger()
taskWithoutSummary := &taskfile.Task{
Desc: "description",
}
taskWithSummary := &taskfile.Task{
Desc: "description",
Summary: "summary",
}
taskWithoutSummaryOrDescription := &taskfile.Task{}
summary.PrintTask(&l, taskWithoutSummary)
assert.Contains(t, buffer.String(), "description")
buffer.Reset()
summary.PrintTask(&l, taskWithSummary)
assert.NotContains(t, buffer.String(), "description")
buffer.Reset()
summary.PrintTask(&l, taskWithoutSummaryOrDescription)
assert.Contains(t, buffer.String(), "\n(task does not have description or summary)\n")
}
func TestPrintAllWithSpaces(t *testing.T) {
buffer, l := createDummyLogger()
t1 := &taskfile.Task{Task: "t1"}
t2 := &taskfile.Task{Task: "t2"}
t3 := &taskfile.Task{Task: "t3"}
tasks := taskfile.Tasks{}
tasks.Set("t1", t1)
tasks.Set("t2", t2)
tasks.Set("t3", t3)
summary.PrintTasks(&l,
&taskfile.Taskfile{Tasks: tasks},
[]taskfile.Call{{Task: "t1"}, {Task: "t2"}, {Task: "t3"}})
assert.True(t, strings.HasPrefix(buffer.String(), "task: t1"))
assert.Contains(t, buffer.String(), "\n(task does not have description or summary)\n\n\ntask: t2")
assert.Contains(t, buffer.String(), "\n(task does not have description or summary)\n\n\ntask: t3")
}
|
package fun
import (
"fmt"
"reflect"
"github.com/marcuswestin/fun-go/errs"
)
type parallel2Result struct {
i int
val interface{}
err errs.Err
}
func Parallel2(funs ...interface{}) ([]interface{}, errs.Err) {
resChan := make(chan parallel2Result)
results := make([]interface{}, len(funs))
// Dispatch functions
for i, fun := range funs {
go func(i int, fun interface{}) {
res := reflect.ValueOf(fun).Call(nil)
val, _ := res[0].Interface().(interface{})
err, _ := res[1].Interface().(errs.Err)
resChan <- parallel2Result{i: i, val: val, err: err}
}(i, fun)
}
// Collect results
for i := 0; i < len(funs); i++ {
res := <-resChan
if res.err != nil {
return nil, res.err
}
results[res.i] = res.val
}
return results, nil
}
func Parallel(args ...interface{}) errs.Err {
if reflect.TypeOf(args[0]).NumOut() == 2 {
funs := args[:len(args)-1]
return parallelWithDone(funs, Last(args))
} else {
return parallelWithoutDone(args)
}
}
func parallelWithoutDone(funs []interface{}) errs.Err {
resChan := make(chan reflect.Value)
for _, fun := range funs {
fun := reflect.ValueOf(fun)
go func() {
resChan <- fun.Call(nil)[0]
}()
}
for i := 0; i < len(funs); i++ {
res := <-resChan
// There was an errs.Err
if !res.IsNil() {
return res.Interface().(errs.Err)
}
}
return nil
}
func parallelWithDone(funs []interface{}, done interface{}) errs.Err {
doneVal := reflect.ValueOf(done)
doneTyp := doneVal.Type()
errorIndex := len(funs)
results := make([]reflect.Value, len(funs)+1)
resChan := make(chan parallelResult)
doneReturnsError := false
// Check types
if doneTyp.NumIn() != len(funs)+1 {
panic(fmt.Sprintf(finalFuncNumArgsMsg, len(funs)+1))
}
if !doneTyp.In(errorIndex).Implements(errorInterface) {
panic(fmt.Sprint(finalFuncErrArgMsg, doneTyp.In(errorIndex)))
}
if doneTyp.NumOut() > 1 {
panic(fmt.Sprint(finalFuncReturnCountMsg, doneTyp.NumOut()))
}
if doneTyp.NumOut() == 1 {
if !doneTyp.Out(0).Implements(errorInterface) {
panic(fmt.Sprint(finalFuncReturnWrongTypeMsg, doneTyp.Out(0)))
}
doneReturnsError = true
}
for funI, fun := range funs {
funTyp := reflect.TypeOf(fun)
if funTyp.NumIn() > 0 {
panic(fmt.Sprintf(argFuncNoArgsMsg, funI+1, reflect.ValueOf(funTyp).Interface()))
}
if funTyp.NumOut() != 2 {
panic(fmt.Sprintf(argFuncNumReturnMsg, funI, funTyp.NumOut()))
}
if funTyp.Out(0) != doneTyp.In(funI) {
panic(fmt.Sprintf(argFuncDoneFuncTypeMismatch, funI, funTyp.Out(0), doneTyp.In(funI)))
}
if !funTyp.Out(1).Implements(errorInterface) {
panic(fmt.Sprintf(argFuncErrReturnMsg, funI, funTyp.Out(1)))
}
}
// Dispatch executions
for i, fun := range funs {
i := i
fun := reflect.ValueOf(fun)
go func() {
returns := fun.Call(nil)
resChan <- parallelResult{index: i, val: returns[0], err: returns[1]}
}()
}
// Collect results
for i := 0; i < len(funs); i++ {
res := <-resChan
// There was an errs.Err
if !res.err.IsNil() {
for funI, fun := range funs {
results[funI] = reflect.Zero(reflect.ValueOf(fun).Type().Out(0))
}
results[errorIndex] = res.err
doneRes := doneVal.Call(results)
if !doneReturnsError {
return res.err.Interface().(errs.Err)
}
return doneRes[0].Interface().(errs.Err)
}
results[res.index] = res.val
}
results[errorIndex] = reflect.ValueOf(&nilError).Elem()
doneRes := doneVal.Call(results)
if !doneReturnsError {
return nil
}
if doneRes[0].IsNil() {
return nil
}
return doneRes[0].Interface().(errs.Err)
}
type parallelResult struct {
index int
val reflect.Value
err reflect.Value
}
var nilError = errs.Err(nil)
var errorInterface = reflect.TypeOf(func(errs.Err) {}).In(0)
const finalFuncErrArgMsg = "Parallel final function's last argument type should be errs.Err but is "
const finalFuncNumArgsMsg = "Parallel final function should take %d arguments"
const argFuncNoArgsMsg = "Parallel functions should not take any arguments\n(offending function is number %d with signature %q)"
const argFuncNumReturnMsg = "Parallel function number %d should return two values (returns %d)"
const argFuncDoneFuncTypeMismatch = "Parallel function number %d returns a %q but final function expects a %q"
const argFuncErrReturnMsg = "Parallel function number %d should return an errs.Err as second return value (returns %q)"
const finalFuncReturnCountMsg = "Parallel final function should return nothing or one errs.Err (returns %d values)"
const finalFuncReturnWrongTypeMsg = "Parallel final function return value must be an errs.Err (is %q)"
|
package size
import (
"container/list"
"context"
"sync"
"github.com/upfluence/pkg/cache/policy"
)
type Policy struct {
sync.Mutex
size int
l *list.List
ks map[string]*list.Element
ctx context.Context
cancel context.CancelFunc
fn func(string)
closeOnce sync.Once
ch chan string
}
func NewLRUPolicy(size int) *Policy {
p := Policy{
l: list.New(),
size: size,
ks: make(map[string]*list.Element),
ch: make(chan string, 1),
}
p.ctx, p.cancel = context.WithCancel(context.Background())
p.fn = p.move
return &p
}
func (p *Policy) C() <-chan string {
return p.ch
}
func (p *Policy) Op(k string, op policy.OpType) error {
if p.ctx.Err() != nil {
return policy.ErrClosed
}
p.Lock()
switch op {
case policy.Set:
p.insert(k)
case policy.Get:
p.fn(k)
case policy.Evict:
p.evict(k)
}
p.Unlock()
return nil
}
func (p *Policy) move(k string) {
e, ok := p.ks[k]
if !ok {
return
}
p.l.MoveToBack(e)
}
func (p *Policy) insert(k string) {
if _, ok := p.ks[k]; ok {
return
}
var e *list.Element
if p.l.Len() == 0 {
e = p.l.PushFront(k)
} else {
e = p.l.InsertAfter(k, p.l.Back())
}
p.ks[k] = e
if p.l.Len() > p.size {
v := p.l.Remove(p.l.Front()).(string)
delete(p.ks, v)
select {
case <-p.ctx.Done():
case p.ch <- v:
}
}
}
func (p *Policy) evict(k string) {
e, ok := p.ks[k]
if !ok {
return
}
p.l.Remove(e)
delete(p.ks, k)
}
func (p *Policy) Close() error {
p.cancel()
p.closeOnce.Do(func() { close(p.ch) })
return nil
}
|
package testenv
import "path"
var (
root = "../.."
)
// SetRoot set the root path for the other relative paths, e.g. AssetPath.
// Usually set to point to the repositories root.
func SetRoot(dir string) {
root = dir
}
// Root returns the relative path to the repositories root
func Root() string {
return root
}
// AssetPath returns the path to an asset
func AssetPath(p ...string) string {
parts := append([]string{root, "e2e", "assets"}, p...)
return path.Join(parts...)
}
// ExamplePath returns the path to the fleet examples
func ExamplePath(p ...string) string {
parts := append([]string{root, "fleet-examples"}, p...)
return path.Join(parts...)
}
|
package main
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)
func main() {
var n int64
var sticks []int64
scanner := bufio.NewScanner(os.Stdin)
if scanner.Scan() {
n, _ = strconv.ParseInt(scanner.Text(), 10, 64)
}
if scanner.Scan() {
s := scanner.Text()
nums := strings.Fields(s)
for _, numstr := range nums {
num, _ := strconv.ParseInt(numstr, 10, 64)
sticks = append(sticks, num)
}
}
looping(n, &sticks)
}
func looping(stickNum int64, ptrSticks *[]int64) {
sticks := *ptrSticks
cutround := 0
for {
s := smallest(sticks)
if s == 0 {
break
}
for i := 0; i < int(stickNum); i++ {
if sticks[i] > 0 {
sticks[i] -= s
cutround++
}
}
if cutround == 0 {
break
}
fmt.Println(cutround)
cutround = 0
}
}
func smallest(sticks []int64) int64 {
s := sticks[0]
for _, num := range sticks {
if num > 0 && s == 0 {
s = num
}
if num > 0 && num < s {
s = num
}
}
return s
}
|
package main
import (
"github.com/Rubentxu/lbricks/engi"
"github.com/Rubentxu/lbricks"
)
var (
imprimir string
bot lbricks.Drawable
batch *engi.Batch
font *engi.Font
tick float64
)
func main() {
game:= &Game{}
game.InitContext()
engi.Open("Demo", 800, 600, false, game.EventSystem)
}
type Game struct {
EventSystem lbricks.EventSystem
}
func (g *Game) InitContext() {
g.EventSystem = &lbricks.CreateEventSystem(100)
}
func Preload(input chan *lbricks.PreloadEvent) {
for {
<- input
engi.Files.Add("bot", "data/icon.png")
engi.Files.Add("font", "data/font.png")
batch = engi.NewBatch(engi.Width(), engi.Height())
}
}
func Setup(input chan *lbricks.SetupEvent) {
<- input
engi.SetBg(0x2d3739)
bot = engi.Files.Image("bot")
font = engi.NewGridFont(engi.Files.Image("font"), 20, 20)
tick = 1.0 / 40.0
imprimir = "holasss"
}
func (g *Game) Render() {
batch.Begin()
font.Print(batch, imprimir, 10, 200, 0xffffff)
batch.Draw(bot, 512, 320, 0.5, 0.5, 10, 10, 0, 0xffffff, 1)
batch.End()
}
|
package main
import (
"bytes"
"fmt"
"io"
"log"
"net"
"net/url"
"strconv"
"strings"
)
func main(){
log.SetFlags(log.LstdFlags | log.Lshortfile)
fmt.Println("proxy main init...")
l,err :=net.Listen("tcp",":1088")
if err !=nil{
log.Panic(err)
}
for{
client,err := l.Accept()
if err != nil{
log.Panic(err)
}
go handleClientRequest(client)
}
}
func handleClientRequest(c net.Conn){
if c==nil{
return
}
defer c.Close()
var b [1024]byte
n,err:=c.Read(b[:])
if err!=nil{
log.Println(err)
return
}
//fmt.Println(string(b[:]))
var method,host,address string
fmt.Sscanf(string(b[:bytes.IndexByte(b[:],'\n')]),"%s%s",&method,&host)
fmt.Println(method)
//fmt.Println(host)
hostPortUrl,err:=url.Parse(host)
if err !=nil{
log.Println(err)
return
}
fmt.Println(hostPortUrl)
if hostPortUrl.Opaque=="443"{
address=hostPortUrl.Scheme+":443"
}else{
if strings.Index(hostPortUrl.Host,":")==-1{
address=hostPortUrl.Scheme+":80"
}else{
address=hostPortUrl.Host
}
}
fmt.Println(address)
server,err:=net.Dial("tcp",address)
if err!=nil{
log.Println(err)
return
}
defer server.Close()
if method =="CONNECT"{
fmt.Fprint(c, "HTTP/1.1 200 Connection established\r\n\r\n")
}else{
server.Write(b[:n])
}
go io.Copy(server,c)
io.Copy(c,server)
}
func doHandleSock5(c net.Conn){
if c==nil{
return
}
defer c.Close()
var b [1024]byte
n,err:=c.Read(b[:])
if err != nil{
log.Println(err)
return
}
//fmt.Println(b)
if b[0]==0x05{
c.Write([]byte{0x05,0x00})
n,err=c.Read(b[:])
//VER CMD RSV ATYP DST.ADDR DST.PORT
//1 1 X'00' 1 Variable 2
//fmt.Println(b[4:20])
//fmt.Println("n:",n)
var host,port string
switch b[3] {
case 0x01:
//fmt.Println("0x01")
host=net.IPv4(b[4],b[5],b[6],b[7]).String()
case 0x03:
//fmt.Println("0x03")
host=string(b[5:n-2])
case 0x04:
//fmt.Println("0x04")
host = net.IP{b[4], b[5], b[6], b[7], b[8], b[9], b[10], b[11], b[12], b[13], b[14], b[15], b[16], b[17], b[18], b[19]}.String()
}
port=strconv.Itoa(int(b[n-2])<<8|int(b[n-1]))
log.Printf("net dail address %s:%s",host,port)
server,err:=net.Dial("tcp",net.JoinHostPort(host,port))
if err!=nil{
log.Println(err)
return
}
defer server.Close()
//VER REP RSV ATYP BND.ADDR BND.PORT
//1 1 X'00' 1 Variable 2
c.Write([]byte{0x05,0x00,0x00,0x01,0x00,0x00,0x00,0x00,0x00,0x00})
go io.Copy(server,c)
io.Copy(c,server)
}
}
|
package main
import "fmt"
func main() {
switch {
case false:
fmt.Println("not printing")
case (2+2 == 4):
fmt.Println("print")
fallthrough
case (3 == 4):
fmt.Println("not printing 2")
fallthrough
case (3 == 3):
fmt.Println("print 2")
fallthrough
default:
fmt.Println("default case")
}
switch "example" {
case "exa":
fmt.Println("exa")
case "e", "x", "a":
fmt.Println("e or x or a")
case "ex", "example":
fmt.Println("Example!")
default:
fmt.Println("Default")
}
}
|
package main
import (
"fmt"
"net/http"
"io/ioutil"
"consistentHashing"
"log"
"strings"
"strconv"
"github.com/julienschmidt/httprouter"
)
// Variable Declarations
// A ring representing the nodes on a circle hashed using Consistent Hashing Algorithm
var Ring *consistentHashing.HashRing
// An array of my server instances i.e. servers running on ports 3000, 3001 and 3002
var MyRESTServers []string
// A map to store generated seed data. This data set would be shared to three server instances, using Consistent Hashing Algorithm
var DataMap = make(map[string]string)
//Main Function
func main() {
fmt.Println("Starting the client")
MyRESTServers = []string{"127.0.0.1:3000",
"127.0.0.1:3001",
"127.0.0.1:3002"}
Ring = consistentHashing.New(MyRESTServers)
mux := httprouter.New()
//handler to service GET ALL request
mux.GET("/keys", GetAllKeys)
//handler to service GET request
mux.GET("/keys/:id", GetKey)
//handler to service PUT request
mux.PUT("/keys/:id/:value", PutKey)
server := http.Server{
Addr: "0.0.0.0:8080",
Handler: mux,
}
server.ListenAndServe()
}
//Main function for Client, if Client is to be run as a Simple Standalone GO application
func mainStandAlone() {
MyRESTServers = []string{"127.0.0.1:3000",
"127.0.0.1:3001",
"127.0.0.1:3002"}
Ring = consistentHashing.New(MyRESTServers)
//Generate seed-data to be distributed across the servers
GenerateSeedData()
//Distribute keys
for key, value := range DataMap {
fmt.Println("Distributing/Saving this <key-valye> pair : <",key,"-",value,">")
PutOperation(key, value)
}
//Try to retrive few keys
fmt.Println("Retrieving FEW keys now!")
GetOperation("2")
GetOperation("4")
GetOperation("6")
//Try to retrive few keys
fmt.Println("Retrieving ALL keys now!")
GetAllOperation("127.0.0.1:3000")
GetAllOperation("127.0.0.1:3001")
GetAllOperation("127.0.0.1:3002")
}
/*
* PutKey function - Function to service PUT REST request on Client
* This will internally send a PUT request to the Server for storing the key and value pair
*/
func PutKey(rw http.ResponseWriter, req *http.Request, p httprouter.Params) {
// Grab id
id := p.ByName("id")
// Grab value
value := p.ByName("value")
server,_ := Ring.GetNode(id)
fmt.Println("The <key-value> pair to be saved : <",id,"-",value,">")
fmt.Println("The server for this key : ",server) //127.0.0.1:3001
//make a corresponding PUT request to the server here
url := "http://" + server + "/keys/" + id + "/" + value
client := &http.Client{}
request, err := http.NewRequest("PUT", url, strings.NewReader(""))
response, err := client.Do(request)
if err != nil {
log.Fatal(err)
} else {
defer response.Body.Close()
contents, err := ioutil.ReadAll(response.Body)
if err != nil {
log.Fatal(err)
}
fmt.Println("The Response is:", contents)
rw.WriteHeader(200)
}
fmt.Println("Key saved successfully!")
fmt.Println("------------------------------------------------------------")
}
/*
* GetAllKey function - Function to service GET ALL request on Client
* This will internally send a GET ALL request to the Server for fetching all the key and value pairs
*/
func GetAllKeys(rw http.ResponseWriter, req *http.Request, p httprouter.Params) {
var server string
results := ""
for index := 0; index < len(MyRESTServers); index++ {
server = MyRESTServers[index]
fmt.Println("Getting all keys from this server : ",server) //127.0.0.1:3001
//make a corresponding GET ALL request to the server here
url := "http://" + server + "/keys"
response, err := http.Get(url)
if err != nil {
log.Fatal(err)
} else {
defer response.Body.Close()
contents, err := ioutil.ReadAll(response.Body)
results = results + string(contents) + "\n "
if err != nil {
log.Fatal(err)
}
}
}
// Write content-type, statuscode, payload
fmt.Println("The Response is:", results)
rw.Header().Set("Content-Type", "application/json")
rw.WriteHeader(200)
fmt.Fprintf(rw, "%s", results)
fmt.Println("All Keys retrieved successfully!")
fmt.Println("------------------------------------------------------------")
}
/*
* GetKey function - Function to service GET REST request on Client
* This will internally send a GET request to the Server for fetching the key and value pair
*/
func GetKey(rw http.ResponseWriter, req *http.Request, p httprouter.Params) {
// Grab id
id := p.ByName("id")
server,_ := Ring.GetNode(id)
fmt.Println("Getting key from this server : ",server) //127.0.0.1:3001
//make a corresponding GET request to the server here
url := "http://" + server + "/keys/" + id
response, err := http.Get(url)
if err != nil {
log.Fatal(err)
} else {
defer response.Body.Close()
contents, err := ioutil.ReadAll(response.Body)
if err != nil {
log.Fatal(err)
}
fmt.Printf("The Response is : %s\n", string(contents));
rw.Header().Set("Content-Type", "application/json")
rw.WriteHeader(200)
fmt.Fprintf(rw, "%s", contents)
}
fmt.Println("Key retrieved successfully!")
fmt.Println("------------------------------------------------------------")
}
//Function to generate seed data for storage
//Keys are : 1 to 26
//Values are : Unicode characters : a - z
func GenerateSeedData() {
value := "abcdefghijklmnopqrstuvwxyz"
// Split after an empty string to get all letters.
result := strings.SplitAfter(value, "")
var key string
j := 1
for i := range(result) {
// Get letter and save it in the map
letter := result[i]
key = strconv.Itoa(j)
DataMap[key] = letter
j++
}
}
/*
* PutOperation function - Function to support PUT operation and shard the data set into three server instances
*/
func PutOperation(key string, value string) {
// Grab id
id := key
server,_ := Ring.GetNode(id)
fmt.Println("The <key-value> pair to be saved : <",key,"-",value,">")
fmt.Println("The server for this key : ",server)
//make a corresponding PUT request to the server here
url := "http://" + server + "/keys/" + id + "/" + value
client := &http.Client{}
request, err := http.NewRequest("PUT", url, strings.NewReader(""))
response, err := client.Do(request)
if err != nil {
log.Fatal(err)
} else {
defer response.Body.Close()
_, err := ioutil.ReadAll(response.Body)
if err != nil {
log.Fatal(err)
}
}
fmt.Println("Key saved successfully!")
fmt.Println("------------------------------------------------------------")
}
/*
* GetOperation function - Function to support GET operation and retrieve keys from sharded the data set into three server instances
*/
func GetOperation(key string) {
// Grab id
id := key
server,_ := Ring.GetNode(id)
fmt.Println("Retrieving key from this server : ",server) //127.0.0.1:3001
//make a corresponding GET request to the server here
url := "http://" + server + "/keys/" + id
response, err := http.Get(url)
if err != nil {
log.Fatal(err)
} else {
defer response.Body.Close()
contents, err := ioutil.ReadAll(response.Body)
if err != nil {
log.Fatal(err)
}
fmt.Printf("The Response is : %s\n", string(contents));
}
fmt.Println("Key retrieved successfully!")
fmt.Println("------------------------------------------------------------")
}
/*
* GetAllOperation function - Function to support GET ALL operation and retrieve ALL keys from any particular server instances
*/
func GetAllOperation(server string) {
fmt.Println("Retrieving ALL keys from this server : ",server)
//make a corresponding GET request to the server here
url := "http://" + server + "/keys"
response, err := http.Get(url)
if err != nil {
log.Fatal(err)
} else {
defer response.Body.Close()
contents, err := ioutil.ReadAll(response.Body)
if err != nil {
log.Fatal(err)
}
fmt.Printf("The Response is : %s\n", string(contents));
}
fmt.Println("Keys retrieved successfully!")
fmt.Println("------------------------------------------------------------")
} |
package markdown
import "testing"
func TestDocument(t *testing.T) {
var tests = []string{
// Empty document.
"",
"",
" ",
"",
// This shouldn't panic.
// https://github.com/russross/blackfriday/issues/172
"[]:<",
"<p>[]:<</p>\n",
// This shouldn't panic.
// https://github.com/russross/blackfriday/issues/173
" [",
"<p>[</p>\n",
}
doTests(t, tests)
}
|
/*
Copyright 2019 The Kubernetes 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
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 slack
// User represents a slack User object.
type User struct {
ID string `json:"id"`
TeamID string `json:"team_id"`
Deleted bool `json:"deleted"`
Color string `json:"color"`
TimeZone string `json:"tz"`
TimeZoneLabel string `json:"tz_label"`
TimeZoneOffset int `json:"tz_offset"`
Profile struct {
AvatarHash string `json:"avatar_hash"`
StatusText string `json:"status_text"`
StatusEmoji string `json:"status_emoji"`
StatusExpiration int `json:"status_expiration"`
RealName string `json:"real_name"`
DisplayName string `json:"display_name"`
Email string `json:"email,omitempty"`
ImageOriginal string `json:"image_original"`
Image24 string `json:"image_24"`
Image32 string `json:"image_32"`
Image48 string `json:"image_48"`
Image72 string `json:"image_72"`
Image192 string `json:"image_192"`
Image512 string `json:"image_512"`
Team string `json:"team"`
} `json:"profile"`
IsAdmin bool `json:"is_admin"`
IsOwner bool `json:"is_owner"`
IsPrimaryOwner bool `json:"is_primary_owner"`
IsRestricted bool `json:"is_restricted"`
IsUltraRestricted bool `json:"is_ultra_restricted"`
IsBot bool `json:"is_bot"`
IsStranger bool `json:"is_stranger"`
IsAppUser bool `json:"is_app_user"`
Has2FA bool `json:"has_2fa"`
Locale string `json:"locale"`
}
// Subteam represents a slack Subteam object.
type Subteam struct {
ID string `json:"id"`
IsUsergroup bool `json:"is_usergroup"`
Name string `json:"name"`
Handle string `json:"handle"`
UserCount int `json:"user_count"`
UpdatedBy string `json:"updated_by"`
CreatedBy string `json:"created_by"`
DeletedBy string `json:"deleted_by"`
CreateTime int `json:"date_create"`
UpdateTime int `json:"date_update"`
DeleteTime int `json:"date_delete"`
}
|
package main
import (
"flag"
"fmt"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"sync"
"golang.org/x/net/html"
)
func getPageURLAndPageNumber() (string, int) {
var numberOfPageToCrawl int
var err error
if len(os.Args) < 2 {
fmt.Printf("Provide url to start crawling")
os.Exit(1)
}
numberOfPageToCrawl = 10
if len(os.Args) > 2 {
if numberOfPageToCrawl, err = strconv.Atoi(os.Args[2]); err != nil {
fmt.Println("Oops. wrong page number provided..")
os.Exit(1)
}
}
uri := os.Args[1]
if uri == "" {
flag.PrintDefaults()
os.Exit(1)
}
return uri, numberOfPageToCrawl
}
func crawl(url, baseURL string, visited *map[string]string, c *counter, wg *sync.WaitGroup, ch chan pageContent) {
//retrieve page content
page, err := parse(url)
wg.Done()
if err != nil {
fmt.Println(err)
return
}
title := getPageTitle(page)
(*visited)[url] = title
links := getPageLinks(nil, page)
internalLinks, externalLinks := separateLinks(links, baseURL)
assets := findAllStaticAssets(nil, page)
singlePageResult := pageContent{
url,
title,
internalLinks,
externalLinks,
assets,
}
//send result through channel for a single page
ch <- singlePageResult
//now we need to crawl all the links we found within the page just crawled until it cross max crawl limit
for _, link := range internalLinks {
if (*visited)[link] == "" && strings.HasPrefix(link, baseURL) {
if c.getNumber() > 0 {
c.UpdateNumber()
fmt.Println("firing crawling on page:", c.getNumber())
go crawl(link, baseURL, visited, c, wg, ch)
}
}
}
}
func getPageTitle(n *html.Node) string {
var title string
if n.Type == html.ElementNode && n.Data == "title" {
return n.FirstChild.Data
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
title = getPageTitle(c)
if title != "" {
break
}
}
return title
}
func getPageLinks(links []string, n *html.Node) []string {
if n.Type == html.ElementNode && n.Data == "a" {
for _, a := range n.Attr {
if a.Key == "href" {
if !isArray(links, a.Val) {
links = append(links, a.Val)
}
}
}
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
links = getPageLinks(links, c)
}
return links
}
func isArray(items []string, value string) bool {
for _, v := range items {
if v == value {
return true
}
}
return false
}
func separateLinks(links []string, baseURL string) (internalLinks []string, externalLinks []string) {
var currentURL string
for _, link := range links {
u, _ := url.Parse(link)
if u.Host != "" {
currentURL = u.Scheme + "://" + u.Host
if strings.Contains(currentURL, baseURL) == false {
externalLinks = append(externalLinks, link)
continue
}
} else {
link = baseURL + link
}
internalLinks = append(internalLinks, link)
}
return
}
func findAllStaticAssets(links []string, n *html.Node) []string {
cssAsset := findCSSAssets(nil, n)
links = append(links, cssAsset...)
jsAssets := findJSAssets(nil, n)
links = append(links, jsAssets...)
return links
}
func findCSSAssets(links []string, n *html.Node) []string {
if n.Type == html.ElementNode && n.Data == "link" {
for _, a := range n.Attr {
if a.Key == "href" {
if !isArray(links, a.Val) {
links = append(links, a.Val)
}
}
}
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
links = findCSSAssets(links, c)
}
return links
}
func findJSAssets(links []string, n *html.Node) []string {
if n.Type == html.ElementNode && n.Data == "script" {
for _, a := range n.Attr {
if a.Key == "src" {
if !isArray(links, a.Val) {
links = append(links, a.Val)
}
}
}
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
links = findJSAssets(links, c)
}
return links
}
func parse(url string) (*html.Node, error) {
response, err := http.Get(url)
if err != nil {
return nil, fmt.Errorf("can not crawl this page: %s", url)
}
respBody, err := html.Parse(response.Body)
if err != nil {
return nil, fmt.Errorf("Cannot parse page")
}
return respBody, err
}
func generatePageSiteMap(page pageContent) {
fmt.Println("<page>")
fmt.Printf(" <title>%s</title>\n", page.title)
fmt.Printf(" <url>%s</url>\n", page.url)
fmt.Println(" <internalLinks>")
for _, link := range page.internalLinks {
fmt.Printf(" <link>%s</link>\n", link)
}
fmt.Println(" </internalLinks>")
fmt.Println(" <externalLinks>")
for _, link := range page.externalLinks {
fmt.Printf(" <link>%s</link>\n", link)
}
fmt.Println(" </externalLinks>")
fmt.Println(" <assets>")
for _, asset := range page.assets {
fmt.Printf(" <asset>%s</asset>\n", asset)
}
fmt.Println(" </assets>")
fmt.Println("</page>")
fmt.Println()
}
|
package xorm
import (
"database/sql"
"fmt"
"reflect"
"runtime/debug"
"testing"
"time"
"strings"
"io/ioutil"
"os"
"encoding/json"
"log"
)
const (
dbUrl = "root:1234@/xtest?charset=utf8"
)
func init() {
SetDebugModel(true)
//f, _ := os.OpenFile("sample.json",os.O_RDONLY, 0777)
f, _ := os.OpenFile("qconf.json",os.O_RDONLY, 0777)
defer f.Close()
configStr, _ := ioutil.ReadAll(f)
var configs map[string]map[string]DbConfig
err := json.Unmarshal([]byte(configStr), &configs)
if err!= nil {
log.Println("decode config error :",err)
}
if false {
v, _ := json.MarshalIndent(configs, "", "\t")
log.Println(string(v))
}
err = InitWithConfig(configs)
if err != nil {
fmt.Println("Register err:", err, string(debug.Stack()))
}
}
//表结构
//CREATE TABLE `user2` (
//`id` int(11) NOT NULL,
//`name` varchar(64) NOT NULL,
//`status` tinyint(4) NOT NULL,
//`ctime` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00' ON UPDATE CURRENT_TIMESTAMP,
//PRIMARY KEY (`id`)
//) DEFAULT CHARSET=utf8
type ormUser struct {
Id int
Name string
Status int
CreateTime time.Time
Other string
}
//必选方法,返回对象对应的数据库名
func (this *ormUser) GetDbName() string {
return "xtest"
}
//可选方法,返回对象对应的表明,默认使用类名转驼峰转下划线的方式匹配
func (this *ormUser) GetTableName() string {
return "user"
}
func (this *ormUser) OrmInfo() map[string]interface{} {
//字段映射配置,可选,默认的使用驼峰转下划线的方式匹配
fieldMap := map[string]string{
"CreateTime": "create_time", //将CreateTime保存到ctime类
"Id": "id", //默认规则,不需配置
}
return map[string]interface{}{
"ignore": "Id,Other", //执行insert时,不需要插入的字段,比如自增的id, 多个字段用逗号分隔,不运行包含空格
"pk": "Id", //主键字段,帮助orm识别哪个列是主键
"fd_map": fieldMap,
}
}
//可选方法,执行写操作前执行
func (this *ormUser) BeforeWrite(typ int) error {
fmt.Println("Before write")
return nil
}
//可选方法,执行写操作后执行
func (this *ormUser) AfterWrite(typ int) error {
fmt.Println("After write")
return nil
}
func TestDbQuery(t *testing.T) {
fmt.Println("=========test db query=========")
var err error
db, err := NewDb("xtest", nil)
// if err != nil {
// t.Error(err)
// }
u := ormUser{}
err = db.QueryRow(&u, "SELECT * FROM user WHERE id=17")
if err != nil && err != ErrNoRows {
t.Error(err.Error())
}
fmt.Println(u)
fmt.Println("=========test query row=========")
users := []ormUser{}
cnt, err := db.QueryRows(&users, "SELECT * FROM USER limit 1,2")
fmt.Println("result count:", cnt)
for _, u := range users {
fmt.Println(u)
}
cnt, err = db.QueryCount("user", "")
fmt.Println("counter:", cnt, "err:", err)
fmt.Println("fetch raw:")
db.QueryRaw(func(rows *sql.Rows) error {
for rows.Next() {
var name string
rows.Scan(&name)
fmt.Println("name:", name)
}
return nil
}, "SELECT name from user where id>?", 1)
}
func TestDbCondition(t *testing.T) {
fmt.Println("=========test db query=========")
var err error
db, err := NewDb("xtest", nil)
// if err != nil {
// t.Error(err)
// }
u := ormUser{}
err = db.QueryRowByCond(&u, "user", NewCondition().And("id", 1))
if err != nil {
t.Error(err.Error())
}
fmt.Println(u)
fmt.Println("=========test query row=========")
users := []ormUser{}
cnt, err := db.QueryRowsByCond(&users, "user", NewCondition().Append("id", 1, ">"))
fmt.Println("result count:", cnt)
for _, u := range users {
fmt.Println(u)
}
cnt, err = db.QueryCount("user", "")
fmt.Println("counter:", cnt, "err:", err)
}
func TestDbWrite(t *testing.T) {
db, err := NewDb("xtest", nil)
if err != nil {
t.Error(err.Error())
}
ret, err := db.Insert("user", "name,create_time", "abc", time.Now())
if err != nil {
t.Error(err.Error())
}
ret.LastInertId()
if err != nil {
t.Error(err.Error())
} else {
fmt.Println("Insert ok, insertId:", ret.LastInertId(), "cnt:", ret.RowsAffected())
}
}
func TestOrmUtil(t *testing.T) {
u := ormUser{Id: 100}
f, _ := getValFromField(&u, "Id")
fmt.Println(f)
val, _ := callMethod(&u, "GetDbName")
fmt.Println(val)
// return
dbName := getDbNameForData(&u)
tableName := getTableNameForData(&u)
fmt.Println("db name:", dbName, "table name:", tableName)
us := []ormUser{}
dbName = getDbNameForData(&us)
tableName = getTableNameForData(&us)
fmt.Println("db name:", dbName, "table name:", tableName)
ptrUs := []*ormUser{}
dbName = getDbNameForData(&ptrUs)
tableName = getTableNameForData(&ptrUs)
fmt.Println("db name:", dbName, "table name:", tableName)
}
func TestOrmMapUtil(t *testing.T) {
obj := ormUser{Id: 100, Name: "fank"}
fMap := GetFieldMap(reflect.TypeOf(obj))
fmt.Println(fMap)
fd, vals, err := getInsertFields(&obj, "", "")
if err != nil {
fmt.Println(err.Error())
}
fmt.Println("fd:", fd, "vals:", vals, "err:", err)
}
func TestOrmQuery(t *testing.T) {
fmt.Println("=========test orm query=========")
u := ormUser{Id: 3}
orm := NewOrm(nil)
orm.QueryObjectByPk(&u, 3)
fmt.Println("user is:", u)
orm.QueryObject(&u, "id=?", 6)
fmt.Println(u)
users := []ormUser{}
cnt, err := orm.QueryObjects(&users, "xtest", "SELECT * FROM user WHERE id > ? LIMIT 1", 1)
if err != nil {
fmt.Println("error:", err)
} else {
fmt.Println("Ret count:", cnt)
for _, u := range users {
fmt.Println(u)
}
}
userPtrs := []*ormUser{}
cnt, err = orm.QueryObjects(&userPtrs, "xtest", "SELECT * FROM user WHERE id > ? AND id < 10 LIMIT 2", 1)
if err != nil {
fmt.Println("error:", err)
} else {
fmt.Println("Ret count:", cnt)
for _, u := range userPtrs {
fmt.Println(u)
}
}
fmt.Println("Query by In Condition:")
cnt, err = orm.QueryObjectsByCond(&users, "xtest", "user", NewCondition().In("id", 1, 2, 3).Fields("id,name").OrderBy("id", "desc").Limit(2))
if err != nil {
fmt.Println("error:", err)
} else {
fmt.Println("Ret count:", cnt)
for _, u := range users {
fmt.Println(u)
}
}
}
//func TestGenQuery(t *testing.T){
// return
// // col1 = b AND col2>c OR d!=d AND col4 IN (a,b,c) ORDER BY time DESC,name ASC LIMIT 10, 1
// cond := NewCondition()
// cond.Eq("col1", "v1").Gt("col2", 100).In("col3", 1,2,3,4).NotIn("col4", "a").Like("col5", "%5").OrderBy("col1", "DESC").OrderBy("col2", "ASC").Limit(1,100)
// sql, params := cond.GenQuery()
// fmt.Println("sql:", sql)
// fmt.Println("params:", params)
//}
func TestOrmWriteBatch(t *testing.T) {
users := []*ormUser{}
for i := 0; i < 2; i++ {
u := ormUser{Id: 100, Name: "aaaaabbc", CreateTime: time.Now()}
users = append(users, &u)
}
orm := NewOrm(nil)
cnt, err := orm.BatchInsert(users[0], &users, "Name", true)
if err != nil {
fmt.Println("err:", err)
} else {
fmt.Println("Insert count", cnt)
}
}
func TestCondition(t *testing.T) {
cond := NewCondition().And("id", 1).And("gender", "0", "!=").Or("age", 10, ">").In("name", []interface{}{"1", "2"}).OrderBy("id", "desc").OrderBy("age", "ASC").Limit(1, 100)
condStr, values := cond.GetCondition()
fmt.Println("cond:", condStr, "values:", values)
}
func TestOrmWrite(t *testing.T) {
fmt.Println("=====Test orm write=========")
u := &ormUser{Id: 117, Name: "2222", CreateTime: time.Now(), Status: 5}
orm := NewOrm(nil)
// ret, err:=orm.Insert(u)
//
// if err!=nil{
// t.Error(err.Error())
// }else{
// fmt.Println("Insert Ok:", ret.LastInertId())
// }
// ret, err := orm.InsertOrUpdate(u)
// if err!=nil{
// t.Error(err.Error())
// }else{
// fmt.Println("Insert or update Ok:", ret.LastInertId(), "cnt:", ret.RowsAffected())
// }
//
u.Name = "b"
u.Status = 5
_, err := orm.Update(u, "", "Name,CreateTimes")
if err != nil {
t.Error(err.Error())
}
// deleteCnt, err := orm.Delete(u)
// if err!=nil{
// t.Error(err.Error())
// }else{
// fmt.Println("Delete Ok: ", deleteCnt)
// }
}
func TestTransation(t *testing.T) {
return
db, err := NewDb("xtest", nil)
if err != nil {
t.Error(err.Error())
}
orm := NewOrmWithDb(db, nil)
err = db.Begin()
if err != nil {
t.Error(err.Error())
}
u := &ormUser{Id: 117, Name: "rollback", CreateTime: time.Now()}
_, err = orm.Insert(u)
if err != nil {
t.Error(err.Error())
}
err = db.Rollback()
if err != nil {
t.Error(err.Error())
} else {
fmt.Println("Rollback ok")
}
u.Name = "commit"
err = db.Begin()
_, err = orm.Insert(u)
if err != nil {
t.Error(err.Error())
}
err = db.Commit()
if err != nil {
t.Error(err.Error())
} else {
fmt.Println("Commit ok")
}
}
//设置自定义的表名、列名映射函数
func TestCustomMapFunc(t *testing.T) {
//设置表名映射规则
SetTableMapFunc(func (tableName string) string{
col := strings.ToLower(tableName[0:1]) + tableName[1:]
fmt.Printf("className:%v tableName:%v\n", tableName, col)
return col
})
//设置列名映射规则
SetFieldMapFunc(func (fieldName string) string{
col := strings.ToLower(fieldName[0:1]) + fieldName[1:]
fmt.Printf("fieldName:%v columnName:%v\n", fieldName, col)
return col
})
var user ormUser
orm := NewOrm(nil)
err := orm.QueryObject(&user, "id=?", 1)
fmt.Println("TestCustomMapFunc err:", err)
}
|
package handler
import (
"context"
"github.com/caos/logging"
"github.com/caos/zitadel/internal/eventstore/models"
es_models "github.com/caos/zitadel/internal/eventstore/models"
"github.com/caos/zitadel/internal/eventstore/spooler"
"github.com/caos/zitadel/internal/iam/repository/eventsourcing/model"
iam_model "github.com/caos/zitadel/internal/iam/repository/view/model"
usr_model "github.com/caos/zitadel/internal/user/model"
usr_event "github.com/caos/zitadel/internal/user/repository/eventsourcing"
usr_es_model "github.com/caos/zitadel/internal/user/repository/eventsourcing/model"
)
type IamMember struct {
handler
userEvents *usr_event.UserEventstore
}
const (
iamMemberTable = "adminapi.iam_members"
)
func (m *IamMember) ViewModel() string {
return iamMemberTable
}
func (m *IamMember) EventQuery() (*models.SearchQuery, error) {
sequence, err := m.view.GetLatestIamMemberSequence()
if err != nil {
return nil, err
}
return es_models.NewSearchQuery().
AggregateTypeFilter(model.IamAggregate, usr_es_model.UserAggregate).
LatestSequenceFilter(sequence.CurrentSequence), nil
}
func (m *IamMember) Reduce(event *models.Event) (err error) {
switch event.AggregateType {
case model.IamAggregate:
err = m.processIamMember(event)
case usr_es_model.UserAggregate:
err = m.processUser(event)
}
return err
}
func (m *IamMember) processIamMember(event *models.Event) (err error) {
member := new(iam_model.IamMemberView)
switch event.Type {
case model.IamMemberAdded:
member.AppendEvent(event)
m.fillData(member)
case model.IamMemberChanged:
err := member.SetData(event)
if err != nil {
return err
}
member, err = m.view.IamMemberByIDs(event.AggregateID, member.UserID)
if err != nil {
return err
}
member.AppendEvent(event)
case model.IamMemberRemoved:
err := member.SetData(event)
if err != nil {
return err
}
return m.view.DeleteIamMember(event.AggregateID, member.UserID, event.Sequence)
default:
return m.view.ProcessedIamMemberSequence(event.Sequence)
}
if err != nil {
return err
}
return m.view.PutIamMember(member, member.Sequence)
}
func (m *IamMember) processUser(event *models.Event) (err error) {
switch event.Type {
case usr_es_model.UserProfileChanged,
usr_es_model.UserEmailChanged:
members, err := m.view.IamMembersByUserID(event.AggregateID)
if err != nil {
return err
}
user, err := m.userEvents.UserByID(context.Background(), event.AggregateID)
if err != nil {
return err
}
for _, member := range members {
m.fillUserData(member, user)
err = m.view.PutIamMember(member, event.Sequence)
if err != nil {
return err
}
}
default:
return m.view.ProcessedIamMemberSequence(event.Sequence)
}
return nil
}
func (m *IamMember) fillData(member *iam_model.IamMemberView) (err error) {
user, err := m.userEvents.UserByID(context.Background(), member.UserID)
if err != nil {
return err
}
m.fillUserData(member, user)
return nil
}
func (m *IamMember) fillUserData(member *iam_model.IamMemberView, user *usr_model.User) {
member.UserName = user.UserName
member.FirstName = user.FirstName
member.LastName = user.LastName
member.Email = user.EmailAddress
member.DisplayName = user.DisplayName
}
func (m *IamMember) OnError(event *models.Event, err error) error {
logging.LogWithFields("SPOOL-Ld9ow", "id", event.AggregateID).WithError(err).Warn("something went wrong in iammember handler")
return spooler.HandleError(event, err, m.view.GetLatestIamMemberFailedEvent, m.view.ProcessedIamMemberFailedEvent, m.view.ProcessedIamMemberSequence, m.errorCountUntilSkip)
}
|
package module
import (
"fmt"
"github.com/dnaeon/gru/graph"
"github.com/dnaeon/gru/resource"
)
// ResourceMap type is a map which keys are the
// resource ids and their values are the actual resources
type ResourceMap map[string]resource.Resource
// ResourceCollection creates a map of the unique resources
// contained within the provided modules.
func ResourceCollection(modules []*Module) (ResourceMap, error) {
moduleMap := make(map[string]string)
resourceMap := make(ResourceMap)
for _, m := range modules {
for _, r := range m.Resources {
id := r.ResourceID()
if _, ok := resourceMap[id]; ok {
return resourceMap, fmt.Errorf("Duplicate resource %s in %s, previous declaration was in %s", id, m.Name, moduleMap[id])
}
moduleMap[id] = m.Name
resourceMap[id] = r
}
}
return resourceMap, nil
}
// DependencyGraph builds a dependency graph for the resource collection
func (rm ResourceMap) DependencyGraph() (*graph.Graph, error) {
g := graph.New()
// A map containing the resource ids and their nodes in the graph
nodes := make(map[string]*graph.Node)
for name := range rm {
node := graph.NewNode(name)
nodes[name] = node
g.AddNode(node)
}
// Connect the nodes in the graph
for name, r := range rm {
before := r.WantBefore()
after := r.WantAfter()
// Connect current resource with the ones that happen after it
for _, dep := range after {
if _, ok := rm[dep]; !ok {
e := fmt.Errorf("Resource %s wants %s, which does not exist", name, dep)
return g, e
}
g.AddEdge(nodes[name], nodes[dep])
}
// Connect current resource with the ones that happen before it
for _, dep := range before {
if _, ok := rm[dep]; !ok {
e := fmt.Errorf("Resource %s wants %s, which does not exist", name, dep)
return g, e
}
g.AddEdge(nodes[dep], nodes[name])
}
}
return g, nil
}
|
package opslevel
// OpsLevel 开放代理套餐种类
type OpsLevel = string
const (
// NORMAL 普通套餐
NORMAL OpsLevel = "normal"
// VIP VIP套餐
VIP OpsLevel = "vip"
// SVIP SVIP套餐
SVIP OpsLevel = "svip"
// ENT 专业版套餐
ENT OpsLevel = "ent"
)
|
package scanner
import (
"testing"
"github.com/lukeomalley/glocks/token"
)
func TestScanner(t *testing.T) {
input := `
var a = 10;
var b = 20;
var c = a + b;
print c;
`
tests := []struct {
expectedType token.Type
expectedLexeme string
}{
{token.VAR, "var"},
{token.IDENTIFIER, "a"},
{token.EQUAL, "="},
{token.NUMBER, "10"},
{token.SEMICOLON, ";"},
{token.VAR, "var"},
{token.IDENTIFIER, "b"},
{token.EQUAL, "="},
{token.NUMBER, "20"},
{token.SEMICOLON, ";"},
{token.VAR, "var"},
{token.IDENTIFIER, "c"},
{token.EQUAL, "="},
{token.IDENTIFIER, "a"},
{token.PLUS, "+"},
{token.IDENTIFIER, "b"},
{token.SEMICOLON, ";"},
{token.PRINT, "print"},
{token.IDENTIFIER, "c"},
{token.SEMICOLON, ";"},
}
scanner := NewScanner(input)
tokens := scanner.ScanTokens()
if len(tests) != len(tokens)-1 {
t.Fatalf("tests - Number of tokens is wrong. Expected: %d, but got %d", len(tests), len(tokens))
}
for i, tt := range tests {
if tt.expectedType != tokens[i].Type {
t.Fatalf("[test %d] - Token type wrong. Expected: %q, but got %q", i, tt.expectedType, tokens[i].Type)
}
if tt.expectedLexeme != tokens[i].Lexeme {
t.Fatalf("[test %d] - Token lexeme wrong. Expected: %q, but got %q", i, tt.expectedLexeme, tokens[i].Lexeme)
}
}
if tokens[len(tokens)-1].Type != token.EOF {
t.Fatalf("tests - Final token is wrong. Expected %q, but got %q", token.EOF, tokens[len(tokens)-1])
}
}
|
// Copyright (c) Red Hat, Inc.
// Copyright Contributors to the Open Cluster Management project
package managedcluster
import (
"fmt"
"os"
"strconv"
clusterv1 "github.com/open-cluster-management/api/cluster/v1"
workv1 "github.com/open-cluster-management/api/work/v1"
hivev1 "github.com/openshift/hive/apis/hive/v1"
corev1 "k8s.io/api/core/v1"
rbacv1 "k8s.io/api/rbac/v1"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/version"
"sigs.k8s.io/controller-runtime/pkg/controller"
"sigs.k8s.io/controller-runtime/pkg/handler"
"sigs.k8s.io/controller-runtime/pkg/manager"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
"sigs.k8s.io/controller-runtime/pkg/source"
)
const (
_v1APIExtensionKubeMinVersion = "v1.16.0"
)
var v1APIExtensionMinVersion = version.MustParseGeneric(_v1APIExtensionKubeMinVersion)
// Add creates a new ManagedCluster Controller and adds it to the Manager. The Manager will set fields on the Controller
// and Start it when the Manager is Started.
func Add(mgr manager.Manager) error {
return add(mgr, newReconciler(mgr))
}
// newReconciler returns a new reconcile.Reconciler
func newReconciler(mgr manager.Manager) reconcile.Reconciler {
client := newCustomClient(mgr.GetClient(), mgr.GetAPIReader())
return &ReconcileManagedCluster{client: client, scheme: mgr.GetScheme()}
}
// add adds a new Controller to mgr with r as the reconcile.Reconciler
func add(mgr manager.Manager, r reconcile.Reconciler) error {
maxConcurrentReconciles := 1
if os.Getenv("MAX_CONCURRENT_RECONCILES") != "" {
var err error
maxConcurrentReconciles, err = strconv.Atoi(os.Getenv("MAX_CONCURRENT_RECONCILES"))
log.Info(fmt.Sprintf("MAX_CONCURRENT_RECONCILES=%d", maxConcurrentReconciles))
if err != nil {
return err
}
}
// Create a new controller
c, err := controller.New("managedcluster-controller",
mgr,
controller.Options{Reconciler: r,
MaxConcurrentReconciles: maxConcurrentReconciles,
})
if err != nil {
return err
}
// Watch for changes to primary resource ManagedCluster
err = c.Watch(
&source.Kind{Type: &clusterv1.ManagedCluster{}},
&handler.EnqueueRequestForObject{},
newManagedClusterSpecPredicate(),
)
if err != nil {
return err
}
// Watch for changes to secondary resource Pods and requeue the owner ManagedCluster
err = c.Watch(
&source.Kind{Type: &rbacv1.ClusterRole{}},
&handler.EnqueueRequestForOwner{
IsController: true,
OwnerType: &clusterv1.ManagedCluster{},
},
)
if err != nil {
log.Error(err, "Fail to add Watch for ClusterRole to controller")
return err
}
err = c.Watch(
&source.Kind{Type: &corev1.ServiceAccount{}},
&handler.EnqueueRequestForOwner{
IsController: true,
OwnerType: &clusterv1.ManagedCluster{},
},
)
if err != nil {
log.Error(err, "Fail to add Watch for ServiceAccount to controller")
return err
}
err = c.Watch(
&source.Kind{Type: &hivev1.ClusterDeployment{}},
&handler.EnqueueRequestsFromMapFunc{
ToRequests: handler.ToRequestsFunc(func(obj handler.MapObject) []reconcile.Request {
return []reconcile.Request{
{
NamespacedName: types.NamespacedName{
Name: obj.Meta.GetName(),
Namespace: obj.Meta.GetNamespace(),
},
},
}
}),
},
)
if err != nil {
log.Error(err, "Fail to add Watch for ClusterDeployment to controller")
return err
}
err = c.Watch(
&source.Kind{Type: &rbacv1.ClusterRoleBinding{}},
&handler.EnqueueRequestForOwner{
IsController: true,
OwnerType: &clusterv1.ManagedCluster{},
},
)
if err != nil {
log.Error(err, "Fail to add Watch for ClusterRoleBinding to controller")
return err
}
err = c.Watch(
&source.Kind{Type: &workv1.ManifestWork{}},
&handler.EnqueueRequestForOwner{
IsController: true,
OwnerType: &clusterv1.ManagedCluster{},
},
newManifestWorkSpecPredicate(),
)
if err != nil {
log.Error(err, "Fail to add Watch for ManifestWork to controller")
return err
}
return nil
}
|
package operations
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"time"
"github.com/go-openapi/errors"
"github.com/go-openapi/runtime"
cr "github.com/go-openapi/runtime/client"
"github.com/go-openapi/swag"
strfmt "github.com/go-openapi/strfmt"
)
// NewCreateFileViaFormParams creates a new CreateFileViaFormParams object
// with the default values initialized.
func NewCreateFileViaFormParams() *CreateFileViaFormParams {
var (
createFoldersDefault bool = bool(true)
)
return &CreateFileViaFormParams{
CreateFolders: &createFoldersDefault,
timeout: cr.DefaultTimeout,
}
}
// NewCreateFileViaFormParamsWithTimeout creates a new CreateFileViaFormParams object
// with the default values initialized, and the ability to set a timeout on a request
func NewCreateFileViaFormParamsWithTimeout(timeout time.Duration) *CreateFileViaFormParams {
var (
createFoldersDefault bool = bool(true)
)
return &CreateFileViaFormParams{
CreateFolders: &createFoldersDefault,
timeout: timeout,
}
}
/*CreateFileViaFormParams contains all the parameters to send to the API endpoint
for the create file via form operation typically these are written to a http.Request
*/
type CreateFileViaFormParams struct {
/*CreateFolders*/
CreateFolders *bool
/*URI*/
URI *string
timeout time.Duration
}
// WithCreateFolders adds the createFolders to the create file via form params
func (o *CreateFileViaFormParams) WithCreateFolders(CreateFolders *bool) *CreateFileViaFormParams {
o.CreateFolders = CreateFolders
return o
}
// WithURI adds the uri to the create file via form params
func (o *CreateFileViaFormParams) WithURI(URI *string) *CreateFileViaFormParams {
o.URI = URI
return o
}
// WriteToRequest writes these params to a swagger request
func (o *CreateFileViaFormParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error {
r.SetTimeout(o.timeout)
var res []error
if o.CreateFolders != nil {
// query param createFolders
var qrCreateFolders bool
if o.CreateFolders != nil {
qrCreateFolders = *o.CreateFolders
}
qCreateFolders := swag.FormatBool(qrCreateFolders)
if qCreateFolders != "" {
if err := r.SetQueryParam("createFolders", qCreateFolders); err != nil {
return err
}
}
}
if o.URI != nil {
// query param uri
var qrURI string
if o.URI != nil {
qrURI = *o.URI
}
qURI := qrURI
if qURI != "" {
if err := r.SetQueryParam("uri", qURI); err != nil {
return err
}
}
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
|
package create
import (
"os"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"github.com/dolittle/platform-api/pkg/aiven"
platformK8s "github.com/dolittle/platform-api/pkg/platform/k8s"
"github.com/dolittle/platform-api/pkg/platform/microservice/m3connector"
"github.com/dolittle/platform-api/pkg/platform/microservice/m3connector/k8s"
)
var environmentCMD = &cobra.Command{
Use: "environment",
Short: "",
Long: ``,
Run: func(cmd *cobra.Command, args []string) {
logrus.SetFormatter(&logrus.JSONFormatter{})
logrus.SetOutput(os.Stdout)
logger := logrus.StandardLogger()
logContext := logger.WithFields(logrus.Fields{
"command": "environment",
})
apiToken := viper.GetString("tools.m3connector.aiven.apiToken")
if apiToken == "" {
logContext.Fatal("you have to provide an Aiven api token")
}
project := viper.GetString("tools.m3connector.aiven.project")
service := viper.GetString("tools.m3connector.aiven.service")
if project == "" || service == "" {
logContext.Fatal("you have to specify both the project and the service")
}
customerID, _ := cmd.Flags().GetString("customer-id")
applicationID, _ := cmd.Flags().GetString("application-id")
environment, _ := cmd.Flags().GetString("environment")
if customerID == "" || applicationID == "" || environment == "" {
logContext.Fatal("you have to specify the customerID, applicationID and environment")
}
logContext = logContext.WithFields(logrus.Fields{
"customer_id": customerID,
"application_id": applicationID,
"environment": environment,
})
aiven, err := aiven.NewClient(apiToken, project, service, logContext)
if err != nil {
logContext.Fatal(err)
}
k8sClient, _ := platformK8s.InitKubernetesClient()
k8sRepo := k8s.NewM3ConnectorRepo(k8sClient, logContext.Logger)
m3connector := m3connector.NewM3Connector(aiven, k8sRepo, logContext)
err = m3connector.CreateEnvironment(customerID, applicationID, environment)
if err != nil {
logContext.Fatal(err)
}
logContext.Info("done")
},
}
func init() {
environmentCMD.Flags().String("customer-id", "", "The customers ID")
environmentCMD.Flags().String("application-id", "", "The applications ID")
environmentCMD.Flags().String("environment", "", "The environment")
}
|
package identity
import (
"bytes"
"context"
"crypto/md5"
"encoding/json"
"fmt"
"os"
"text/template"
"github.com/dexidp/dex/server"
dexstorage "github.com/dexidp/dex/storage"
"github.com/ghodss/yaml"
"github.com/pkg/errors"
kotsv1beta1 "github.com/replicatedhq/kots/kotskinds/apis/kots/v1beta1"
dextypes "github.com/replicatedhq/kots/pkg/identity/types/dex"
"github.com/replicatedhq/kots/pkg/ingress"
kotsadmtypes "github.com/replicatedhq/kots/pkg/kotsadm/types"
kotsadmversion "github.com/replicatedhq/kots/pkg/kotsadm/version"
"github.com/segmentio/ksuid"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
extensionsv1beta1 "k8s.io/api/extensions/v1beta1"
rbacv1 "k8s.io/api/rbac/v1"
kuberneteserrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
k8stypes "k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/intstr"
"k8s.io/client-go/kubernetes"
)
const (
DexDeploymentName, DexServiceName, DexIngressName = "kotsadm-dex", "kotsadm-dex", "kotsadm-dex"
DexServiceAccountName, DexRoleName, DexRoleBindingName = "kotsadm-dex", "kotsadm-dex", "kotsadm-dex"
DexSecretName = "kotsadm-dex"
DexPostgresSecretName = "kotsadm-dex-postgres"
)
var (
AdditionalLabels = map[string]string{
KotsIdentityLabelKey: KotsIdentityLabelValue,
}
)
func Deploy(ctx context.Context, clientset kubernetes.Interface, namespace string, identityConfig kotsv1beta1.IdentityConfig, ingressConfig kotsv1beta1.IngressConfig, registryOptions *kotsadmtypes.KotsadmOptions) error {
if err := ValidateConfig(ctx, namespace, identityConfig, ingressConfig); err != nil {
return errors.Wrap(err, "invalid identity config")
}
if err := ensureServiceAccount(ctx, clientset, namespace); err != nil {
return errors.Wrap(err, "failed to ensure service account")
}
if err := ensureRole(ctx, clientset, namespace); err != nil {
return errors.Wrap(err, "failed to ensure role")
}
if err := ensureRoleBinding(ctx, clientset, namespace); err != nil {
return errors.Wrap(err, "failed to ensure role binding")
}
marshalledDexConfig, err := getDexConfig(ctx, clientset, namespace, identityConfig.Spec, ingressConfig.Spec)
if err != nil {
return errors.Wrap(err, "failed to marshal dex config")
}
if err := ensureSecret(ctx, clientset, namespace, marshalledDexConfig); err != nil {
return errors.Wrap(err, "failed to ensure secret")
}
if err := ensureDeployment(ctx, clientset, namespace, marshalledDexConfig, registryOptions); err != nil {
return errors.Wrap(err, "failed to ensure deployment")
}
if err := ensureService(ctx, clientset, namespace, identityConfig.Spec.IngressConfig); err != nil {
return errors.Wrap(err, "failed to ensure service")
}
if err := ensureIngress(ctx, clientset, namespace, identityConfig.Spec.IngressConfig); err != nil {
return errors.Wrap(err, "failed to ensure ingress")
}
return nil
}
func Configure(ctx context.Context, clientset kubernetes.Interface, namespace string, identityConfig kotsv1beta1.IdentityConfig, ingressConfig kotsv1beta1.IngressConfig) error {
if err := ValidateConfig(ctx, namespace, identityConfig, ingressConfig); err != nil {
return errors.Wrap(err, "invalid identity config")
}
marshalledDexConfig, err := getDexConfig(ctx, clientset, namespace, identityConfig.Spec, ingressConfig.Spec)
if err != nil {
return errors.Wrap(err, "failed to marshal dex config")
}
if err := ensureSecret(ctx, clientset, namespace, marshalledDexConfig); err != nil {
return errors.Wrap(err, "failed to ensure secret")
}
if err := patchDeploymentSecret(ctx, clientset, namespace, marshalledDexConfig); err != nil {
return errors.Wrap(err, "failed to patch deployment secret")
}
return nil
}
func ensureSecret(ctx context.Context, clientset kubernetes.Interface, namespace string, marshalledConfig []byte) error {
secret, err := secretResource(DexSecretName, marshalledConfig)
if err != nil {
return errors.Wrap(err, "failed to get secret resource")
}
existingSecret, err := clientset.CoreV1().Secrets(namespace).Get(ctx, DexSecretName, metav1.GetOptions{})
if err != nil {
if !kuberneteserrors.IsNotFound(err) {
return errors.Wrap(err, "failed to get existing secret")
}
_, err = clientset.CoreV1().Secrets(namespace).Create(ctx, secret, metav1.CreateOptions{})
if err != nil {
return errors.Wrap(err, "failed to create secret")
}
return nil
}
existingSecret = updateSecret(existingSecret, secret)
_, err = clientset.CoreV1().Secrets(namespace).Update(ctx, existingSecret, metav1.UpdateOptions{})
if err != nil {
return errors.Wrap(err, "failed to update secret")
}
return nil
}
func getExistingDexConfig(ctx context.Context, clientset kubernetes.Interface, namespace string) (*dextypes.Config, error) {
dexConfig := dextypes.Config{}
existingSecret, err := clientset.CoreV1().Secrets(namespace).Get(ctx, DexSecretName, metav1.GetOptions{})
if err != nil {
if !kuberneteserrors.IsNotFound(err) {
return nil, errors.Wrap(err, "failed to get existing secret")
}
return &dexConfig, nil
}
err = yaml.Unmarshal(existingSecret.Data["dexConfig.yaml"], &dexConfig)
if err != nil {
return nil, errors.Wrap(err, "failed to unmarshal dexConfig.yaml")
}
return &dexConfig, nil
}
func getDexPostgresPassword(ctx context.Context, clientset kubernetes.Interface, namespace string) (string, error) {
secret, err := clientset.CoreV1().Secrets(namespace).Get(ctx, DexPostgresSecretName, metav1.GetOptions{})
if err != nil {
return "", errors.Wrap(err, "failed to get postgress secret")
}
return string(secret.Data["password"]), nil
}
func getDexConfig(ctx context.Context, clientset kubernetes.Interface, namespace string, identitySpec kotsv1beta1.IdentityConfigSpec, ingressSpec kotsv1beta1.IngressConfigSpec) ([]byte, error) {
existingConfig, err := getExistingDexConfig(ctx, clientset, namespace)
if err != nil {
return nil, errors.Wrap(err, "failed to get existing dex config")
}
postgresPassword, err := getDexPostgresPassword(ctx, clientset, namespace)
if err != nil {
return nil, errors.Wrap(err, "failed to get dex postgres password")
}
kotsadmAddress := identitySpec.AdminConsoleAddress
if kotsadmAddress == "" && ingressSpec.Enabled {
kotsadmAddress = ingress.GetAddress(ingressSpec)
}
staticClients := existingConfig.StaticClients
kotsadmClient := dexstorage.Client{
ID: "kotsadm",
Name: "kotsadm",
Secret: ksuid.New().String(),
RedirectURIs: []string{
fmt.Sprintf("%s/api/v1/oidc/login/callback", kotsadmAddress),
},
}
foundKotsClient := false
for i := range staticClients {
if staticClients[i].ID == "kotsadm" {
staticClients[i].RedirectURIs = kotsadmClient.RedirectURIs
foundKotsClient = true
}
}
if !foundKotsClient {
staticClients = append(staticClients, kotsadmClient)
}
config := dextypes.Config{
Logger: dextypes.Logger{
Level: "debug",
Format: "text",
},
Issuer: DexIssuerURL(identitySpec),
Storage: dextypes.Storage{
Type: "postgres",
Config: dextypes.Postgres{
NetworkDB: dextypes.NetworkDB{
Database: "dex",
User: "dex",
Host: "kotsadm-postgres",
Password: postgresPassword,
},
SSL: dextypes.SSL{
Mode: "disable", // TODO ssl
},
},
},
Web: dextypes.Web{
HTTP: "0.0.0.0:5556",
},
Frontend: server.WebConfig{
Issuer: "KOTS",
},
OAuth2: dextypes.OAuth2{
SkipApprovalScreen: true,
AlwaysShowLoginScreen: true,
},
StaticClients: staticClients,
EnablePasswordDB: false,
}
if len(identitySpec.DexConnectors.Value) > 0 {
dexConnectors, err := IdentityDexConnectorsToDexTypeConnectors(identitySpec.DexConnectors.Value)
if err != nil {
return nil, errors.Wrap(err, "failed to unmarshal dex connectors")
}
config.StaticConnectors = dexConnectors
}
if err := config.Validate(); err != nil {
return nil, errors.Wrap(err, "failed to validate dex config")
}
marshalledConfig, err := yaml.Marshal(config)
if err != nil {
return nil, errors.Wrap(err, "failed to marshal dex config")
}
buf := bytes.NewBuffer(nil)
t, err := template.New("kotsadm-dex").Funcs(template.FuncMap{
"OIDCIdentityCallbackURL": func() string { return DexCallbackURL(identitySpec) },
}).Parse(string(marshalledConfig))
if err != nil {
return nil, errors.Wrap(err, "failed to parse dex config for templating")
}
if err := t.Execute(buf, nil); err != nil {
return nil, errors.Wrap(err, "failed to execute template")
}
return buf.Bytes(), nil
}
func secretResource(secretName string, marshalledConfig []byte) (*corev1.Secret, error) {
return &corev1.Secret{
TypeMeta: metav1.TypeMeta{
APIVersion: "v1",
Kind: "Secret",
},
ObjectMeta: metav1.ObjectMeta{
Name: secretName,
Labels: kotsadmtypes.GetKotsadmLabels(AdditionalLabels),
},
Data: map[string][]byte{
"dexConfig.yaml": marshalledConfig,
},
}, nil
}
func updateSecret(existingSecret, desiredSecret *corev1.Secret) *corev1.Secret {
existingSecret.Data = desiredSecret.Data
return existingSecret
}
func ensureDeployment(ctx context.Context, clientset kubernetes.Interface, namespace string, marshalledDexConfig []byte, registryOptions *kotsadmtypes.KotsadmOptions) error {
configChecksum := fmt.Sprintf("%x", md5.Sum(marshalledDexConfig))
deployment := deploymentResource(DexDeploymentName, DexServiceAccountName, configChecksum, namespace, registryOptions)
existingDeployment, err := clientset.AppsV1().Deployments(namespace).Get(ctx, DexDeploymentName, metav1.GetOptions{})
if err != nil {
if !kuberneteserrors.IsNotFound(err) {
return errors.Wrap(err, "failed to get existing deployment")
}
_, err = clientset.AppsV1().Deployments(namespace).Create(ctx, deployment, metav1.CreateOptions{})
if err != nil {
return errors.Wrap(err, "failed to create deployment")
}
return nil
}
existingDeployment = updateDeployment(existingDeployment, deployment)
_, err = clientset.AppsV1().Deployments(namespace).Update(ctx, existingDeployment, metav1.UpdateOptions{})
if err != nil {
return errors.Wrap(err, "failed to update deployment")
}
return nil
}
func patchDeploymentSecret(ctx context.Context, clientset kubernetes.Interface, namespace string, marshalledDexConfig []byte) error {
configChecksum := fmt.Sprintf("%x", md5.Sum(marshalledDexConfig))
deployment := deploymentResource(DexDeploymentName, DexServiceAccountName, configChecksum, namespace, nil)
patch := fmt.Sprintf(`{"spec":{"template":{"metadata":{"annotations":{"kots.io/dex-secret-checksum":"%s"}}}}}`, deployment.Spec.Template.ObjectMeta.Annotations["kots.io/dex-secret-checksum"])
_, err := clientset.AppsV1().Deployments(namespace).Patch(ctx, deployment.Name, k8stypes.StrategicMergePatchType, []byte(patch), metav1.PatchOptions{})
if err != nil {
return errors.Wrap(err, "failed to patch deployment")
}
return nil
}
var (
dexCPUResource = resource.MustParse("100m")
dexMemoryResource = resource.MustParse("50Mi")
)
func deploymentResource(deploymentName, serviceAccountName, configChecksum, namespace string, registryOptions *kotsadmtypes.KotsadmOptions) *appsv1.Deployment {
replicas := int32(2)
volume := configSecretVolume()
image := "quay.io/dexidp/dex:v2.26.0"
imagePullSecrets := []corev1.LocalObjectReference{}
if registryOptions != nil {
if s := kotsadmversion.KotsadmPullSecret(namespace, *registryOptions); s != nil {
image = fmt.Sprintf("%s/dex:%s", kotsadmversion.KotsadmRegistry(*registryOptions), kotsadmversion.KotsadmTag(*registryOptions))
imagePullSecrets = []corev1.LocalObjectReference{
{
Name: s.ObjectMeta.Name,
},
}
}
}
return &appsv1.Deployment{
TypeMeta: metav1.TypeMeta{
APIVersion: "apps/v1",
Kind: "Deployment",
},
ObjectMeta: metav1.ObjectMeta{
Name: deploymentName,
Labels: kotsadmtypes.GetKotsadmLabels(AdditionalLabels),
},
Spec: appsv1.DeploymentSpec{
Replicas: &replicas,
Selector: &metav1.LabelSelector{
MatchLabels: map[string]string{
"app": "kotsadm-dex",
},
},
Template: corev1.PodTemplateSpec{
ObjectMeta: metav1.ObjectMeta{
Labels: map[string]string{
"app": "kotsadm-dex",
},
Annotations: map[string]string{
"kots.io/dex-secret-checksum": configChecksum,
},
},
Spec: corev1.PodSpec{
ServiceAccountName: serviceAccountName,
ImagePullSecrets: imagePullSecrets,
Containers: []corev1.Container{
{
Image: image,
ImagePullPolicy: corev1.PullIfNotPresent,
Name: "dex",
Command: []string{"/usr/local/bin/dex", "serve", "/etc/dex/cfg/dexConfig.yaml"},
Ports: []corev1.ContainerPort{
{Name: "http", ContainerPort: 5556},
},
VolumeMounts: []corev1.VolumeMount{
{Name: volume.Name, MountPath: "/etc/dex/cfg"},
},
Resources: corev1.ResourceRequirements{
// Limits: corev1.ResourceList{
// "cpu": dexCPUResource,
// "memory": dexMemoryResource,
// },
Requests: corev1.ResourceList{
"cpu": dexCPUResource,
"memory": dexMemoryResource,
},
},
},
},
Volumes: []corev1.Volume{
volume,
},
},
},
},
}
}
func configSecretVolume() corev1.Volume {
return corev1.Volume{
Name: "config",
VolumeSource: corev1.VolumeSource{
Secret: &corev1.SecretVolumeSource{
SecretName: DexSecretName,
},
},
}
}
func updateDeployment(existingDeployment, desiredDeployment *appsv1.Deployment) *appsv1.Deployment {
if len(existingDeployment.Spec.Template.Spec.Containers) == 0 {
// wtf
return desiredDeployment
}
if existingDeployment.Spec.Template.Annotations == nil {
existingDeployment.Spec.Template.ObjectMeta.Annotations = map[string]string{}
}
existingDeployment.Spec.Template.ObjectMeta.Annotations["kots.io/dex-secret-checksum"] = desiredDeployment.Spec.Template.ObjectMeta.Annotations["kots.io/dex-secret-checksum"]
existingDeployment.Spec.Template.Spec.Containers[0].Image = desiredDeployment.Spec.Template.Spec.Containers[0].Image
existingDeployment = updateDeploymentConfigSecretVolume(existingDeployment, desiredDeployment)
return existingDeployment
}
func updateDeploymentConfigSecretVolume(existingDeployment *appsv1.Deployment, desiredDeployment *appsv1.Deployment) *appsv1.Deployment {
if len(existingDeployment.Spec.Template.Spec.Containers) == 0 {
return desiredDeployment
}
newConfigSecretVolume := configSecretVolume()
newConfigSecretVolumeMount := corev1.VolumeMount{Name: newConfigSecretVolume.Name, MountPath: "/etc/dex/cfg"}
var existingSecretVolumeName string
for i, volumeMount := range existingDeployment.Spec.Template.Spec.Containers[0].VolumeMounts {
if volumeMount.MountPath == "/etc/dex/cfg" {
existingSecretVolumeName = volumeMount.Name
existingDeployment.Spec.Template.Spec.Containers[0].VolumeMounts[i] = newConfigSecretVolumeMount
break
}
}
if existingSecretVolumeName != "" {
for i, volume := range existingDeployment.Spec.Template.Spec.Volumes {
if volume.Name == existingSecretVolumeName {
existingDeployment.Spec.Template.Spec.Volumes[i] = newConfigSecretVolume
}
}
return existingDeployment
}
existingDeployment.Spec.Template.Spec.Containers[0].VolumeMounts =
append(existingDeployment.Spec.Template.Spec.Containers[0].VolumeMounts, newConfigSecretVolumeMount)
existingDeployment.Spec.Template.Spec.Volumes =
append(existingDeployment.Spec.Template.Spec.Volumes, newConfigSecretVolume)
return existingDeployment
}
func ensureService(ctx context.Context, clientset kubernetes.Interface, namespace string, ingressSpec kotsv1beta1.IngressConfigSpec) error {
service := serviceResource(DexServiceName, ingressSpec)
existingService, err := clientset.CoreV1().Services(namespace).Get(ctx, DexServiceName, metav1.GetOptions{})
if err != nil {
if !kuberneteserrors.IsNotFound(err) {
return errors.Wrap(err, "failed to get existing service")
}
_, err = clientset.CoreV1().Services(namespace).Create(ctx, service, metav1.CreateOptions{})
if err != nil {
return errors.Wrap(err, "failed to create service")
}
return nil
}
existingService = updateService(existingService, service)
_, err = clientset.CoreV1().Services(namespace).Update(ctx, existingService, metav1.UpdateOptions{})
if err != nil {
return errors.Wrap(err, "failed to update service")
}
return nil
}
func serviceResource(serviceName string, ingressSpec kotsv1beta1.IngressConfigSpec) *corev1.Service {
serviceType := corev1.ServiceTypeClusterIP
port := corev1.ServicePort{
Name: "http",
Port: 5556,
TargetPort: intstr.IntOrString{Type: intstr.Int, IntVal: 5556},
}
if ingressSpec.Enabled && ingressSpec.NodePort != nil && ingressSpec.NodePort.Port != 0 {
port.NodePort = int32(ingressSpec.NodePort.Port)
serviceType = corev1.ServiceTypeNodePort
}
return &corev1.Service{
TypeMeta: metav1.TypeMeta{
APIVersion: "v1",
Kind: "Service",
},
ObjectMeta: metav1.ObjectMeta{
Name: serviceName,
Labels: kotsadmtypes.GetKotsadmLabels(AdditionalLabels),
},
Spec: corev1.ServiceSpec{
Type: serviceType,
Selector: map[string]string{
"app": "kotsadm-dex",
},
Ports: []corev1.ServicePort{
port,
},
},
}
}
func updateService(existingService, desiredService *corev1.Service) *corev1.Service {
existingService.Spec.Ports = desiredService.Spec.Ports
return existingService
}
func ensureServiceAccount(ctx context.Context, clientset kubernetes.Interface, namespace string) error {
_, err := clientset.CoreV1().ServiceAccounts(namespace).Get(ctx, DexServiceAccountName, metav1.GetOptions{})
if err != nil {
if !kuberneteserrors.IsNotFound(err) {
return errors.Wrap(err, "failed to get existing service account")
}
_, err = clientset.CoreV1().ServiceAccounts(namespace).Create(ctx, serviceAccountResource(DexServiceAccountName), metav1.CreateOptions{})
if err != nil {
return errors.Wrap(err, "failed to create service account")
}
return nil
}
// no patch necessary
return nil
}
func serviceAccountResource(serviceAccountName string) *corev1.ServiceAccount {
return &corev1.ServiceAccount{
TypeMeta: metav1.TypeMeta{
APIVersion: "v1",
Kind: "ServiceAccount",
},
ObjectMeta: metav1.ObjectMeta{
Name: serviceAccountName,
Labels: kotsadmtypes.GetKotsadmLabels(AdditionalLabels),
},
}
}
func ensureRole(ctx context.Context, clientset kubernetes.Interface, namespace string) error {
_, err := clientset.RbacV1().Roles(namespace).Get(ctx, DexRoleName, metav1.GetOptions{})
if err != nil {
if !kuberneteserrors.IsNotFound(err) {
return errors.Wrap(err, "failed to get existing role")
}
_, err = clientset.RbacV1().Roles(namespace).Create(ctx, roleResource(DexRoleName), metav1.CreateOptions{})
if err != nil {
return errors.Wrap(err, "failed to create role")
}
return nil
}
// no patch necessary
return nil
}
func roleResource(roleName string) *rbacv1.Role {
return &rbacv1.Role{
TypeMeta: metav1.TypeMeta{
APIVersion: "rbac.authorization.k8s.io/v1",
Kind: "Role",
},
ObjectMeta: metav1.ObjectMeta{
Name: roleName,
Labels: kotsadmtypes.GetKotsadmLabels(AdditionalLabels),
},
Rules: []rbacv1.PolicyRule{
{
APIGroups: []string{"dex.coreos.com"}, // API group created by dex
Resources: []string{"*"},
Verbs: []string{"*"},
},
{
// This will no longer be needed if kots deploys dex crds
APIGroups: []string{"apiextensions.k8s.io"},
Resources: []string{"customresourcedefinitions"},
Verbs: []string{"create"}, // To manage its own resources, dex must be able to create customresourcedefinitions
},
},
}
}
func ensureRoleBinding(ctx context.Context, clientset kubernetes.Interface, namespace string) error {
_, err := clientset.RbacV1().RoleBindings(namespace).Get(ctx, DexRoleBindingName, metav1.GetOptions{})
if err != nil {
if !kuberneteserrors.IsNotFound(err) {
return errors.Wrap(err, "failed to get existing role binding")
}
roleBinding := roleBindingResource(DexRoleBindingName, DexRoleName, DexServiceAccountName, namespace)
_, err = clientset.RbacV1().RoleBindings(namespace).Create(ctx, roleBinding, metav1.CreateOptions{})
if err != nil {
return errors.Wrap(err, "failed to create role binding")
}
return nil
}
// no patch necessary
return nil
}
func roleBindingResource(roleBindingName, roleName, serviceAccountName, serviceAccountNamespace string) *rbacv1.RoleBinding {
return &rbacv1.RoleBinding{
TypeMeta: metav1.TypeMeta{
APIVersion: "rbac.authorization.k8s.io/v1",
Kind: "RoleBinding",
},
ObjectMeta: metav1.ObjectMeta{
Name: roleBindingName,
Labels: kotsadmtypes.GetKotsadmLabels(AdditionalLabels),
},
RoleRef: rbacv1.RoleRef{
APIGroup: "rbac.authorization.k8s.io",
Kind: "Role",
Name: roleName,
},
Subjects: []rbacv1.Subject{
{
Kind: "ServiceAccount",
Name: serviceAccountName,
Namespace: serviceAccountNamespace,
},
},
}
}
func EnsurePostgresSecret(ctx context.Context, clientset kubernetes.Interface, namespace string) error {
secret := postgresSecretResource(DexPostgresSecretName)
_, err := clientset.CoreV1().Secrets(namespace).Get(ctx, DexPostgresSecretName, metav1.GetOptions{})
if err != nil {
if !kuberneteserrors.IsNotFound(err) {
return errors.Wrap(err, "failed to get existing secret")
}
_, err = clientset.CoreV1().Secrets(namespace).Create(ctx, secret, metav1.CreateOptions{})
if err != nil {
return errors.Wrap(err, "failed to create secret")
}
return nil
}
// no patch needed
return nil
}
func postgresSecretResource(secretName string) *corev1.Secret {
generatedPassword := ksuid.New().String()
return &corev1.Secret{
TypeMeta: metav1.TypeMeta{
APIVersion: "v1",
Kind: "Secret",
},
ObjectMeta: metav1.ObjectMeta{
Name: secretName,
Labels: kotsadmtypes.GetKotsadmLabels(AdditionalLabels),
},
Data: map[string][]byte{
"password": []byte(generatedPassword),
},
}
}
func ensureIngress(ctx context.Context, clientset kubernetes.Interface, namespace string, ingressSpec kotsv1beta1.IngressConfigSpec) error {
if !ingressSpec.Enabled || ingressSpec.Ingress == nil {
return deleteIngress(ctx, clientset, namespace)
}
dexIngress := ingressResource(namespace, *ingressSpec.Ingress)
return ingress.EnsureIngress(ctx, clientset, namespace, dexIngress)
}
func ingressResource(namespace string, ingressConfig kotsv1beta1.IngressResourceConfig) *extensionsv1beta1.Ingress {
return ingress.IngressFromConfig(ingressConfig, DexIngressName, DexServiceName, 5556, AdditionalLabels)
}
func IdentityDexConnectorsToDexTypeConnectors(conns []kotsv1beta1.DexConnector) ([]dextypes.Connector, error) {
dexConnectors := []dextypes.Connector{}
for _, conn := range conns {
f, ok := server.ConnectorsConfig[conn.Type]
if !ok {
return nil, errors.Errorf("unknown connector type %q", conn.Type)
}
connConfig := f()
if len(conn.Config.Raw) != 0 {
data := []byte(os.ExpandEnv(string(conn.Config.Raw)))
if err := json.Unmarshal(data, connConfig); err != nil {
return nil, errors.Wrap(err, "failed to unmarshal connector config")
}
}
dexConnectors = append(dexConnectors, dextypes.Connector{
Type: conn.Type,
Name: conn.Name,
ID: conn.ID,
Config: connConfig,
})
}
return dexConnectors, nil
}
|
package main
import "fmt"
func main() {
arr := []int{8, 9, 5, 7, 1, 2, 5, 7, 6, 3, 5, 4, 8, 1, 8, 5, 3, 5, 8, 4}
result := mergeSort(arr, "s")
fmt.Println(result)
fmt.Println(arr[len(arr):])
}
/**
归并排序(Merge sort,台湾译作:合并排序)是建立在归并操作上的一种有效的排序算法。该算法是采用分治法(Divide and Conquer)的一个非常典型的应用
分治思想,时间复杂度为:O(n*log(n))
*/
func mergeSort(arr []int, name string) []int {
fmt.Println(name, arr)
if len(arr) < 2 {
return arr
}
i := len(arr) / 2
fmt.Println(i)
left := mergeSort(arr[0:i], "l")
right := mergeSort(arr[i:], "r")
result := merge(left, right)
fmt.Println("result", result)
return result
}
func merge(left, right []int) []int {
fmt.Println("left", left)
fmt.Println("right", right)
result := make([]int, 0)
m, n := 0, 0 // left和right的index位置
l, r := len(left), len(right)
for m < l && n < r {
if left[m] > right[n] {
result = append(result, right[n])
n++
continue
}
result = append(result, left[m])
m++
}
result = append(result, right[n:]...) // 这里竟然没有报数组越界的异常?
result = append(result, left[m:]...)
return result
}
|
package main
import "fmt"
func fact(x uint) uint {
if x <= 1 {
return 1
}
return x * fact(x-1)
}
func fibo_(x int, dp map[int]int) int {
if v, ok := dp[x]; ok {
return v
}
if x <= 1 {
return 1
}
dp[x] = fibo_(x-1, dp) + fibo_(x-2, dp)
return dp[x]
}
func fibo(x int) int {
return fibo_(x, make(map[int]int))
}
func main() {
fmt.Println("Hello, World")
// fmt.Println(fact(10))
fmt.Println(fibo(100))
}
|
package auth
import (
"fmt"
"net/http"
"os"
"regexp"
"strings"
"time"
"github.com/dgrijalva/jwt-go"
)
type userModel struct {
Email string `binding:"required"`
Password string `binding:"required"`
}
// Regex for containing one "@", one period and at least one character before and after them
var emailRegex = regexp.MustCompile(`^[^@\s]+@[^@\s\.]+\.[^@\.\s]+$`)
// Regex for containing 6 characters with only numbers
var passwordRegex = regexp.MustCompile(`^[0-9]{6}$`)
func (user userModel) validate() bool {
if emailRegex.MatchString(user.Email) && passwordRegex.MatchString(user.Password) {
return true
}
return false
}
// CreateToken receives and user email and returns a valid token or and error
func CreateToken(userEmail string) (string, error) {
var err error
os.Setenv("ACCESS_SECRET", "jdnfksdmfksd") //this should be in an env file
atClaims := jwt.MapClaims{}
atClaims["authorized"] = true
atClaims["user_email"] = userEmail
atClaims["exp"] = time.Now().Add(time.Hour * 24).Unix()
// Create token
at := jwt.NewWithClaims(jwt.SigningMethodHS256, atClaims)
// Sign token
token, err := at.SignedString([]byte(os.Getenv("ACCESS_SECRET")))
if err != nil {
return "", err
}
return token, nil
}
func extractToken(r *http.Request) string {
bearToken := r.Header.Get("Authorization")
// Remove the prefix Bearer
strArr := strings.Split(bearToken, " ")
if len(strArr) == 2 {
return strArr[1]
}
return ""
}
func verifyToken(r *http.Request) (*jwt.Token, error) {
tokenStr := extractToken(r)
token, err := jwt.Parse(tokenStr, func(token *jwt.Token) (interface{}, error) {
//Make sure that the token method conform to "SigningMethodHMAC"
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
return []byte(os.Getenv("ACCESS_SECRET")), nil
})
if err != nil {
return nil, err
}
return token, nil
}
// ValidateToken returns nil if the token is valid or else returns an error
func ValidateToken(r *http.Request) error {
token, err := verifyToken(r)
if err != nil {
return err
}
if _, ok := token.Claims.(jwt.Claims); !ok && !token.Valid {
return err
}
return nil
}
|
// Copyright 2019 Copyright (c) 2019 SAP SE or an SAP affiliate company. All rights reserved. This file is licensed under the Apache Software License, v. 2 except as noted otherwise in the LICENSE file.
//
// 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 componentdescriptor
// Component describes a component consisting of the git repository url and a version.
type Component struct {
Name string `json:"name"`
Version string `json:"version"`
}
// ComponentList is a set of multiple components.
type ComponentList []*Component
// ComponentJSON is the object that is written to the elastic search metadata.
type ComponentJSON struct {
Version string `json:"version"`
}
type components struct {
components []*Component
componentSet map[Component]bool
}
|
package scraper
// DefaultBootstrapAddrs are the set of bootstrap addresses the scraper will connect to by default.
var DefaultBootstrapAddrs = []string{
"/dnsaddr/sjc-2.bootstrap.libp2p.io/p2p/QmZa1sAxajnQjVM8WjWXoMbmPd7NsWhfKsPkErzpm9wGkp",
"/dnsaddr/bootstrap.libp2p.io/p2p/QmNnooDu7bfjPFoTZYxMNLWUQJyrVwtbZg5gBMjTezGAJN",
"/dnsaddr/bootstrap.libp2p.io/p2p/QmQCU2EcMqAqQPR2i9bChDtGNJchTbq5TbXJJ16u19uLTa",
"/dnsaddr/bootstrap.libp2p.io/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb",
"/dnsaddr/bootstrap.libp2p.io/p2p/QmcZf59bWwK5XFi76CZX8cbJ4BhTzzA3gU1ZjYZcYW3dwt",
"/ip4/104.131.131.82/tcp/4001/p2p/QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ",
}
|
package ab_method
import (
//"fmt"
//"strings"
"math"
"sync"
"shogi"
)
type Watcher interface {
OnCheck( Node )
}
type Param struct {
Limit float64
Level int
RestLevel float64
Sign float64
Watcher Watcher
Parallel int
}
type Node interface {
String() string
Choices() []shogi.Command
Choose( shogi.Command ) (Node, float64)
Point() float64
Stop() bool
SolvParallel( inch chan SolvInChan, outch chan SolvOutChan )
Hash() uint64
}
type Walker interface {
Inspect( Node )
}
type SolvInChan struct {
Finish bool
Param Param
Node Node
Choice shogi.Command
}
type SolvOutChan struct {
Result []shogi.Command
Point float64
Err error
}
type CacheItem struct {
RestLevel float64
Point float64
Choices []shogi.Command
}
var cache = make( map[uint64]*CacheItem, 1000*1000 )
// solvNodeの並列化バージョン
func solvNodeParallel( param Param, node Node, choices []shogi.Command ) ( []shogi.Command, float64 ) {
var r_choices []shogi.Command
child_param := param
child_param.Level += 1
child_param.Sign = -param.Sign
child_param.Limit = math.MaxInt32
child_param.Parallel = 1
r_point := -math.MaxFloat64
inch := make(chan SolvInChan)
outch := make(chan SolvOutChan)
if param.Parallel > len(choices) { param.Parallel = len(choices) }
for i:=0; i<param.Parallel; i++ {
go node.SolvParallel(inch, outch)
}
num_sent := 0
num_buf := 0
for i:=0; i<len(choices); i++ {
for ; num_sent < len(choices) && num_buf < param.Parallel; {
child, use_level := node.Choose( choices[num_sent] )
child_param.RestLevel = param.RestLevel - use_level
inch <- SolvInChan{false,child_param, child, choices[num_sent] }
num_sent++
num_buf++
}
res := <- outch
num_buf--
result := res.Result
point := res.Point
point = -point
if r_point < point {
r_choices = result
r_point = point
child_param.Limit = -point
// アルファ/ベータカット
if point >= param.Limit {
// fmt.Printf("%salpha/beta cut %v point:%d limit:%d\n",
// strings.Repeat(" ", child_param.Level), child, point, param.Limit);
break
}
}
}
for i:=0; i<param.Parallel; i++ {
inch <- SolvInChan{true,child_param, nil, shogi.Command{}}
}
return r_choices, r_point
}
var mutex sync.Mutex
func SolvNode( param Param, node Node ) ( []shogi.Command, float64 ) {
// fmt.Printf( "%ssolving: %s alpha:%d\n", strings.Repeat(" ", param.Level), node, param.Limit )
var r_choices []shogi.Command
var r_point float64
node.Hash()
mutex.Lock()
if param.Watcher != nil { param.Watcher.OnCheck( node ) }
item, exists := cache[node.Hash()]
mutex.Unlock()
if exists && item.RestLevel >= param.RestLevel {
// キャッシュが利用できる
r_choices = item.Choices
r_point = item.Point
}else{
// キャッシュが利用できない
choices := node.Choices()
if exists && len(item.Choices)>0 {
choices = append( []shogi.Command{item.Choices[0]}, choices... )
}
if param.RestLevel >= 0 && !node.Stop() && len(choices) > 0 {
if param.Parallel > 1 {
r_choices, r_point = solvNodeParallel( param, node, choices )
}else{
child_param := param
child_param.Level += 1
child_param.Sign = -param.Sign
child_param.Limit = math.MaxInt32
r_point = -math.MaxFloat64
for i, choice := range choices {
child, use_level := node.Choose( choice )
child_param.RestLevel = param.RestLevel - use_level
if i == 0 { child_param.RestLevel += 0.5 }
result, point := SolvNode( child_param, child )
point = -point
if r_point < point {
r_choices = append( []shogi.Command{choice}, result... )
r_point = point
child_param.Limit = -point
// アルファ/ベータカット
if point >= param.Limit {
// fmt.Printf("%salpha/beta cut %v point:%d limit:%d\n",
// strings.Repeat(" ", child_param.Level), child, point, param.Limit);
break
}
}
}
}
}else{
r_choices = []shogi.Command{}
r_point = node.Point() * param.Sign
}
if len(cache) < 1000000 {
mutex.Lock()
cache[node.Hash()] = &CacheItem{param.RestLevel, r_point, r_choices}
mutex.Unlock()
}
}
// fmt.Printf( "%ssolved: %s %d\n", strings.Repeat(" ", param.Level), r_choices, r_point )
return r_choices, r_point
}
var age = 0
func Solv( node Node, level float64, positive bool, parallel int, watcher Watcher) ([]shogi.Command, float64) {
sign := 1.0
if !positive { sign = -1 }
param := Param{9999999,0,level,sign,watcher,parallel}
a, b := SolvNode( param, node )
println( "cachesize:", len(cache) )
return a,b
}
func SolvRepeat( node Node, level float64, positive bool, parallel int, watcher Watcher) ([]shogi.Command, float64) {
var a []shogi.Command
var b float64
//cache = make( map[uint64]*CacheItem, 1000000 )
for i:=1.0; i<=level; i+=1.0 {
if i == level {
a, b = Solv( node, i, positive, parallel, nil )
}else{
a, b = Solv( node, i, positive, parallel, nil )
}
}
/*
num_delete := 0
for hash,item := range cache {
if item.Age < age {
num_delete++
delete( cache,hash )
}
}
println( "deleted:", num_delete )
age++
*/
return a,b
}
|
package formula
// import (
// "encoding/json"
// "io"
// "io/ioutil"
// "os"
// "path/filepath"
// "strconv"
// )
// // Formula is
// type Formula struct {
// Number1 string
// Number2 string
// }
// // Output is
// type Output struct {
// Input *Formula `json:"input,omitempty"`
// Sum string `json:"output"`
// }
// const outputFile = "/output.json"
// // Run is
// func (h Formula) Run(writer io.Writer) {
// n1, _ := strconv.Atoi(h.Number1)
// n2, _ := strconv.Atoi(h.Number2)
// sum := n1 + n2
// output := strconv.Itoa(sum)
// myObj := Output{Sum: output}
// bytes, _ := json.Marshal(myObj)
// pwd := RitchieDir()
// if err := ioutil.WriteFile(pwd+outputFile, bytes, os.ModePerm); err != nil {
// os.Exit(1)
// }
// }
// // RitchieDir is
// func RitchieDir() string {
// myDir, _ := os.UserHomeDir()
// return filepath.Join(myDir, ".rit")
// }
|
package hndlrs_test
import (
"testing"
"graphelier/core/graphelier-service/api/hndlrs"
"graphelier/core/graphelier-service/models"
. "graphelier/core/graphelier-service/utils/test_utils"
"github.com/stretchr/testify/assert"
)
var instrumentGains []*models.InstrumentGain = []*models.InstrumentGain{
&models.InstrumentGain{Instrument: "test", Unit: 1.00, Percentage: 10.00},
&models.InstrumentGain{Instrument: "test2", Unit: -1.00, Percentage: -10.00},
}
var instrumentGainsSingle []*models.InstrumentGain = []*models.InstrumentGain{
&models.InstrumentGain{Instrument: "test", Unit: 1.00, Percentage: 10.00},
}
func TestFetchInstrumentGainsSingle(t *testing.T) {
mockedDB := MockDb(t)
defer Ctrl.Finish()
mockedDB.EXPECT().
GetInstrumentGains([]string{"test"}, uint64(1), uint64(2)).
Return(instrumentGainsSingle, nil)
var result []*models.InstrumentGain
err := MakeRequest(
hndlrs.FetchInstrumentGains, // Function under test
mockedDB,
"GET",
"/gain/test/1/2",
map[string]string{
"instruments" : "test",
"current_timestamp": "1",
"other_timestamp": "2",
},
&result,
)
assert.Nil(t, err)
assert.Equal(t, instrumentGainsSingle, result)
}
func TestFetchInstrumentGainsMultiple(t *testing.T) {
mockedDB := MockDb(t)
defer Ctrl.Finish()
mockedDB.EXPECT().
GetInstrumentGains([]string{"test","test2"}, uint64(1), uint64(2)).
Return(instrumentGains, nil)
var result []*models.InstrumentGain
err := MakeRequest(
hndlrs.FetchInstrumentGains, // Function under test
mockedDB,
"GET",
"/gain/test,test2/1/2",
map[string]string{
"instruments" : "test,test2",
"current_timestamp": "1",
"other_timestamp": "2",
},
&result,
)
assert.Nil(t, err)
assert.Equal(t, instrumentGains, result)
} |
package main
import (
"fmt"
"os"
"path/filepath"
"strings"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/openshift-metalkube/kni-installer/pkg/asset/installconfig"
assetstore "github.com/openshift-metalkube/kni-installer/pkg/asset/store"
"github.com/openshift-metalkube/kni-installer/pkg/terraform"
gatheraws "github.com/openshift-metalkube/kni-installer/pkg/terraform/gather/aws"
gatherazure "github.com/openshift-metalkube/kni-installer/pkg/terraform/gather/azure"
gatherlibvirt "github.com/openshift-metalkube/kni-installer/pkg/terraform/gather/libvirt"
gatheropenstack "github.com/openshift-metalkube/kni-installer/pkg/terraform/gather/openstack"
"github.com/openshift-metalkube/kni-installer/pkg/types"
awstypes "github.com/openshift-metalkube/kni-installer/pkg/types/aws"
azuretypes "github.com/openshift-metalkube/kni-installer/pkg/types/azure"
libvirttypes "github.com/openshift-metalkube/kni-installer/pkg/types/libvirt"
openstacktypes "github.com/openshift-metalkube/kni-installer/pkg/types/openstack"
)
func newGatherCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "gather",
Short: "Gather debugging data for a given installation failure",
Long: `Gather debugging data for a given installation failure.
When installation for Openshift cluster fails, gathering all the data useful for debugging can
become a difficult task. This command helps users to collect the most relevant information that can be used
to debug the installation failures`,
RunE: func(cmd *cobra.Command, args []string) error {
return cmd.Help()
},
}
cmd.AddCommand(newGatherBootstrapCmd())
return cmd
}
var (
gatherBootstrapOpts struct {
bootstrap string
masters []string
}
)
func newGatherBootstrapCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "bootstrap",
Short: "Gather debugging data for a failing-to-bootstrap control plane",
Args: cobra.ExactArgs(0),
Run: func(_ *cobra.Command, _ []string) {
cleanup := setupFileHook(rootOpts.dir)
defer cleanup()
err := runGatherBootstrapCmd(rootOpts.dir)
if err != nil {
logrus.Fatal(err)
}
},
}
cmd.PersistentFlags().StringVar(&gatherBootstrapOpts.bootstrap, "bootstrap", "", "Hostname or IP of the bootstrap host")
cmd.PersistentFlags().StringArrayVar(&gatherBootstrapOpts.masters, "master", []string{}, "Hostnames or IPs of all control plane hosts")
return cmd
}
func runGatherBootstrapCmd(directory string) error {
tfStateFilePath := filepath.Join(directory, terraform.StateFileName)
_, err := os.Stat(tfStateFilePath)
if os.IsNotExist(err) {
return unSupportedPlatformGather()
}
if err != nil {
return err
}
assetStore, err := assetstore.NewStore(directory)
if err != nil {
return errors.Wrap(err, "failed to create asset store")
}
config := &installconfig.InstallConfig{}
if err := assetStore.Fetch(config); err != nil {
return errors.Wrapf(err, "failed to fetch %s", config.Name())
}
tfstate, err := terraform.ReadState(tfStateFilePath)
if err != nil {
return errors.Wrapf(err, "failed to read state from %q", tfStateFilePath)
}
bootstrap, port, masters, err := extractHostAddresses(config.Config, tfstate)
if err != nil {
if err2, ok := err.(errUnSupportedGatherPlatform); ok {
logrus.Error(err2)
return unSupportedPlatformGather()
}
return errors.Wrapf(err, "failed to get bootstrap and control plane host addresses from %q", tfStateFilePath)
}
logGatherBootstrap(bootstrap, port, masters)
return nil
}
func logGatherBootstrap(bootstrap string, port int, masters []string) {
var (
sshport string
scpport string
)
if port != 22 {
sshport = fmt.Sprintf(" -p %d", port)
scpport = fmt.Sprintf(" -P %d", port)
}
if s, ok := os.LookupEnv("SSH_AUTH_SOCK"); !ok || s == "" {
logrus.Info("Make sure ssh-agent is running, env SSH_AUTH_SOCK is set to the ssh-agent's UNIX socket and your private key is added to the agent.")
}
logrus.Info("Use the following commands to gather logs from the cluster")
logrus.Infof("ssh -A%s core@%s '/usr/local/bin/installer-gather.sh %s'", sshport, bootstrap, strings.Join(masters, " "))
logrus.Infof("scp%s core@%s:~/log-bundle.tar.gz .", scpport, bootstrap)
}
func extractHostAddresses(config *types.InstallConfig, tfstate *terraform.State) (bootstrap string, port int, masters []string, err error) {
port = 22
switch config.Platform.Name() {
case awstypes.Name:
bootstrap, err = gatheraws.BootstrapIP(tfstate)
if err != nil {
return bootstrap, port, masters, err
}
masters, err = gatheraws.ControlPlaneIPs(tfstate)
if err != nil {
logrus.Error(err)
}
case azuretypes.Name:
port = 2200
bootstrap, err = gatherazure.BootstrapIP(tfstate)
if err != nil {
return bootstrap, port, masters, err
}
masters, err = gatherazure.ControlPlaneIPs(tfstate)
if err != nil {
logrus.Error(err)
}
case libvirttypes.Name:
bootstrap, err = gatherlibvirt.BootstrapIP(tfstate)
if err != nil {
return bootstrap, port, masters, err
}
masters, err = gatherlibvirt.ControlPlaneIPs(tfstate)
if err != nil {
logrus.Error(err)
}
case openstacktypes.Name:
bootstrap, err = gatheropenstack.BootstrapIP(tfstate)
if err != nil {
return bootstrap, port, masters, err
}
masters, err = gatheropenstack.ControlPlaneIPs(tfstate)
if err != nil {
logrus.Error(err)
}
default:
return "", port, nil, errUnSupportedGatherPlatform{Message: fmt.Sprintf("Cannot fetch the bootstrap and control plane host addresses from state file for %s platform", config.Platform.Name())}
}
return bootstrap, port, masters, nil
}
type errUnSupportedGatherPlatform struct {
Message string
}
func (e errUnSupportedGatherPlatform) Error() string {
return e.Message
}
func unSupportedPlatformGather() error {
if gatherBootstrapOpts.bootstrap == "" || len(gatherBootstrapOpts.masters) == 0 {
return errors.New("boostrap host address and at least one control plane host address must be provided")
}
logGatherBootstrap(gatherBootstrapOpts.bootstrap, 22, gatherBootstrapOpts.masters)
return nil
}
|
package service
import (
"encoding/json"
"net/http"
"strings"
"sync"
"github.com/labstack/echo"
"github.com/Aegon-n/sentinel-bot/socks5-proxy/nodes/master-node/models"
"github.com/Aegon-n/sentinel-bot/socks5-proxy/nodes/master-node/utils"
)
func AddNewUser(ctx echo.Context) error {
var body models.AddUser
if err := json.NewDecoder(ctx.Request().Body).Decode(&body); err != nil {
ctx.JSONBlob(http.StatusInternalServerError, []byte("error while reading request body"))
return err
}
wg := new(sync.WaitGroup)
var cmd strings.Builder
_, e := cmd.WriteString("printf ")
if e != nil {
return nil
}
_, e = cmd.WriteString("'" + body.Password + "\n" + body.Password + "\n" + "'" + " | adduser " + body.Username)
if e != nil {
return nil
}
//cmd := "printf 'MemsIr[OkAj4\nMemsIr[OkAj4\n' | adduser awesome"
wg.Add(1)
go utils.ExecCmd(cmd.String(), wg)
wg.Wait()
//if e != nil {
// log.Println("error while executing command")
// return nil
//}
ctx.JSONBlob(http.StatusCreated, []byte(`{"message": "added user"}`))
return nil
}
func RemoveUser(ctx echo.Context) error {
var body models.DelUser
if err := json.NewDecoder(ctx.Request().Body).Decode(&body); err != nil {
ctx.JSONBlob(http.StatusInternalServerError, []byte(`{"message": "error while deleting user"}`))
return nil
}
defer ctx.Request().Body.Close()
wg := new(sync.WaitGroup)
cmd := "deluser " + body.Username
wg.Add(1)
go utils.ExecCmd(cmd, wg)
wg.Wait()
ctx.JSONBlob(http.StatusAccepted, []byte(`{"message": "deleted user"}`))
return nil
}
func RootFunc(ctx echo.Context) error {
ctx.JSONBlob(http.StatusOK, []byte(`{"status": "up"}`))
return nil
}
|
package codes
import (
//"fmt"
)
func RomanNumeral(s string) int {
s="CMLII"
reflect:=make(map[string]int,0)
reflect["M"]=1000
reflect["D"]=500
reflect["C"]=100
reflect["L"]=50
reflect["X"]=10
reflect["V"]=5
reflect["I"]=1
res :=[]byte(s)
before :=res[0]
result :=0
for i:=range res{
result += reflect[string(res[i])]
if before!=res[i]&&reflect[string(before)]<reflect[string(res[i])]{
result-=reflect[string(before)]*2
}
before=res[i]
}
return result
} |
/*
Copyright 2020 The Skaffold 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
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 build
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"testing"
"github.com/GoogleContainerTools/skaffold/v2/pkg/skaffold/platform"
"github.com/GoogleContainerTools/skaffold/v2/pkg/skaffold/schema/latest"
"github.com/GoogleContainerTools/skaffold/v2/testutil"
)
func TestWithLogFile(t *testing.T) {
logBuildInProgress := "building img with tag img:123"
logBuildFailed := "failed to build img with tag img:123"
logFilename := " - writing logs to " + filepath.Join(os.TempDir(), "skaffold", "build", "img.log")
tests := []struct {
description string
builder ArtifactBuilder
muted Muted
shouldErr bool
expectedDigest string
logsFound []string
logsNotFound []string
}{
{
description: "all logs",
builder: fakeBuilder,
muted: muted(false),
shouldErr: false,
expectedDigest: "digest",
logsFound: []string{logBuildInProgress},
logsNotFound: []string{logFilename},
},
{
description: "mute build logs",
builder: fakeBuilder,
muted: muted(true),
shouldErr: false,
expectedDigest: "digest",
logsFound: []string{logFilename},
logsNotFound: []string{logBuildInProgress},
},
{
description: "failed build - all logs",
builder: fakeFailingBuilder,
muted: muted(false),
shouldErr: true,
expectedDigest: "",
logsFound: []string{logBuildFailed},
logsNotFound: []string{logFilename},
},
{
description: "failed build - muted logs",
builder: fakeFailingBuilder,
muted: muted(true),
shouldErr: true,
expectedDigest: "",
logsFound: []string{logFilename},
logsNotFound: []string{logBuildFailed},
},
}
for _, test := range tests {
testutil.Run(t, test.description, func(t *testutil.T) {
var out bytes.Buffer
builder := WithLogFile(test.builder, test.muted)
digest, err := builder(context.Background(), &out, &latest.Artifact{ImageName: "img"}, "img:123", platform.All)
t.CheckErrorAndDeepEqual(test.shouldErr, err, test.expectedDigest, digest)
for _, found := range test.logsFound {
t.CheckContains(found, out.String())
}
for _, notFound := range test.logsNotFound {
t.CheckFalse(strings.Contains(out.String(), notFound))
}
})
}
}
func fakeBuilder(_ context.Context, out io.Writer, a *latest.Artifact, tag string, platforms platform.Matcher) (string, error) {
fmt.Fprintln(out, "building", a.ImageName, "with tag", tag)
return "digest", nil
}
func fakeFailingBuilder(_ context.Context, out io.Writer, a *latest.Artifact, tag string, platforms platform.Matcher) (string, error) {
fmt.Fprintln(out, "failed to build", a.ImageName, "with tag", tag)
return "", errors.New("bug")
}
type muted bool
func (m muted) MuteBuild() bool {
return bool(m)
}
|
// SPDX-License-Identifier: ISC
// Copyright (c) 2014-2020 Bitmark Inc.
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package fingerprint
import "encoding/hex"
// type for SHA3 fingerprints
type Fingerprint [32]byte
// MarshalText - convert fingerprint to little endian hex text
func (fingerprint Fingerprint) MarshalText() ([]byte, error) {
size := hex.EncodedLen(len(fingerprint))
buffer := make([]byte, size)
hex.Encode(buffer, fingerprint[:])
return buffer, nil
}
|
package Watcher
import (
"bytes"
"github.com/radovskyb/watcher"
"github.com/victorneuret/WatcherUpload/watcher/Config"
"io"
"log"
"mime/multipart"
"net/http"
"os"
"path/filepath"
)
func upload(event watcher.Event) {
file, err := os.Open(event.Path)
if err != nil {
log.Println(err)
return
}
defer func() {
err = file.Close()
if err != nil {
log.Println(err)
}
}()
config := Config.GetConfig()
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
relPath, err := filepath.Rel(config.WatchDir, event.Path)
if err != nil {
log.Println(err)
return
}
part, err := writer.CreateFormFile("file", relPath)
if err != nil {
log.Println(err)
return
}
_, err = io.Copy(part, file)
if err != nil {
log.Println(err)
return
}
err = writer.Close()
if err != nil {
log.Println(err)
return
}
r, _ := http.NewRequest("POST", config.ServerURL+config.UploadPath, body)
r.Header.Add("Content-Type", writer.FormDataContentType())
client := &http.Client{}
_, err = client.Do(r)
if err != nil {
log.Println(err)
return
}
}
|
/* hello-world-math-very-simple
This is not meant to be in any way a detailed list of the math
capability of GO only a demonstration of some of the simple math
operators that GO uses. this may be expanded later in another folder
to show more complex math operations
*/
package main //this is an executable file
import "fmt" //importing the fmt package allows us to use Println
func main() { //Main function
fmt.Println("20 + 3 =", 20+3) //+ to add
fmt.Println("20 - 3 =", 20-3) //- so subtract
fmt.Println("20 * 3 =", 20*3) //* to multiply
fmt.Println("20 / 3 =", 20/3) //'/' to divide
fmt.Println("20 % 3 =", 20%3) //% for mod
}
|
package math
import (
"jean/instructions/base"
"jean/instructions/factory"
"jean/rtda/jvmstack"
)
type DDIV struct {
base.NoOperandsInstruction
}
func (d *DDIV) Execute(frame *jvmstack.Frame) {
stack := frame.OperandStack()
v2 := stack.PopDouble()
v1 := stack.PopDouble()
res := v1 / v2
stack.PushDouble(res)
}
type FDIV struct {
base.NoOperandsInstruction
}
func (f *FDIV) Execute(frame *jvmstack.Frame) {
stack := frame.OperandStack()
v2 := stack.PopFloat()
v1 := stack.PopFloat()
res := v1 / v2
stack.PushFloat(res)
}
type IDIV struct {
base.NoOperandsInstruction
}
func (i *IDIV) Execute(frame *jvmstack.Frame) {
stack := frame.OperandStack()
v2 := stack.PopInt()
v1 := stack.PopInt()
if v2 == 0 {
panic("java.lang.ArithmeticException: / by zero")
}
res := v1 / v2
stack.PushInt(res)
}
type LDIV struct {
base.NoOperandsInstruction
}
func (l *LDIV) Execute(frame *jvmstack.Frame) {
stack := frame.OperandStack()
v2 := stack.PopLong()
v1 := stack.PopLong()
if v2 == 0 {
panic("java.lang.ArithmeticException: / by zero")
}
res := v1 / v2
stack.PushLong(res)
}
func init() {
idiv := &IDIV{}
ldiv := &LDIV{}
fdiv := &FDIV{}
ddiv := &DDIV{}
factory.Factory.AddInstruction(0x6c, func() base.Instruction {
return idiv
})
factory.Factory.AddInstruction(0x6d, func() base.Instruction {
return ldiv
})
factory.Factory.AddInstruction(0x6e, func() base.Instruction {
return fdiv
})
factory.Factory.AddInstruction(0x6f, func() base.Instruction {
return ddiv
})
}
|
package ravendb
// Size describes size of entity on disk
type Size struct {
SizeInBytes int64 `json:"SizeInBytes"`
HumaneSize string `json:"HumaneSize"`
}
|
package memory
import "github.com/adamluzsi/frameless/pkg/reflectkit"
// getNamespaceFor gives back the namespace string, or if empty, then set the namespace to the type value
func getNamespaceFor[T any](typ string, namespace *string) string {
if len(*namespace) == 0 {
*namespace = reflectkit.FullyQualifiedName(*new(T))
}
return typ + "/" + *namespace
}
|
package service
import (
"be_fs/models"
"be_fs/repository"
"fmt"
"log"
"net/http"
"strconv"
"github.com/labstack/echo"
)
type ResponseModel struct {
Code int `json: "code" validate: "required"`
Message string `json: "message" validate: "required"`
}
// Createfunction
func CreateUser(c echo.Context) error {
Res := &ResponseModel{400, "Bad Request"}
U := new(models.User)
if err := c.Bind(U); err != nil {
return nil
}
Res = (*ResponseModel)(repository.CreateUser(U))
return c.JSON(http.StatusOK, Res)
}
// ReadAllUserFunction
func ReadAllUser(c echo.Context) error {
limit := c.Param("limit")
dataLimit, _ := strconv.Atoi(limit)
offset := c.Param("offset")
dataOffset, _ := strconv.Atoi(offset)
result := repository.ReadAllUser(dataLimit, dataOffset)
return c.JSON(http.StatusOK, result)
}
// ReadAllUserFunction
func ReadAllUserNoLimit(c echo.Context) error {
result := repository.ReadAllUserNoLimit()
return c.JSON(http.StatusOK, result)
}
// ReadIdUserFunction
func ReadIdUser(c echo.Context) error {
id := c.Param("userId")
data, _ := strconv.Atoi(id)
result := repository.ReadByIdUser(data)
return c.JSON(http.StatusOK, result)
}
// UpdateFunction
func UpdateUser(c echo.Context) error {
Res := &ResponseModel{400, "Bad Request"}
id := c.Param("userId")
data, _ := strconv.Atoi(id)
U := new(models.User)
if err := c.Bind(U); err != nil {
log.Println(err.Error())
return nil
}
Res = (*ResponseModel)(repository.UpdateUser(U, data))
return c.JSON(http.StatusOK, Res)
}
// DeleteFunction
func DeleteUser(c echo.Context) error {
Res := &ResponseModel{400, "Bad Request"}
id := c.Param("userId")
data, _ := strconv.Atoi(id)
fmt.Println("userId", data)
Res = (*ResponseModel)(repository.DeleteUser(data))
return c.JSON(http.StatusOK, Res)
}
|
package naming
import "bytes"
func isLowerByte(r byte) bool {
return r >= 'a' && r <= 'z'
}
func isUpperByte(r byte) bool {
return r >= 'A' && r <= 'Z'
}
func toLowerByte(r byte) byte {
return r + ('a' - 'A')
}
func toUpperByte(r byte) byte {
return r - ('a' - 'A')
}
// underline naming to hump naming
// aa_bb_cc to AaBbCc
// aa_Bb_cc to AaBbCc
func HumpNaming(name string) string {
if len(name) <= 0 {
return name
}
var buf bytes.Buffer
for i := 0; i < len(name); i++ {
// this is '_'
if name[i] == '_' {
continue
}
// the first byte
if (i == 0 ||
// last is '_'
(i > 0 && name[i-1] == '_')) &&
// this is lower
isLowerByte(name[i]) {
buf.WriteByte(toUpperByte(name[i]))
} else {
buf.WriteByte(name[i])
}
}
return buf.String()
}
func FirstLower(name string) string {
if len(name) <= 0 {
return name
}
var buf bytes.Buffer
if isUpperByte(name[0]) {
buf.WriteByte(toLowerByte(name[0]))
}
for i := 1; i < len(name); i++ {
buf.WriteByte(name[i])
}
return buf.String()
}
// hump naming to underline naming
// AaBbCc to aa_bb_cc
// AaBBCc to aa_bb_cc
func UnderlineNaming(name string) string {
if len(name) <= 0 {
return name
}
var buf bytes.Buffer
for i := 0; i < len(name); i++ {
// this is lower
if isLowerByte(name[i]) {
buf.WriteByte(name[i])
continue
}
// this is upper
// not the first byte
if i > 1 && (
// last byte is lower
isLowerByte(name[i-1]) ||
// next byte is lower
(i+1 < len(name) && isLowerByte(name[i+1]))) {
buf.WriteByte('_')
}
buf.WriteByte(toLowerByte(name[i]))
}
return buf.String()
}
|
package main
import (
"encoding/json"
"errors"
"fmt"
"github.com/gotk3/gotk3/glib"
"github.com/gotk3/gotk3/gtk"
"io/ioutil"
"log"
"os"
"os/user"
"strconv"
"strings"
"sync"
"time"
"github.com/subgraph/fw-daemon/sgfw"
)
type fpPreferences struct {
Winheight uint
Winwidth uint
Wintop uint
Winleft uint
}
type decisionWaiter struct {
Cond *sync.Cond
Lock sync.Locker
Ready bool
Scope int
Rule string
}
type ruleColumns struct {
Path string
Proto string
Pid int
Target string
Hostname string
Port int
UID int
GID int
Uname string
Gname string
Origin string
Scope int
}
var userPrefs fpPreferences
var mainWin *gtk.Window
var Notebook *gtk.Notebook
var globalLS *gtk.ListStore
var globalTV *gtk.TreeView
var decisionWaiters []*decisionWaiter
var editApp, editTarget, editPort, editUser, editGroup *gtk.Entry
var comboProto *gtk.ComboBoxText
var radioOnce, radioProcess, radioParent, radioSession, radioPermanent *gtk.RadioButton
var btnApprove, btnDeny, btnIgnore *gtk.Button
var chkUser, chkGroup *gtk.CheckButton
func dumpDecisions() {
fmt.Println("XXX Total of decisions pending: ", len(decisionWaiters))
for i := 0; i < len(decisionWaiters); i++ {
fmt.Printf("XXX %d ready = %v, rule = %v\n", i+1, decisionWaiters[i].Ready, decisionWaiters[i].Rule)
}
}
func addDecision() *decisionWaiter {
decision := decisionWaiter{Lock: &sync.Mutex{}, Ready: false, Scope: int(sgfw.APPLY_ONCE), Rule: ""}
decision.Cond = sync.NewCond(decision.Lock)
decisionWaiters = append(decisionWaiters, &decision)
return &decision
}
func promptInfo(msg string) {
dialog := gtk.MessageDialogNew(mainWin, 0, gtk.MESSAGE_INFO, gtk.BUTTONS_OK, "Displaying full log info:")
// dialog.SetDefaultGeometry(500, 200)
tv, err := gtk.TextViewNew()
if err != nil {
log.Fatal("Unable to create TextView:", err)
}
tvbuf, err := tv.GetBuffer()
if err != nil {
log.Fatal("Unable to get buffer:", err)
}
tvbuf.SetText(msg)
tv.SetEditable(false)
tv.SetWrapMode(gtk.WRAP_WORD)
scrollbox, err := gtk.ScrolledWindowNew(nil, nil)
if err != nil {
log.Fatal("Unable to create scrolled window:", err)
}
scrollbox.Add(tv)
scrollbox.SetSizeRequest(500, 100)
box, err := dialog.GetContentArea()
if err != nil {
log.Fatal("Unable to get content area of dialog:", err)
}
box.Add(scrollbox)
dialog.ShowAll()
dialog.Run()
dialog.Destroy()
//self.set_default_size(150, 100)
}
func promptChoice(msg string) int {
dialog := gtk.MessageDialogNew(mainWin, 0, gtk.MESSAGE_ERROR, gtk.BUTTONS_YES_NO, msg)
result := dialog.Run()
dialog.Destroy()
return result
}
func promptError(msg string) {
dialog := gtk.MessageDialogNew(mainWin, 0, gtk.MESSAGE_ERROR, gtk.BUTTONS_CLOSE, "Error: %s", msg)
dialog.Run()
dialog.Destroy()
}
func getConfigPath() string {
usr, err := user.Current()
if err != nil {
fmt.Fprintf(os.Stderr, "Error: could not determine location of user preferences file:", err, "\n")
return ""
}
prefPath := usr.HomeDir + "/.fwprompt.json"
return prefPath
}
func savePreferences() bool {
usr, err := user.Current()
if err != nil {
fmt.Fprintf(os.Stderr, "Error: could not determine location of user preferences file:", err, "\n")
return false
}
prefPath := usr.HomeDir + "/.fwprompt.json"
jsonPrefs, err := json.Marshal(userPrefs)
if err != nil {
fmt.Fprintf(os.Stderr, "Error: could not generate user preferences data:", err, "\n")
return false
}
err = ioutil.WriteFile(prefPath, jsonPrefs, 0644)
if err != nil {
fmt.Fprintf(os.Stderr, "Error: could not save user preferences data:", err, "\n")
return false
}
return true
}
func loadPreferences() bool {
usr, err := user.Current()
if err != nil {
fmt.Fprintf(os.Stderr, "Error: could not determine location of user preferences file: %v", err, "\n")
return false
}
prefPath := usr.HomeDir + "/.fwprompt.json"
jfile, err := ioutil.ReadFile(prefPath)
if err != nil {
fmt.Fprintf(os.Stderr, "Error: could not read preference data from file: %v", err, "\n")
return false
}
err = json.Unmarshal(jfile, &userPrefs)
if err != nil {
fmt.Fprintf(os.Stderr, "Error: could not load preferences data from file: %v", err, "\n")
return false
}
fmt.Println(userPrefs)
return true
}
func get_hbox() *gtk.Box {
hbox, err := gtk.BoxNew(gtk.ORIENTATION_HORIZONTAL, 0)
if err != nil {
log.Fatal("Unable to create horizontal box:", err)
}
return hbox
}
func get_vbox() *gtk.Box {
vbox, err := gtk.BoxNew(gtk.ORIENTATION_VERTICAL, 0)
if err != nil {
log.Fatal("Unable to create vertical box:", err)
}
return vbox
}
func get_checkbox(text string, activated bool) *gtk.CheckButton {
cb, err := gtk.CheckButtonNewWithLabel(text)
if err != nil {
log.Fatal("Unable to create new checkbox:", err)
}
cb.SetActive(activated)
return cb
}
func get_combobox() *gtk.ComboBoxText {
combo, err := gtk.ComboBoxTextNew()
if err != nil {
log.Fatal("Unable to create combo box:", err)
}
combo.Append("tcp", "TCP")
combo.Append("udp", "UDP")
combo.Append("icmp", "ICMP")
combo.SetActive(0)
return combo
}
func get_radiobutton(group *gtk.RadioButton, label string, activated bool) *gtk.RadioButton {
if group == nil {
radiobutton, err := gtk.RadioButtonNewWithLabel(nil, label)
if err != nil {
log.Fatal("Unable to create radio button:", err)
}
radiobutton.SetActive(activated)
return radiobutton
}
radiobutton, err := gtk.RadioButtonNewWithLabelFromWidget(group, label)
if err != nil {
log.Fatal("Unable to create radio button in group:", err)
}
radiobutton.SetActive(activated)
return radiobutton
}
func get_entry(text string) *gtk.Entry {
entry, err := gtk.EntryNew()
if err != nil {
log.Fatal("Unable to create text entry:", err)
}
entry.SetText(text)
return entry
}
func get_label(text string) *gtk.Label {
label, err := gtk.LabelNew(text)
if err != nil {
log.Fatal("Unable to create label in GUI:", err)
return nil
}
return label
}
func createColumn(title string, id int) *gtk.TreeViewColumn {
cellRenderer, err := gtk.CellRendererTextNew()
if err != nil {
log.Fatal("Unable to create text cell renderer:", err)
}
column, err := gtk.TreeViewColumnNewWithAttribute(title, cellRenderer, "text", id)
if err != nil {
log.Fatal("Unable to create cell column:", err)
}
column.SetSortColumnID(id)
column.SetResizable(true)
return column
}
func createListStore(general bool) *gtk.ListStore {
colData := []glib.Type{glib.TYPE_INT, glib.TYPE_STRING, glib.TYPE_STRING, glib.TYPE_INT, glib.TYPE_STRING, glib.TYPE_STRING, glib.TYPE_INT, glib.TYPE_INT, glib.TYPE_INT, glib.TYPE_STRING, glib.TYPE_STRING}
listStore, err := gtk.ListStoreNew(colData...)
if err != nil {
log.Fatal("Unable to create list store:", err)
}
return listStore
}
func addRequest(listStore *gtk.ListStore, path, proto string, pid int, ipaddr, hostname string, port, uid, gid int, origin string, is_socks bool, optstring string, sandbox string) *decisionWaiter {
if listStore == nil {
listStore = globalLS
waitTimes := []int{1, 2, 5, 10}
if listStore == nil {
log.Print("SGFW prompter was not ready to receive firewall request... waiting")
}
for _, wtime := range waitTimes {
time.Sleep(time.Duration(wtime) * time.Second)
listStore = globalLS
if listStore != nil {
break
}
log.Print("SGFW prompter is still waiting...")
}
}
if listStore == nil {
log.Fatal("SGFW prompter GUI failed to load for unknown reasons")
}
iter := listStore.Append()
if is_socks {
if (optstring != "") && (strings.Index(optstring, "SOCKS") == -1) {
optstring = "SOCKS5 / " + optstring
} else if optstring == "" {
optstring = "SOCKS5"
}
}
colVals := make([]interface{}, 11)
colVals[0] = 1
colVals[1] = path
colVals[2] = proto
colVals[3] = pid
if ipaddr == "" {
colVals[4] = "---"
} else {
colVals[4] = ipaddr
}
colVals[5] = hostname
colVals[6] = port
colVals[7] = uid
colVals[8] = gid
colVals[9] = origin
colVals[10] = optstring
colNums := make([]int, len(colVals))
for n := 0; n < len(colVals); n++ {
colNums[n] = n
}
err := listStore.Set(iter, colNums, colVals)
if err != nil {
log.Fatal("Unable to add row:", err)
}
decision := addDecision()
dumpDecisions()
toggleHover()
return decision
}
func setup_settings() {
box, err := gtk.BoxNew(gtk.ORIENTATION_VERTICAL, 0)
if err != nil {
log.Fatal("Unable to create settings box:", err)
}
scrollbox, err := gtk.ScrolledWindowNew(nil, nil)
if err != nil {
log.Fatal("Unable to create settings scrolled window:", err)
}
hLabel, err := gtk.LabelNew("Settings")
if err != nil {
log.Fatal("Unable to create notebook label:", err)
}
scrollbox.Add(box)
scrollbox.SetSizeRequest(600, 400)
tv, err := gtk.TreeViewNew()
if err != nil {
log.Fatal("Unable to create treeview:", err)
}
h := get_hbox()
l := get_label("Log to file:")
b, err := gtk.ButtonNewWithLabel("Save")
if err != nil {
log.Fatal("Unable to create button:", err)
}
h.PackStart(l, false, true, 10)
h.PackStart(b, false, true, 10)
h.SetMarginTop(10)
box.Add(h)
h = get_hbox()
h.SetMarginTop(0)
h.SetMarginBottom(20)
box.Add(h)
box.Add(tv)
b.Connect("clicked", func() {
fmt.Println("CLICKED")
if err != nil {
promptError("Unexpected error saving log file info: " + err.Error())
return
}
})
Notebook.AppendPage(scrollbox, hLabel)
}
func lsGetStr(ls *gtk.ListStore, iter *gtk.TreeIter, idx int) (string, error) {
val, err := globalLS.GetValue(iter, idx)
if err != nil {
return "", err
}
sval, err := val.GetString()
if err != nil {
return "", err
}
return sval, nil
}
func lsGetInt(ls *gtk.ListStore, iter *gtk.TreeIter, idx int) (int, error) {
val, err := globalLS.GetValue(iter, idx)
if err != nil {
return 0, err
}
ival, err := val.GoValue()
if err != nil {
return 0, err
}
return ival.(int), nil
}
func makeDecision(idx int, rule string, scope int) {
decisionWaiters[idx].Cond.L.Lock()
decisionWaiters[idx].Rule = rule
decisionWaiters[idx].Scope = scope
decisionWaiters[idx].Ready = true
decisionWaiters[idx].Cond.Signal()
decisionWaiters[idx].Cond.L.Unlock()
}
func toggleHover() {
mainWin.SetKeepAbove(len(decisionWaiters) > 0)
}
func toggleValidRuleState() {
ok := true
if numSelections() <= 0 {
ok = false
}
str, err := editApp.GetText()
if err != nil || strings.Trim(str, "\t ") == "" {
ok = false
}
str, err = editTarget.GetText()
if err != nil || strings.Trim(str, "\t ") == "" {
ok = false
}
str, err = editPort.GetText()
if err != nil || strings.Trim(str, "\t ") == "" {
ok = false
} else {
pval, err := strconv.Atoi(str)
if err != nil || pval < 0 || pval > 65535 {
ok = false
}
}
if chkUser.GetActive() {
str, err = editUser.GetText()
if err != nil || strings.Trim(str, "\t ") == "" {
ok = false
}
}
if chkGroup.GetActive() {
str, err = editGroup.GetText()
if err != nil || strings.Trim(str, "\t ") == "" {
ok = false
}
}
btnApprove.SetSensitive(ok)
btnDeny.SetSensitive(ok)
btnIgnore.SetSensitive(ok)
}
func createCurrentRule() (ruleColumns, error) {
rule := ruleColumns{Scope: int(sgfw.APPLY_ONCE)}
var err error = nil
if radioProcess.GetActive() {
rule.Scope = int(sgfw.APPLY_PROCESS)
} else if radioParent.GetActive() {
return rule, errors.New("Parent process scope is unsupported at the moment")
} else if radioSession.GetActive() {
rule.Scope = int(sgfw.APPLY_SESSION)
} else if radioPermanent.GetActive() {
rule.Scope = int(sgfw.APPLY_FOREVER)
} else {
rule.Scope = int(sgfw.APPLY_ONCE)
}
rule.Path, err = editApp.GetText()
if err != nil {
return rule, err
}
ports, err := editPort.GetText()
if err != nil {
return rule, err
}
rule.Port, err = strconv.Atoi(ports)
if err != nil {
return rule, err
}
rule.Target, err = editTarget.GetText()
if err != nil {
return rule, err
}
rule.Proto = comboProto.GetActiveID()
rule.UID, rule.GID = 0, 0
rule.Uname, rule.Gname = "", ""
/* Pid int
Origin string */
return rule, nil
}
func clearEditor() {
editApp.SetText("")
editTarget.SetText("")
editPort.SetText("")
editUser.SetText("")
editGroup.SetText("")
comboProto.SetActive(0)
radioOnce.SetActive(true)
radioProcess.SetActive(false)
radioParent.SetActive(false)
radioSession.SetActive(false)
radioPermanent.SetActive(false)
chkUser.SetActive(false)
chkGroup.SetActive(false)
}
func removeSelectedRule(idx int, rmdecision bool) error {
fmt.Println("XXX: attempting to remove idx = ", idx)
path, err := gtk.TreePathNewFromString(fmt.Sprintf("%d", idx))
if err != nil {
return err
}
iter, err := globalLS.GetIter(path)
if err != nil {
return err
}
globalLS.Remove(iter)
if rmdecision {
decisionWaiters = append(decisionWaiters[:idx], decisionWaiters[idx+1:]...)
}
toggleHover()
return nil
}
func numSelections() int {
sel, err := globalTV.GetSelection()
if err != nil {
return -1
}
rows := sel.GetSelectedRows(globalLS)
return int(rows.Length())
}
func getSelectedRule() (ruleColumns, int, error) {
rule := ruleColumns{}
sel, err := globalTV.GetSelection()
if err != nil {
return rule, -1, err
}
rows := sel.GetSelectedRows(globalLS)
if rows.Length() <= 0 {
return rule, -1, errors.New("No selection was made")
}
rdata := rows.NthData(0)
lIndex, err := strconv.Atoi(rdata.(*gtk.TreePath).String())
if err != nil {
return rule, -1, err
}
fmt.Println("lindex = ", lIndex)
path, err := gtk.TreePathNewFromString(fmt.Sprintf("%d", lIndex))
if err != nil {
return rule, -1, err
}
iter, err := globalLS.GetIter(path)
if err != nil {
return rule, -1, err
}
rule.Path, err = lsGetStr(globalLS, iter, 1)
if err != nil {
return rule, -1, err
}
rule.Proto, err = lsGetStr(globalLS, iter, 2)
if err != nil {
return rule, -1, err
}
rule.Pid, err = lsGetInt(globalLS, iter, 3)
if err != nil {
return rule, -1, err
}
rule.Target, err = lsGetStr(globalLS, iter, 4)
if err != nil {
return rule, -1, err
}
rule.Hostname, err = lsGetStr(globalLS, iter, 5)
if err != nil {
return rule, -1, err
}
rule.Port, err = lsGetInt(globalLS, iter, 6)
if err != nil {
return rule, -1, err
}
rule.UID, err = lsGetInt(globalLS, iter, 7)
if err != nil {
return rule, -1, err
}
rule.GID, err = lsGetInt(globalLS, iter, 8)
if err != nil {
return rule, -1, err
}
rule.Origin, err = lsGetStr(globalLS, iter, 9)
if err != nil {
return rule, -1, err
}
return rule, lIndex, nil
}
func main() {
decisionWaiters = make([]*decisionWaiter, 0)
_, err := newDbusServer()
if err != nil {
log.Fatal("Error:", err)
return
}
loadPreferences()
gtk.Init(nil)
// Create a new toplevel window, set its title, and connect it to the "destroy" signal to exit the GTK main loop when it is destroyed.
mainWin, err = gtk.WindowNew(gtk.WINDOW_TOPLEVEL)
if err != nil {
log.Fatal("Unable to create window:", err)
}
mainWin.SetTitle("SGOS fw-daemon Prompter")
mainWin.Connect("destroy", func() {
fmt.Println("Shutting down...")
savePreferences()
gtk.MainQuit()
})
mainWin.Connect("configure-event", func() {
w, h := mainWin.GetSize()
userPrefs.Winwidth, userPrefs.Winheight = uint(w), uint(h)
l, t := mainWin.GetPosition()
userPrefs.Winleft, userPrefs.Wintop = uint(l), uint(t)
})
mainWin.SetPosition(gtk.WIN_POS_CENTER)
Notebook, err = gtk.NotebookNew()
if err != nil {
log.Fatal("Unable to create new notebook:", err)
}
loglevel := "Firewall Traffic Pending Approval"
nbLabel, err := gtk.LabelNew(loglevel)
if err != nil {
log.Fatal("Unable to create notebook label:", err)
}
box, err := gtk.BoxNew(gtk.ORIENTATION_VERTICAL, 0)
if err != nil {
log.Fatal("Unable to create box:", err)
}
scrollbox, err := gtk.ScrolledWindowNew(nil, nil)
if err != nil {
log.Fatal("Unable to create scrolled window:", err)
}
tv, err := gtk.TreeViewNew()
if err != nil {
log.Fatal("Unable to create treeview:", err)
}
globalTV = tv
tv.SetSizeRequest(300, 300)
tv.SetHeadersClickable(true)
btnApprove, err = gtk.ButtonNewWithLabel("Approve")
if err != nil {
log.Fatal("Unable to create button:", err)
}
btnDeny, err = gtk.ButtonNewWithLabel("Deny")
if err != nil {
log.Fatal("Unable to create button:", err)
}
btnIgnore, err = gtk.ButtonNewWithLabel("Ignore")
if err != nil {
log.Fatal("Unable to create button:", err)
}
btnApprove.SetSensitive(false)
btnDeny.SetSensitive(false)
btnIgnore.SetSensitive(false)
bb := get_hbox()
bb.PackStart(btnApprove, false, false, 5)
bb.PackStart(btnDeny, false, false, 5)
bb.PackStart(btnIgnore, false, false, 5)
editbox := get_vbox()
hbox := get_hbox()
lbl := get_label("Application path:")
editApp = get_entry("")
editApp.Connect("changed", toggleValidRuleState)
hbox.PackStart(lbl, false, false, 10)
hbox.PackStart(editApp, true, true, 50)
editbox.PackStart(hbox, false, false, 5)
hbox = get_hbox()
lbl = get_label("Target host/IP:")
editTarget = get_entry("")
editTarget.Connect("changed", toggleValidRuleState)
hbox.PackStart(lbl, false, false, 10)
hbox.PackStart(editTarget, false, false, 5)
lbl = get_label("Port:")
editPort = get_entry("")
editPort.Connect("changed", toggleValidRuleState)
hbox.PackStart(lbl, false, false, 5)
hbox.PackStart(editPort, false, false, 5)
lbl = get_label("Protocol:")
comboProto = get_combobox()
hbox.PackStart(lbl, false, true, 5)
hbox.PackStart(comboProto, false, false, 5)
editbox.PackStart(hbox, false, false, 5)
hbox = get_hbox()
lbl = get_label("Apply rule:")
radioOnce = get_radiobutton(nil, "Once", true)
radioProcess = get_radiobutton(radioOnce, "This Process", false)
radioParent = get_radiobutton(radioOnce, "Parent Process", false)
radioSession = get_radiobutton(radioOnce, "Session", false)
radioPermanent = get_radiobutton(radioOnce, "Permanent", false)
radioParent.SetSensitive(false)
hbox.PackStart(lbl, false, false, 10)
hbox.PackStart(radioOnce, false, false, 5)
hbox.PackStart(radioProcess, false, false, 5)
hbox.PackStart(radioParent, false, false, 5)
hbox.PackStart(radioSession, false, false, 5)
hbox.PackStart(radioPermanent, false, false, 5)
editbox.PackStart(hbox, false, false, 5)
hbox = get_hbox()
chkUser = get_checkbox("Apply to UID/username", false)
chkUser.Connect("toggled", toggleValidRuleState)
editUser = get_entry("")
editUser.Connect("changed", toggleValidRuleState)
hbox.PackStart(chkUser, false, false, 10)
hbox.PackStart(editUser, false, false, 10)
chkGroup = get_checkbox("Apply to GID/group:", false)
chkGroup.Connect("toggled", toggleValidRuleState)
editGroup = get_entry("")
editGroup.Connect("changed", toggleValidRuleState)
hbox.PackStart(chkGroup, false, false, 10)
hbox.PackStart(editGroup, false, false, 10)
editbox.PackStart(hbox, false, false, 5)
box.PackStart(bb, false, false, 5)
box.PackStart(editbox, false, false, 5)
scrollbox.Add(tv)
// box.PackStart(tv, false, true, 5)
box.PackStart(scrollbox, false, true, 5)
tv.AppendColumn(createColumn("#", 0))
tv.AppendColumn(createColumn("Path", 1))
tv.AppendColumn(createColumn("Protocol", 2))
tv.AppendColumn(createColumn("PID", 3))
tv.AppendColumn(createColumn("IP Address", 4))
tv.AppendColumn(createColumn("Hostname", 5))
tv.AppendColumn(createColumn("Port", 6))
tv.AppendColumn(createColumn("UID", 7))
tv.AppendColumn(createColumn("GID", 8))
tv.AppendColumn(createColumn("Origin", 9))
tv.AppendColumn(createColumn("Details", 10))
listStore := createListStore(true)
globalLS = listStore
tv.SetModel(listStore)
btnApprove.Connect("clicked", func() {
rule, idx, err := getSelectedRule()
if err != nil {
promptError("Error occurred processing request: " + err.Error())
return
}
rule, err = createCurrentRule()
if err != nil {
promptError("Error occurred constructing new rule: " + err.Error())
return
}
fmt.Println("rule = ", rule)
rulestr := "ALLOW|" + rule.Proto + ":" + rule.Target + ":" + strconv.Itoa(rule.Port)
fmt.Println("RULESTR = ", rulestr)
makeDecision(idx, rulestr, int(rule.Scope))
fmt.Println("Decision made.")
err = removeSelectedRule(idx, true)
if err == nil {
clearEditor()
} else {
promptError("Error setting new rule: " + err.Error())
}
})
btnDeny.Connect("clicked", func() {
rule, idx, err := getSelectedRule()
if err != nil {
promptError("Error occurred processing request: " + err.Error())
return
}
rule, err = createCurrentRule()
if err != nil {
promptError("Error occurred constructing new rule: " + err.Error())
return
}
fmt.Println("rule = ", rule)
rulestr := "DENY|" + rule.Proto + ":" + rule.Target + ":" + strconv.Itoa(rule.Port)
fmt.Println("RULESTR = ", rulestr)
makeDecision(idx, rulestr, int(rule.Scope))
fmt.Println("Decision made.")
err = removeSelectedRule(idx, true)
if err == nil {
clearEditor()
} else {
promptError("Error setting new rule: " + err.Error())
}
})
btnIgnore.Connect("clicked", func() {
_, idx, err := getSelectedRule()
if err != nil {
promptError("Error occurred processing request: " + err.Error())
return
}
makeDecision(idx, "", 0)
fmt.Println("Decision made.")
err = removeSelectedRule(idx, true)
if err == nil {
clearEditor()
} else {
promptError("Error setting new rule: " + err.Error())
}
})
// tv.SetActivateOnSingleClick(true)
tv.Connect("row-activated", func() {
seldata, _, err := getSelectedRule()
if err != nil {
promptError("Unexpected error reading selected rule: " + err.Error())
return
}
editApp.SetText(seldata.Path)
if seldata.Hostname != "" {
editTarget.SetText(seldata.Hostname)
} else {
editTarget.SetText(seldata.Target)
}
editPort.SetText(strconv.Itoa(seldata.Port))
radioOnce.SetActive(true)
radioProcess.SetActive(false)
radioProcess.SetSensitive(seldata.Pid > 0)
radioParent.SetActive(false)
radioSession.SetActive(false)
radioPermanent.SetActive(false)
comboProto.SetActiveID(seldata.Proto)
if seldata.Uname != "" {
editUser.SetText(seldata.Uname)
} else if seldata.UID != -1 {
editUser.SetText(strconv.Itoa(seldata.UID))
} else {
editUser.SetText("")
}
if seldata.Gname != "" {
editGroup.SetText(seldata.Gname)
} else if seldata.GID != -1 {
editGroup.SetText(strconv.Itoa(seldata.GID))
} else {
editGroup.SetText("")
}
chkUser.SetActive(false)
chkGroup.SetActive(false)
return
})
scrollbox.SetSizeRequest(600, 400)
// Notebook.AppendPage(scrollbox, nbLabel)
Notebook.AppendPage(box, nbLabel)
// setup_settings()
mainWin.Add(Notebook)
if userPrefs.Winheight > 0 && userPrefs.Winwidth > 0 {
// fmt.Printf("height was %d, width was %d\n", userPrefs.Winheight, userPrefs.Winwidth)
mainWin.Resize(int(userPrefs.Winwidth), int(userPrefs.Winheight))
} else {
mainWin.SetDefaultSize(850, 450)
}
if userPrefs.Wintop > 0 && userPrefs.Winleft > 0 {
mainWin.Move(int(userPrefs.Winleft), int(userPrefs.Wintop))
}
mainWin.ShowAll()
// mainWin.SetKeepAbove(true)
gtk.Main()
}
|
package controllers
import (
"github.com/astaxie/beego"
"restapp/models"
)
type ProxyController struct {
beego.Controller
}
func (p *ProxyController) GetUserInfo() {
proxy := &models.Proxy{}
err, users := proxy.GetAllUser()
if err != nil {
p.Data["error"] = err
} else {
p.Data["data"] = users
}
p.ServeJSON()
}
|
package Search_Insert_Position
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestSearchInsert(t *testing.T) {
ast := assert.New(t)
ast.Equal(searchInsert([]int{1, 3, 5, 6}, 5), 2)
ast.Equal(searchInsert([]int{1, 3, 5, 6}, 2), 1)
ast.Equal(searchInsert([]int{1, 3, 5, 6}, 7), 4)
ast.Equal(searchInsert([]int{1, 3, 5, 6}, 0), 0)
}
func TestSearchInsertII(t *testing.T) {
ast := assert.New(t)
ast.Equal(searchInsert2([]int{1, 3, 5, 6}, 5), 2)
ast.Equal(searchInsert2([]int{1, 3, 5, 6}, 2), 1)
ast.Equal(searchInsert2([]int{1, 3, 5, 6}, 7), 4)
ast.Equal(searchInsert2([]int{1, 3, 5, 6}, 0), 0)
}
|
package config
import "log"
// GetConfig get current config
func GetConfig() Config {
return config
}
// GetAPIID get API ID
func GetAPIID() string {
return config.ApiId
}
// GetAPIHash get API Hash
func GetAPIHash() string {
return config.ApiHash
}
// GetBotToken get bot token
func GetBotToken() string {
return config.BotToken
}
// GetChatID get chat ID
func GetChatID() int64 {
return config.ChatId
}
// SetChatID update chat ID
func SetChatID(value int64) {
config.ChatId = value
}
// GetChatUsername get chat username
func GetChatUsername() string {
return config.ChatUsername
}
// GetPinnedMessage get pinned message ID
func GetPinnedMessage() int64 {
return config.PinnedMsg << 20
}
// SetPinnedMessage update pinned message ID
func SetPinnedMessage(value int64) {
config.PinnedMsg = value >> 20
}
// GetBeefWebPort get Beefweb port
func GetBeefWebPort() int {
return config.BeefwebPort
}
// GetPlaylistID get playlist ID
func GetPlaylistID() string {
return config.PlaylistId
}
// SetChatSelectLimit set select limit of group chat
func SetChatSelectLimit(value int) {
config.LimitSetting.ChatSelectLimit = value
}
// GetChatSelectLimit get select limit of group chat
func GetChatSelectLimit() int {
return config.LimitSetting.ChatSelectLimit
}
// SetPrivateChatSelectLimit set select limit of private chat
func SetPrivateChatSelectLimit(value int) {
config.LimitSetting.PriSelectLimit = value
}
// GetPrivateChatSelectLimit get select limit of private chat
func GetPrivateChatSelectLimit() int {
return config.LimitSetting.PriSelectLimit
}
// SetRowLimit set row limit
func SetRowLimit(value int) {
config.LimitSetting.RowLimit = value
}
// GetRowLimit get row limit
func GetRowLimit() int {
return config.LimitSetting.RowLimit
}
// SetQueueLimit set queue song limit
func SetQueueLimit(value int) {
config.LimitSetting.QueueLimit = value
}
// GetQueueLimit get queue song limit
func GetQueueLimit() int {
return config.LimitSetting.QueueLimit
}
// SetRecentLimit set recent song limit
func SetRecentLimit(value int) {
config.LimitSetting.RecentLimit = value
}
// GetRecentLimit get recent song limit
func GetRecentLimit() int {
return config.LimitSetting.RecentLimit
}
// SetReqSongLimit set request song limit
func SetReqSongLimit(value int) {
config.LimitSetting.ReqSongPerMin = value
}
// GetReqSongLimit get request song limit
func GetReqSongLimit() int {
return config.LimitSetting.ReqSongPerMin
}
// IsVoteEnabled return true if vote is enabled
func IsVoteEnabled() bool {
return config.VoteSetting.Enable
}
// SetVoteEnable set vote on or off
func SetVoteEnable(value bool) {
config.VoteSetting.Enable = value
}
// SetSuccessRate set vote success rate
func SetSuccessRate(value float64) {
config.VoteSetting.PctOfSuccess = value
}
// GetSuccessRate get vote success rate
func GetSuccessRate() float64 {
return config.VoteSetting.PctOfSuccess
}
// SetPtcpEnable update participants only
func SetPtcpEnable(value bool) {
config.VoteSetting.PtcpsOnly = value
}
// IsPtcpsOnly return true if only participants which are in a voice chat can vote
func IsPtcpsOnly() bool {
return config.VoteSetting.PtcpsOnly
}
// SetVoteTime update the vote time
func SetVoteTime(value int32) {
config.VoteSetting.VoteTime = value
}
// GetVoteTime get vote time
func GetVoteTime() int32 {
return config.VoteSetting.VoteTime
}
// SetReleaseTime set lock the vote seconds after vote ended
func SetReleaseTime(value int64) {
config.VoteSetting.ReleaseTime = value
}
// GetReleaseTime get lock the vote seconds after vote ended
func GetReleaseTime() int64 {
return config.VoteSetting.ReleaseTime
}
// SetUpdateTime update the vote update time
func SetUpdateTime(value int32) {
config.VoteSetting.UpdateTime = value
}
// GetUpdateTime get vote update time
func GetUpdateTime() int32 {
return config.VoteSetting.UpdateTime
}
// IsJoinNeeded return true if only users which are in the group can vote
func IsJoinNeeded() bool {
return config.VoteSetting.UserMustJoin
}
// SetJoinEnable update user must join
func SetJoinEnable(value bool) {
config.VoteSetting.UserMustJoin = value
}
// IsWebEnabled return true if userbot mode is disabled
func IsWebEnabled() bool {
return config.WebSetting.Enable
}
// GetWebPort get web port
func GetWebPort() int {
return config.WebSetting.Port
}
func compareUpdateVoteTime() {
if GetUpdateTime() > GetVoteTime() {
SetUpdateTime(5)
log.Println("'update_time' is greater than 'vote_time' is not allowed.\n" +
"Applying default value(5s) to 'update_time'.")
}
}
func checkVoteTimeIsTooSmall() {
if GetVoteTime() < 5 {
SetVoteTime(5)
log.Println("'vote_time' is smaller than 5s is not allowed.\n" +
"Value increased to 5s")
}
}
func checkUpdateTimeIsTooSmall() {
if GetUpdateTime() < 5 {
SetUpdateTime(5)
log.Println("'update_time' is smaller than 5s is not allowed.\n" +
"Value increased to 5s")
}
}
|
package serve
import "net/http"
// Context for serve
type Context struct {
Server *Server
Namespace *Namespace
Application *Application
Module *Module
User *User
URL string
Path string
}
// NewContext for create new context
func NewContext(server *Server, r *http.Request) *Context {
ctx := new(Context)
url := r.URL.Path
ctx.URL = url
ctx.Server = server
ctx.User = NewUser("")
system := server.System
system.Build(ctx, url)
//auth := new(routeAuthenticator)
//auth.Validate(ctx, r)
return ctx
}
|
package main
import (
"flag"
"io/ioutil"
"log"
"net/http"
)
var args = []string{
"https://dns.twnic.tw/dns-query",
"https://doh-2.seby.io/dns-query",
"https://dns.containerpi.com/dns-query",
"https://cloudflare-dns.com/dns-query",
"https://doh-fi.blahdns.com/dns-query",
"https://doh-jp.blahdns.com/dns-query",
"https://dns.dns-over-https.com/dns-query",
"https://doh.securedns.eu/dns-query",
"https://dns.rubyfish.cn/dns-query",
}
func main() {
//DNSResolvers := setupResolvers()
// Let's setup our flags and parse them
resolverTarget := flag.String("resolver", "https://cloudflare-dns.com/dns-query", "File of targets to connect to (host:port). Port is optional.")
queryTarget := flag.String("q", "example.com", "The domain to query")
queryType := flag.String("type", "A", "The type of DNS query to make; default is A")
flag.Parse()
response, err := BaseRequest(*resolverTarget, *queryTarget, *queryType)
if err != nil {
log.Printf("Error: %v", response)
}
log.Println(response)
}
// BaseRequest makes a DNS over HTTP (DOH) GET request for a specified query
func BaseRequest(server, query, qtype string) (string, error) {
//encquery := base64.StdEncoding.EncodeToString([]byte(query))
//encquery = url.QueryEscape(encquery)
qurl := server + "?name=" + query + "&type=" + qtype
client := &http.Client{}
req, _ := http.NewRequest("GET", qurl, nil)
req.Header.Set("accept", "application/dns-json")
res, err := client.Do(req)
if err != nil {
log.Println("Error getting the url")
return "", err
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
log.Println("Error getting the url")
return "", err
}
return string(body), nil
}
// Add a post resolution ?
|
package tools
import (
"bufio"
"errors"
"io"
"io/ioutil"
"os"
"path"
"path/filepath"
"strings"
"github.com/theckman/go-flock"
)
//CheckPath 检查文件夹是否存在,不存在则创建
func CheckPath(logPath string) error {
dir := filepath.Dir(logPath)
_, err := os.Stat(dir)
if err != nil {
if os.IsNotExist(err) {
err := os.MkdirAll(dir, os.ModePerm)
if err != nil {
return err
}
}
}
return nil
}
// GetFileSuffix 去除文件扩展名
func GetFileSuffix(s string) string {
fileSuffix := path.Ext(s)
filenameOnly := strings.TrimSuffix(s, fileSuffix)
return filenameOnly
}
// LockOrDie 加锁文件夹
func LockOrDie(dir string) (*flock.Flock, error) {
f := flock.New(dir)
success, err := f.TryLock()
if err != nil {
return nil, err
}
if !success {
return nil, err
}
return f, nil
}
// MakeDirectory 创建 directory if is not exists
func MakeDirectory(dir string) error {
if _, err := os.Stat(dir); err != nil {
if os.IsNotExist(err) {
return os.Mkdir(dir, 0775)
}
return err
}
return nil
}
//PathExists 判断文件夹是否存在
func PathExists(path string) (bool, error) {
_, err := os.Stat(path)
if err == nil {
return true, nil
}
if os.IsNotExist(err) {
return false, nil
}
return false, err
}
//GetAllFile 获取pathname路径下所有扩展名为suffix的文件名数组
func GetAllFile(pathname string, suffix string) (fileSlice []string) {
rd, err := ioutil.ReadDir(pathname)
if err != nil {
return
}
for _, fi := range rd {
if fi.IsDir() {
continue
//GetAllFile(path.Join(pathname, fi.Name()))
} else {
if suffix != "" {
if strings.HasSuffix(fi.Name(), suffix) {
fileSlice = append(fileSlice, fi.Name())
}
} else {
fileSlice = append(fileSlice, fi.Name())
}
}
}
return
}
/** CopyDir
* 拷贝文件夹,同时拷贝文件夹中的文件
* @param srcPath 需要拷贝的文件夹路径: D:/test
* @param destPath 拷贝到的位置: D:/backup/
*/
func CopyDir(srcPath string, destPath string) error {
//检测目录正确性
if srcInfo, err := os.Stat(srcPath); err != nil {
return err
} else {
if !srcInfo.IsDir() {
e := errors.New("srcPath不是一个正确的目录!")
return e
}
}
if destInfo, err := os.Stat(destPath); err != nil {
if err := MakeDirectory(destPath); err != nil {
return err
}
} else {
if !destInfo.IsDir() {
e := errors.New("destInfo不是一个正确的目录!")
return e
}
}
//加上拷贝时间:不用可以去掉
//destPath = destPath + "_" + time.Now().Format("20060102150405")
err := filepath.Walk(srcPath, func(path string, f os.FileInfo, err error) error {
if f == nil {
return err
}
if !f.IsDir() {
path := strings.Replace(path, "\\", "/", -1)
destNewPath := strings.Replace(path, srcPath, destPath, -1)
CopyFile(path, destNewPath)
}
return nil
})
return err
}
//生成目录并拷贝文件
func CopyFile(src, dest string) (w int64, err error) {
srcFile, err := os.Open(src)
if err != nil {
return
}
defer srcFile.Close()
//分割path目录
destSplitPathDirs := strings.Split(dest, "/")
//检测时候存在目录
destSplitPath := ""
for index, dir := range destSplitPathDirs {
if index < len(destSplitPathDirs)-1 {
destSplitPath = destSplitPath + dir + "/"
b, _ := PathExists(destSplitPath)
if !b {
//创建目录
err := os.Mkdir(destSplitPath, os.ModePerm)
if err != nil {
return w, err
}
}
}
}
dstFile, err := os.Create(dest)
if err != nil {
return
}
defer dstFile.Close()
return io.Copy(dstFile, srcFile)
}
//解析text文件内容
func ReadFile(path string) (str string, err error) {
//打开文件的路径
fi, err := os.Open(path)
if err != nil {
err = errors.New(path + "不是一个正确的目录!")
return
}
defer fi.Close()
//读取文件的内容
fd, err := ioutil.ReadAll(fi)
if err != nil {
err = errors.New(path + "读取文件失败!")
return
}
str = string(fd)
return str, err
}
//WriteFile 写入text文件内容
//coverType true 覆盖写入,false 追加写入
func WriteFile(path, info string, coverType bool) (err error) {
var fl *os.File
flag := os.O_APPEND | os.O_WRONLY
if coverType {
flag = os.O_APPEND | os.O_TRUNC | os.O_WRONLY
}
if CheckFileIsExist(path) { //如果文件存在
fl, err = os.OpenFile(path, flag, 0666) //打开文件
} else {
fl, err = os.Create(path) //创建文件
}
if err != nil {
err = errors.New(path + "打开文件失败!")
return
}
defer fl.Close()
n, err := fl.WriteString(info + "\n")
if err == nil && n < len(info) {
err = errors.New(path + "写入失败!")
}
return
}
//WriteFile 写入Byte文件内容
//coverType true 覆盖写入,false 追加写入
func WriteFileByte(path string, info []byte, coverType bool) (err error) {
var fl *os.File
flag := os.O_APPEND | os.O_WRONLY
if coverType {
flag = os.O_APPEND | os.O_TRUNC | os.O_WRONLY
}
if CheckFileIsExist(path) { //如果文件存在
fl, err = os.OpenFile(path, flag, os.ModePerm) //打开文件
} else {
fl, err = os.Create(path) //创建文件
}
defer fl.Close()
if err != nil {
// err = errors.New(path + "打开文件失败!")
return
}
n, err := fl.Write(info)
if err == nil && n < len(info) {
err = errors.New(path + "写入失败!")
}
return
}
/**
* 判断文件是否存在 存在返回 true 不存在返回false
*/
func CheckFileIsExist(filename string) bool {
var exist = true
if _, err := os.Stat(filename); os.IsNotExist(err) {
exist = false
}
return exist
}
func GetDirList(dirpath, pathStr string) []DirBody {
var allFile []DirBody
finfo, _ := ioutil.ReadDir(dirpath)
//info, _ := os.Stat(dirpath)
//allFile.Label = info.Name()
//chiledrens := make([]DirBody, 0)
for _, x := range finfo {
//var dirInfo DirBody
var chiledren DirBody
if x.IsDir() {
realPath := filepath.Join(dirpath, x.Name())
realDir := filepath.Join(pathStr, x.Name())
chiledren.Label = x.Name()
chiledren.Dir = realDir
chiledren.Icon = "el-icon-folder"
chiledren.Children = append(chiledren.Children, GetDirList(realPath, realDir)...)
allFile = append(allFile, chiledren)
}
}
return allFile
}
type DirBody struct {
Label string `json:"label"`
Children []DirBody `json:"children"`
Icon string `json:"icon"`
Dir string `json:"dir"`
}
//递归查找空目录
func FindEmptyFolder(dirname string) (emptys []string, err error) {
// Golang学习 - io/ioutil 包
// https://www.cnblogs.com/golove/p/3278444.html
files, err := ioutil.ReadDir(dirname)
if err != nil {
return nil, err
}
// 判断底下是否有文件
if len(files) == 0 {
return []string{dirname}, nil
}
for _, file := range files {
if file.IsDir() {
edirs, err := FindEmptyFolder(path.Join(dirname, file.Name()))
if err != nil {
return nil, err
}
if edirs != nil {
emptys = append(emptys, edirs...)
}
}
}
return emptys, nil
}
func EmptyFloder(dir string) error {
emptys, err := FindEmptyFolder(dir)
if err != nil {
return err
}
for _, dir := range emptys {
if err := os.Remove(dir); err != nil {
return err
} else {
return err
}
}
return nil
}
func substr(s string, pos, length int) (string, string) {
runes := []rune(s)
l := pos + length
if l > len(runes) {
l = len(runes)
}
return string(runes[pos : l+1]), string(runes[l+1:])
}
func GetParentDirectory(dirctory, prefix string) (string, string, bool) {
index := strings.Index(dirctory, prefix)
if index > -1 {
res, eres := substr(dirctory, 0, index)
return res, eres, true
}
return dirctory, "", false
}
// ReadLine 读取指定行的内容
func ReadLine(fileName string, lineNumber int) string {
file, _ := os.Open(fileName)
fileScanner := bufio.NewScanner(file)
lineCount := 1
for fileScanner.Scan() {
if lineCount == lineNumber {
return fileScanner.Text()
}
lineCount++
}
defer file.Close()
return ""
}
|
package billing
import (
"github.com/stripe/stripe-go"
"github.com/stripe/stripe-go/charge"
)
const SECRET_KEY = "sk_live_IS0W5w62ttenjEpuQozj4VDE"
func Charge(amount uint, token string, name string) (chargeID string, err error) {
stripe.Key = SECRET_KEY
chargeParams := &stripe.ChargeParams{
Amount: uint64(amount * 100),
Currency: "usd",
Customer: token,
Desc: "Charge for " + name,
}
ch, err := charge.New(chargeParams)
if err != nil {
return
}
chargeID = ch.ID
return
}
|
// Copyright © 2020. All rights reserved.
// Author: Ilya Stroy.
// Contacts: qioalice@gmail.com, https://github.com/qioalice
// License: https://opensource.org/licenses/MIT
package ekaletter
import (
"fmt"
"reflect"
"time"
"unsafe"
"github.com/qioalice/ekago/v2/internal/ekaclike"
"github.com/qioalice/ekago/v2/internal/ekafield"
"github.com/modern-go/reflect2"
)
var (
reflectedTimeTime = reflect2.TypeOf(time.Time{})
reflectedTimeDuration = reflect2.TypeOf(time.Duration(0))
)
// addImplicitField adds new field to l.Fields treating 'name' as field's name,
// 'value' as field's value and using 'typ' (assuming it's value's type)
// to recognize how to convert Golang's interface{} to the 'Field' object.
func (li *LetterItem) addImplicitField(name string, value interface{}, typ reflect2.Type) {
varyField := name != "" && name[len(name)-1] == '?'
if varyField {
name = name[:len(name)-1]
}
var f ekafield.Field
switch {
case value == nil && varyField:
// do nothing
return
case value == nil:
li.Fields = append(li.Fields, ekafield.NilValue(name, ekafield.KIND_TYPE_INVALID))
return
case typ == reflectedTimeTime:
var timeVal time.Time
typ.UnsafeSet(unsafe.Pointer(&timeVal), reflect2.PtrOf(value))
f = ekafield.Time(name, timeVal)
goto recognizer
case typ == reflectedTimeDuration:
var durationVal time.Duration
typ.UnsafeSet(unsafe.Pointer(&durationVal), reflect2.PtrOf(value))
f = ekafield.Duration(name, durationVal)
goto recognizer
// PLACE TYPES ABOVE THAT HAS String() METHOD BUT YOU DON'T WANT TO USE IT.
case typ.Implements(ekafield.ReflectedTypeFmtStringer):
f = ekafield.Stringer(name, value.(fmt.Stringer))
goto recognizer
}
switch typ.Kind() {
case reflect.Ptr:
// Maybe it's typed nil pointer? We can't dereference nil pointer
// but I guess it's important to log nil pointer as is even if
// FLAG_ALLOW_IMPLICIT_POINTERS is not set (because what can we do otherwise?)
logPtrAsIs :=
li.Flags.TestAll(FLAG_ALLOW_IMPLICIT_POINTERS) ||
ekaclike.TakeRealAddr(value) == nil
if logPtrAsIs {
f = ekafield.Addr(name, value)
} else {
value = typ.Indirect(value)
li.addImplicitField(name, value, reflect2.TypeOf(value))
}
case reflect.Bool:
var boolVal bool
typ.UnsafeSet(unsafe.Pointer(&boolVal), reflect2.PtrOf(value))
f = ekafield.Bool(name, boolVal)
case reflect.Int:
var intVal int
typ.UnsafeSet(unsafe.Pointer(&intVal), reflect2.PtrOf(value))
f = ekafield.Int(name, intVal)
case reflect.Int8:
var int8Val int8
typ.UnsafeSet(unsafe.Pointer(&int8Val), reflect2.PtrOf(value))
f = ekafield.Int8(name, int8Val)
case reflect.Int16:
var int16Val int16
typ.UnsafeSet(unsafe.Pointer(&int16Val), reflect2.PtrOf(value))
f = ekafield.Int16(name, int16Val)
case reflect.Int32:
var int32Val int32
typ.UnsafeSet(unsafe.Pointer(&int32Val), reflect2.PtrOf(value))
f = ekafield.Int32(name, int32Val)
case reflect.Int64:
var int64Val int64
typ.UnsafeSet(unsafe.Pointer(&int64Val), reflect2.PtrOf(value))
f = ekafield.Int64(name, int64Val)
case reflect.Uint:
var uintVal uint64
typ.UnsafeSet(unsafe.Pointer(&uintVal), reflect2.PtrOf(value))
f = ekafield.Uint64(name, uintVal)
case reflect.Uint8:
var uint8Val uint8
typ.UnsafeSet(unsafe.Pointer(&uint8Val), reflect2.PtrOf(value))
f = ekafield.Uint8(name, uint8Val)
case reflect.Uint16:
var uint16Val uint16
typ.UnsafeSet(unsafe.Pointer(&uint16Val), reflect2.PtrOf(value))
f = ekafield.Uint16(name, uint16Val)
case reflect.Uint32:
var uint32Val uint32
typ.UnsafeSet(unsafe.Pointer(&uint32Val), reflect2.PtrOf(value))
f = ekafield.Uint32(name, uint32Val)
case reflect.Uint64:
var uint64Val uint64
typ.UnsafeSet(unsafe.Pointer(&uint64Val), reflect2.PtrOf(value))
f = ekafield.Uint64(name, uint64Val)
case reflect.Float32:
var float32Val float32
typ.UnsafeSet(unsafe.Pointer(&float32Val), reflect2.PtrOf(value))
f = ekafield.Float32(name, float32Val)
case reflect.Float64:
var float64Val float64
typ.UnsafeSet(unsafe.Pointer(&float64Val), reflect2.PtrOf(value))
f = ekafield.Float64(name, float64Val)
case reflect.Complex64:
var complex64Val complex64
typ.UnsafeSet(unsafe.Pointer(&complex64Val), reflect2.PtrOf(value))
f = ekafield.Complex64(name, complex64Val)
case reflect.Complex128:
var complex128Val complex128
typ.UnsafeSet(unsafe.Pointer(&complex128Val), reflect2.PtrOf(value))
f = ekafield.Complex128(name, complex128Val)
case reflect.String:
var stringVal string
typ.UnsafeSet(unsafe.Pointer(&stringVal), reflect2.PtrOf(value))
f = ekafield.String(name, stringVal)
case reflect.Uintptr, reflect.UnsafePointer:
f = ekafield.Addr(name, value)
// TODO: handle all structs, handle structs with Valid (bool) = false as null
default:
}
recognizer:
if !(varyField && f.IsZero()) {
li.Fields = append(li.Fields, f)
}
}
// addExplicitFieldByPtr adds 'f' to the l.Fields only if it's not nil and
// if it's not a vary-zero field.
func (li *LetterItem) addExplicitFieldByPtr(f *ekafield.Field) {
if f != nil {
li.addExplicitField2(*f)
}
}
// addExplicitField2 adds 'f' to the l.Fields only if it's not vary-zero field.
func (li *LetterItem) addExplicitField2(f ekafield.Field) {
varyField := f.Key != "" && f.Key[len(f.Key)-1] == '?'
if varyField {
f.Key = f.Key[:len(f.Key)-1]
}
if !(varyField && f.IsZero()) {
li.Fields = append(li.Fields, f)
}
}
|
package main
import (
"bufio"
"flag"
"fmt"
"os"
"strconv"
)
var port = flag.String("serial", "/dev/ttyACM0", "The serial port for the arduino")
var outfile = flag.String("outfile", "", "output file to write to")
func main() {
flag.Parse()
readings := make(chan uint16)
port, err := os.Open(*port)
if err != nil {
panic(err)
}
buf := bufio.NewReader(port)
go func() {
for {
by, err := buf.ReadBytes('\n')
if err != nil {
panic(err)
}
if len(by) == 1 {
continue
}
by = by[:len(by)-1]
i, err := strconv.Atoi(string(by))
// every once in a while the serial port gets overloaded
// or the heart thing gets confused and sends invalid
// inputs that appear to be two numbers mixed together.
// While I'd love to fix that on the Arduino side, in the
// meantime we need to handle it. 1024 is the top end of
// what it is supposed to emit:
// https://www.arduino.cc/en/Reference/AnalogRead
// and most such distortions appear to result in numbers larger
// than that.
// Also, as far as FFTs are concerned I'm pretty sure it's much
// better to drop a sample than to put a spurious transient in
// it, which will spray high frequencies everywhere.
if err == nil && i < 1024 {
readings <- uint16(i)
} else {
if i >= 65535 {
continue
}
fmt.Println(err)
}
}
}()
}
|
package LeetCode
import "fmt"
func Code70() {
fmt.Println(climbStairs(4))
}
/**
假设你正在爬楼梯。需要 n 阶你才能到达楼顶。
每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢?
注意:给定 n 是一个正整数。
示例 1:
输入: 2
输出: 2
解释: 有两种方法可以爬到楼顶。
1. 1 阶 + 1 阶
2. 2 阶
示例 2:
输入: 3
输出: 3
解释: 有三种方法可以爬到楼顶。
1. 1 阶 + 1 阶 + 1 阶
2. 1 阶 + 2 阶
3. 2 阶 + 1 阶
*/
func climbStairs(n int) int {
var arr = map[int]int{}
if n <= 0 {
return 0
}
if n <= 3 {
return n
}
arr[1] = 1
arr[2] = 2
i := 0
for i = 3; i < n+1; i++ {
arr[i] = arr[i-1] + arr[i-2]
}
return arr[n]
}
|
package adapter
import (
"github.com/Placons/oneapp-logger/logger"
"io"
)
// closes http body stream while preserving error in defer
func closeBody(body io.ReadCloser, err *error, l *logger.StandardLogger) {
l.Debug("Closing body stream.")
e := body.Close()
if err == nil && e != nil {
l.Debug("Got an error while closing body stream. Returning error.")
err = &e
l.ErrorWithErr("Got an error while closing body stream.", *err)
}
l.Debug("Closed body stream.")
}
|
package gemini
import (
"context"
"encoding/json"
"net/http"
)
type TickerInput struct {
Ticker string
}
type TickerResponse struct {
Ask string `json:"ask"`
Bid string `json:"bid"`
Last string `json:"last"`
Volume Volume `json:"volume"`
}
type Volume struct {
Btc string `json:"BTC"`
Usd string `json:"USD"`
Timestamp int64 `json:"timestamp"`
}
// Ticker get ticker information about trading symbols
func (c *Client) Ticker(ctx context.Context, i *TickerInput) (*TickerResponse, error) {
var response *TickerResponse
request := "/v1/pubticker/"
req, err := http.NewRequestWithContext(ctx,
http.MethodGet,
c.BaseURL+request+i.Ticker,
nil,
)
if err != nil {
return nil, err
}
rawResponse, err := c.doPublicRequest(req)
if rawResponse == nil || err != nil {
return nil, err
}
if err := json.Unmarshal(rawResponse, &response); err != nil {
return nil, err
}
return response, nil
}
|
package grpc
import (
"context"
"database/sql"
"fmt"
"net"
"github.com/bns-engineering/platformbanking-card/common/logging"
pt "github.com/bns-engineering/platformbanking-card/handler/grpc/proto"
"github.com/bns-engineering/platformbanking-presenter/common/lookup"
"google.golang.org/grpc"
"google.golang.org/grpc/reflection"
)
//Server structure
type Server struct {
GrpcServer *grpc.Server
DBConn *sql.DB
}
// New - creates new grpc server
func New() *Server {
server := Server{}
s := grpc.NewServer()
pt.RegisterCardHandlerServer(s, &server)
reflection.Register(s)
server.GrpcServer = s
return &server
}
// Start - starts grpc server
func (s *Server) Start(port string) {
go func() {
lis, err := net.Listen("tcp", fmt.Sprintf(port))
if err != nil {
strlog := fmt.Sprintf("failed to listen: %v", err)
logging.InfoLn(strlog)
}
strlog := fmt.Sprintf("GRPC Started. Listening on port: %s", port)
logging.InfoLn(strlog)
if err := s.GrpcServer.Serve(lis); err != nil {
strlog := fmt.Sprintf("failed to serve: %s", err)
logging.InfoLn(strlog)
}
}()
}
// Ping - get ping pong
func (s *Server) Ping(ctx context.Context, in *pt.PingRq) (reply *pt.PingRp, err error) {
reply = &pt.PingRp{}
reply.ResponseCode = lookup.SUCCESS
return
}
|
package main
import (
"bufio"
"os"
"fmt"
"strconv"
"strings"
)
func main() {
//var s string
//var s2 string
//
//// Send in the reference of the string s
//fmt.Scanln(&s, &s2)
//// Print the value of it.
//fmt.Println(s, s2)
reader := bufio.NewReader(os.Stdin)
fmt.Print("Enter string: ")
str, _ := reader.ReadString('\n')
fmt.Println(str)
// For a float number
fmt.Print("Enter number: ")
str, _ = reader.ReadString('\n')
f, err := strconv.ParseFloat(strings.TrimSpace(str), 64)
if err != nil{
fmt.Println(err)
} else {
fmt.Println(f)
}
}
|
package scraper
import (
"bytes"
"errors"
"net/http"
"net/http/cookiejar"
"strings"
)
var app App
//Debug to set debugging mode for more logging output
var Debug *bool
//Start Scraper which logs into lms portal and creates a client cookiejar which stores cookie which is useful to maintain
//login session throughout the running of daemon service.
func Start() error {
// file, errlog := os.OpenFile("logs.txt", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)
// if errlog != nil {
// log.Fatal(errlog)
// }
// log.SetOutput(file)
jar, _ := cookiejar.New(nil)
app = App{
Client: &http.Client{Jar: jar},
}
loginstatus, _ := app.login()
if len(loginstatus) > 0 {
return errors.New(loginstatus)
}
return nil
}
//Stop Scraper application and logout of lms called when daemon is stopped
func Stop() error {
if app.isLoggedIn {
app.logout()
} else {
return errors.New("Service was not Started to Stop so ... did not stop the service")
}
return nil
}
//GetEventsTerm function helps to get Events byte array with terminal color support
func GetEventsTerm() []byte {
events := app.getEvents()
var buffer bytes.Buffer
courseID := 0
var setColor bool
for _, event := range events {
if courseID != event.CourseID {
courseID = event.CourseID
buffer.WriteString("\\x1b[38;2;250;169;22m")
setColor = true
}
buffer.WriteString(event.Name)
buffer.WriteString(" ")
buffer.WriteString(event.Formattedtime)
buffer.WriteString("\\n")
if setColor {
setColor = false
buffer.WriteString("\\x1b[38;2;251;255;254m")
}
}
buffer.WriteString("\\x1b[0m\n")
return buffer.Bytes()
}
//GetEvents to get Events byte array to be sent to socket client
func GetEvents() []byte {
events := app.getEvents()
var buffer bytes.Buffer
for _, event := range events {
buffer.WriteString(event.Name)
buffer.WriteString(" ")
buffer.WriteString(event.Formattedtime)
buffer.WriteString("\n")
}
return buffer.Bytes()
}
//GetEventsConky to get Events byte array with conky color support
func GetEventsConky() []byte {
events := app.getEvents()
var buffer bytes.Buffer
courseID := 0
var setColor bool
for _, event := range events {
if courseID != event.CourseID {
courseID = event.CourseID
buffer.WriteString("${#FAA916}")
setColor = true
}
buffer.WriteString(event.Name)
buffer.WriteString(" ")
buffer.WriteString(event.Formattedtime)
buffer.WriteString("\n")
if setColor {
setColor = false
buffer.WriteString("${#FBFFFE}")
}
}
return buffer.Bytes()
}
//GetAnnouncementsTerm to get Announcements byte array with terminal color support
func GetAnnouncementsTerm() []byte {
announcements := app.getAnnouncements()
var buffer bytes.Buffer
courseID := 0
var setColor bool
for _, announcement := range announcements {
if courseID != announcement.CourseID {
courseID = announcement.CourseID
buffer.WriteString("\\x1b[38;2;250;169;22m")
setColor = true
}
buffer.WriteString(announcement.Date)
buffer.WriteString(" ")
buffer.WriteString(announcement.Name)
buffer.WriteString(" ")
info := strings.ReplaceAll(announcement.Info, "#", "\\#")
buffer.WriteString(info)
buffer.WriteString("\n")
if setColor {
setColor = false
buffer.WriteString("\\x1b[38;2;251;255;254m")
}
}
buffer.WriteString("\\x1b[0m\n")
return buffer.Bytes()
}
//GetAnnouncements to get Announcements byte array to be send to socket client
func GetAnnouncements() []byte {
announcements := app.getAnnouncements()
var buffer bytes.Buffer
for _, announcement := range announcements {
buffer.WriteString(announcement.Date)
buffer.WriteString(" ")
buffer.WriteString(announcement.Name)
buffer.WriteString(" ")
info := strings.ReplaceAll(announcement.Info, "#", "\\#")
buffer.WriteString(info)
buffer.WriteString("\n")
}
return buffer.Bytes()
}
//GetAnnouncementsConky to get Announcements byte array with conky color support
func GetAnnouncementsConky() []byte {
announcements := app.getAnnouncements()
var buffer bytes.Buffer
courseID := 0
var setColor bool
for _, announcement := range announcements {
if courseID != announcement.CourseID {
courseID = announcement.CourseID
buffer.WriteString("${#FAA916}")
setColor = true
}
buffer.WriteString(announcement.Date)
buffer.WriteString(" ")
buffer.WriteString(announcement.Name)
buffer.WriteString(" ")
info := strings.ReplaceAll(announcement.Info, "#", "\\#")
buffer.WriteString(info)
buffer.WriteString("\n")
if setColor {
setColor = false
buffer.WriteString("${#FBFFFE}")
}
}
return buffer.Bytes()
}
//GetUnknownResponse for Unknown Args given to Socket server
func GetUnknownResponse() []byte {
var buffer bytes.Buffer
buffer.WriteString("Unknown Command\n")
return buffer.Bytes()
}
//SetUserPass sets username and password to login to lms portal
func SetUserPass(user string, pass string) {
username = user
password = pass
}
//GetUserName returns username which is used to login into lms portal
func GetUserName() string {
return username
}
//SetDebugMode to set debug Mode for enabling more logs
func SetDebugMode(debug *bool) {
Debug = debug
}
|
package main
import (
"context"
"fmt"
"time"
)
func main() {
forever := make(chan struct{})
ctx, cancel := context.WithCancel(context.Background())
go func(ctx context.Context) {
for {
select {
case <-ctx.Done():
forever <-struct{}{}
return
default:
fmt.Println("for loop...")
}
time.Sleep(500 * time.Millisecond)
}
}(ctx)
go func() {
fmt.Println(" 3秒之后 cancel 掉 context,才写入 ctx.Done()")
time.Sleep(3 * time.Second)
cancel()
}()
// 阻塞的作用
<-forever
fmt.Println("done...")
}
|
package service
import (
"galaxy-weather/model"
"github.com/sirupsen/logrus"
)
type IPeriodService interface {
GetAll() (*[]model.Period, error)
GetStats() (interface{}, error)
}
type periodService struct{}
func newPeriodService() IPeriodService {
return &periodService{}
}
var PeriodService = newPeriodService()
func (ps periodService) GetAll() (*[]model.Period, error) {
var periods = make([]model.Period, 0)
weatherList, err := WeatherService.GetAll()
if err != nil {
logrus.Errorf("[PeriodService.GetAll] Error getting periods: %s", err.Error())
return nil, err
}
var period *model.Period
for _, day := range *weatherList {
day.WeatherType = day.ToType()
if day.WeatherType == model.Unknown {
continue
}
if period == nil {
period = fromDay(day)
continue
}
if period.WeatherType == day.WeatherType {
period.End = day.Day
continue
} else {
if period.WeatherType == model.Rain && day.WeatherType == model.HeavyRain {
period.Peak = new(uint)
*period.Peak = day.Day
continue
}
periods = append(periods, *period)
period = fromDay(day)
}
}
return &periods, nil
}
func fromDay(day model.Weather) *model.Period {
period := new(model.Period)
period.Start = day.Day
period.End = day.Day
period.WeatherType = day.WeatherType
period.Weather = day.Weather
return period
}
func (ps periodService) GetStats() (interface{}, error) {
stats := model.Stats{
Drought: 0,
Rain: 0,
RainPeaks: []uint{},
Optimal: 0,
}
periods, err := ps.GetAll()
if err != nil {
return nil, err
}
for _, period := range *periods {
if period.WeatherType == model.Drought {
stats.Drought++
}
if period.WeatherType == model.OptimalTemperature {
stats.Optimal++
}
if period.WeatherType == model.Rain {
stats.Rain++
if period.Peak != nil && *period.Peak > 0 {
stats.RainPeaks = append(stats.RainPeaks, *period.Peak)
}
}
}
return stats, nil
}
|
package mmseg
import (
"math"
)
type wordPoint struct {
Offset, Length, Freq int
}
type chunk struct {
Length int
WordPoints []wordPoint
}
func (this *chunk) Get(index int) wordPoint {
return this.WordPoints[index]
}
func (this *chunk) WordAverageLength() float64 {
return float64(this.Length) / float64(len(this.WordPoints))
}
func (this *chunk) Variance() float64 {
averageLength := this.WordAverageLength()
sum := float64(0)
for _, wordPoint := range this.WordPoints {
sum = sum + (math.Pow(float64(wordPoint.Length)-averageLength, 2))
}
return math.Sqrt(sum / float64(len(this.WordPoints)))
}
func (this *chunk) Degree() float64 {
sum := float64(0)
for _, wordPoint := range this.WordPoints {
sum = sum + math.Log10(float64(wordPoint.Freq))
}
return sum
}
|
package main
import (
"fmt"
)
var (
commandsCount = 10
// вероятность для того что используется регистровая адрессация
memoryVer float32 = 0.6
commandType float32 = 0.7
// CLC counting by type 2
commandCounting = 6
// CLC counting for memory access
commandMemoryCount = 3
)
func main() {
// reading from console
reader := NewReader()
reader.Read()
commands := make([]Command, 0)
for i := 0; i < commandsCount; i++ {
cmd := NewCommand(i)
cmd.SetCommand(commands, i)
commands = append(commands, cmd)
}
for _, el := range commands {
fmt.Println(el.FormatString())
}
result := CountArrangeTime(commands)
fmt.Println("---------------")
fmt.Println("Calculation time: ", result)
}
|
package sequence
import (
"crypto/sha256"
"fmt"
"os"
"strconv"
"strings"
"sync"
"sync/atomic"
)
type Sequence struct {
name string
filePath string
i int64
saveMtx sync.Mutex
lastSaved int64
DiskSaved int64
}
func NewSequence(name string, dir string) *Sequence {
s := &Sequence{name: name}
s.filePath = fmt.Sprintf("%s/%x.txt", dir, sha256.Sum256([]byte(fmt.Sprintf("%s_%s", name, dir))))
f, err := os.Open(s.filePath)
if err == nil {
buf := make([]byte, 65536)
_, err = f.Read(buf)
if err != nil {
return s
}
if f.Close() != nil {
return s
}
st := strings.Split(string(buf), "\n")
var i int64
i, err = strconv.ParseInt(st[0], 10, 64)
if err != nil {
return s
}
if name != st[1] {
return s
}
if fmt.Sprintf("%x", sha256.Sum256([]byte(fmt.Sprintf("%d%s", i, s.name)))) != st[2] {
return s
}
s.i = i
}
return s
}
func (s Sequence) Name() string {
return s.name
}
// Each goroutine get atomic value
func (s *Sequence) Next() (int64, error) {
return atomic.AddInt64(&s.i, 1), s.safeSave()
}
func (s *Sequence) Current() int64 {
return atomic.LoadInt64(&s.i)
}
func (s *Sequence) safeSave() error {
s.saveMtx.Lock()
defer s.saveMtx.Unlock()
return s.save()
}
func (s *Sequence) save() error {
i := atomic.LoadInt64(&s.i)
if i == s.lastSaved {
return nil
}
f, err := os.Create(s.filePath)
if err != nil {
return err
}
defer f.Close()
_, err = f.WriteString(fmt.Sprintf("%d\n%s\n%x\n", i, s.name, sha256.Sum256([]byte(fmt.Sprintf("%d%s", i, s.name)))))
if err != nil {
return err
}
s.lastSaved = i
s.DiskSaved++
return nil
}
|
package bean_util
import (
"errors"
"github.com/goinggo/mapstructure"
"reflect"
"strings"
)
func ProToStandard(in interface{}, out interface{}) (err error) {
if in == nil || out == nil {
err = errors.New("[ProToStandard] in or out is nil")
}
m := make(map[string]interface{})
elem := reflect.ValueOf(&in).Elem()
relType := elem.Type()
for i := 0; i < relType.NumField(); i++ {
if !strings.Contains(relType.Field(i).Name, "XXX") {
m[relType.Field(i).Name] = elem.Field(i).Interface()
}
}
//将 map 转换为指定的结构体
err = mapstructure.Decode(m, out)
return
}
|
package hbox
import (
"fmt"
"path/filepath"
"io/fs"
"os/exec"
"strings"
"github.com/gregfolker/honey/pkg/log"
"github.com/pkg/errors"
)
const (
HboxExt = ".hbox"
HboxToMp4 = "HboxToMp4.exe"
)
func HboxToMp4Present(d string) error {
found := false
err := filepath.Walk(d, func(path string, f fs.FileInfo, err error) error {
if f.IsDir() {
return filepath.SkipDir
}
if f.Name() == HboxToMp4 {
log.NewEntry(fmt.Sprintf("Found %s at %s", f.Name(), path))
if !found {
found = true
return nil
} else {
return errors.New(fmt.Sprintf("found multiple instances of %s in %s\n", f.Name(), path))
}
}
return nil
})
return err
}
func GetHboxFilename(d string) (string, error) {
file := ""
err := filepath.Walk(d, func(path string, f fs.FileInfo, err error) error {
if f.IsDir() {
return filepath.SkipDir
}
if filepath.Ext(f.Name()) == HboxExt {
log.NewEntry(fmt.Sprintf("Found %s at %s", f.Name(), path))
if file == "" {
file = f.Name()
return nil
} else {
return errors.New(fmt.Sprintf("found multiple *%s files in %s\n", HboxExt, path))
}
}
return nil
})
return file, err
}
func RunHboxToMp4(d string, f string) error {
cmdstr := strings.Join([]string{HboxToMp4, f, "out"}, " ")
cmd := exec.Command("sh", "-c", cmdstr)
log.NewEntry(fmt.Sprintf("Running cmd=%s", cmdstr))
if stdout, err := cmd.Output(); err != nil {
return err
} else {
fmt.Println(string(stdout))
}
return nil
}
|
// Helper functions to access/update db.
package model
import (
"errors"
"time"
"github.com/jinzhu/gorm"
_ "github.com/golang-migrate/migrate/database/postgres" // Driver
_ "github.com/golang-migrate/migrate/source/file" // Driver
_ "github.com/lib/pq" // Driver
)
//GetUsersInARoom : get all users for a particular room.
func GetUsersInARoom(db *gorm.DB, roomID uint) ([]*User, error) {
rows, err := db.Select("users.id, users.name").
Table("users").
Joins("LEFT JOIN usersrooms ON users.id = usersrooms.user_id").
Where("usersrooms.room_id = ?", roomID).Rows()
if err != nil {
return []*User{}, err
}
users := []*User{}
defer rows.Close()
for rows.Next() {
user := &User{}
err = db.ScanRows(rows, user)
if err != nil {
// handle this error
return []*User{}, err
}
users = append(users, user)
}
return users, nil
}
//GetRooms: get all rooms, populating whether given user has joined and notification status.
func GetRooms(db *gorm.DB, userID uint) ([]*RoomDetail, error) {
rooms := []*RoomDetail{}
subquery := db.Select("usersrooms.*").Table("usersrooms").Where("user_id = ?", userID).SubQuery()
rows, err := db.Select(`rooms.id, rooms.name, rooms.room_type,
ur.user_id IS NOT NULL as inroom, COALESCE(ur.unread, false) as unread`).
Table("rooms").
Joins("LEFT JOIN ? as ur ON rooms.id = ur.room_id", subquery).
Where("ur.user_id IS NOT NULL OR rooms.room_type = B'0'").
Rows()
if gorm.IsRecordNotFoundError(err) {
return rooms, nil
}
if err != nil {
return rooms, err
}
defer rows.Close()
for rows.Next() {
room := &RoomDetail{}
err = db.ScanRows(rows, room)
if err != nil {
return []*RoomDetail{}, err
}
rooms = append(rooms, room)
}
return rooms, nil
}
// GetAllMessagesFromRoom get all messages for a particular room.
func GetAllMessagesFromRoom(db *gorm.DB, roomID uint) ([]*MessageHistory, error) {
rows, err := db.Table("messages").
Select("messages.id, messages.time, messages.body, messages.sender_id, messages.room_id, users.name").
Joins("join users on messages.sender_id = users.id").
Where("messages.room_id = ?", roomID).
Order("messages.id").
Rows()
if err != nil {
return []*MessageHistory{}, err
}
messages := []*MessageHistory{}
defer rows.Close()
for rows.Next() {
message := &MessageHistory{}
err = db.ScanRows(rows, message)
if err != nil {
return []*MessageHistory{}, err
}
messages = append(messages, message)
}
return messages, nil
}
// UpdateNotificationStatus update where a user has notification from given room
func UpdateNotificationStatus(db *gorm.DB, roomID uint, userID uint, hasUnread bool) error {
sqlStatement := `
UPDATE usersrooms
SET unread = ?
WHERE room_id = ? AND user_id = ?;`
return db.Exec(sqlStatement, hasUnread, roomID, userID).Error
}
// GetUserNameByID: get a user's name by id
func GetUserNameByID(db *gorm.DB, user_id uint) string {
userName := struct {
Name string
}{}
db.Table("users").Select("name").Where("id = ?", user_id).Scan(&userName)
return userName.Name
}
// InsertUser: insert a new user
func InsertUser(db *gorm.DB, u *User) error {
sqlStatement := `
INSERT INTO users (name, email, jwt_token, password_digest)
VALUES(?,?,?,?)`
return db.Exec(sqlStatement, u.Name, u.Email, u.JWTToken, u.PasswordDigest).Error
}
// InsertRoom creates a new room and returns its ID as string
func InsertRoom(db *gorm.DB, room_name string, room_type int) (uint, error) {
newRoom := &Room{
RoomName: room_name,
Type: room_type,
}
if dbc := db.Create(newRoom); dbc.Error != nil {
return 0, dbc.Error
}
return newRoom.ID, nil
}
// InsertDMRoom creates a new direct message room and returns its ID and name as string
func InsertDMRoom(db *gorm.DB, user_id uint, tar_user_id uint) (uint, string, error) {
userName, tarUserName := GetUserNameByID(db, user_id), GetUserNameByID(db, tar_user_id)
if userName == "" || tarUserName == "" {
return 0, "", errors.New("User not found or empty name")
}
newRoomName := userName + "~" + tarUserName
newRoomID, err := InsertRoom(db, newRoomName, 1)
if err != nil {
return 0, "", err
}
// Add both members to the new room
if err := InsertUserroom(db, user_id, newRoomID, false); err != nil {
return 0, "", err
}
if err := InsertUserroom(db, tar_user_id, newRoomID, false); err != nil {
return 0, "", err
}
return newRoomID, newRoomName, nil
}
// InsertUserroom insert a new userroom
func InsertUserroom(db *gorm.DB, user_id uint, room_id uint, unread bool) error {
sqlStatement := `
INSERT INTO usersrooms (user_id, room_id, unread)
VALUES(?,?,?)`
return db.Exec(sqlStatement, user_id, room_id, unread).Error
}
// InsertMessage insert a new message
func InsertMessage(db *gorm.DB, time time.Time, body string, sender_id uint, room_id uint) error {
sqlStatement := `
INSERT INTO messages (time, body, sender_id, room_id)
VALUES(?,?,?,?)`
return db.Exec(sqlStatement, time, body, sender_id, room_id).Error
}
|
package main
type point {
x, y int
}
|
package system
import (
potato "github.com/rise-worlds/potato-go"
)
func NewBidname(bidder, newname potato.AccountName, bid potato.Asset) *potato.Action {
a := &potato.Action{
Account: AN("potato"),
Name: ActN("bidname"),
Authorization: []potato.PermissionLevel{
{Actor: bidder, Permission: PN("active")},
},
ActionData: potato.NewActionData(Bidname{
Bidder: bidder,
Newname: newname,
Bid: bid,
}),
}
return a
}
// Bidname represents the `potato.system_contract::bidname` action.
type Bidname struct {
Bidder potato.AccountName `json:"bidder"`
Newname potato.AccountName `json:"newname"`
Bid potato.Asset `json:"bid"` // specified in potato
}
|
package ravendb
import (
"net/http"
)
var (
_ IServerOperation = &GetDatabaseRecordOperation{}
)
type GetDatabaseRecordOperation struct {
database string
Command *GetDatabaseRecordCommand
}
func NewGetDatabaseRecordOperation(database string) *GetDatabaseRecordOperation {
return &GetDatabaseRecordOperation{
database: database,
}
}
func (o *GetDatabaseRecordOperation) GetCommand(conventions *DocumentConventions) (RavenCommand, error) {
o.Command = NewGetDatabaseRecordCommand(conventions, o.database)
return o.Command, nil
}
var _ RavenCommand = &GetDatabaseRecordCommand{}
type GetDatabaseRecordCommand struct {
RavenCommandBase
conventions *DocumentConventions
database string
Result *DatabaseRecordWithEtag
}
func NewGetDatabaseRecordCommand(conventions *DocumentConventions, database string) *GetDatabaseRecordCommand {
cmd := &GetDatabaseRecordCommand{
RavenCommandBase: NewRavenCommandBase(),
conventions: conventions,
database: database,
}
return cmd
}
func (c *GetDatabaseRecordCommand) CreateRequest(node *ServerNode) (*http.Request, error) {
url := node.URL + "/admin/databases?name=" + c.database
return newHttpGet(url)
}
func (c *GetDatabaseRecordCommand) SetResponse(response []byte, fromCache bool) error {
if len(response) == 0 {
c.Result = nil
return nil
}
return jsonUnmarshal(response, &c.Result)
}
|
package main
import (
"math"
"github.com/davecgh/go-spew/spew"
)
type Point struct {
x float64
y float64
}
func distance(p, q Point) float64 {
dx := p.x - q.x
dy := p.y - q.y
return math.Sqrt(dx*dx + dy*dy)
}
func main() {
var p Point
var q Point = Point{10, 10}
r := Point{x: 100, y: 100}
spew.Dump(p, q, r)
spew.Dump(p.x, p.y, q.x, q.y, r.x, r.y)
spew.Println(distance(p, q))
spew.Println(distance(p, r))
spew.Println(distance(q, r))
}
|
package controllers
import (
"bookingSystem/models"
"github.com/astaxie/beego/orm"
)
type AuthAdminController struct {
Base
}
// @router /auth/login [get,post]
func (c *AuthAdminController) Login() {
if c.Ctx.Request.Method == "GET" {
c.TplName = "login.html"
} else {
c.SetSession("admin_auth", 1)
o := orm.NewOrm()
var user models.User
username := c.GetString("username")
o.QueryTable("b_user").Filter("username", username).One(&user)
if user.Password == str2md5(c.GetString("password")+user.Salt) {
c.AjaxOk("登陆成功")
} else {
c.AjaxErr("用户名或密码不正确")
}
}
}
// @router /auth/logout [get]
func (c *AuthAdminController) Logout() {
c.DelSession("admin_auth")
c.StopRun()
}
|
package apis
import (
. "background/models"
"github.com/gin-gonic/gin"
"net/http"
"strconv"
)
// GetClassesStudentApi
// path: classes_student
// Input: ID,password
// Output(JSON array)
// img: String
// (标识课程的照片,如果没有照片就弄个默认的)
// name: String
// (课程名字)
// ID: String
// (课程ID)
func GetClassesStudentApi(c *gin.Context) {
id := c.Query("ID")
password := c.Query("password")
s := Student{Id: id, Password: password}
classes := s.GetClassesStudent()
c.IndentedJSON(200, classes)
}
// JoinClassApi
// path: joinclass
// Input: ID, password, classid
// Output(JSON)
// result: int
//(1表示加入成功,0表示加入不成功)
func JoinClassApi(c *gin.Context) {
id := c.Query("ID")
password := c.Query("password")
classId := c.Query("classid")
s := Student{Id: id, Password: password}
joined := s.JoinClass(classId)
c.JSON(http.StatusOK, gin.H{
"result": joined,
})
}
// GetHomeworkListStudentApi
// path:homeworks_student
// Input: ID, password, classid
// type: int
// (返回array的排序准则,0为按发布时间排序,最先发布的排在前面,索引小,为1的话还未提交的作业排在前面,其余的按照发布时间排序)
// Output(JSONArray)
// name: string
// pub_time: string
// ddl: string
// status: string
// id(id of homework)
func GetHomeworkListStudentApi(c *gin.Context) {
id := c.Query("ID")
password := c.Query("password")
classId := c.Query("classid")
rank, _ := strconv.Atoi(c.Query("type"))
s := Student{Id: id, Password: password}
hwList := s.GetHomeworkListStudent(classId, rank)
c.IndentedJSON(200, hwList)
}
|
package protocol
import (
"io"
"github.com/13k/go-steam-resources/steamlang"
"github.com/13k/go-steam/steamid"
)
// ClientStructMessage represents a struct backed client message.
type ClientStructMessage struct {
Header *ClientStructMessageHeader
Body StructMessageBody
Payload []byte
}
var _ ClientMessage = (*ClientStructMessage)(nil)
func NewClientStructMessage(body StructMessageBody, payload []byte) *ClientStructMessage {
header := NewClientStructMessageHeader()
header.SetEMsg(body.GetEMsg())
return &ClientStructMessage{
Header: header,
Body: body,
Payload: payload,
}
}
func (m *ClientStructMessage) Type() steamlang.EMsg {
return m.Header.EMsg()
}
func (m *ClientStructMessage) IsProto() bool {
return m.Header.IsProto()
}
func (m *ClientStructMessage) SessionID() int32 {
return m.Header.SessionID()
}
func (m *ClientStructMessage) SetSessionID(session int32) {
m.Header.SetSessionID(session)
}
func (m *ClientStructMessage) SteamID() steamid.SteamID {
return m.Header.SteamID()
}
func (m *ClientStructMessage) SetSteamID(s steamid.SteamID) {
m.Header.SetSteamID(s)
}
func (m *ClientStructMessage) SourceJobID() JobID {
return m.Header.SourceJobID()
}
func (m *ClientStructMessage) SetSourceJobID(job JobID) {
m.Header.SetSourceJobID(job)
}
func (m *ClientStructMessage) TargetJobID() JobID {
return m.Header.TargetJobID()
}
func (m *ClientStructMessage) SetTargetJobID(job JobID) {
m.Header.SetTargetJobID(job)
}
func (m *ClientStructMessage) Serialize(w io.Writer) error {
if err := m.Header.Serialize(w); err != nil {
return err
}
if err := m.Body.Serialize(w); err != nil {
return err
}
_, err := w.Write(m.Payload)
return err
}
|
package ffxiv
import (
"bytes"
"errors"
"fmt"
"regexp"
"strconv"
"strings"
"unicode"
"github.com/PuerkitoBio/goquery"
"github.com/aerogo/http/client"
)
var digit = regexp.MustCompile("[0-9]+")
// Character represents a Final Fantasy XIV character.
type Character struct {
Nick string
Server string
DataCenter string
Class string
Level int
ItemLevel int
}
// GetCharacter fetches character data for a given character ID.
func GetCharacter(id string) (*Character, error) {
url := fmt.Sprintf("https://na.finalfantasyxiv.com/lodestone/character/%s", id)
response, err := client.Get(url).End()
if err != nil {
return nil, err
}
page := response.Bytes()
reader := bytes.NewReader(page)
document, err := goquery.NewDocumentFromReader(reader)
if err != nil {
return nil, err
}
characterName := document.Find(".frame__chara__name").Text()
if characterName == "" {
return nil, errors.New("Error parsing character name")
}
// This will look like: "Asura (Mana)"
characterServerAndDataCenter := document.Find(".frame__chara__world").Text()
if characterServerAndDataCenter == "" {
return nil, errors.New("Error parsing character server")
}
// Normalize whitespace characters
characterServerAndDataCenter = strings.Map(func(r rune) rune {
if unicode.IsSpace(r) {
return ' '
}
return r
}, characterServerAndDataCenter)
// Split the server and data center
serverInfo := strings.Split(characterServerAndDataCenter, " ")
if len(serverInfo) < 2 {
return nil, errors.New("Character server info does not seem to include the data center")
}
characterServer := serverInfo[0]
characterDataCenter := serverInfo[1]
characterDataCenter = strings.TrimPrefix(characterDataCenter, "(")
characterDataCenter = strings.TrimSuffix(characterDataCenter, ")")
if characterDataCenter == "" {
return nil, errors.New("Error parsing character data center")
}
// Level
characterLevel := document.Find(".character__class__data").Text()
if characterLevel == "" {
return nil, errors.New("Error parsing character level")
}
// Weapon
characterWeapon := document.Find(".db-tooltip__item__category").Text()
if characterWeapon == "" {
return nil, errors.New("Error parsing character class")
}
level, err := strconv.Atoi(digit.FindStringSubmatch(characterLevel)[0])
if err != nil {
return nil, err
}
itemLevel := calculateItemLevel(document)
className := getJobName(document)
if className == "" {
// Determine class name using the weapon info
className = strings.Split(characterWeapon, "'")[0]
className = strings.Replace(className, "Two-handed", "", -1)
className = strings.Replace(className, "One-handed", "", -1)
className = strings.TrimSpace(className)
}
character := &Character{
Nick: characterName,
Class: className,
Server: characterServer,
DataCenter: characterDataCenter,
Level: level,
ItemLevel: itemLevel,
}
return character, nil
}
// calculateItemLevel will try to return the average of all item levels.
func calculateItemLevel(document *goquery.Document) int {
items := document.Find(".item_detail_box")
itemCount := 0
itemLevelSum := 0
items.Each(func(i int, item *goquery.Selection) {
itemCategory := strings.ToLower(item.Find(".db-tooltip__item__category").Text())
// Ignore soul crystals
if itemCategory == "soul crystal" {
return
}
// Two-handed weapons are counted twice
weight := 1
if strings.Contains(itemCategory, "two-handed") {
weight = 2
}
// Find item level
itemLevelText := item.Find(".db-tooltip__item__level").Text()
itemLevelText = digit.FindStringSubmatch(itemLevelText)[0]
itemLevel, err := strconv.Atoi(itemLevelText)
if err != nil {
return
}
itemLevelSum += itemLevel * weight
itemCount += weight
})
if itemCount == 0 {
return 0
}
return itemLevelSum / itemCount
}
// getJobName finds the job name by looking at the soul crystal text.
func getJobName(document *goquery.Document) string {
const soulCrystalPrefix = "Soul of the "
jobName := ""
itemNames := document.Find(".db-tooltip__item__name")
itemNames.EachWithBreak(func(i int, item *goquery.Selection) bool {
itemName := item.Text()
if strings.HasPrefix(itemName, soulCrystalPrefix) {
jobName = itemName[len(soulCrystalPrefix):]
return false
}
return true
})
return jobName
}
|
package cmd
import (
"fmt"
"github.com/bitmaelum/bitmaelum-server/core"
"github.com/bitmaelum/bitmaelum-server/core/account/client"
"github.com/bitmaelum/bitmaelum-server/core/password"
"github.com/opentracing/opentracing-go/log"
"github.com/spf13/cobra"
)
var unlockAccountCmd = &cobra.Command{
Use: "unlock-account",
Short: "Unlock an account. No password is needed to send/receive mail",
Run: func(cmd *cobra.Command, args []string) {
addr, err := core.NewAddressFromString(*address)
if err != nil {
log.Error(err)
return
}
if ! client.IsLocked(*addr) {
fmt.Printf("This account is already unlocked.\n")
return
}
err = client.UnlockAccount(*addr, password.AskPassword())
if err != nil {
log.Error(err)
return
}
fmt.Printf("This account is now unlocked.\n")
},
}
func init() {
rootCmd.AddCommand(unlockAccountCmd)
address = unlockAccountCmd.Flags().String("address", "","Address to unlock")
_ = unlockAccountCmd.MarkFlagRequired("address")
}
|
//package with commands
package commands
// Help возвращает приветственное сообщение
func Help() string {
return "Поиск по имени: /search или /s \n" +
"Поиск по автору: /author или /a \n" +
"Последние 20 книг: /last или /l \n" +
"Случайная книга: /r \n" +
"Статистика: /stat \n\n" +
"------------------------------------\n" +
"Внимание! Если ответ слишком большой, Telegram не даст его " +
"вывести из-за слишком большого ответа. Поэтому не пытайтесь " +
"искать автора по фамилии Иванов или аналогичное, ответа просто не будет. \n\n" +
"При открытии книг может быть небольшой таймаут из-за большого размера файла."
}
|
package main
func each(handler func(string), text string) bool {
if finished {
return false
}
if len(text) >= maxlen {
handler(text)
} else {
handler(text)
for i, c := range dict {
if len(text) < len(startAt) && i < startAt[len(text)] {
continue
}
if !each(handler, text+string(c)) {
return false
}
}
}
return true
}
|
package migration
import "net/http"
func (op *Payload_OtpParameters) ServeHTTP(w http.ResponseWriter, r *http.Request) {
pic, err := op.QR()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Write(pic)
}
|
package pushTemplate
import (
"github.com/JeonYang/chanPool"
)
type Push interface {
Push(send ...Send) error
Start()
Stop()
}
func NewPush(chanPool chanPool.Pool, resultChanLen, resultsMaxLen int, resultFunc func(result []Result)) Push {
return &push{chanPool: chanPool, resultMaxLen: resultsMaxLen, resultChan: make(chan Result, resultChanLen), resultFinishSignal: make(chan struct{}), resultFunc: resultFunc}
}
type push struct {
chanPool chanPool.Pool
resultMaxLen int
resultChan chan Result
resultFinishSignal chan struct{}
resultFunc func(result []Result)
}
func (this *push) Push(send ...Send) error {
for _, v := range send {
err := this.chanPool.AddJob(func() {
result := v.Send()
this.resultChan <- result
})
if err != nil {
return err
}
}
return nil
}
// 开启
func (this *push) Start() {
// 开启发送消息协程
this.chanPool.Start()
// 开启消息反馈处理协程
this.startResultWork()
}
// 停止
func (this *push) Stop() {
this.chanPool.Stop()
close(this.resultChan)
<-this.resultFinishSignal
close(this.resultFinishSignal)
this.chanPool.Close()
}
// 开启反馈数据处理
func (this *push) startResultWork() {
go func() {
ok := true
results := make([]Result, 0)
for {
var send Result
select {
case send, ok = <-this.resultChan:
if !ok {
this.resultFunc(results)
this.resultFinishSignal <- struct{}{}
} else {
results = append(results, send)
if len(results) == this.resultMaxLen {
this.resultFunc(results)
results = make([]Result, 0)
}
}
}
if !ok {
break
}
}
}()
}
|
package leetcode
/*
665. 非递减数列
给你一个长度为 n 的整数数组,请你判断在 最多 改变 1 个元素的情况下,该数组能否变成一个非递减数列。
我们是这样定义一个非递减数列的: 对于数组中所有的 i (0 <= i <= n-2),总满足 nums[i] <= nums[i + 1]。
示例 1:
输入: nums = [4,2,3]
输出: true
解释: 你可以通过把第一个4变成1来使得它成为一个非递减数列。
示例 2:
输入: nums = [4,2,1]
输出: false
解释: 你不能在只改变一个元素的情况下将其变为非递减数列。
说明:
1 <= n <= 10 ^ 4
- 10 ^ 5 <= nums[i] <= 10 ^ 5
*/
func checkPossibility(nums []int) bool {
s := len(nums)
if s < 3 {
return true
}
fix := false
for i := 0; i < s-1; i++ {
if nums[i] > nums[i+1] {
if fix {
return false
}
fix = true
if i == 0 || nums[i+1] >= nums[i-1] {
nums[i] = nums[i+1]
} else {
nums[i+1] = nums[i]
}
}
}
return true
}
|
/**
* (C) Copyright IBM Corp. 2021.
*
* 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 appconfigurationv1_test
import (
"bytes"
"context"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/http/httptest"
"os"
"time"
"github.com/IBM/appconfiguration-go-admin-sdk/appconfigurationv1"
"github.com/IBM/go-sdk-core/v5/core"
"github.com/go-openapi/strfmt"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
var _ = Describe(`AppConfigurationV1`, func() {
var testServer *httptest.Server
Describe(`Service constructor tests`, func() {
It(`Instantiate service client`, func() {
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1(&appconfigurationv1.AppConfigurationV1Options{
Authenticator: &core.NoAuthAuthenticator{},
})
Expect(appConfigurationService).ToNot(BeNil())
Expect(serviceErr).To(BeNil())
})
It(`Instantiate service client with error: Invalid URL`, func() {
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1(&appconfigurationv1.AppConfigurationV1Options{
URL: "{BAD_URL_STRING",
})
Expect(appConfigurationService).To(BeNil())
Expect(serviceErr).ToNot(BeNil())
})
It(`Instantiate service client with error: Invalid Auth`, func() {
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1(&appconfigurationv1.AppConfigurationV1Options{
URL: "https://appconfigurationv1/api",
Authenticator: &core.BasicAuthenticator{
Username: "",
Password: "",
},
})
Expect(appConfigurationService).To(BeNil())
Expect(serviceErr).ToNot(BeNil())
})
})
Describe(`Service constructor tests using external config`, func() {
Context(`Using external config, construct service client instances`, func() {
// Map containing environment variables used in testing.
var testEnvironment = map[string]string{
"APP_CONFIGURATION_URL": "https://appconfigurationv1/api",
"APP_CONFIGURATION_AUTH_TYPE": "noauth",
}
It(`Create service client using external config successfully`, func() {
SetTestEnvironment(testEnvironment)
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1UsingExternalConfig(&appconfigurationv1.AppConfigurationV1Options{})
Expect(appConfigurationService).ToNot(BeNil())
Expect(serviceErr).To(BeNil())
ClearTestEnvironment(testEnvironment)
clone := appConfigurationService.Clone()
Expect(clone).ToNot(BeNil())
Expect(clone.Service != appConfigurationService.Service).To(BeTrue())
Expect(clone.GetServiceURL()).To(Equal(appConfigurationService.GetServiceURL()))
Expect(clone.Service.Options.Authenticator).To(Equal(appConfigurationService.Service.Options.Authenticator))
})
It(`Create service client using external config and set url from constructor successfully`, func() {
SetTestEnvironment(testEnvironment)
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1UsingExternalConfig(&appconfigurationv1.AppConfigurationV1Options{
URL: "https://testService/api",
})
Expect(appConfigurationService).ToNot(BeNil())
Expect(serviceErr).To(BeNil())
Expect(appConfigurationService.Service.GetServiceURL()).To(Equal("https://testService/api"))
ClearTestEnvironment(testEnvironment)
clone := appConfigurationService.Clone()
Expect(clone).ToNot(BeNil())
Expect(clone.Service != appConfigurationService.Service).To(BeTrue())
Expect(clone.GetServiceURL()).To(Equal(appConfigurationService.GetServiceURL()))
Expect(clone.Service.Options.Authenticator).To(Equal(appConfigurationService.Service.Options.Authenticator))
})
It(`Create service client using external config and set url programatically successfully`, func() {
SetTestEnvironment(testEnvironment)
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1UsingExternalConfig(&appconfigurationv1.AppConfigurationV1Options{})
err := appConfigurationService.SetServiceURL("https://testService/api")
Expect(err).To(BeNil())
Expect(appConfigurationService).ToNot(BeNil())
Expect(serviceErr).To(BeNil())
Expect(appConfigurationService.Service.GetServiceURL()).To(Equal("https://testService/api"))
ClearTestEnvironment(testEnvironment)
clone := appConfigurationService.Clone()
Expect(clone).ToNot(BeNil())
Expect(clone.Service != appConfigurationService.Service).To(BeTrue())
Expect(clone.GetServiceURL()).To(Equal(appConfigurationService.GetServiceURL()))
Expect(clone.Service.Options.Authenticator).To(Equal(appConfigurationService.Service.Options.Authenticator))
})
})
Context(`Using external config, construct service client instances with error: Invalid Auth`, func() {
// Map containing environment variables used in testing.
var testEnvironment = map[string]string{
"APP_CONFIGURATION_URL": "https://appconfigurationv1/api",
"APP_CONFIGURATION_AUTH_TYPE": "someOtherAuth",
}
SetTestEnvironment(testEnvironment)
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1UsingExternalConfig(&appconfigurationv1.AppConfigurationV1Options{})
It(`Instantiate service client with error`, func() {
Expect(appConfigurationService).To(BeNil())
Expect(serviceErr).ToNot(BeNil())
ClearTestEnvironment(testEnvironment)
})
})
Context(`Using external config, construct service client instances with error: Invalid URL`, func() {
// Map containing environment variables used in testing.
var testEnvironment = map[string]string{
"APP_CONFIGURATION_AUTH_TYPE": "NOAuth",
}
SetTestEnvironment(testEnvironment)
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1UsingExternalConfig(&appconfigurationv1.AppConfigurationV1Options{
URL: "{BAD_URL_STRING",
})
It(`Instantiate service client with error`, func() {
Expect(appConfigurationService).To(BeNil())
Expect(serviceErr).ToNot(BeNil())
ClearTestEnvironment(testEnvironment)
})
})
})
Describe(`Regional endpoint tests`, func() {
It(`GetServiceURLForRegion(region string)`, func() {
var url string
var err error
url, err = appconfigurationv1.GetServiceURLForRegion("INVALID_REGION")
Expect(url).To(BeEmpty())
Expect(err).ToNot(BeNil())
fmt.Fprintf(GinkgoWriter, "Expected error: %s\n", err.Error())
})
})
Describe(`ListEnvironments(listEnvironmentsOptions *ListEnvironmentsOptions) - Operation response error`, func() {
listEnvironmentsPath := "/environments"
Context(`Using mock server endpoint`, func() {
BeforeEach(func() {
testServer = httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
defer GinkgoRecover()
// Verify the contents of the request
Expect(req.URL.EscapedPath()).To(Equal(listEnvironmentsPath))
Expect(req.Method).To(Equal("GET"))
// TODO: Add check for expand query parameter
Expect(req.URL.Query()["sort"]).To(Equal([]string{"created_time"}))
Expect(req.URL.Query()["tags"]).To(Equal([]string{"version 1.1, pre-release"}))
Expect(req.URL.Query()["limit"]).To(Equal([]string{fmt.Sprint(int64(1))}))
Expect(req.URL.Query()["offset"]).To(Equal([]string{fmt.Sprint(int64(0))}))
res.Header().Set("Content-type", "application/json")
res.WriteHeader(200)
fmt.Fprintf(res, `} this is not valid json {`)
}))
})
It(`Invoke ListEnvironments with error: Operation response processing error`, func() {
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1(&appconfigurationv1.AppConfigurationV1Options{
URL: testServer.URL,
Authenticator: &core.NoAuthAuthenticator{},
})
Expect(serviceErr).To(BeNil())
Expect(appConfigurationService).ToNot(BeNil())
// Construct an instance of the ListEnvironmentsOptions model
listEnvironmentsOptionsModel := new(appconfigurationv1.ListEnvironmentsOptions)
listEnvironmentsOptionsModel.Expand = core.BoolPtr(true)
listEnvironmentsOptionsModel.Sort = core.StringPtr("created_time")
listEnvironmentsOptionsModel.Tags = core.StringPtr("version 1.1, pre-release")
listEnvironmentsOptionsModel.Include = []string{"features"}
listEnvironmentsOptionsModel.Limit = core.Int64Ptr(int64(1))
listEnvironmentsOptionsModel.Offset = core.Int64Ptr(int64(0))
listEnvironmentsOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"}
// Expect response parsing to fail since we are receiving a text/plain response
result, response, operationErr := appConfigurationService.ListEnvironments(listEnvironmentsOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(response).ToNot(BeNil())
Expect(result).To(BeNil())
// Enable retries and test again
appConfigurationService.EnableRetries(0, 0)
result, response, operationErr = appConfigurationService.ListEnvironments(listEnvironmentsOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(response).ToNot(BeNil())
Expect(result).To(BeNil())
})
AfterEach(func() {
testServer.Close()
})
})
})
Describe(`ListEnvironments(listEnvironmentsOptions *ListEnvironmentsOptions)`, func() {
listEnvironmentsPath := "/environments"
var serverSleepTime time.Duration
Context(`Using mock server endpoint`, func() {
BeforeEach(func() {
serverSleepTime = 0
testServer = httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
defer GinkgoRecover()
// Verify the contents of the request
Expect(req.URL.EscapedPath()).To(Equal(listEnvironmentsPath))
Expect(req.Method).To(Equal("GET"))
// TODO: Add check for expand query parameter
Expect(req.URL.Query()["sort"]).To(Equal([]string{"created_time"}))
Expect(req.URL.Query()["tags"]).To(Equal([]string{"version 1.1, pre-release"}))
Expect(req.URL.Query()["limit"]).To(Equal([]string{fmt.Sprint(int64(1))}))
Expect(req.URL.Query()["offset"]).To(Equal([]string{fmt.Sprint(int64(0))}))
// Sleep a short time to support a timeout test
time.Sleep(serverSleepTime)
// Set mock response
res.Header().Set("Content-type", "application/json")
res.WriteHeader(200)
fmt.Fprintf(res, "%s", `{"environments": [{"name": "Name", "environment_id": "EnvironmentID", "description": "Description", "tags": "Tags", "color_code": "#FDD13A", "created_time": "2019-01-01T12:00:00", "updated_time": "2019-01-01T12:00:00", "href": "Href", "features": [{"feature_id": "FeatureID", "name": "Name"}], "properties": [{"property_id": "PropertyID", "name": "Name"}]}], "limit": 5, "offset": 6, "total_count": 10, "first": {"href": "Href"}, "previous": {"href": "Href"}, "next": {"href": "Href"}, "last": {"href": "Href"}}`)
}))
})
It(`Invoke ListEnvironments successfully`, func() {
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1(&appconfigurationv1.AppConfigurationV1Options{
URL: testServer.URL,
Authenticator: &core.NoAuthAuthenticator{},
})
Expect(serviceErr).To(BeNil())
Expect(appConfigurationService).ToNot(BeNil())
appConfigurationService.EnableRetries(0, 0)
// Invoke operation with nil options model (negative test)
result, response, operationErr := appConfigurationService.ListEnvironments(nil)
Expect(operationErr).NotTo(BeNil())
Expect(response).To(BeNil())
Expect(result).To(BeNil())
// Construct an instance of the ListEnvironmentsOptions model
listEnvironmentsOptionsModel := new(appconfigurationv1.ListEnvironmentsOptions)
listEnvironmentsOptionsModel.Expand = core.BoolPtr(true)
listEnvironmentsOptionsModel.Sort = core.StringPtr("created_time")
listEnvironmentsOptionsModel.Tags = core.StringPtr("version 1.1, pre-release")
listEnvironmentsOptionsModel.Include = []string{"features"}
listEnvironmentsOptionsModel.Limit = core.Int64Ptr(int64(1))
listEnvironmentsOptionsModel.Offset = core.Int64Ptr(int64(0))
listEnvironmentsOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"}
// Invoke operation with valid options model (positive test)
result, response, operationErr = appConfigurationService.ListEnvironments(listEnvironmentsOptionsModel)
Expect(operationErr).To(BeNil())
Expect(response).ToNot(BeNil())
Expect(result).ToNot(BeNil())
// Invoke operation with a Context to test a timeout error
ctx, cancelFunc := context.WithTimeout(context.Background(), 80*time.Millisecond)
defer cancelFunc()
serverSleepTime = 100 * time.Millisecond
_, _, operationErr = appConfigurationService.ListEnvironmentsWithContext(ctx, listEnvironmentsOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(operationErr.Error()).To(ContainSubstring("deadline exceeded"))
serverSleepTime = time.Duration(0)
// Disable retries and test again
appConfigurationService.DisableRetries()
result, response, operationErr = appConfigurationService.ListEnvironments(listEnvironmentsOptionsModel)
Expect(operationErr).To(BeNil())
Expect(response).ToNot(BeNil())
Expect(result).ToNot(BeNil())
// Re-test the timeout error with retries disabled
ctx, cancelFunc2 := context.WithTimeout(context.Background(), 80*time.Millisecond)
defer cancelFunc2()
serverSleepTime = 100 * time.Millisecond
_, _, operationErr = appConfigurationService.ListEnvironmentsWithContext(ctx, listEnvironmentsOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(operationErr.Error()).To(ContainSubstring("deadline exceeded"))
serverSleepTime = time.Duration(0)
})
It(`Invoke ListEnvironments with error: Operation request error`, func() {
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1(&appconfigurationv1.AppConfigurationV1Options{
URL: testServer.URL,
Authenticator: &core.NoAuthAuthenticator{},
})
Expect(serviceErr).To(BeNil())
Expect(appConfigurationService).ToNot(BeNil())
// Construct an instance of the ListEnvironmentsOptions model
listEnvironmentsOptionsModel := new(appconfigurationv1.ListEnvironmentsOptions)
listEnvironmentsOptionsModel.Expand = core.BoolPtr(true)
listEnvironmentsOptionsModel.Sort = core.StringPtr("created_time")
listEnvironmentsOptionsModel.Tags = core.StringPtr("version 1.1, pre-release")
listEnvironmentsOptionsModel.Include = []string{"features"}
listEnvironmentsOptionsModel.Limit = core.Int64Ptr(int64(1))
listEnvironmentsOptionsModel.Offset = core.Int64Ptr(int64(0))
listEnvironmentsOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"}
// Invoke operation with empty URL (negative test)
err := appConfigurationService.SetServiceURL("")
Expect(err).To(BeNil())
result, response, operationErr := appConfigurationService.ListEnvironments(listEnvironmentsOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(operationErr.Error()).To(ContainSubstring(core.ERRORMSG_SERVICE_URL_MISSING))
Expect(response).To(BeNil())
Expect(result).To(BeNil())
})
AfterEach(func() {
testServer.Close()
})
})
})
Describe(`CreateEnvironment(createEnvironmentOptions *CreateEnvironmentOptions) - Operation response error`, func() {
createEnvironmentPath := "/environments"
Context(`Using mock server endpoint`, func() {
BeforeEach(func() {
testServer = httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
defer GinkgoRecover()
// Verify the contents of the request
Expect(req.URL.EscapedPath()).To(Equal(createEnvironmentPath))
Expect(req.Method).To(Equal("POST"))
res.Header().Set("Content-type", "application/json")
res.WriteHeader(201)
fmt.Fprintf(res, `} this is not valid json {`)
}))
})
It(`Invoke CreateEnvironment with error: Operation response processing error`, func() {
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1(&appconfigurationv1.AppConfigurationV1Options{
URL: testServer.URL,
Authenticator: &core.NoAuthAuthenticator{},
})
Expect(serviceErr).To(BeNil())
Expect(appConfigurationService).ToNot(BeNil())
// Construct an instance of the CreateEnvironmentOptions model
createEnvironmentOptionsModel := new(appconfigurationv1.CreateEnvironmentOptions)
createEnvironmentOptionsModel.Name = core.StringPtr("Dev environment")
createEnvironmentOptionsModel.EnvironmentID = core.StringPtr("dev-environment")
createEnvironmentOptionsModel.Description = core.StringPtr("Dev environment description")
createEnvironmentOptionsModel.Tags = core.StringPtr("development")
createEnvironmentOptionsModel.ColorCode = core.StringPtr("#FDD13A")
createEnvironmentOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"}
// Expect response parsing to fail since we are receiving a text/plain response
result, response, operationErr := appConfigurationService.CreateEnvironment(createEnvironmentOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(response).ToNot(BeNil())
Expect(result).To(BeNil())
// Enable retries and test again
appConfigurationService.EnableRetries(0, 0)
result, response, operationErr = appConfigurationService.CreateEnvironment(createEnvironmentOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(response).ToNot(BeNil())
Expect(result).To(BeNil())
})
AfterEach(func() {
testServer.Close()
})
})
})
Describe(`CreateEnvironment(createEnvironmentOptions *CreateEnvironmentOptions)`, func() {
createEnvironmentPath := "/environments"
var serverSleepTime time.Duration
Context(`Using mock server endpoint`, func() {
BeforeEach(func() {
serverSleepTime = 0
testServer = httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
defer GinkgoRecover()
// Verify the contents of the request
Expect(req.URL.EscapedPath()).To(Equal(createEnvironmentPath))
Expect(req.Method).To(Equal("POST"))
// For gzip-disabled operation, verify Content-Encoding is not set.
Expect(req.Header.Get("Content-Encoding")).To(BeEmpty())
// If there is a body, then make sure we can read it
bodyBuf := new(bytes.Buffer)
if req.Header.Get("Content-Encoding") == "gzip" {
body, err := core.NewGzipDecompressionReader(req.Body)
Expect(err).To(BeNil())
_, err = bodyBuf.ReadFrom(body)
Expect(err).To(BeNil())
} else {
_, err := bodyBuf.ReadFrom(req.Body)
Expect(err).To(BeNil())
}
fmt.Fprintf(GinkgoWriter, " Request body: %s", bodyBuf.String())
// Sleep a short time to support a timeout test
time.Sleep(serverSleepTime)
// Set mock response
res.Header().Set("Content-type", "application/json")
res.WriteHeader(201)
fmt.Fprintf(res, "%s", `{"name": "Name", "environment_id": "EnvironmentID", "description": "Description", "tags": "Tags", "color_code": "#FDD13A", "created_time": "2019-01-01T12:00:00", "updated_time": "2019-01-01T12:00:00", "href": "Href", "features": [{"feature_id": "FeatureID", "name": "Name"}], "properties": [{"property_id": "PropertyID", "name": "Name"}]}`)
}))
})
It(`Invoke CreateEnvironment successfully`, func() {
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1(&appconfigurationv1.AppConfigurationV1Options{
URL: testServer.URL,
Authenticator: &core.NoAuthAuthenticator{},
})
Expect(serviceErr).To(BeNil())
Expect(appConfigurationService).ToNot(BeNil())
appConfigurationService.EnableRetries(0, 0)
// Invoke operation with nil options model (negative test)
result, response, operationErr := appConfigurationService.CreateEnvironment(nil)
Expect(operationErr).NotTo(BeNil())
Expect(response).To(BeNil())
Expect(result).To(BeNil())
// Construct an instance of the CreateEnvironmentOptions model
createEnvironmentOptionsModel := new(appconfigurationv1.CreateEnvironmentOptions)
createEnvironmentOptionsModel.Name = core.StringPtr("Dev environment")
createEnvironmentOptionsModel.EnvironmentID = core.StringPtr("dev-environment")
createEnvironmentOptionsModel.Description = core.StringPtr("Dev environment description")
createEnvironmentOptionsModel.Tags = core.StringPtr("development")
createEnvironmentOptionsModel.ColorCode = core.StringPtr("#FDD13A")
createEnvironmentOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"}
// Invoke operation with valid options model (positive test)
result, response, operationErr = appConfigurationService.CreateEnvironment(createEnvironmentOptionsModel)
Expect(operationErr).To(BeNil())
Expect(response).ToNot(BeNil())
Expect(result).ToNot(BeNil())
// Invoke operation with a Context to test a timeout error
ctx, cancelFunc := context.WithTimeout(context.Background(), 80*time.Millisecond)
defer cancelFunc()
serverSleepTime = 100 * time.Millisecond
_, _, operationErr = appConfigurationService.CreateEnvironmentWithContext(ctx, createEnvironmentOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(operationErr.Error()).To(ContainSubstring("deadline exceeded"))
serverSleepTime = time.Duration(0)
// Disable retries and test again
appConfigurationService.DisableRetries()
result, response, operationErr = appConfigurationService.CreateEnvironment(createEnvironmentOptionsModel)
Expect(operationErr).To(BeNil())
Expect(response).ToNot(BeNil())
Expect(result).ToNot(BeNil())
// Re-test the timeout error with retries disabled
ctx, cancelFunc2 := context.WithTimeout(context.Background(), 80*time.Millisecond)
defer cancelFunc2()
serverSleepTime = 100 * time.Millisecond
_, _, operationErr = appConfigurationService.CreateEnvironmentWithContext(ctx, createEnvironmentOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(operationErr.Error()).To(ContainSubstring("deadline exceeded"))
serverSleepTime = time.Duration(0)
})
It(`Invoke CreateEnvironment with error: Operation validation and request error`, func() {
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1(&appconfigurationv1.AppConfigurationV1Options{
URL: testServer.URL,
Authenticator: &core.NoAuthAuthenticator{},
})
Expect(serviceErr).To(BeNil())
Expect(appConfigurationService).ToNot(BeNil())
// Construct an instance of the CreateEnvironmentOptions model
createEnvironmentOptionsModel := new(appconfigurationv1.CreateEnvironmentOptions)
createEnvironmentOptionsModel.Name = core.StringPtr("Dev environment")
createEnvironmentOptionsModel.EnvironmentID = core.StringPtr("dev-environment")
createEnvironmentOptionsModel.Description = core.StringPtr("Dev environment description")
createEnvironmentOptionsModel.Tags = core.StringPtr("development")
createEnvironmentOptionsModel.ColorCode = core.StringPtr("#FDD13A")
createEnvironmentOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"}
// Invoke operation with empty URL (negative test)
err := appConfigurationService.SetServiceURL("")
Expect(err).To(BeNil())
result, response, operationErr := appConfigurationService.CreateEnvironment(createEnvironmentOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(operationErr.Error()).To(ContainSubstring(core.ERRORMSG_SERVICE_URL_MISSING))
Expect(response).To(BeNil())
Expect(result).To(BeNil())
// Construct a second instance of the CreateEnvironmentOptions model with no property values
createEnvironmentOptionsModelNew := new(appconfigurationv1.CreateEnvironmentOptions)
// Invoke operation with invalid model (negative test)
result, response, operationErr = appConfigurationService.CreateEnvironment(createEnvironmentOptionsModelNew)
Expect(operationErr).ToNot(BeNil())
Expect(response).To(BeNil())
Expect(result).To(BeNil())
})
AfterEach(func() {
testServer.Close()
})
})
})
Describe(`UpdateEnvironment(updateEnvironmentOptions *UpdateEnvironmentOptions) - Operation response error`, func() {
updateEnvironmentPath := "/environments/testString"
Context(`Using mock server endpoint`, func() {
BeforeEach(func() {
testServer = httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
defer GinkgoRecover()
// Verify the contents of the request
Expect(req.URL.EscapedPath()).To(Equal(updateEnvironmentPath))
Expect(req.Method).To(Equal("PUT"))
res.Header().Set("Content-type", "application/json")
res.WriteHeader(200)
fmt.Fprintf(res, `} this is not valid json {`)
}))
})
It(`Invoke UpdateEnvironment with error: Operation response processing error`, func() {
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1(&appconfigurationv1.AppConfigurationV1Options{
URL: testServer.URL,
Authenticator: &core.NoAuthAuthenticator{},
})
Expect(serviceErr).To(BeNil())
Expect(appConfigurationService).ToNot(BeNil())
// Construct an instance of the UpdateEnvironmentOptions model
updateEnvironmentOptionsModel := new(appconfigurationv1.UpdateEnvironmentOptions)
updateEnvironmentOptionsModel.EnvironmentID = core.StringPtr("testString")
updateEnvironmentOptionsModel.Name = core.StringPtr("testString")
updateEnvironmentOptionsModel.Description = core.StringPtr("testString")
updateEnvironmentOptionsModel.Tags = core.StringPtr("testString")
updateEnvironmentOptionsModel.ColorCode = core.StringPtr("#FDD13A")
updateEnvironmentOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"}
// Expect response parsing to fail since we are receiving a text/plain response
result, response, operationErr := appConfigurationService.UpdateEnvironment(updateEnvironmentOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(response).ToNot(BeNil())
Expect(result).To(BeNil())
// Enable retries and test again
appConfigurationService.EnableRetries(0, 0)
result, response, operationErr = appConfigurationService.UpdateEnvironment(updateEnvironmentOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(response).ToNot(BeNil())
Expect(result).To(BeNil())
})
AfterEach(func() {
testServer.Close()
})
})
})
Describe(`UpdateEnvironment(updateEnvironmentOptions *UpdateEnvironmentOptions)`, func() {
updateEnvironmentPath := "/environments/testString"
var serverSleepTime time.Duration
Context(`Using mock server endpoint`, func() {
BeforeEach(func() {
serverSleepTime = 0
testServer = httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
defer GinkgoRecover()
// Verify the contents of the request
Expect(req.URL.EscapedPath()).To(Equal(updateEnvironmentPath))
Expect(req.Method).To(Equal("PUT"))
// For gzip-disabled operation, verify Content-Encoding is not set.
Expect(req.Header.Get("Content-Encoding")).To(BeEmpty())
// If there is a body, then make sure we can read it
bodyBuf := new(bytes.Buffer)
if req.Header.Get("Content-Encoding") == "gzip" {
body, err := core.NewGzipDecompressionReader(req.Body)
Expect(err).To(BeNil())
_, err = bodyBuf.ReadFrom(body)
Expect(err).To(BeNil())
} else {
_, err := bodyBuf.ReadFrom(req.Body)
Expect(err).To(BeNil())
}
fmt.Fprintf(GinkgoWriter, " Request body: %s", bodyBuf.String())
// Sleep a short time to support a timeout test
time.Sleep(serverSleepTime)
// Set mock response
res.Header().Set("Content-type", "application/json")
res.WriteHeader(200)
fmt.Fprintf(res, "%s", `{"name": "Name", "environment_id": "EnvironmentID", "description": "Description", "tags": "Tags", "color_code": "#FDD13A", "created_time": "2019-01-01T12:00:00", "updated_time": "2019-01-01T12:00:00", "href": "Href", "features": [{"feature_id": "FeatureID", "name": "Name"}], "properties": [{"property_id": "PropertyID", "name": "Name"}]}`)
}))
})
It(`Invoke UpdateEnvironment successfully`, func() {
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1(&appconfigurationv1.AppConfigurationV1Options{
URL: testServer.URL,
Authenticator: &core.NoAuthAuthenticator{},
})
Expect(serviceErr).To(BeNil())
Expect(appConfigurationService).ToNot(BeNil())
appConfigurationService.EnableRetries(0, 0)
// Invoke operation with nil options model (negative test)
result, response, operationErr := appConfigurationService.UpdateEnvironment(nil)
Expect(operationErr).NotTo(BeNil())
Expect(response).To(BeNil())
Expect(result).To(BeNil())
// Construct an instance of the UpdateEnvironmentOptions model
updateEnvironmentOptionsModel := new(appconfigurationv1.UpdateEnvironmentOptions)
updateEnvironmentOptionsModel.EnvironmentID = core.StringPtr("testString")
updateEnvironmentOptionsModel.Name = core.StringPtr("testString")
updateEnvironmentOptionsModel.Description = core.StringPtr("testString")
updateEnvironmentOptionsModel.Tags = core.StringPtr("testString")
updateEnvironmentOptionsModel.ColorCode = core.StringPtr("#FDD13A")
updateEnvironmentOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"}
// Invoke operation with valid options model (positive test)
result, response, operationErr = appConfigurationService.UpdateEnvironment(updateEnvironmentOptionsModel)
Expect(operationErr).To(BeNil())
Expect(response).ToNot(BeNil())
Expect(result).ToNot(BeNil())
// Invoke operation with a Context to test a timeout error
ctx, cancelFunc := context.WithTimeout(context.Background(), 80*time.Millisecond)
defer cancelFunc()
serverSleepTime = 100 * time.Millisecond
_, _, operationErr = appConfigurationService.UpdateEnvironmentWithContext(ctx, updateEnvironmentOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(operationErr.Error()).To(ContainSubstring("deadline exceeded"))
serverSleepTime = time.Duration(0)
// Disable retries and test again
appConfigurationService.DisableRetries()
result, response, operationErr = appConfigurationService.UpdateEnvironment(updateEnvironmentOptionsModel)
Expect(operationErr).To(BeNil())
Expect(response).ToNot(BeNil())
Expect(result).ToNot(BeNil())
// Re-test the timeout error with retries disabled
ctx, cancelFunc2 := context.WithTimeout(context.Background(), 80*time.Millisecond)
defer cancelFunc2()
serverSleepTime = 100 * time.Millisecond
_, _, operationErr = appConfigurationService.UpdateEnvironmentWithContext(ctx, updateEnvironmentOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(operationErr.Error()).To(ContainSubstring("deadline exceeded"))
serverSleepTime = time.Duration(0)
})
It(`Invoke UpdateEnvironment with error: Operation validation and request error`, func() {
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1(&appconfigurationv1.AppConfigurationV1Options{
URL: testServer.URL,
Authenticator: &core.NoAuthAuthenticator{},
})
Expect(serviceErr).To(BeNil())
Expect(appConfigurationService).ToNot(BeNil())
// Construct an instance of the UpdateEnvironmentOptions model
updateEnvironmentOptionsModel := new(appconfigurationv1.UpdateEnvironmentOptions)
updateEnvironmentOptionsModel.EnvironmentID = core.StringPtr("testString")
updateEnvironmentOptionsModel.Name = core.StringPtr("testString")
updateEnvironmentOptionsModel.Description = core.StringPtr("testString")
updateEnvironmentOptionsModel.Tags = core.StringPtr("testString")
updateEnvironmentOptionsModel.ColorCode = core.StringPtr("#FDD13A")
updateEnvironmentOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"}
// Invoke operation with empty URL (negative test)
err := appConfigurationService.SetServiceURL("")
Expect(err).To(BeNil())
result, response, operationErr := appConfigurationService.UpdateEnvironment(updateEnvironmentOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(operationErr.Error()).To(ContainSubstring(core.ERRORMSG_SERVICE_URL_MISSING))
Expect(response).To(BeNil())
Expect(result).To(BeNil())
// Construct a second instance of the UpdateEnvironmentOptions model with no property values
updateEnvironmentOptionsModelNew := new(appconfigurationv1.UpdateEnvironmentOptions)
// Invoke operation with invalid model (negative test)
result, response, operationErr = appConfigurationService.UpdateEnvironment(updateEnvironmentOptionsModelNew)
Expect(operationErr).ToNot(BeNil())
Expect(response).To(BeNil())
Expect(result).To(BeNil())
})
AfterEach(func() {
testServer.Close()
})
})
})
Describe(`GetEnvironment(getEnvironmentOptions *GetEnvironmentOptions) - Operation response error`, func() {
getEnvironmentPath := "/environments/testString"
Context(`Using mock server endpoint`, func() {
BeforeEach(func() {
testServer = httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
defer GinkgoRecover()
// Verify the contents of the request
Expect(req.URL.EscapedPath()).To(Equal(getEnvironmentPath))
Expect(req.Method).To(Equal("GET"))
// TODO: Add check for expand query parameter
res.Header().Set("Content-type", "application/json")
res.WriteHeader(200)
fmt.Fprintf(res, `} this is not valid json {`)
}))
})
It(`Invoke GetEnvironment with error: Operation response processing error`, func() {
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1(&appconfigurationv1.AppConfigurationV1Options{
URL: testServer.URL,
Authenticator: &core.NoAuthAuthenticator{},
})
Expect(serviceErr).To(BeNil())
Expect(appConfigurationService).ToNot(BeNil())
// Construct an instance of the GetEnvironmentOptions model
getEnvironmentOptionsModel := new(appconfigurationv1.GetEnvironmentOptions)
getEnvironmentOptionsModel.EnvironmentID = core.StringPtr("testString")
getEnvironmentOptionsModel.Expand = core.BoolPtr(true)
getEnvironmentOptionsModel.Include = []string{"features"}
getEnvironmentOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"}
// Expect response parsing to fail since we are receiving a text/plain response
result, response, operationErr := appConfigurationService.GetEnvironment(getEnvironmentOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(response).ToNot(BeNil())
Expect(result).To(BeNil())
// Enable retries and test again
appConfigurationService.EnableRetries(0, 0)
result, response, operationErr = appConfigurationService.GetEnvironment(getEnvironmentOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(response).ToNot(BeNil())
Expect(result).To(BeNil())
})
AfterEach(func() {
testServer.Close()
})
})
})
Describe(`GetEnvironment(getEnvironmentOptions *GetEnvironmentOptions)`, func() {
getEnvironmentPath := "/environments/testString"
var serverSleepTime time.Duration
Context(`Using mock server endpoint`, func() {
BeforeEach(func() {
serverSleepTime = 0
testServer = httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
defer GinkgoRecover()
// Verify the contents of the request
Expect(req.URL.EscapedPath()).To(Equal(getEnvironmentPath))
Expect(req.Method).To(Equal("GET"))
// TODO: Add check for expand query parameter
// Sleep a short time to support a timeout test
time.Sleep(serverSleepTime)
// Set mock response
res.Header().Set("Content-type", "application/json")
res.WriteHeader(200)
fmt.Fprintf(res, "%s", `{"name": "Name", "environment_id": "EnvironmentID", "description": "Description", "tags": "Tags", "color_code": "#FDD13A", "created_time": "2019-01-01T12:00:00", "updated_time": "2019-01-01T12:00:00", "href": "Href", "features": [{"feature_id": "FeatureID", "name": "Name"}], "properties": [{"property_id": "PropertyID", "name": "Name"}]}`)
}))
})
It(`Invoke GetEnvironment successfully`, func() {
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1(&appconfigurationv1.AppConfigurationV1Options{
URL: testServer.URL,
Authenticator: &core.NoAuthAuthenticator{},
})
Expect(serviceErr).To(BeNil())
Expect(appConfigurationService).ToNot(BeNil())
appConfigurationService.EnableRetries(0, 0)
// Invoke operation with nil options model (negative test)
result, response, operationErr := appConfigurationService.GetEnvironment(nil)
Expect(operationErr).NotTo(BeNil())
Expect(response).To(BeNil())
Expect(result).To(BeNil())
// Construct an instance of the GetEnvironmentOptions model
getEnvironmentOptionsModel := new(appconfigurationv1.GetEnvironmentOptions)
getEnvironmentOptionsModel.EnvironmentID = core.StringPtr("testString")
getEnvironmentOptionsModel.Expand = core.BoolPtr(true)
getEnvironmentOptionsModel.Include = []string{"features"}
getEnvironmentOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"}
// Invoke operation with valid options model (positive test)
result, response, operationErr = appConfigurationService.GetEnvironment(getEnvironmentOptionsModel)
Expect(operationErr).To(BeNil())
Expect(response).ToNot(BeNil())
Expect(result).ToNot(BeNil())
// Invoke operation with a Context to test a timeout error
ctx, cancelFunc := context.WithTimeout(context.Background(), 80*time.Millisecond)
defer cancelFunc()
serverSleepTime = 100 * time.Millisecond
_, _, operationErr = appConfigurationService.GetEnvironmentWithContext(ctx, getEnvironmentOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(operationErr.Error()).To(ContainSubstring("deadline exceeded"))
serverSleepTime = time.Duration(0)
// Disable retries and test again
appConfigurationService.DisableRetries()
result, response, operationErr = appConfigurationService.GetEnvironment(getEnvironmentOptionsModel)
Expect(operationErr).To(BeNil())
Expect(response).ToNot(BeNil())
Expect(result).ToNot(BeNil())
// Re-test the timeout error with retries disabled
ctx, cancelFunc2 := context.WithTimeout(context.Background(), 80*time.Millisecond)
defer cancelFunc2()
serverSleepTime = 100 * time.Millisecond
_, _, operationErr = appConfigurationService.GetEnvironmentWithContext(ctx, getEnvironmentOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(operationErr.Error()).To(ContainSubstring("deadline exceeded"))
serverSleepTime = time.Duration(0)
})
It(`Invoke GetEnvironment with error: Operation validation and request error`, func() {
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1(&appconfigurationv1.AppConfigurationV1Options{
URL: testServer.URL,
Authenticator: &core.NoAuthAuthenticator{},
})
Expect(serviceErr).To(BeNil())
Expect(appConfigurationService).ToNot(BeNil())
// Construct an instance of the GetEnvironmentOptions model
getEnvironmentOptionsModel := new(appconfigurationv1.GetEnvironmentOptions)
getEnvironmentOptionsModel.EnvironmentID = core.StringPtr("testString")
getEnvironmentOptionsModel.Expand = core.BoolPtr(true)
getEnvironmentOptionsModel.Include = []string{"features"}
getEnvironmentOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"}
// Invoke operation with empty URL (negative test)
err := appConfigurationService.SetServiceURL("")
Expect(err).To(BeNil())
result, response, operationErr := appConfigurationService.GetEnvironment(getEnvironmentOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(operationErr.Error()).To(ContainSubstring(core.ERRORMSG_SERVICE_URL_MISSING))
Expect(response).To(BeNil())
Expect(result).To(BeNil())
// Construct a second instance of the GetEnvironmentOptions model with no property values
getEnvironmentOptionsModelNew := new(appconfigurationv1.GetEnvironmentOptions)
// Invoke operation with invalid model (negative test)
result, response, operationErr = appConfigurationService.GetEnvironment(getEnvironmentOptionsModelNew)
Expect(operationErr).ToNot(BeNil())
Expect(response).To(BeNil())
Expect(result).To(BeNil())
})
AfterEach(func() {
testServer.Close()
})
})
})
Describe(`DeleteEnvironment(deleteEnvironmentOptions *DeleteEnvironmentOptions)`, func() {
deleteEnvironmentPath := "/environments/testString"
Context(`Using mock server endpoint`, func() {
BeforeEach(func() {
testServer = httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
defer GinkgoRecover()
// Verify the contents of the request
Expect(req.URL.EscapedPath()).To(Equal(deleteEnvironmentPath))
Expect(req.Method).To(Equal("DELETE"))
res.WriteHeader(204)
}))
})
It(`Invoke DeleteEnvironment successfully`, func() {
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1(&appconfigurationv1.AppConfigurationV1Options{
URL: testServer.URL,
Authenticator: &core.NoAuthAuthenticator{},
})
Expect(serviceErr).To(BeNil())
Expect(appConfigurationService).ToNot(BeNil())
appConfigurationService.EnableRetries(0, 0)
// Invoke operation with nil options model (negative test)
response, operationErr := appConfigurationService.DeleteEnvironment(nil)
Expect(operationErr).NotTo(BeNil())
Expect(response).To(BeNil())
// Construct an instance of the DeleteEnvironmentOptions model
deleteEnvironmentOptionsModel := new(appconfigurationv1.DeleteEnvironmentOptions)
deleteEnvironmentOptionsModel.EnvironmentID = core.StringPtr("testString")
deleteEnvironmentOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"}
// Invoke operation with valid options model (positive test)
response, operationErr = appConfigurationService.DeleteEnvironment(deleteEnvironmentOptionsModel)
Expect(operationErr).To(BeNil())
Expect(response).ToNot(BeNil())
// Disable retries and test again
appConfigurationService.DisableRetries()
response, operationErr = appConfigurationService.DeleteEnvironment(deleteEnvironmentOptionsModel)
Expect(operationErr).To(BeNil())
Expect(response).ToNot(BeNil())
})
It(`Invoke DeleteEnvironment with error: Operation validation and request error`, func() {
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1(&appconfigurationv1.AppConfigurationV1Options{
URL: testServer.URL,
Authenticator: &core.NoAuthAuthenticator{},
})
Expect(serviceErr).To(BeNil())
Expect(appConfigurationService).ToNot(BeNil())
// Construct an instance of the DeleteEnvironmentOptions model
deleteEnvironmentOptionsModel := new(appconfigurationv1.DeleteEnvironmentOptions)
deleteEnvironmentOptionsModel.EnvironmentID = core.StringPtr("testString")
deleteEnvironmentOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"}
// Invoke operation with empty URL (negative test)
err := appConfigurationService.SetServiceURL("")
Expect(err).To(BeNil())
response, operationErr := appConfigurationService.DeleteEnvironment(deleteEnvironmentOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(operationErr.Error()).To(ContainSubstring(core.ERRORMSG_SERVICE_URL_MISSING))
Expect(response).To(BeNil())
// Construct a second instance of the DeleteEnvironmentOptions model with no property values
deleteEnvironmentOptionsModelNew := new(appconfigurationv1.DeleteEnvironmentOptions)
// Invoke operation with invalid model (negative test)
response, operationErr = appConfigurationService.DeleteEnvironment(deleteEnvironmentOptionsModelNew)
Expect(operationErr).ToNot(BeNil())
Expect(response).To(BeNil())
})
AfterEach(func() {
testServer.Close()
})
})
})
Describe(`Service constructor tests`, func() {
It(`Instantiate service client`, func() {
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1(&appconfigurationv1.AppConfigurationV1Options{
Authenticator: &core.NoAuthAuthenticator{},
})
Expect(appConfigurationService).ToNot(BeNil())
Expect(serviceErr).To(BeNil())
})
It(`Instantiate service client with error: Invalid URL`, func() {
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1(&appconfigurationv1.AppConfigurationV1Options{
URL: "{BAD_URL_STRING",
})
Expect(appConfigurationService).To(BeNil())
Expect(serviceErr).ToNot(BeNil())
})
It(`Instantiate service client with error: Invalid Auth`, func() {
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1(&appconfigurationv1.AppConfigurationV1Options{
URL: "https://appconfigurationv1/api",
Authenticator: &core.BasicAuthenticator{
Username: "",
Password: "",
},
})
Expect(appConfigurationService).To(BeNil())
Expect(serviceErr).ToNot(BeNil())
})
})
Describe(`Service constructor tests using external config`, func() {
Context(`Using external config, construct service client instances`, func() {
// Map containing environment variables used in testing.
var testEnvironment = map[string]string{
"APP_CONFIGURATION_URL": "https://appconfigurationv1/api",
"APP_CONFIGURATION_AUTH_TYPE": "noauth",
}
It(`Create service client using external config successfully`, func() {
SetTestEnvironment(testEnvironment)
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1UsingExternalConfig(&appconfigurationv1.AppConfigurationV1Options{})
Expect(appConfigurationService).ToNot(BeNil())
Expect(serviceErr).To(BeNil())
ClearTestEnvironment(testEnvironment)
clone := appConfigurationService.Clone()
Expect(clone).ToNot(BeNil())
Expect(clone.Service != appConfigurationService.Service).To(BeTrue())
Expect(clone.GetServiceURL()).To(Equal(appConfigurationService.GetServiceURL()))
Expect(clone.Service.Options.Authenticator).To(Equal(appConfigurationService.Service.Options.Authenticator))
})
It(`Create service client using external config and set url from constructor successfully`, func() {
SetTestEnvironment(testEnvironment)
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1UsingExternalConfig(&appconfigurationv1.AppConfigurationV1Options{
URL: "https://testService/api",
})
Expect(appConfigurationService).ToNot(BeNil())
Expect(serviceErr).To(BeNil())
Expect(appConfigurationService.Service.GetServiceURL()).To(Equal("https://testService/api"))
ClearTestEnvironment(testEnvironment)
clone := appConfigurationService.Clone()
Expect(clone).ToNot(BeNil())
Expect(clone.Service != appConfigurationService.Service).To(BeTrue())
Expect(clone.GetServiceURL()).To(Equal(appConfigurationService.GetServiceURL()))
Expect(clone.Service.Options.Authenticator).To(Equal(appConfigurationService.Service.Options.Authenticator))
})
It(`Create service client using external config and set url programatically successfully`, func() {
SetTestEnvironment(testEnvironment)
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1UsingExternalConfig(&appconfigurationv1.AppConfigurationV1Options{})
err := appConfigurationService.SetServiceURL("https://testService/api")
Expect(err).To(BeNil())
Expect(appConfigurationService).ToNot(BeNil())
Expect(serviceErr).To(BeNil())
Expect(appConfigurationService.Service.GetServiceURL()).To(Equal("https://testService/api"))
ClearTestEnvironment(testEnvironment)
clone := appConfigurationService.Clone()
Expect(clone).ToNot(BeNil())
Expect(clone.Service != appConfigurationService.Service).To(BeTrue())
Expect(clone.GetServiceURL()).To(Equal(appConfigurationService.GetServiceURL()))
Expect(clone.Service.Options.Authenticator).To(Equal(appConfigurationService.Service.Options.Authenticator))
})
})
Context(`Using external config, construct service client instances with error: Invalid Auth`, func() {
// Map containing environment variables used in testing.
var testEnvironment = map[string]string{
"APP_CONFIGURATION_URL": "https://appconfigurationv1/api",
"APP_CONFIGURATION_AUTH_TYPE": "someOtherAuth",
}
SetTestEnvironment(testEnvironment)
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1UsingExternalConfig(&appconfigurationv1.AppConfigurationV1Options{})
It(`Instantiate service client with error`, func() {
Expect(appConfigurationService).To(BeNil())
Expect(serviceErr).ToNot(BeNil())
ClearTestEnvironment(testEnvironment)
})
})
Context(`Using external config, construct service client instances with error: Invalid URL`, func() {
// Map containing environment variables used in testing.
var testEnvironment = map[string]string{
"APP_CONFIGURATION_AUTH_TYPE": "NOAuth",
}
SetTestEnvironment(testEnvironment)
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1UsingExternalConfig(&appconfigurationv1.AppConfigurationV1Options{
URL: "{BAD_URL_STRING",
})
It(`Instantiate service client with error`, func() {
Expect(appConfigurationService).To(BeNil())
Expect(serviceErr).ToNot(BeNil())
ClearTestEnvironment(testEnvironment)
})
})
})
Describe(`Regional endpoint tests`, func() {
It(`GetServiceURLForRegion(region string)`, func() {
var url string
var err error
url, err = appconfigurationv1.GetServiceURLForRegion("INVALID_REGION")
Expect(url).To(BeEmpty())
Expect(err).ToNot(BeNil())
fmt.Fprintf(GinkgoWriter, "Expected error: %s\n", err.Error())
})
})
Describe(`ListCollections(listCollectionsOptions *ListCollectionsOptions) - Operation response error`, func() {
listCollectionsPath := "/collections"
Context(`Using mock server endpoint`, func() {
BeforeEach(func() {
testServer = httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
defer GinkgoRecover()
// Verify the contents of the request
Expect(req.URL.EscapedPath()).To(Equal(listCollectionsPath))
Expect(req.Method).To(Equal("GET"))
// TODO: Add check for expand query parameter
Expect(req.URL.Query()["sort"]).To(Equal([]string{"created_time"}))
Expect(req.URL.Query()["tags"]).To(Equal([]string{"version 1.1, pre-release"}))
Expect(req.URL.Query()["limit"]).To(Equal([]string{fmt.Sprint(int64(1))}))
Expect(req.URL.Query()["offset"]).To(Equal([]string{fmt.Sprint(int64(0))}))
res.Header().Set("Content-type", "application/json")
res.WriteHeader(200)
fmt.Fprintf(res, `} this is not valid json {`)
}))
})
It(`Invoke ListCollections with error: Operation response processing error`, func() {
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1(&appconfigurationv1.AppConfigurationV1Options{
URL: testServer.URL,
Authenticator: &core.NoAuthAuthenticator{},
})
Expect(serviceErr).To(BeNil())
Expect(appConfigurationService).ToNot(BeNil())
// Construct an instance of the ListCollectionsOptions model
listCollectionsOptionsModel := new(appconfigurationv1.ListCollectionsOptions)
listCollectionsOptionsModel.Expand = core.BoolPtr(true)
listCollectionsOptionsModel.Sort = core.StringPtr("created_time")
listCollectionsOptionsModel.Tags = core.StringPtr("version 1.1, pre-release")
listCollectionsOptionsModel.Features = []string{"testString"}
listCollectionsOptionsModel.Properties = []string{"testString"}
listCollectionsOptionsModel.Include = []string{"features"}
listCollectionsOptionsModel.Limit = core.Int64Ptr(int64(1))
listCollectionsOptionsModel.Offset = core.Int64Ptr(int64(0))
listCollectionsOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"}
// Expect response parsing to fail since we are receiving a text/plain response
result, response, operationErr := appConfigurationService.ListCollections(listCollectionsOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(response).ToNot(BeNil())
Expect(result).To(BeNil())
// Enable retries and test again
appConfigurationService.EnableRetries(0, 0)
result, response, operationErr = appConfigurationService.ListCollections(listCollectionsOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(response).ToNot(BeNil())
Expect(result).To(BeNil())
})
AfterEach(func() {
testServer.Close()
})
})
})
Describe(`ListCollections(listCollectionsOptions *ListCollectionsOptions)`, func() {
listCollectionsPath := "/collections"
var serverSleepTime time.Duration
Context(`Using mock server endpoint`, func() {
BeforeEach(func() {
serverSleepTime = 0
testServer = httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
defer GinkgoRecover()
// Verify the contents of the request
Expect(req.URL.EscapedPath()).To(Equal(listCollectionsPath))
Expect(req.Method).To(Equal("GET"))
// TODO: Add check for expand query parameter
Expect(req.URL.Query()["sort"]).To(Equal([]string{"created_time"}))
Expect(req.URL.Query()["tags"]).To(Equal([]string{"version 1.1, pre-release"}))
Expect(req.URL.Query()["limit"]).To(Equal([]string{fmt.Sprint(int64(1))}))
Expect(req.URL.Query()["offset"]).To(Equal([]string{fmt.Sprint(int64(0))}))
// Sleep a short time to support a timeout test
time.Sleep(serverSleepTime)
// Set mock response
res.Header().Set("Content-type", "application/json")
res.WriteHeader(200)
fmt.Fprintf(res, "%s", `{"collections": [{"name": "Name", "collection_id": "CollectionID", "description": "Description", "tags": "Tags", "created_time": "2019-01-01T12:00:00", "updated_time": "2019-01-01T12:00:00", "href": "Href", "features": [{"feature_id": "FeatureID", "name": "Name"}], "properties": [{"property_id": "PropertyID", "name": "Name"}], "features_count": 13, "properties_count": 15}], "limit": 5, "offset": 6, "total_count": 10, "first": {"href": "Href"}, "previous": {"href": "Href"}, "next": {"href": "Href"}, "last": {"href": "Href"}}`)
}))
})
It(`Invoke ListCollections successfully`, func() {
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1(&appconfigurationv1.AppConfigurationV1Options{
URL: testServer.URL,
Authenticator: &core.NoAuthAuthenticator{},
})
Expect(serviceErr).To(BeNil())
Expect(appConfigurationService).ToNot(BeNil())
appConfigurationService.EnableRetries(0, 0)
// Invoke operation with nil options model (negative test)
result, response, operationErr := appConfigurationService.ListCollections(nil)
Expect(operationErr).NotTo(BeNil())
Expect(response).To(BeNil())
Expect(result).To(BeNil())
// Construct an instance of the ListCollectionsOptions model
listCollectionsOptionsModel := new(appconfigurationv1.ListCollectionsOptions)
listCollectionsOptionsModel.Expand = core.BoolPtr(true)
listCollectionsOptionsModel.Sort = core.StringPtr("created_time")
listCollectionsOptionsModel.Tags = core.StringPtr("version 1.1, pre-release")
listCollectionsOptionsModel.Features = []string{"testString"}
listCollectionsOptionsModel.Properties = []string{"testString"}
listCollectionsOptionsModel.Include = []string{"features"}
listCollectionsOptionsModel.Limit = core.Int64Ptr(int64(1))
listCollectionsOptionsModel.Offset = core.Int64Ptr(int64(0))
listCollectionsOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"}
// Invoke operation with valid options model (positive test)
result, response, operationErr = appConfigurationService.ListCollections(listCollectionsOptionsModel)
Expect(operationErr).To(BeNil())
Expect(response).ToNot(BeNil())
Expect(result).ToNot(BeNil())
// Invoke operation with a Context to test a timeout error
ctx, cancelFunc := context.WithTimeout(context.Background(), 80*time.Millisecond)
defer cancelFunc()
serverSleepTime = 100 * time.Millisecond
_, _, operationErr = appConfigurationService.ListCollectionsWithContext(ctx, listCollectionsOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(operationErr.Error()).To(ContainSubstring("deadline exceeded"))
serverSleepTime = time.Duration(0)
// Disable retries and test again
appConfigurationService.DisableRetries()
result, response, operationErr = appConfigurationService.ListCollections(listCollectionsOptionsModel)
Expect(operationErr).To(BeNil())
Expect(response).ToNot(BeNil())
Expect(result).ToNot(BeNil())
// Re-test the timeout error with retries disabled
ctx, cancelFunc2 := context.WithTimeout(context.Background(), 80*time.Millisecond)
defer cancelFunc2()
serverSleepTime = 100 * time.Millisecond
_, _, operationErr = appConfigurationService.ListCollectionsWithContext(ctx, listCollectionsOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(operationErr.Error()).To(ContainSubstring("deadline exceeded"))
serverSleepTime = time.Duration(0)
})
It(`Invoke ListCollections with error: Operation request error`, func() {
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1(&appconfigurationv1.AppConfigurationV1Options{
URL: testServer.URL,
Authenticator: &core.NoAuthAuthenticator{},
})
Expect(serviceErr).To(BeNil())
Expect(appConfigurationService).ToNot(BeNil())
// Construct an instance of the ListCollectionsOptions model
listCollectionsOptionsModel := new(appconfigurationv1.ListCollectionsOptions)
listCollectionsOptionsModel.Expand = core.BoolPtr(true)
listCollectionsOptionsModel.Sort = core.StringPtr("created_time")
listCollectionsOptionsModel.Tags = core.StringPtr("version 1.1, pre-release")
listCollectionsOptionsModel.Features = []string{"testString"}
listCollectionsOptionsModel.Properties = []string{"testString"}
listCollectionsOptionsModel.Include = []string{"features"}
listCollectionsOptionsModel.Limit = core.Int64Ptr(int64(1))
listCollectionsOptionsModel.Offset = core.Int64Ptr(int64(0))
listCollectionsOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"}
// Invoke operation with empty URL (negative test)
err := appConfigurationService.SetServiceURL("")
Expect(err).To(BeNil())
result, response, operationErr := appConfigurationService.ListCollections(listCollectionsOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(operationErr.Error()).To(ContainSubstring(core.ERRORMSG_SERVICE_URL_MISSING))
Expect(response).To(BeNil())
Expect(result).To(BeNil())
})
AfterEach(func() {
testServer.Close()
})
})
})
Describe(`CreateCollection(createCollectionOptions *CreateCollectionOptions) - Operation response error`, func() {
createCollectionPath := "/collections"
Context(`Using mock server endpoint`, func() {
BeforeEach(func() {
testServer = httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
defer GinkgoRecover()
// Verify the contents of the request
Expect(req.URL.EscapedPath()).To(Equal(createCollectionPath))
Expect(req.Method).To(Equal("POST"))
res.Header().Set("Content-type", "application/json")
res.WriteHeader(201)
fmt.Fprintf(res, `} this is not valid json {`)
}))
})
It(`Invoke CreateCollection with error: Operation response processing error`, func() {
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1(&appconfigurationv1.AppConfigurationV1Options{
URL: testServer.URL,
Authenticator: &core.NoAuthAuthenticator{},
})
Expect(serviceErr).To(BeNil())
Expect(appConfigurationService).ToNot(BeNil())
// Construct an instance of the CreateCollectionOptions model
createCollectionOptionsModel := new(appconfigurationv1.CreateCollectionOptions)
createCollectionOptionsModel.Name = core.StringPtr("Web App Collection")
createCollectionOptionsModel.CollectionID = core.StringPtr("web-app-collection")
createCollectionOptionsModel.Description = core.StringPtr("Collection for Web application")
createCollectionOptionsModel.Tags = core.StringPtr("version: 1.1, pre-release")
createCollectionOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"}
// Expect response parsing to fail since we are receiving a text/plain response
result, response, operationErr := appConfigurationService.CreateCollection(createCollectionOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(response).ToNot(BeNil())
Expect(result).To(BeNil())
// Enable retries and test again
appConfigurationService.EnableRetries(0, 0)
result, response, operationErr = appConfigurationService.CreateCollection(createCollectionOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(response).ToNot(BeNil())
Expect(result).To(BeNil())
})
AfterEach(func() {
testServer.Close()
})
})
})
Describe(`CreateCollection(createCollectionOptions *CreateCollectionOptions)`, func() {
createCollectionPath := "/collections"
var serverSleepTime time.Duration
Context(`Using mock server endpoint`, func() {
BeforeEach(func() {
serverSleepTime = 0
testServer = httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
defer GinkgoRecover()
// Verify the contents of the request
Expect(req.URL.EscapedPath()).To(Equal(createCollectionPath))
Expect(req.Method).To(Equal("POST"))
// For gzip-disabled operation, verify Content-Encoding is not set.
Expect(req.Header.Get("Content-Encoding")).To(BeEmpty())
// If there is a body, then make sure we can read it
bodyBuf := new(bytes.Buffer)
if req.Header.Get("Content-Encoding") == "gzip" {
body, err := core.NewGzipDecompressionReader(req.Body)
Expect(err).To(BeNil())
_, err = bodyBuf.ReadFrom(body)
Expect(err).To(BeNil())
} else {
_, err := bodyBuf.ReadFrom(req.Body)
Expect(err).To(BeNil())
}
fmt.Fprintf(GinkgoWriter, " Request body: %s", bodyBuf.String())
// Sleep a short time to support a timeout test
time.Sleep(serverSleepTime)
// Set mock response
res.Header().Set("Content-type", "application/json")
res.WriteHeader(201)
fmt.Fprintf(res, "%s", `{"name": "Name", "collection_id": "CollectionID", "description": "Description", "tags": "Tags", "created_time": "2019-01-01T12:00:00", "updated_time": "2019-01-01T12:00:00", "href": "Href"}`)
}))
})
It(`Invoke CreateCollection successfully`, func() {
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1(&appconfigurationv1.AppConfigurationV1Options{
URL: testServer.URL,
Authenticator: &core.NoAuthAuthenticator{},
})
Expect(serviceErr).To(BeNil())
Expect(appConfigurationService).ToNot(BeNil())
appConfigurationService.EnableRetries(0, 0)
// Invoke operation with nil options model (negative test)
result, response, operationErr := appConfigurationService.CreateCollection(nil)
Expect(operationErr).NotTo(BeNil())
Expect(response).To(BeNil())
Expect(result).To(BeNil())
// Construct an instance of the CreateCollectionOptions model
createCollectionOptionsModel := new(appconfigurationv1.CreateCollectionOptions)
createCollectionOptionsModel.Name = core.StringPtr("Web App Collection")
createCollectionOptionsModel.CollectionID = core.StringPtr("web-app-collection")
createCollectionOptionsModel.Description = core.StringPtr("Collection for Web application")
createCollectionOptionsModel.Tags = core.StringPtr("version: 1.1, pre-release")
createCollectionOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"}
// Invoke operation with valid options model (positive test)
result, response, operationErr = appConfigurationService.CreateCollection(createCollectionOptionsModel)
Expect(operationErr).To(BeNil())
Expect(response).ToNot(BeNil())
Expect(result).ToNot(BeNil())
// Invoke operation with a Context to test a timeout error
ctx, cancelFunc := context.WithTimeout(context.Background(), 80*time.Millisecond)
defer cancelFunc()
serverSleepTime = 100 * time.Millisecond
_, _, operationErr = appConfigurationService.CreateCollectionWithContext(ctx, createCollectionOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(operationErr.Error()).To(ContainSubstring("deadline exceeded"))
serverSleepTime = time.Duration(0)
// Disable retries and test again
appConfigurationService.DisableRetries()
result, response, operationErr = appConfigurationService.CreateCollection(createCollectionOptionsModel)
Expect(operationErr).To(BeNil())
Expect(response).ToNot(BeNil())
Expect(result).ToNot(BeNil())
// Re-test the timeout error with retries disabled
ctx, cancelFunc2 := context.WithTimeout(context.Background(), 80*time.Millisecond)
defer cancelFunc2()
serverSleepTime = 100 * time.Millisecond
_, _, operationErr = appConfigurationService.CreateCollectionWithContext(ctx, createCollectionOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(operationErr.Error()).To(ContainSubstring("deadline exceeded"))
serverSleepTime = time.Duration(0)
})
It(`Invoke CreateCollection with error: Operation validation and request error`, func() {
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1(&appconfigurationv1.AppConfigurationV1Options{
URL: testServer.URL,
Authenticator: &core.NoAuthAuthenticator{},
})
Expect(serviceErr).To(BeNil())
Expect(appConfigurationService).ToNot(BeNil())
// Construct an instance of the CreateCollectionOptions model
createCollectionOptionsModel := new(appconfigurationv1.CreateCollectionOptions)
createCollectionOptionsModel.Name = core.StringPtr("Web App Collection")
createCollectionOptionsModel.CollectionID = core.StringPtr("web-app-collection")
createCollectionOptionsModel.Description = core.StringPtr("Collection for Web application")
createCollectionOptionsModel.Tags = core.StringPtr("version: 1.1, pre-release")
createCollectionOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"}
// Invoke operation with empty URL (negative test)
err := appConfigurationService.SetServiceURL("")
Expect(err).To(BeNil())
result, response, operationErr := appConfigurationService.CreateCollection(createCollectionOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(operationErr.Error()).To(ContainSubstring(core.ERRORMSG_SERVICE_URL_MISSING))
Expect(response).To(BeNil())
Expect(result).To(BeNil())
// Construct a second instance of the CreateCollectionOptions model with no property values
createCollectionOptionsModelNew := new(appconfigurationv1.CreateCollectionOptions)
// Invoke operation with invalid model (negative test)
result, response, operationErr = appConfigurationService.CreateCollection(createCollectionOptionsModelNew)
Expect(operationErr).ToNot(BeNil())
Expect(response).To(BeNil())
Expect(result).To(BeNil())
})
AfterEach(func() {
testServer.Close()
})
})
})
Describe(`UpdateCollection(updateCollectionOptions *UpdateCollectionOptions) - Operation response error`, func() {
updateCollectionPath := "/collections/testString"
Context(`Using mock server endpoint`, func() {
BeforeEach(func() {
testServer = httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
defer GinkgoRecover()
// Verify the contents of the request
Expect(req.URL.EscapedPath()).To(Equal(updateCollectionPath))
Expect(req.Method).To(Equal("PUT"))
res.Header().Set("Content-type", "application/json")
res.WriteHeader(200)
fmt.Fprintf(res, `} this is not valid json {`)
}))
})
It(`Invoke UpdateCollection with error: Operation response processing error`, func() {
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1(&appconfigurationv1.AppConfigurationV1Options{
URL: testServer.URL,
Authenticator: &core.NoAuthAuthenticator{},
})
Expect(serviceErr).To(BeNil())
Expect(appConfigurationService).ToNot(BeNil())
// Construct an instance of the UpdateCollectionOptions model
updateCollectionOptionsModel := new(appconfigurationv1.UpdateCollectionOptions)
updateCollectionOptionsModel.CollectionID = core.StringPtr("testString")
updateCollectionOptionsModel.Name = core.StringPtr("testString")
updateCollectionOptionsModel.Description = core.StringPtr("testString")
updateCollectionOptionsModel.Tags = core.StringPtr("testString")
updateCollectionOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"}
// Expect response parsing to fail since we are receiving a text/plain response
result, response, operationErr := appConfigurationService.UpdateCollection(updateCollectionOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(response).ToNot(BeNil())
Expect(result).To(BeNil())
// Enable retries and test again
appConfigurationService.EnableRetries(0, 0)
result, response, operationErr = appConfigurationService.UpdateCollection(updateCollectionOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(response).ToNot(BeNil())
Expect(result).To(BeNil())
})
AfterEach(func() {
testServer.Close()
})
})
})
Describe(`UpdateCollection(updateCollectionOptions *UpdateCollectionOptions)`, func() {
updateCollectionPath := "/collections/testString"
var serverSleepTime time.Duration
Context(`Using mock server endpoint`, func() {
BeforeEach(func() {
serverSleepTime = 0
testServer = httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
defer GinkgoRecover()
// Verify the contents of the request
Expect(req.URL.EscapedPath()).To(Equal(updateCollectionPath))
Expect(req.Method).To(Equal("PUT"))
// For gzip-disabled operation, verify Content-Encoding is not set.
Expect(req.Header.Get("Content-Encoding")).To(BeEmpty())
// If there is a body, then make sure we can read it
bodyBuf := new(bytes.Buffer)
if req.Header.Get("Content-Encoding") == "gzip" {
body, err := core.NewGzipDecompressionReader(req.Body)
Expect(err).To(BeNil())
_, err = bodyBuf.ReadFrom(body)
Expect(err).To(BeNil())
} else {
_, err := bodyBuf.ReadFrom(req.Body)
Expect(err).To(BeNil())
}
fmt.Fprintf(GinkgoWriter, " Request body: %s", bodyBuf.String())
// Sleep a short time to support a timeout test
time.Sleep(serverSleepTime)
// Set mock response
res.Header().Set("Content-type", "application/json")
res.WriteHeader(200)
fmt.Fprintf(res, "%s", `{"name": "Name", "collection_id": "CollectionID", "description": "Description", "tags": "Tags", "created_time": "2019-01-01T12:00:00", "updated_time": "2019-01-01T12:00:00", "href": "Href"}`)
}))
})
It(`Invoke UpdateCollection successfully`, func() {
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1(&appconfigurationv1.AppConfigurationV1Options{
URL: testServer.URL,
Authenticator: &core.NoAuthAuthenticator{},
})
Expect(serviceErr).To(BeNil())
Expect(appConfigurationService).ToNot(BeNil())
appConfigurationService.EnableRetries(0, 0)
// Invoke operation with nil options model (negative test)
result, response, operationErr := appConfigurationService.UpdateCollection(nil)
Expect(operationErr).NotTo(BeNil())
Expect(response).To(BeNil())
Expect(result).To(BeNil())
// Construct an instance of the UpdateCollectionOptions model
updateCollectionOptionsModel := new(appconfigurationv1.UpdateCollectionOptions)
updateCollectionOptionsModel.CollectionID = core.StringPtr("testString")
updateCollectionOptionsModel.Name = core.StringPtr("testString")
updateCollectionOptionsModel.Description = core.StringPtr("testString")
updateCollectionOptionsModel.Tags = core.StringPtr("testString")
updateCollectionOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"}
// Invoke operation with valid options model (positive test)
result, response, operationErr = appConfigurationService.UpdateCollection(updateCollectionOptionsModel)
Expect(operationErr).To(BeNil())
Expect(response).ToNot(BeNil())
Expect(result).ToNot(BeNil())
// Invoke operation with a Context to test a timeout error
ctx, cancelFunc := context.WithTimeout(context.Background(), 80*time.Millisecond)
defer cancelFunc()
serverSleepTime = 100 * time.Millisecond
_, _, operationErr = appConfigurationService.UpdateCollectionWithContext(ctx, updateCollectionOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(operationErr.Error()).To(ContainSubstring("deadline exceeded"))
serverSleepTime = time.Duration(0)
// Disable retries and test again
appConfigurationService.DisableRetries()
result, response, operationErr = appConfigurationService.UpdateCollection(updateCollectionOptionsModel)
Expect(operationErr).To(BeNil())
Expect(response).ToNot(BeNil())
Expect(result).ToNot(BeNil())
// Re-test the timeout error with retries disabled
ctx, cancelFunc2 := context.WithTimeout(context.Background(), 80*time.Millisecond)
defer cancelFunc2()
serverSleepTime = 100 * time.Millisecond
_, _, operationErr = appConfigurationService.UpdateCollectionWithContext(ctx, updateCollectionOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(operationErr.Error()).To(ContainSubstring("deadline exceeded"))
serverSleepTime = time.Duration(0)
})
It(`Invoke UpdateCollection with error: Operation validation and request error`, func() {
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1(&appconfigurationv1.AppConfigurationV1Options{
URL: testServer.URL,
Authenticator: &core.NoAuthAuthenticator{},
})
Expect(serviceErr).To(BeNil())
Expect(appConfigurationService).ToNot(BeNil())
// Construct an instance of the UpdateCollectionOptions model
updateCollectionOptionsModel := new(appconfigurationv1.UpdateCollectionOptions)
updateCollectionOptionsModel.CollectionID = core.StringPtr("testString")
updateCollectionOptionsModel.Name = core.StringPtr("testString")
updateCollectionOptionsModel.Description = core.StringPtr("testString")
updateCollectionOptionsModel.Tags = core.StringPtr("testString")
updateCollectionOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"}
// Invoke operation with empty URL (negative test)
err := appConfigurationService.SetServiceURL("")
Expect(err).To(BeNil())
result, response, operationErr := appConfigurationService.UpdateCollection(updateCollectionOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(operationErr.Error()).To(ContainSubstring(core.ERRORMSG_SERVICE_URL_MISSING))
Expect(response).To(BeNil())
Expect(result).To(BeNil())
// Construct a second instance of the UpdateCollectionOptions model with no property values
updateCollectionOptionsModelNew := new(appconfigurationv1.UpdateCollectionOptions)
// Invoke operation with invalid model (negative test)
result, response, operationErr = appConfigurationService.UpdateCollection(updateCollectionOptionsModelNew)
Expect(operationErr).ToNot(BeNil())
Expect(response).To(BeNil())
Expect(result).To(BeNil())
})
AfterEach(func() {
testServer.Close()
})
})
})
Describe(`GetCollection(getCollectionOptions *GetCollectionOptions) - Operation response error`, func() {
getCollectionPath := "/collections/testString"
Context(`Using mock server endpoint`, func() {
BeforeEach(func() {
testServer = httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
defer GinkgoRecover()
// Verify the contents of the request
Expect(req.URL.EscapedPath()).To(Equal(getCollectionPath))
Expect(req.Method).To(Equal("GET"))
// TODO: Add check for expand query parameter
res.Header().Set("Content-type", "application/json")
res.WriteHeader(200)
fmt.Fprintf(res, `} this is not valid json {`)
}))
})
It(`Invoke GetCollection with error: Operation response processing error`, func() {
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1(&appconfigurationv1.AppConfigurationV1Options{
URL: testServer.URL,
Authenticator: &core.NoAuthAuthenticator{},
})
Expect(serviceErr).To(BeNil())
Expect(appConfigurationService).ToNot(BeNil())
// Construct an instance of the GetCollectionOptions model
getCollectionOptionsModel := new(appconfigurationv1.GetCollectionOptions)
getCollectionOptionsModel.CollectionID = core.StringPtr("testString")
getCollectionOptionsModel.Expand = core.BoolPtr(true)
getCollectionOptionsModel.Include = []string{"features"}
getCollectionOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"}
// Expect response parsing to fail since we are receiving a text/plain response
result, response, operationErr := appConfigurationService.GetCollection(getCollectionOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(response).ToNot(BeNil())
Expect(result).To(BeNil())
// Enable retries and test again
appConfigurationService.EnableRetries(0, 0)
result, response, operationErr = appConfigurationService.GetCollection(getCollectionOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(response).ToNot(BeNil())
Expect(result).To(BeNil())
})
AfterEach(func() {
testServer.Close()
})
})
})
Describe(`GetCollection(getCollectionOptions *GetCollectionOptions)`, func() {
getCollectionPath := "/collections/testString"
var serverSleepTime time.Duration
Context(`Using mock server endpoint`, func() {
BeforeEach(func() {
serverSleepTime = 0
testServer = httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
defer GinkgoRecover()
// Verify the contents of the request
Expect(req.URL.EscapedPath()).To(Equal(getCollectionPath))
Expect(req.Method).To(Equal("GET"))
// TODO: Add check for expand query parameter
// Sleep a short time to support a timeout test
time.Sleep(serverSleepTime)
// Set mock response
res.Header().Set("Content-type", "application/json")
res.WriteHeader(200)
fmt.Fprintf(res, "%s", `{"name": "Name", "collection_id": "CollectionID", "description": "Description", "tags": "Tags", "created_time": "2019-01-01T12:00:00", "updated_time": "2019-01-01T12:00:00", "href": "Href", "features": [{"feature_id": "FeatureID", "name": "Name"}], "properties": [{"property_id": "PropertyID", "name": "Name"}], "features_count": 13, "properties_count": 15}`)
}))
})
It(`Invoke GetCollection successfully`, func() {
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1(&appconfigurationv1.AppConfigurationV1Options{
URL: testServer.URL,
Authenticator: &core.NoAuthAuthenticator{},
})
Expect(serviceErr).To(BeNil())
Expect(appConfigurationService).ToNot(BeNil())
appConfigurationService.EnableRetries(0, 0)
// Invoke operation with nil options model (negative test)
result, response, operationErr := appConfigurationService.GetCollection(nil)
Expect(operationErr).NotTo(BeNil())
Expect(response).To(BeNil())
Expect(result).To(BeNil())
// Construct an instance of the GetCollectionOptions model
getCollectionOptionsModel := new(appconfigurationv1.GetCollectionOptions)
getCollectionOptionsModel.CollectionID = core.StringPtr("testString")
getCollectionOptionsModel.Expand = core.BoolPtr(true)
getCollectionOptionsModel.Include = []string{"features"}
getCollectionOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"}
// Invoke operation with valid options model (positive test)
result, response, operationErr = appConfigurationService.GetCollection(getCollectionOptionsModel)
Expect(operationErr).To(BeNil())
Expect(response).ToNot(BeNil())
Expect(result).ToNot(BeNil())
// Invoke operation with a Context to test a timeout error
ctx, cancelFunc := context.WithTimeout(context.Background(), 80*time.Millisecond)
defer cancelFunc()
serverSleepTime = 100 * time.Millisecond
_, _, operationErr = appConfigurationService.GetCollectionWithContext(ctx, getCollectionOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(operationErr.Error()).To(ContainSubstring("deadline exceeded"))
serverSleepTime = time.Duration(0)
// Disable retries and test again
appConfigurationService.DisableRetries()
result, response, operationErr = appConfigurationService.GetCollection(getCollectionOptionsModel)
Expect(operationErr).To(BeNil())
Expect(response).ToNot(BeNil())
Expect(result).ToNot(BeNil())
// Re-test the timeout error with retries disabled
ctx, cancelFunc2 := context.WithTimeout(context.Background(), 80*time.Millisecond)
defer cancelFunc2()
serverSleepTime = 100 * time.Millisecond
_, _, operationErr = appConfigurationService.GetCollectionWithContext(ctx, getCollectionOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(operationErr.Error()).To(ContainSubstring("deadline exceeded"))
serverSleepTime = time.Duration(0)
})
It(`Invoke GetCollection with error: Operation validation and request error`, func() {
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1(&appconfigurationv1.AppConfigurationV1Options{
URL: testServer.URL,
Authenticator: &core.NoAuthAuthenticator{},
})
Expect(serviceErr).To(BeNil())
Expect(appConfigurationService).ToNot(BeNil())
// Construct an instance of the GetCollectionOptions model
getCollectionOptionsModel := new(appconfigurationv1.GetCollectionOptions)
getCollectionOptionsModel.CollectionID = core.StringPtr("testString")
getCollectionOptionsModel.Expand = core.BoolPtr(true)
getCollectionOptionsModel.Include = []string{"features"}
getCollectionOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"}
// Invoke operation with empty URL (negative test)
err := appConfigurationService.SetServiceURL("")
Expect(err).To(BeNil())
result, response, operationErr := appConfigurationService.GetCollection(getCollectionOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(operationErr.Error()).To(ContainSubstring(core.ERRORMSG_SERVICE_URL_MISSING))
Expect(response).To(BeNil())
Expect(result).To(BeNil())
// Construct a second instance of the GetCollectionOptions model with no property values
getCollectionOptionsModelNew := new(appconfigurationv1.GetCollectionOptions)
// Invoke operation with invalid model (negative test)
result, response, operationErr = appConfigurationService.GetCollection(getCollectionOptionsModelNew)
Expect(operationErr).ToNot(BeNil())
Expect(response).To(BeNil())
Expect(result).To(BeNil())
})
AfterEach(func() {
testServer.Close()
})
})
})
Describe(`DeleteCollection(deleteCollectionOptions *DeleteCollectionOptions)`, func() {
deleteCollectionPath := "/collections/testString"
Context(`Using mock server endpoint`, func() {
BeforeEach(func() {
testServer = httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
defer GinkgoRecover()
// Verify the contents of the request
Expect(req.URL.EscapedPath()).To(Equal(deleteCollectionPath))
Expect(req.Method).To(Equal("DELETE"))
res.WriteHeader(204)
}))
})
It(`Invoke DeleteCollection successfully`, func() {
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1(&appconfigurationv1.AppConfigurationV1Options{
URL: testServer.URL,
Authenticator: &core.NoAuthAuthenticator{},
})
Expect(serviceErr).To(BeNil())
Expect(appConfigurationService).ToNot(BeNil())
appConfigurationService.EnableRetries(0, 0)
// Invoke operation with nil options model (negative test)
response, operationErr := appConfigurationService.DeleteCollection(nil)
Expect(operationErr).NotTo(BeNil())
Expect(response).To(BeNil())
// Construct an instance of the DeleteCollectionOptions model
deleteCollectionOptionsModel := new(appconfigurationv1.DeleteCollectionOptions)
deleteCollectionOptionsModel.CollectionID = core.StringPtr("testString")
deleteCollectionOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"}
// Invoke operation with valid options model (positive test)
response, operationErr = appConfigurationService.DeleteCollection(deleteCollectionOptionsModel)
Expect(operationErr).To(BeNil())
Expect(response).ToNot(BeNil())
// Disable retries and test again
appConfigurationService.DisableRetries()
response, operationErr = appConfigurationService.DeleteCollection(deleteCollectionOptionsModel)
Expect(operationErr).To(BeNil())
Expect(response).ToNot(BeNil())
})
It(`Invoke DeleteCollection with error: Operation validation and request error`, func() {
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1(&appconfigurationv1.AppConfigurationV1Options{
URL: testServer.URL,
Authenticator: &core.NoAuthAuthenticator{},
})
Expect(serviceErr).To(BeNil())
Expect(appConfigurationService).ToNot(BeNil())
// Construct an instance of the DeleteCollectionOptions model
deleteCollectionOptionsModel := new(appconfigurationv1.DeleteCollectionOptions)
deleteCollectionOptionsModel.CollectionID = core.StringPtr("testString")
deleteCollectionOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"}
// Invoke operation with empty URL (negative test)
err := appConfigurationService.SetServiceURL("")
Expect(err).To(BeNil())
response, operationErr := appConfigurationService.DeleteCollection(deleteCollectionOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(operationErr.Error()).To(ContainSubstring(core.ERRORMSG_SERVICE_URL_MISSING))
Expect(response).To(BeNil())
// Construct a second instance of the DeleteCollectionOptions model with no property values
deleteCollectionOptionsModelNew := new(appconfigurationv1.DeleteCollectionOptions)
// Invoke operation with invalid model (negative test)
response, operationErr = appConfigurationService.DeleteCollection(deleteCollectionOptionsModelNew)
Expect(operationErr).ToNot(BeNil())
Expect(response).To(BeNil())
})
AfterEach(func() {
testServer.Close()
})
})
})
Describe(`Service constructor tests`, func() {
It(`Instantiate service client`, func() {
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1(&appconfigurationv1.AppConfigurationV1Options{
Authenticator: &core.NoAuthAuthenticator{},
})
Expect(appConfigurationService).ToNot(BeNil())
Expect(serviceErr).To(BeNil())
})
It(`Instantiate service client with error: Invalid URL`, func() {
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1(&appconfigurationv1.AppConfigurationV1Options{
URL: "{BAD_URL_STRING",
})
Expect(appConfigurationService).To(BeNil())
Expect(serviceErr).ToNot(BeNil())
})
It(`Instantiate service client with error: Invalid Auth`, func() {
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1(&appconfigurationv1.AppConfigurationV1Options{
URL: "https://appconfigurationv1/api",
Authenticator: &core.BasicAuthenticator{
Username: "",
Password: "",
},
})
Expect(appConfigurationService).To(BeNil())
Expect(serviceErr).ToNot(BeNil())
})
})
Describe(`Service constructor tests using external config`, func() {
Context(`Using external config, construct service client instances`, func() {
// Map containing environment variables used in testing.
var testEnvironment = map[string]string{
"APP_CONFIGURATION_URL": "https://appconfigurationv1/api",
"APP_CONFIGURATION_AUTH_TYPE": "noauth",
}
It(`Create service client using external config successfully`, func() {
SetTestEnvironment(testEnvironment)
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1UsingExternalConfig(&appconfigurationv1.AppConfigurationV1Options{})
Expect(appConfigurationService).ToNot(BeNil())
Expect(serviceErr).To(BeNil())
ClearTestEnvironment(testEnvironment)
clone := appConfigurationService.Clone()
Expect(clone).ToNot(BeNil())
Expect(clone.Service != appConfigurationService.Service).To(BeTrue())
Expect(clone.GetServiceURL()).To(Equal(appConfigurationService.GetServiceURL()))
Expect(clone.Service.Options.Authenticator).To(Equal(appConfigurationService.Service.Options.Authenticator))
})
It(`Create service client using external config and set url from constructor successfully`, func() {
SetTestEnvironment(testEnvironment)
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1UsingExternalConfig(&appconfigurationv1.AppConfigurationV1Options{
URL: "https://testService/api",
})
Expect(appConfigurationService).ToNot(BeNil())
Expect(serviceErr).To(BeNil())
Expect(appConfigurationService.Service.GetServiceURL()).To(Equal("https://testService/api"))
ClearTestEnvironment(testEnvironment)
clone := appConfigurationService.Clone()
Expect(clone).ToNot(BeNil())
Expect(clone.Service != appConfigurationService.Service).To(BeTrue())
Expect(clone.GetServiceURL()).To(Equal(appConfigurationService.GetServiceURL()))
Expect(clone.Service.Options.Authenticator).To(Equal(appConfigurationService.Service.Options.Authenticator))
})
It(`Create service client using external config and set url programatically successfully`, func() {
SetTestEnvironment(testEnvironment)
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1UsingExternalConfig(&appconfigurationv1.AppConfigurationV1Options{})
err := appConfigurationService.SetServiceURL("https://testService/api")
Expect(err).To(BeNil())
Expect(appConfigurationService).ToNot(BeNil())
Expect(serviceErr).To(BeNil())
Expect(appConfigurationService.Service.GetServiceURL()).To(Equal("https://testService/api"))
ClearTestEnvironment(testEnvironment)
clone := appConfigurationService.Clone()
Expect(clone).ToNot(BeNil())
Expect(clone.Service != appConfigurationService.Service).To(BeTrue())
Expect(clone.GetServiceURL()).To(Equal(appConfigurationService.GetServiceURL()))
Expect(clone.Service.Options.Authenticator).To(Equal(appConfigurationService.Service.Options.Authenticator))
})
})
Context(`Using external config, construct service client instances with error: Invalid Auth`, func() {
// Map containing environment variables used in testing.
var testEnvironment = map[string]string{
"APP_CONFIGURATION_URL": "https://appconfigurationv1/api",
"APP_CONFIGURATION_AUTH_TYPE": "someOtherAuth",
}
SetTestEnvironment(testEnvironment)
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1UsingExternalConfig(&appconfigurationv1.AppConfigurationV1Options{})
It(`Instantiate service client with error`, func() {
Expect(appConfigurationService).To(BeNil())
Expect(serviceErr).ToNot(BeNil())
ClearTestEnvironment(testEnvironment)
})
})
Context(`Using external config, construct service client instances with error: Invalid URL`, func() {
// Map containing environment variables used in testing.
var testEnvironment = map[string]string{
"APP_CONFIGURATION_AUTH_TYPE": "NOAuth",
}
SetTestEnvironment(testEnvironment)
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1UsingExternalConfig(&appconfigurationv1.AppConfigurationV1Options{
URL: "{BAD_URL_STRING",
})
It(`Instantiate service client with error`, func() {
Expect(appConfigurationService).To(BeNil())
Expect(serviceErr).ToNot(BeNil())
ClearTestEnvironment(testEnvironment)
})
})
})
Describe(`Regional endpoint tests`, func() {
It(`GetServiceURLForRegion(region string)`, func() {
var url string
var err error
url, err = appconfigurationv1.GetServiceURLForRegion("INVALID_REGION")
Expect(url).To(BeEmpty())
Expect(err).ToNot(BeNil())
fmt.Fprintf(GinkgoWriter, "Expected error: %s\n", err.Error())
})
})
Describe(`ListFeatures(listFeaturesOptions *ListFeaturesOptions) - Operation response error`, func() {
listFeaturesPath := "/environments/testString/features"
Context(`Using mock server endpoint`, func() {
BeforeEach(func() {
testServer = httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
defer GinkgoRecover()
// Verify the contents of the request
Expect(req.URL.EscapedPath()).To(Equal(listFeaturesPath))
Expect(req.Method).To(Equal("GET"))
// TODO: Add check for expand query parameter
Expect(req.URL.Query()["sort"]).To(Equal([]string{"created_time"}))
Expect(req.URL.Query()["tags"]).To(Equal([]string{"version 1.1, pre-release"}))
Expect(req.URL.Query()["limit"]).To(Equal([]string{fmt.Sprint(int64(1))}))
Expect(req.URL.Query()["offset"]).To(Equal([]string{fmt.Sprint(int64(0))}))
res.Header().Set("Content-type", "application/json")
res.WriteHeader(200)
fmt.Fprintf(res, `} this is not valid json {`)
}))
})
It(`Invoke ListFeatures with error: Operation response processing error`, func() {
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1(&appconfigurationv1.AppConfigurationV1Options{
URL: testServer.URL,
Authenticator: &core.NoAuthAuthenticator{},
})
Expect(serviceErr).To(BeNil())
Expect(appConfigurationService).ToNot(BeNil())
// Construct an instance of the ListFeaturesOptions model
listFeaturesOptionsModel := new(appconfigurationv1.ListFeaturesOptions)
listFeaturesOptionsModel.EnvironmentID = core.StringPtr("testString")
listFeaturesOptionsModel.Expand = core.BoolPtr(true)
listFeaturesOptionsModel.Sort = core.StringPtr("created_time")
listFeaturesOptionsModel.Tags = core.StringPtr("version 1.1, pre-release")
listFeaturesOptionsModel.Collections = []string{"testString"}
listFeaturesOptionsModel.Segments = []string{"testString"}
listFeaturesOptionsModel.Include = []string{"collections"}
listFeaturesOptionsModel.Limit = core.Int64Ptr(int64(1))
listFeaturesOptionsModel.Offset = core.Int64Ptr(int64(0))
listFeaturesOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"}
// Expect response parsing to fail since we are receiving a text/plain response
result, response, operationErr := appConfigurationService.ListFeatures(listFeaturesOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(response).ToNot(BeNil())
Expect(result).To(BeNil())
// Enable retries and test again
appConfigurationService.EnableRetries(0, 0)
result, response, operationErr = appConfigurationService.ListFeatures(listFeaturesOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(response).ToNot(BeNil())
Expect(result).To(BeNil())
})
AfterEach(func() {
testServer.Close()
})
})
})
Describe(`ListFeatures(listFeaturesOptions *ListFeaturesOptions)`, func() {
listFeaturesPath := "/environments/testString/features"
var serverSleepTime time.Duration
Context(`Using mock server endpoint`, func() {
BeforeEach(func() {
serverSleepTime = 0
testServer = httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
defer GinkgoRecover()
// Verify the contents of the request
Expect(req.URL.EscapedPath()).To(Equal(listFeaturesPath))
Expect(req.Method).To(Equal("GET"))
// TODO: Add check for expand query parameter
Expect(req.URL.Query()["sort"]).To(Equal([]string{"created_time"}))
Expect(req.URL.Query()["tags"]).To(Equal([]string{"version 1.1, pre-release"}))
Expect(req.URL.Query()["limit"]).To(Equal([]string{fmt.Sprint(int64(1))}))
Expect(req.URL.Query()["offset"]).To(Equal([]string{fmt.Sprint(int64(0))}))
// Sleep a short time to support a timeout test
time.Sleep(serverSleepTime)
// Set mock response
res.Header().Set("Content-type", "application/json")
res.WriteHeader(200)
fmt.Fprintf(res, "%s", `{"features": [{"name": "Name", "feature_id": "FeatureID", "description": "Description", "type": "BOOLEAN", "enabled_value": "anyValue", "disabled_value": "anyValue", "enabled": false, "tags": "Tags", "segment_rules": [{"rules": [{"segments": ["Segments"]}], "value": "anyValue", "order": 5}], "segment_exists": false, "collections": [{"collection_id": "CollectionID", "name": "Name"}], "created_time": "2019-01-01T12:00:00", "updated_time": "2019-01-01T12:00:00", "evaluation_time": "2019-01-01T12:00:00", "href": "Href"}], "limit": 5, "offset": 6, "total_count": 10, "first": {"href": "Href"}, "previous": {"href": "Href"}, "next": {"href": "Href"}, "last": {"href": "Href"}}`)
}))
})
It(`Invoke ListFeatures successfully`, func() {
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1(&appconfigurationv1.AppConfigurationV1Options{
URL: testServer.URL,
Authenticator: &core.NoAuthAuthenticator{},
})
Expect(serviceErr).To(BeNil())
Expect(appConfigurationService).ToNot(BeNil())
appConfigurationService.EnableRetries(0, 0)
// Invoke operation with nil options model (negative test)
result, response, operationErr := appConfigurationService.ListFeatures(nil)
Expect(operationErr).NotTo(BeNil())
Expect(response).To(BeNil())
Expect(result).To(BeNil())
// Construct an instance of the ListFeaturesOptions model
listFeaturesOptionsModel := new(appconfigurationv1.ListFeaturesOptions)
listFeaturesOptionsModel.EnvironmentID = core.StringPtr("testString")
listFeaturesOptionsModel.Expand = core.BoolPtr(true)
listFeaturesOptionsModel.Sort = core.StringPtr("created_time")
listFeaturesOptionsModel.Tags = core.StringPtr("version 1.1, pre-release")
listFeaturesOptionsModel.Collections = []string{"testString"}
listFeaturesOptionsModel.Segments = []string{"testString"}
listFeaturesOptionsModel.Include = []string{"collections"}
listFeaturesOptionsModel.Limit = core.Int64Ptr(int64(1))
listFeaturesOptionsModel.Offset = core.Int64Ptr(int64(0))
listFeaturesOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"}
// Invoke operation with valid options model (positive test)
result, response, operationErr = appConfigurationService.ListFeatures(listFeaturesOptionsModel)
Expect(operationErr).To(BeNil())
Expect(response).ToNot(BeNil())
Expect(result).ToNot(BeNil())
// Invoke operation with a Context to test a timeout error
ctx, cancelFunc := context.WithTimeout(context.Background(), 80*time.Millisecond)
defer cancelFunc()
serverSleepTime = 100 * time.Millisecond
_, _, operationErr = appConfigurationService.ListFeaturesWithContext(ctx, listFeaturesOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(operationErr.Error()).To(ContainSubstring("deadline exceeded"))
serverSleepTime = time.Duration(0)
// Disable retries and test again
appConfigurationService.DisableRetries()
result, response, operationErr = appConfigurationService.ListFeatures(listFeaturesOptionsModel)
Expect(operationErr).To(BeNil())
Expect(response).ToNot(BeNil())
Expect(result).ToNot(BeNil())
// Re-test the timeout error with retries disabled
ctx, cancelFunc2 := context.WithTimeout(context.Background(), 80*time.Millisecond)
defer cancelFunc2()
serverSleepTime = 100 * time.Millisecond
_, _, operationErr = appConfigurationService.ListFeaturesWithContext(ctx, listFeaturesOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(operationErr.Error()).To(ContainSubstring("deadline exceeded"))
serverSleepTime = time.Duration(0)
})
It(`Invoke ListFeatures with error: Operation validation and request error`, func() {
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1(&appconfigurationv1.AppConfigurationV1Options{
URL: testServer.URL,
Authenticator: &core.NoAuthAuthenticator{},
})
Expect(serviceErr).To(BeNil())
Expect(appConfigurationService).ToNot(BeNil())
// Construct an instance of the ListFeaturesOptions model
listFeaturesOptionsModel := new(appconfigurationv1.ListFeaturesOptions)
listFeaturesOptionsModel.EnvironmentID = core.StringPtr("testString")
listFeaturesOptionsModel.Expand = core.BoolPtr(true)
listFeaturesOptionsModel.Sort = core.StringPtr("created_time")
listFeaturesOptionsModel.Tags = core.StringPtr("version 1.1, pre-release")
listFeaturesOptionsModel.Collections = []string{"testString"}
listFeaturesOptionsModel.Segments = []string{"testString"}
listFeaturesOptionsModel.Include = []string{"collections"}
listFeaturesOptionsModel.Limit = core.Int64Ptr(int64(1))
listFeaturesOptionsModel.Offset = core.Int64Ptr(int64(0))
listFeaturesOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"}
// Invoke operation with empty URL (negative test)
err := appConfigurationService.SetServiceURL("")
Expect(err).To(BeNil())
result, response, operationErr := appConfigurationService.ListFeatures(listFeaturesOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(operationErr.Error()).To(ContainSubstring(core.ERRORMSG_SERVICE_URL_MISSING))
Expect(response).To(BeNil())
Expect(result).To(BeNil())
// Construct a second instance of the ListFeaturesOptions model with no property values
listFeaturesOptionsModelNew := new(appconfigurationv1.ListFeaturesOptions)
// Invoke operation with invalid model (negative test)
result, response, operationErr = appConfigurationService.ListFeatures(listFeaturesOptionsModelNew)
Expect(operationErr).ToNot(BeNil())
Expect(response).To(BeNil())
Expect(result).To(BeNil())
})
AfterEach(func() {
testServer.Close()
})
})
})
Describe(`CreateFeature(createFeatureOptions *CreateFeatureOptions) - Operation response error`, func() {
createFeaturePath := "/environments/testString/features"
Context(`Using mock server endpoint`, func() {
BeforeEach(func() {
testServer = httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
defer GinkgoRecover()
// Verify the contents of the request
Expect(req.URL.EscapedPath()).To(Equal(createFeaturePath))
Expect(req.Method).To(Equal("POST"))
res.Header().Set("Content-type", "application/json")
res.WriteHeader(201)
fmt.Fprintf(res, `} this is not valid json {`)
}))
})
It(`Invoke CreateFeature with error: Operation response processing error`, func() {
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1(&appconfigurationv1.AppConfigurationV1Options{
URL: testServer.URL,
Authenticator: &core.NoAuthAuthenticator{},
})
Expect(serviceErr).To(BeNil())
Expect(appConfigurationService).ToNot(BeNil())
// Construct an instance of the TargetSegments model
targetSegmentsModel := new(appconfigurationv1.TargetSegments)
targetSegmentsModel.Segments = []string{"testString"}
// Construct an instance of the SegmentRule model
segmentRuleModel := new(appconfigurationv1.SegmentRule)
segmentRuleModel.Rules = []appconfigurationv1.TargetSegments{*targetSegmentsModel}
segmentRuleModel.Value = core.StringPtr("true")
segmentRuleModel.Order = core.Int64Ptr(int64(1))
// Construct an instance of the CollectionRef model
collectionRefModel := new(appconfigurationv1.CollectionRef)
collectionRefModel.CollectionID = core.StringPtr("ghzinc")
// Construct an instance of the CreateFeatureOptions model
createFeatureOptionsModel := new(appconfigurationv1.CreateFeatureOptions)
createFeatureOptionsModel.EnvironmentID = core.StringPtr("testString")
createFeatureOptionsModel.Name = core.StringPtr("Cycle Rentals")
createFeatureOptionsModel.FeatureID = core.StringPtr("cycle-rentals")
createFeatureOptionsModel.Type = core.StringPtr("BOOLEAN")
createFeatureOptionsModel.EnabledValue = core.StringPtr("true")
createFeatureOptionsModel.DisabledValue = core.StringPtr("false")
createFeatureOptionsModel.Description = core.StringPtr("Feature flag to enable Cycle Rentals")
createFeatureOptionsModel.Enabled = core.BoolPtr(true)
createFeatureOptionsModel.Tags = core.StringPtr("version: 1.1, pre-release")
createFeatureOptionsModel.SegmentRules = []appconfigurationv1.SegmentRule{*segmentRuleModel}
createFeatureOptionsModel.Collections = []appconfigurationv1.CollectionRef{*collectionRefModel}
createFeatureOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"}
// Expect response parsing to fail since we are receiving a text/plain response
result, response, operationErr := appConfigurationService.CreateFeature(createFeatureOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(response).ToNot(BeNil())
Expect(result).To(BeNil())
// Enable retries and test again
appConfigurationService.EnableRetries(0, 0)
result, response, operationErr = appConfigurationService.CreateFeature(createFeatureOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(response).ToNot(BeNil())
Expect(result).To(BeNil())
})
AfterEach(func() {
testServer.Close()
})
})
})
Describe(`CreateFeature(createFeatureOptions *CreateFeatureOptions)`, func() {
createFeaturePath := "/environments/testString/features"
var serverSleepTime time.Duration
Context(`Using mock server endpoint`, func() {
BeforeEach(func() {
serverSleepTime = 0
testServer = httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
defer GinkgoRecover()
// Verify the contents of the request
Expect(req.URL.EscapedPath()).To(Equal(createFeaturePath))
Expect(req.Method).To(Equal("POST"))
// For gzip-disabled operation, verify Content-Encoding is not set.
Expect(req.Header.Get("Content-Encoding")).To(BeEmpty())
// If there is a body, then make sure we can read it
bodyBuf := new(bytes.Buffer)
if req.Header.Get("Content-Encoding") == "gzip" {
body, err := core.NewGzipDecompressionReader(req.Body)
Expect(err).To(BeNil())
_, err = bodyBuf.ReadFrom(body)
Expect(err).To(BeNil())
} else {
_, err := bodyBuf.ReadFrom(req.Body)
Expect(err).To(BeNil())
}
fmt.Fprintf(GinkgoWriter, " Request body: %s", bodyBuf.String())
// Sleep a short time to support a timeout test
time.Sleep(serverSleepTime)
// Set mock response
res.Header().Set("Content-type", "application/json")
res.WriteHeader(201)
fmt.Fprintf(res, "%s", `{"name": "Name", "feature_id": "FeatureID", "description": "Description", "type": "BOOLEAN", "enabled_value": "anyValue", "disabled_value": "anyValue", "enabled": false, "tags": "Tags", "segment_rules": [{"rules": [{"segments": ["Segments"]}], "value": "anyValue", "order": 5}], "segment_exists": false, "collections": [{"collection_id": "CollectionID", "name": "Name"}], "created_time": "2019-01-01T12:00:00", "updated_time": "2019-01-01T12:00:00", "evaluation_time": "2019-01-01T12:00:00", "href": "Href"}`)
}))
})
It(`Invoke CreateFeature successfully`, func() {
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1(&appconfigurationv1.AppConfigurationV1Options{
URL: testServer.URL,
Authenticator: &core.NoAuthAuthenticator{},
})
Expect(serviceErr).To(BeNil())
Expect(appConfigurationService).ToNot(BeNil())
appConfigurationService.EnableRetries(0, 0)
// Invoke operation with nil options model (negative test)
result, response, operationErr := appConfigurationService.CreateFeature(nil)
Expect(operationErr).NotTo(BeNil())
Expect(response).To(BeNil())
Expect(result).To(BeNil())
// Construct an instance of the TargetSegments model
targetSegmentsModel := new(appconfigurationv1.TargetSegments)
targetSegmentsModel.Segments = []string{"testString"}
// Construct an instance of the SegmentRule model
segmentRuleModel := new(appconfigurationv1.SegmentRule)
segmentRuleModel.Rules = []appconfigurationv1.TargetSegments{*targetSegmentsModel}
segmentRuleModel.Value = core.StringPtr("true")
segmentRuleModel.Order = core.Int64Ptr(int64(1))
// Construct an instance of the CollectionRef model
collectionRefModel := new(appconfigurationv1.CollectionRef)
collectionRefModel.CollectionID = core.StringPtr("ghzinc")
// Construct an instance of the CreateFeatureOptions model
createFeatureOptionsModel := new(appconfigurationv1.CreateFeatureOptions)
createFeatureOptionsModel.EnvironmentID = core.StringPtr("testString")
createFeatureOptionsModel.Name = core.StringPtr("Cycle Rentals")
createFeatureOptionsModel.FeatureID = core.StringPtr("cycle-rentals")
createFeatureOptionsModel.Type = core.StringPtr("BOOLEAN")
createFeatureOptionsModel.EnabledValue = core.StringPtr("true")
createFeatureOptionsModel.DisabledValue = core.StringPtr("false")
createFeatureOptionsModel.Description = core.StringPtr("Feature flag to enable Cycle Rentals")
createFeatureOptionsModel.Enabled = core.BoolPtr(true)
createFeatureOptionsModel.Tags = core.StringPtr("version: 1.1, pre-release")
createFeatureOptionsModel.SegmentRules = []appconfigurationv1.SegmentRule{*segmentRuleModel}
createFeatureOptionsModel.Collections = []appconfigurationv1.CollectionRef{*collectionRefModel}
createFeatureOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"}
// Invoke operation with valid options model (positive test)
result, response, operationErr = appConfigurationService.CreateFeature(createFeatureOptionsModel)
Expect(operationErr).To(BeNil())
Expect(response).ToNot(BeNil())
Expect(result).ToNot(BeNil())
// Invoke operation with a Context to test a timeout error
ctx, cancelFunc := context.WithTimeout(context.Background(), 80*time.Millisecond)
defer cancelFunc()
serverSleepTime = 100 * time.Millisecond
_, _, operationErr = appConfigurationService.CreateFeatureWithContext(ctx, createFeatureOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(operationErr.Error()).To(ContainSubstring("deadline exceeded"))
serverSleepTime = time.Duration(0)
// Disable retries and test again
appConfigurationService.DisableRetries()
result, response, operationErr = appConfigurationService.CreateFeature(createFeatureOptionsModel)
Expect(operationErr).To(BeNil())
Expect(response).ToNot(BeNil())
Expect(result).ToNot(BeNil())
// Re-test the timeout error with retries disabled
ctx, cancelFunc2 := context.WithTimeout(context.Background(), 80*time.Millisecond)
defer cancelFunc2()
serverSleepTime = 100 * time.Millisecond
_, _, operationErr = appConfigurationService.CreateFeatureWithContext(ctx, createFeatureOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(operationErr.Error()).To(ContainSubstring("deadline exceeded"))
serverSleepTime = time.Duration(0)
})
It(`Invoke CreateFeature with error: Operation validation and request error`, func() {
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1(&appconfigurationv1.AppConfigurationV1Options{
URL: testServer.URL,
Authenticator: &core.NoAuthAuthenticator{},
})
Expect(serviceErr).To(BeNil())
Expect(appConfigurationService).ToNot(BeNil())
// Construct an instance of the TargetSegments model
targetSegmentsModel := new(appconfigurationv1.TargetSegments)
targetSegmentsModel.Segments = []string{"testString"}
// Construct an instance of the SegmentRule model
segmentRuleModel := new(appconfigurationv1.SegmentRule)
segmentRuleModel.Rules = []appconfigurationv1.TargetSegments{*targetSegmentsModel}
segmentRuleModel.Value = core.StringPtr("true")
segmentRuleModel.Order = core.Int64Ptr(int64(1))
// Construct an instance of the CollectionRef model
collectionRefModel := new(appconfigurationv1.CollectionRef)
collectionRefModel.CollectionID = core.StringPtr("ghzinc")
// Construct an instance of the CreateFeatureOptions model
createFeatureOptionsModel := new(appconfigurationv1.CreateFeatureOptions)
createFeatureOptionsModel.EnvironmentID = core.StringPtr("testString")
createFeatureOptionsModel.Name = core.StringPtr("Cycle Rentals")
createFeatureOptionsModel.FeatureID = core.StringPtr("cycle-rentals")
createFeatureOptionsModel.Type = core.StringPtr("BOOLEAN")
createFeatureOptionsModel.EnabledValue = core.StringPtr("true")
createFeatureOptionsModel.DisabledValue = core.StringPtr("false")
createFeatureOptionsModel.Description = core.StringPtr("Feature flag to enable Cycle Rentals")
createFeatureOptionsModel.Enabled = core.BoolPtr(true)
createFeatureOptionsModel.Tags = core.StringPtr("version: 1.1, pre-release")
createFeatureOptionsModel.SegmentRules = []appconfigurationv1.SegmentRule{*segmentRuleModel}
createFeatureOptionsModel.Collections = []appconfigurationv1.CollectionRef{*collectionRefModel}
createFeatureOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"}
// Invoke operation with empty URL (negative test)
err := appConfigurationService.SetServiceURL("")
Expect(err).To(BeNil())
result, response, operationErr := appConfigurationService.CreateFeature(createFeatureOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(operationErr.Error()).To(ContainSubstring(core.ERRORMSG_SERVICE_URL_MISSING))
Expect(response).To(BeNil())
Expect(result).To(BeNil())
// Construct a second instance of the CreateFeatureOptions model with no property values
createFeatureOptionsModelNew := new(appconfigurationv1.CreateFeatureOptions)
// Invoke operation with invalid model (negative test)
result, response, operationErr = appConfigurationService.CreateFeature(createFeatureOptionsModelNew)
Expect(operationErr).ToNot(BeNil())
Expect(response).To(BeNil())
Expect(result).To(BeNil())
})
AfterEach(func() {
testServer.Close()
})
})
})
Describe(`UpdateFeature(updateFeatureOptions *UpdateFeatureOptions) - Operation response error`, func() {
updateFeaturePath := "/environments/testString/features/testString"
Context(`Using mock server endpoint`, func() {
BeforeEach(func() {
testServer = httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
defer GinkgoRecover()
// Verify the contents of the request
Expect(req.URL.EscapedPath()).To(Equal(updateFeaturePath))
Expect(req.Method).To(Equal("PUT"))
res.Header().Set("Content-type", "application/json")
res.WriteHeader(200)
fmt.Fprintf(res, `} this is not valid json {`)
}))
})
It(`Invoke UpdateFeature with error: Operation response processing error`, func() {
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1(&appconfigurationv1.AppConfigurationV1Options{
URL: testServer.URL,
Authenticator: &core.NoAuthAuthenticator{},
})
Expect(serviceErr).To(BeNil())
Expect(appConfigurationService).ToNot(BeNil())
// Construct an instance of the TargetSegments model
targetSegmentsModel := new(appconfigurationv1.TargetSegments)
targetSegmentsModel.Segments = []string{"testString"}
// Construct an instance of the SegmentRule model
segmentRuleModel := new(appconfigurationv1.SegmentRule)
segmentRuleModel.Rules = []appconfigurationv1.TargetSegments{*targetSegmentsModel}
segmentRuleModel.Value = core.StringPtr("testString")
segmentRuleModel.Order = core.Int64Ptr(int64(38))
// Construct an instance of the CollectionRef model
collectionRefModel := new(appconfigurationv1.CollectionRef)
collectionRefModel.CollectionID = core.StringPtr("testString")
// Construct an instance of the UpdateFeatureOptions model
updateFeatureOptionsModel := new(appconfigurationv1.UpdateFeatureOptions)
updateFeatureOptionsModel.EnvironmentID = core.StringPtr("testString")
updateFeatureOptionsModel.FeatureID = core.StringPtr("testString")
updateFeatureOptionsModel.Name = core.StringPtr("testString")
updateFeatureOptionsModel.Description = core.StringPtr("testString")
updateFeatureOptionsModel.EnabledValue = core.StringPtr("testString")
updateFeatureOptionsModel.DisabledValue = core.StringPtr("testString")
updateFeatureOptionsModel.Enabled = core.BoolPtr(true)
updateFeatureOptionsModel.Tags = core.StringPtr("testString")
updateFeatureOptionsModel.SegmentRules = []appconfigurationv1.SegmentRule{*segmentRuleModel}
updateFeatureOptionsModel.Collections = []appconfigurationv1.CollectionRef{*collectionRefModel}
updateFeatureOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"}
// Expect response parsing to fail since we are receiving a text/plain response
result, response, operationErr := appConfigurationService.UpdateFeature(updateFeatureOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(response).ToNot(BeNil())
Expect(result).To(BeNil())
// Enable retries and test again
appConfigurationService.EnableRetries(0, 0)
result, response, operationErr = appConfigurationService.UpdateFeature(updateFeatureOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(response).ToNot(BeNil())
Expect(result).To(BeNil())
})
AfterEach(func() {
testServer.Close()
})
})
})
Describe(`UpdateFeature(updateFeatureOptions *UpdateFeatureOptions)`, func() {
updateFeaturePath := "/environments/testString/features/testString"
var serverSleepTime time.Duration
Context(`Using mock server endpoint`, func() {
BeforeEach(func() {
serverSleepTime = 0
testServer = httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
defer GinkgoRecover()
// Verify the contents of the request
Expect(req.URL.EscapedPath()).To(Equal(updateFeaturePath))
Expect(req.Method).To(Equal("PUT"))
// For gzip-disabled operation, verify Content-Encoding is not set.
Expect(req.Header.Get("Content-Encoding")).To(BeEmpty())
// If there is a body, then make sure we can read it
bodyBuf := new(bytes.Buffer)
if req.Header.Get("Content-Encoding") == "gzip" {
body, err := core.NewGzipDecompressionReader(req.Body)
Expect(err).To(BeNil())
_, err = bodyBuf.ReadFrom(body)
Expect(err).To(BeNil())
} else {
_, err := bodyBuf.ReadFrom(req.Body)
Expect(err).To(BeNil())
}
fmt.Fprintf(GinkgoWriter, " Request body: %s", bodyBuf.String())
// Sleep a short time to support a timeout test
time.Sleep(serverSleepTime)
// Set mock response
res.Header().Set("Content-type", "application/json")
res.WriteHeader(200)
fmt.Fprintf(res, "%s", `{"name": "Name", "feature_id": "FeatureID", "description": "Description", "type": "BOOLEAN", "enabled_value": "anyValue", "disabled_value": "anyValue", "enabled": false, "tags": "Tags", "segment_rules": [{"rules": [{"segments": ["Segments"]}], "value": "anyValue", "order": 5}], "segment_exists": false, "collections": [{"collection_id": "CollectionID", "name": "Name"}], "created_time": "2019-01-01T12:00:00", "updated_time": "2019-01-01T12:00:00", "evaluation_time": "2019-01-01T12:00:00", "href": "Href"}`)
}))
})
It(`Invoke UpdateFeature successfully`, func() {
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1(&appconfigurationv1.AppConfigurationV1Options{
URL: testServer.URL,
Authenticator: &core.NoAuthAuthenticator{},
})
Expect(serviceErr).To(BeNil())
Expect(appConfigurationService).ToNot(BeNil())
appConfigurationService.EnableRetries(0, 0)
// Invoke operation with nil options model (negative test)
result, response, operationErr := appConfigurationService.UpdateFeature(nil)
Expect(operationErr).NotTo(BeNil())
Expect(response).To(BeNil())
Expect(result).To(BeNil())
// Construct an instance of the TargetSegments model
targetSegmentsModel := new(appconfigurationv1.TargetSegments)
targetSegmentsModel.Segments = []string{"testString"}
// Construct an instance of the SegmentRule model
segmentRuleModel := new(appconfigurationv1.SegmentRule)
segmentRuleModel.Rules = []appconfigurationv1.TargetSegments{*targetSegmentsModel}
segmentRuleModel.Value = core.StringPtr("testString")
segmentRuleModel.Order = core.Int64Ptr(int64(38))
// Construct an instance of the CollectionRef model
collectionRefModel := new(appconfigurationv1.CollectionRef)
collectionRefModel.CollectionID = core.StringPtr("testString")
// Construct an instance of the UpdateFeatureOptions model
updateFeatureOptionsModel := new(appconfigurationv1.UpdateFeatureOptions)
updateFeatureOptionsModel.EnvironmentID = core.StringPtr("testString")
updateFeatureOptionsModel.FeatureID = core.StringPtr("testString")
updateFeatureOptionsModel.Name = core.StringPtr("testString")
updateFeatureOptionsModel.Description = core.StringPtr("testString")
updateFeatureOptionsModel.EnabledValue = core.StringPtr("testString")
updateFeatureOptionsModel.DisabledValue = core.StringPtr("testString")
updateFeatureOptionsModel.Enabled = core.BoolPtr(true)
updateFeatureOptionsModel.Tags = core.StringPtr("testString")
updateFeatureOptionsModel.SegmentRules = []appconfigurationv1.SegmentRule{*segmentRuleModel}
updateFeatureOptionsModel.Collections = []appconfigurationv1.CollectionRef{*collectionRefModel}
updateFeatureOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"}
// Invoke operation with valid options model (positive test)
result, response, operationErr = appConfigurationService.UpdateFeature(updateFeatureOptionsModel)
Expect(operationErr).To(BeNil())
Expect(response).ToNot(BeNil())
Expect(result).ToNot(BeNil())
// Invoke operation with a Context to test a timeout error
ctx, cancelFunc := context.WithTimeout(context.Background(), 80*time.Millisecond)
defer cancelFunc()
serverSleepTime = 100 * time.Millisecond
_, _, operationErr = appConfigurationService.UpdateFeatureWithContext(ctx, updateFeatureOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(operationErr.Error()).To(ContainSubstring("deadline exceeded"))
serverSleepTime = time.Duration(0)
// Disable retries and test again
appConfigurationService.DisableRetries()
result, response, operationErr = appConfigurationService.UpdateFeature(updateFeatureOptionsModel)
Expect(operationErr).To(BeNil())
Expect(response).ToNot(BeNil())
Expect(result).ToNot(BeNil())
// Re-test the timeout error with retries disabled
ctx, cancelFunc2 := context.WithTimeout(context.Background(), 80*time.Millisecond)
defer cancelFunc2()
serverSleepTime = 100 * time.Millisecond
_, _, operationErr = appConfigurationService.UpdateFeatureWithContext(ctx, updateFeatureOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(operationErr.Error()).To(ContainSubstring("deadline exceeded"))
serverSleepTime = time.Duration(0)
})
It(`Invoke UpdateFeature with error: Operation validation and request error`, func() {
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1(&appconfigurationv1.AppConfigurationV1Options{
URL: testServer.URL,
Authenticator: &core.NoAuthAuthenticator{},
})
Expect(serviceErr).To(BeNil())
Expect(appConfigurationService).ToNot(BeNil())
// Construct an instance of the TargetSegments model
targetSegmentsModel := new(appconfigurationv1.TargetSegments)
targetSegmentsModel.Segments = []string{"testString"}
// Construct an instance of the SegmentRule model
segmentRuleModel := new(appconfigurationv1.SegmentRule)
segmentRuleModel.Rules = []appconfigurationv1.TargetSegments{*targetSegmentsModel}
segmentRuleModel.Value = core.StringPtr("testString")
segmentRuleModel.Order = core.Int64Ptr(int64(38))
// Construct an instance of the CollectionRef model
collectionRefModel := new(appconfigurationv1.CollectionRef)
collectionRefModel.CollectionID = core.StringPtr("testString")
// Construct an instance of the UpdateFeatureOptions model
updateFeatureOptionsModel := new(appconfigurationv1.UpdateFeatureOptions)
updateFeatureOptionsModel.EnvironmentID = core.StringPtr("testString")
updateFeatureOptionsModel.FeatureID = core.StringPtr("testString")
updateFeatureOptionsModel.Name = core.StringPtr("testString")
updateFeatureOptionsModel.Description = core.StringPtr("testString")
updateFeatureOptionsModel.EnabledValue = core.StringPtr("testString")
updateFeatureOptionsModel.DisabledValue = core.StringPtr("testString")
updateFeatureOptionsModel.Enabled = core.BoolPtr(true)
updateFeatureOptionsModel.Tags = core.StringPtr("testString")
updateFeatureOptionsModel.SegmentRules = []appconfigurationv1.SegmentRule{*segmentRuleModel}
updateFeatureOptionsModel.Collections = []appconfigurationv1.CollectionRef{*collectionRefModel}
updateFeatureOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"}
// Invoke operation with empty URL (negative test)
err := appConfigurationService.SetServiceURL("")
Expect(err).To(BeNil())
result, response, operationErr := appConfigurationService.UpdateFeature(updateFeatureOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(operationErr.Error()).To(ContainSubstring(core.ERRORMSG_SERVICE_URL_MISSING))
Expect(response).To(BeNil())
Expect(result).To(BeNil())
// Construct a second instance of the UpdateFeatureOptions model with no property values
updateFeatureOptionsModelNew := new(appconfigurationv1.UpdateFeatureOptions)
// Invoke operation with invalid model (negative test)
result, response, operationErr = appConfigurationService.UpdateFeature(updateFeatureOptionsModelNew)
Expect(operationErr).ToNot(BeNil())
Expect(response).To(BeNil())
Expect(result).To(BeNil())
})
AfterEach(func() {
testServer.Close()
})
})
})
Describe(`UpdateFeatureValues(updateFeatureValuesOptions *UpdateFeatureValuesOptions) - Operation response error`, func() {
updateFeatureValuesPath := "/environments/testString/features/testString"
Context(`Using mock server endpoint`, func() {
BeforeEach(func() {
testServer = httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
defer GinkgoRecover()
// Verify the contents of the request
Expect(req.URL.EscapedPath()).To(Equal(updateFeatureValuesPath))
Expect(req.Method).To(Equal("PATCH"))
res.Header().Set("Content-type", "application/json")
res.WriteHeader(200)
fmt.Fprintf(res, `} this is not valid json {`)
}))
})
It(`Invoke UpdateFeatureValues with error: Operation response processing error`, func() {
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1(&appconfigurationv1.AppConfigurationV1Options{
URL: testServer.URL,
Authenticator: &core.NoAuthAuthenticator{},
})
Expect(serviceErr).To(BeNil())
Expect(appConfigurationService).ToNot(BeNil())
// Construct an instance of the TargetSegments model
targetSegmentsModel := new(appconfigurationv1.TargetSegments)
targetSegmentsModel.Segments = []string{"testString"}
// Construct an instance of the SegmentRule model
segmentRuleModel := new(appconfigurationv1.SegmentRule)
segmentRuleModel.Rules = []appconfigurationv1.TargetSegments{*targetSegmentsModel}
segmentRuleModel.Value = core.StringPtr("testString")
segmentRuleModel.Order = core.Int64Ptr(int64(38))
// Construct an instance of the UpdateFeatureValuesOptions model
updateFeatureValuesOptionsModel := new(appconfigurationv1.UpdateFeatureValuesOptions)
updateFeatureValuesOptionsModel.EnvironmentID = core.StringPtr("testString")
updateFeatureValuesOptionsModel.FeatureID = core.StringPtr("testString")
updateFeatureValuesOptionsModel.Name = core.StringPtr("testString")
updateFeatureValuesOptionsModel.Description = core.StringPtr("testString")
updateFeatureValuesOptionsModel.Tags = core.StringPtr("testString")
updateFeatureValuesOptionsModel.EnabledValue = core.StringPtr("testString")
updateFeatureValuesOptionsModel.DisabledValue = core.StringPtr("testString")
updateFeatureValuesOptionsModel.SegmentRules = []appconfigurationv1.SegmentRule{*segmentRuleModel}
updateFeatureValuesOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"}
// Expect response parsing to fail since we are receiving a text/plain response
result, response, operationErr := appConfigurationService.UpdateFeatureValues(updateFeatureValuesOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(response).ToNot(BeNil())
Expect(result).To(BeNil())
// Enable retries and test again
appConfigurationService.EnableRetries(0, 0)
result, response, operationErr = appConfigurationService.UpdateFeatureValues(updateFeatureValuesOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(response).ToNot(BeNil())
Expect(result).To(BeNil())
})
AfterEach(func() {
testServer.Close()
})
})
})
Describe(`UpdateFeatureValues(updateFeatureValuesOptions *UpdateFeatureValuesOptions)`, func() {
updateFeatureValuesPath := "/environments/testString/features/testString"
var serverSleepTime time.Duration
Context(`Using mock server endpoint`, func() {
BeforeEach(func() {
serverSleepTime = 0
testServer = httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
defer GinkgoRecover()
// Verify the contents of the request
Expect(req.URL.EscapedPath()).To(Equal(updateFeatureValuesPath))
Expect(req.Method).To(Equal("PATCH"))
// For gzip-disabled operation, verify Content-Encoding is not set.
Expect(req.Header.Get("Content-Encoding")).To(BeEmpty())
// If there is a body, then make sure we can read it
bodyBuf := new(bytes.Buffer)
if req.Header.Get("Content-Encoding") == "gzip" {
body, err := core.NewGzipDecompressionReader(req.Body)
Expect(err).To(BeNil())
_, err = bodyBuf.ReadFrom(body)
Expect(err).To(BeNil())
} else {
_, err := bodyBuf.ReadFrom(req.Body)
Expect(err).To(BeNil())
}
fmt.Fprintf(GinkgoWriter, " Request body: %s", bodyBuf.String())
// Sleep a short time to support a timeout test
time.Sleep(serverSleepTime)
// Set mock response
res.Header().Set("Content-type", "application/json")
res.WriteHeader(200)
fmt.Fprintf(res, "%s", `{"name": "Name", "feature_id": "FeatureID", "description": "Description", "type": "BOOLEAN", "enabled_value": "anyValue", "disabled_value": "anyValue", "enabled": false, "tags": "Tags", "segment_rules": [{"rules": [{"segments": ["Segments"]}], "value": "anyValue", "order": 5}], "segment_exists": false, "collections": [{"collection_id": "CollectionID", "name": "Name"}], "created_time": "2019-01-01T12:00:00", "updated_time": "2019-01-01T12:00:00", "evaluation_time": "2019-01-01T12:00:00", "href": "Href"}`)
}))
})
It(`Invoke UpdateFeatureValues successfully`, func() {
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1(&appconfigurationv1.AppConfigurationV1Options{
URL: testServer.URL,
Authenticator: &core.NoAuthAuthenticator{},
})
Expect(serviceErr).To(BeNil())
Expect(appConfigurationService).ToNot(BeNil())
appConfigurationService.EnableRetries(0, 0)
// Invoke operation with nil options model (negative test)
result, response, operationErr := appConfigurationService.UpdateFeatureValues(nil)
Expect(operationErr).NotTo(BeNil())
Expect(response).To(BeNil())
Expect(result).To(BeNil())
// Construct an instance of the TargetSegments model
targetSegmentsModel := new(appconfigurationv1.TargetSegments)
targetSegmentsModel.Segments = []string{"testString"}
// Construct an instance of the SegmentRule model
segmentRuleModel := new(appconfigurationv1.SegmentRule)
segmentRuleModel.Rules = []appconfigurationv1.TargetSegments{*targetSegmentsModel}
segmentRuleModel.Value = core.StringPtr("testString")
segmentRuleModel.Order = core.Int64Ptr(int64(38))
// Construct an instance of the UpdateFeatureValuesOptions model
updateFeatureValuesOptionsModel := new(appconfigurationv1.UpdateFeatureValuesOptions)
updateFeatureValuesOptionsModel.EnvironmentID = core.StringPtr("testString")
updateFeatureValuesOptionsModel.FeatureID = core.StringPtr("testString")
updateFeatureValuesOptionsModel.Name = core.StringPtr("testString")
updateFeatureValuesOptionsModel.Description = core.StringPtr("testString")
updateFeatureValuesOptionsModel.Tags = core.StringPtr("testString")
updateFeatureValuesOptionsModel.EnabledValue = core.StringPtr("testString")
updateFeatureValuesOptionsModel.DisabledValue = core.StringPtr("testString")
updateFeatureValuesOptionsModel.SegmentRules = []appconfigurationv1.SegmentRule{*segmentRuleModel}
updateFeatureValuesOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"}
// Invoke operation with valid options model (positive test)
result, response, operationErr = appConfigurationService.UpdateFeatureValues(updateFeatureValuesOptionsModel)
Expect(operationErr).To(BeNil())
Expect(response).ToNot(BeNil())
Expect(result).ToNot(BeNil())
// Invoke operation with a Context to test a timeout error
ctx, cancelFunc := context.WithTimeout(context.Background(), 80*time.Millisecond)
defer cancelFunc()
serverSleepTime = 100 * time.Millisecond
_, _, operationErr = appConfigurationService.UpdateFeatureValuesWithContext(ctx, updateFeatureValuesOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(operationErr.Error()).To(ContainSubstring("deadline exceeded"))
serverSleepTime = time.Duration(0)
// Disable retries and test again
appConfigurationService.DisableRetries()
result, response, operationErr = appConfigurationService.UpdateFeatureValues(updateFeatureValuesOptionsModel)
Expect(operationErr).To(BeNil())
Expect(response).ToNot(BeNil())
Expect(result).ToNot(BeNil())
// Re-test the timeout error with retries disabled
ctx, cancelFunc2 := context.WithTimeout(context.Background(), 80*time.Millisecond)
defer cancelFunc2()
serverSleepTime = 100 * time.Millisecond
_, _, operationErr = appConfigurationService.UpdateFeatureValuesWithContext(ctx, updateFeatureValuesOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(operationErr.Error()).To(ContainSubstring("deadline exceeded"))
serverSleepTime = time.Duration(0)
})
It(`Invoke UpdateFeatureValues with error: Operation validation and request error`, func() {
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1(&appconfigurationv1.AppConfigurationV1Options{
URL: testServer.URL,
Authenticator: &core.NoAuthAuthenticator{},
})
Expect(serviceErr).To(BeNil())
Expect(appConfigurationService).ToNot(BeNil())
// Construct an instance of the TargetSegments model
targetSegmentsModel := new(appconfigurationv1.TargetSegments)
targetSegmentsModel.Segments = []string{"testString"}
// Construct an instance of the SegmentRule model
segmentRuleModel := new(appconfigurationv1.SegmentRule)
segmentRuleModel.Rules = []appconfigurationv1.TargetSegments{*targetSegmentsModel}
segmentRuleModel.Value = core.StringPtr("testString")
segmentRuleModel.Order = core.Int64Ptr(int64(38))
// Construct an instance of the UpdateFeatureValuesOptions model
updateFeatureValuesOptionsModel := new(appconfigurationv1.UpdateFeatureValuesOptions)
updateFeatureValuesOptionsModel.EnvironmentID = core.StringPtr("testString")
updateFeatureValuesOptionsModel.FeatureID = core.StringPtr("testString")
updateFeatureValuesOptionsModel.Name = core.StringPtr("testString")
updateFeatureValuesOptionsModel.Description = core.StringPtr("testString")
updateFeatureValuesOptionsModel.Tags = core.StringPtr("testString")
updateFeatureValuesOptionsModel.EnabledValue = core.StringPtr("testString")
updateFeatureValuesOptionsModel.DisabledValue = core.StringPtr("testString")
updateFeatureValuesOptionsModel.SegmentRules = []appconfigurationv1.SegmentRule{*segmentRuleModel}
updateFeatureValuesOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"}
// Invoke operation with empty URL (negative test)
err := appConfigurationService.SetServiceURL("")
Expect(err).To(BeNil())
result, response, operationErr := appConfigurationService.UpdateFeatureValues(updateFeatureValuesOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(operationErr.Error()).To(ContainSubstring(core.ERRORMSG_SERVICE_URL_MISSING))
Expect(response).To(BeNil())
Expect(result).To(BeNil())
// Construct a second instance of the UpdateFeatureValuesOptions model with no property values
updateFeatureValuesOptionsModelNew := new(appconfigurationv1.UpdateFeatureValuesOptions)
// Invoke operation with invalid model (negative test)
result, response, operationErr = appConfigurationService.UpdateFeatureValues(updateFeatureValuesOptionsModelNew)
Expect(operationErr).ToNot(BeNil())
Expect(response).To(BeNil())
Expect(result).To(BeNil())
})
AfterEach(func() {
testServer.Close()
})
})
})
Describe(`GetFeature(getFeatureOptions *GetFeatureOptions) - Operation response error`, func() {
getFeaturePath := "/environments/testString/features/testString"
Context(`Using mock server endpoint`, func() {
BeforeEach(func() {
testServer = httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
defer GinkgoRecover()
// Verify the contents of the request
Expect(req.URL.EscapedPath()).To(Equal(getFeaturePath))
Expect(req.Method).To(Equal("GET"))
Expect(req.URL.Query()["include"]).To(Equal([]string{"collections"}))
res.Header().Set("Content-type", "application/json")
res.WriteHeader(200)
fmt.Fprintf(res, `} this is not valid json {`)
}))
})
It(`Invoke GetFeature with error: Operation response processing error`, func() {
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1(&appconfigurationv1.AppConfigurationV1Options{
URL: testServer.URL,
Authenticator: &core.NoAuthAuthenticator{},
})
Expect(serviceErr).To(BeNil())
Expect(appConfigurationService).ToNot(BeNil())
// Construct an instance of the GetFeatureOptions model
getFeatureOptionsModel := new(appconfigurationv1.GetFeatureOptions)
getFeatureOptionsModel.EnvironmentID = core.StringPtr("testString")
getFeatureOptionsModel.FeatureID = core.StringPtr("testString")
getFeatureOptionsModel.Include = core.StringPtr("collections")
getFeatureOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"}
// Expect response parsing to fail since we are receiving a text/plain response
result, response, operationErr := appConfigurationService.GetFeature(getFeatureOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(response).ToNot(BeNil())
Expect(result).To(BeNil())
// Enable retries and test again
appConfigurationService.EnableRetries(0, 0)
result, response, operationErr = appConfigurationService.GetFeature(getFeatureOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(response).ToNot(BeNil())
Expect(result).To(BeNil())
})
AfterEach(func() {
testServer.Close()
})
})
})
Describe(`GetFeature(getFeatureOptions *GetFeatureOptions)`, func() {
getFeaturePath := "/environments/testString/features/testString"
var serverSleepTime time.Duration
Context(`Using mock server endpoint`, func() {
BeforeEach(func() {
serverSleepTime = 0
testServer = httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
defer GinkgoRecover()
// Verify the contents of the request
Expect(req.URL.EscapedPath()).To(Equal(getFeaturePath))
Expect(req.Method).To(Equal("GET"))
Expect(req.URL.Query()["include"]).To(Equal([]string{"collections"}))
// Sleep a short time to support a timeout test
time.Sleep(serverSleepTime)
// Set mock response
res.Header().Set("Content-type", "application/json")
res.WriteHeader(200)
fmt.Fprintf(res, "%s", `{"name": "Name", "feature_id": "FeatureID", "description": "Description", "type": "BOOLEAN", "enabled_value": "anyValue", "disabled_value": "anyValue", "enabled": false, "tags": "Tags", "segment_rules": [{"rules": [{"segments": ["Segments"]}], "value": "anyValue", "order": 5}], "segment_exists": false, "collections": [{"collection_id": "CollectionID", "name": "Name"}], "created_time": "2019-01-01T12:00:00", "updated_time": "2019-01-01T12:00:00", "evaluation_time": "2019-01-01T12:00:00", "href": "Href"}`)
}))
})
It(`Invoke GetFeature successfully`, func() {
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1(&appconfigurationv1.AppConfigurationV1Options{
URL: testServer.URL,
Authenticator: &core.NoAuthAuthenticator{},
})
Expect(serviceErr).To(BeNil())
Expect(appConfigurationService).ToNot(BeNil())
appConfigurationService.EnableRetries(0, 0)
// Invoke operation with nil options model (negative test)
result, response, operationErr := appConfigurationService.GetFeature(nil)
Expect(operationErr).NotTo(BeNil())
Expect(response).To(BeNil())
Expect(result).To(BeNil())
// Construct an instance of the GetFeatureOptions model
getFeatureOptionsModel := new(appconfigurationv1.GetFeatureOptions)
getFeatureOptionsModel.EnvironmentID = core.StringPtr("testString")
getFeatureOptionsModel.FeatureID = core.StringPtr("testString")
getFeatureOptionsModel.Include = core.StringPtr("collections")
getFeatureOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"}
// Invoke operation with valid options model (positive test)
result, response, operationErr = appConfigurationService.GetFeature(getFeatureOptionsModel)
Expect(operationErr).To(BeNil())
Expect(response).ToNot(BeNil())
Expect(result).ToNot(BeNil())
// Invoke operation with a Context to test a timeout error
ctx, cancelFunc := context.WithTimeout(context.Background(), 80*time.Millisecond)
defer cancelFunc()
serverSleepTime = 100 * time.Millisecond
_, _, operationErr = appConfigurationService.GetFeatureWithContext(ctx, getFeatureOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(operationErr.Error()).To(ContainSubstring("deadline exceeded"))
serverSleepTime = time.Duration(0)
// Disable retries and test again
appConfigurationService.DisableRetries()
result, response, operationErr = appConfigurationService.GetFeature(getFeatureOptionsModel)
Expect(operationErr).To(BeNil())
Expect(response).ToNot(BeNil())
Expect(result).ToNot(BeNil())
// Re-test the timeout error with retries disabled
ctx, cancelFunc2 := context.WithTimeout(context.Background(), 80*time.Millisecond)
defer cancelFunc2()
serverSleepTime = 100 * time.Millisecond
_, _, operationErr = appConfigurationService.GetFeatureWithContext(ctx, getFeatureOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(operationErr.Error()).To(ContainSubstring("deadline exceeded"))
serverSleepTime = time.Duration(0)
})
It(`Invoke GetFeature with error: Operation validation and request error`, func() {
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1(&appconfigurationv1.AppConfigurationV1Options{
URL: testServer.URL,
Authenticator: &core.NoAuthAuthenticator{},
})
Expect(serviceErr).To(BeNil())
Expect(appConfigurationService).ToNot(BeNil())
// Construct an instance of the GetFeatureOptions model
getFeatureOptionsModel := new(appconfigurationv1.GetFeatureOptions)
getFeatureOptionsModel.EnvironmentID = core.StringPtr("testString")
getFeatureOptionsModel.FeatureID = core.StringPtr("testString")
getFeatureOptionsModel.Include = core.StringPtr("collections")
getFeatureOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"}
// Invoke operation with empty URL (negative test)
err := appConfigurationService.SetServiceURL("")
Expect(err).To(BeNil())
result, response, operationErr := appConfigurationService.GetFeature(getFeatureOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(operationErr.Error()).To(ContainSubstring(core.ERRORMSG_SERVICE_URL_MISSING))
Expect(response).To(BeNil())
Expect(result).To(BeNil())
// Construct a second instance of the GetFeatureOptions model with no property values
getFeatureOptionsModelNew := new(appconfigurationv1.GetFeatureOptions)
// Invoke operation with invalid model (negative test)
result, response, operationErr = appConfigurationService.GetFeature(getFeatureOptionsModelNew)
Expect(operationErr).ToNot(BeNil())
Expect(response).To(BeNil())
Expect(result).To(BeNil())
})
AfterEach(func() {
testServer.Close()
})
})
})
Describe(`DeleteFeature(deleteFeatureOptions *DeleteFeatureOptions)`, func() {
deleteFeaturePath := "/environments/testString/features/testString"
Context(`Using mock server endpoint`, func() {
BeforeEach(func() {
testServer = httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
defer GinkgoRecover()
// Verify the contents of the request
Expect(req.URL.EscapedPath()).To(Equal(deleteFeaturePath))
Expect(req.Method).To(Equal("DELETE"))
res.WriteHeader(204)
}))
})
It(`Invoke DeleteFeature successfully`, func() {
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1(&appconfigurationv1.AppConfigurationV1Options{
URL: testServer.URL,
Authenticator: &core.NoAuthAuthenticator{},
})
Expect(serviceErr).To(BeNil())
Expect(appConfigurationService).ToNot(BeNil())
appConfigurationService.EnableRetries(0, 0)
// Invoke operation with nil options model (negative test)
response, operationErr := appConfigurationService.DeleteFeature(nil)
Expect(operationErr).NotTo(BeNil())
Expect(response).To(BeNil())
// Construct an instance of the DeleteFeatureOptions model
deleteFeatureOptionsModel := new(appconfigurationv1.DeleteFeatureOptions)
deleteFeatureOptionsModel.EnvironmentID = core.StringPtr("testString")
deleteFeatureOptionsModel.FeatureID = core.StringPtr("testString")
deleteFeatureOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"}
// Invoke operation with valid options model (positive test)
response, operationErr = appConfigurationService.DeleteFeature(deleteFeatureOptionsModel)
Expect(operationErr).To(BeNil())
Expect(response).ToNot(BeNil())
// Disable retries and test again
appConfigurationService.DisableRetries()
response, operationErr = appConfigurationService.DeleteFeature(deleteFeatureOptionsModel)
Expect(operationErr).To(BeNil())
Expect(response).ToNot(BeNil())
})
It(`Invoke DeleteFeature with error: Operation validation and request error`, func() {
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1(&appconfigurationv1.AppConfigurationV1Options{
URL: testServer.URL,
Authenticator: &core.NoAuthAuthenticator{},
})
Expect(serviceErr).To(BeNil())
Expect(appConfigurationService).ToNot(BeNil())
// Construct an instance of the DeleteFeatureOptions model
deleteFeatureOptionsModel := new(appconfigurationv1.DeleteFeatureOptions)
deleteFeatureOptionsModel.EnvironmentID = core.StringPtr("testString")
deleteFeatureOptionsModel.FeatureID = core.StringPtr("testString")
deleteFeatureOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"}
// Invoke operation with empty URL (negative test)
err := appConfigurationService.SetServiceURL("")
Expect(err).To(BeNil())
response, operationErr := appConfigurationService.DeleteFeature(deleteFeatureOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(operationErr.Error()).To(ContainSubstring(core.ERRORMSG_SERVICE_URL_MISSING))
Expect(response).To(BeNil())
// Construct a second instance of the DeleteFeatureOptions model with no property values
deleteFeatureOptionsModelNew := new(appconfigurationv1.DeleteFeatureOptions)
// Invoke operation with invalid model (negative test)
response, operationErr = appConfigurationService.DeleteFeature(deleteFeatureOptionsModelNew)
Expect(operationErr).ToNot(BeNil())
Expect(response).To(BeNil())
})
AfterEach(func() {
testServer.Close()
})
})
})
Describe(`ToggleFeature(toggleFeatureOptions *ToggleFeatureOptions) - Operation response error`, func() {
toggleFeaturePath := "/environments/testString/features/testString/toggle"
Context(`Using mock server endpoint`, func() {
BeforeEach(func() {
testServer = httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
defer GinkgoRecover()
// Verify the contents of the request
Expect(req.URL.EscapedPath()).To(Equal(toggleFeaturePath))
Expect(req.Method).To(Equal("PUT"))
res.Header().Set("Content-type", "application/json")
res.WriteHeader(200)
fmt.Fprintf(res, `} this is not valid json {`)
}))
})
It(`Invoke ToggleFeature with error: Operation response processing error`, func() {
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1(&appconfigurationv1.AppConfigurationV1Options{
URL: testServer.URL,
Authenticator: &core.NoAuthAuthenticator{},
})
Expect(serviceErr).To(BeNil())
Expect(appConfigurationService).ToNot(BeNil())
// Construct an instance of the ToggleFeatureOptions model
toggleFeatureOptionsModel := new(appconfigurationv1.ToggleFeatureOptions)
toggleFeatureOptionsModel.EnvironmentID = core.StringPtr("testString")
toggleFeatureOptionsModel.FeatureID = core.StringPtr("testString")
toggleFeatureOptionsModel.Enabled = core.BoolPtr(true)
toggleFeatureOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"}
// Expect response parsing to fail since we are receiving a text/plain response
result, response, operationErr := appConfigurationService.ToggleFeature(toggleFeatureOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(response).ToNot(BeNil())
Expect(result).To(BeNil())
// Enable retries and test again
appConfigurationService.EnableRetries(0, 0)
result, response, operationErr = appConfigurationService.ToggleFeature(toggleFeatureOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(response).ToNot(BeNil())
Expect(result).To(BeNil())
})
AfterEach(func() {
testServer.Close()
})
})
})
Describe(`ToggleFeature(toggleFeatureOptions *ToggleFeatureOptions)`, func() {
toggleFeaturePath := "/environments/testString/features/testString/toggle"
var serverSleepTime time.Duration
Context(`Using mock server endpoint`, func() {
BeforeEach(func() {
serverSleepTime = 0
testServer = httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
defer GinkgoRecover()
// Verify the contents of the request
Expect(req.URL.EscapedPath()).To(Equal(toggleFeaturePath))
Expect(req.Method).To(Equal("PUT"))
// For gzip-disabled operation, verify Content-Encoding is not set.
Expect(req.Header.Get("Content-Encoding")).To(BeEmpty())
// If there is a body, then make sure we can read it
bodyBuf := new(bytes.Buffer)
if req.Header.Get("Content-Encoding") == "gzip" {
body, err := core.NewGzipDecompressionReader(req.Body)
Expect(err).To(BeNil())
_, err = bodyBuf.ReadFrom(body)
Expect(err).To(BeNil())
} else {
_, err := bodyBuf.ReadFrom(req.Body)
Expect(err).To(BeNil())
}
fmt.Fprintf(GinkgoWriter, " Request body: %s", bodyBuf.String())
// Sleep a short time to support a timeout test
time.Sleep(serverSleepTime)
// Set mock response
res.Header().Set("Content-type", "application/json")
res.WriteHeader(200)
fmt.Fprintf(res, "%s", `{"name": "Name", "feature_id": "FeatureID", "description": "Description", "type": "BOOLEAN", "enabled_value": "anyValue", "disabled_value": "anyValue", "enabled": false, "tags": "Tags", "segment_rules": [{"rules": [{"segments": ["Segments"]}], "value": "anyValue", "order": 5}], "segment_exists": false, "collections": [{"collection_id": "CollectionID", "name": "Name"}], "created_time": "2019-01-01T12:00:00", "updated_time": "2019-01-01T12:00:00", "evaluation_time": "2019-01-01T12:00:00", "href": "Href"}`)
}))
})
It(`Invoke ToggleFeature successfully`, func() {
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1(&appconfigurationv1.AppConfigurationV1Options{
URL: testServer.URL,
Authenticator: &core.NoAuthAuthenticator{},
})
Expect(serviceErr).To(BeNil())
Expect(appConfigurationService).ToNot(BeNil())
appConfigurationService.EnableRetries(0, 0)
// Invoke operation with nil options model (negative test)
result, response, operationErr := appConfigurationService.ToggleFeature(nil)
Expect(operationErr).NotTo(BeNil())
Expect(response).To(BeNil())
Expect(result).To(BeNil())
// Construct an instance of the ToggleFeatureOptions model
toggleFeatureOptionsModel := new(appconfigurationv1.ToggleFeatureOptions)
toggleFeatureOptionsModel.EnvironmentID = core.StringPtr("testString")
toggleFeatureOptionsModel.FeatureID = core.StringPtr("testString")
toggleFeatureOptionsModel.Enabled = core.BoolPtr(true)
toggleFeatureOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"}
// Invoke operation with valid options model (positive test)
result, response, operationErr = appConfigurationService.ToggleFeature(toggleFeatureOptionsModel)
Expect(operationErr).To(BeNil())
Expect(response).ToNot(BeNil())
Expect(result).ToNot(BeNil())
// Invoke operation with a Context to test a timeout error
ctx, cancelFunc := context.WithTimeout(context.Background(), 80*time.Millisecond)
defer cancelFunc()
serverSleepTime = 100 * time.Millisecond
_, _, operationErr = appConfigurationService.ToggleFeatureWithContext(ctx, toggleFeatureOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(operationErr.Error()).To(ContainSubstring("deadline exceeded"))
serverSleepTime = time.Duration(0)
// Disable retries and test again
appConfigurationService.DisableRetries()
result, response, operationErr = appConfigurationService.ToggleFeature(toggleFeatureOptionsModel)
Expect(operationErr).To(BeNil())
Expect(response).ToNot(BeNil())
Expect(result).ToNot(BeNil())
// Re-test the timeout error with retries disabled
ctx, cancelFunc2 := context.WithTimeout(context.Background(), 80*time.Millisecond)
defer cancelFunc2()
serverSleepTime = 100 * time.Millisecond
_, _, operationErr = appConfigurationService.ToggleFeatureWithContext(ctx, toggleFeatureOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(operationErr.Error()).To(ContainSubstring("deadline exceeded"))
serverSleepTime = time.Duration(0)
})
It(`Invoke ToggleFeature with error: Operation validation and request error`, func() {
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1(&appconfigurationv1.AppConfigurationV1Options{
URL: testServer.URL,
Authenticator: &core.NoAuthAuthenticator{},
})
Expect(serviceErr).To(BeNil())
Expect(appConfigurationService).ToNot(BeNil())
// Construct an instance of the ToggleFeatureOptions model
toggleFeatureOptionsModel := new(appconfigurationv1.ToggleFeatureOptions)
toggleFeatureOptionsModel.EnvironmentID = core.StringPtr("testString")
toggleFeatureOptionsModel.FeatureID = core.StringPtr("testString")
toggleFeatureOptionsModel.Enabled = core.BoolPtr(true)
toggleFeatureOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"}
// Invoke operation with empty URL (negative test)
err := appConfigurationService.SetServiceURL("")
Expect(err).To(BeNil())
result, response, operationErr := appConfigurationService.ToggleFeature(toggleFeatureOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(operationErr.Error()).To(ContainSubstring(core.ERRORMSG_SERVICE_URL_MISSING))
Expect(response).To(BeNil())
Expect(result).To(BeNil())
// Construct a second instance of the ToggleFeatureOptions model with no property values
toggleFeatureOptionsModelNew := new(appconfigurationv1.ToggleFeatureOptions)
// Invoke operation with invalid model (negative test)
result, response, operationErr = appConfigurationService.ToggleFeature(toggleFeatureOptionsModelNew)
Expect(operationErr).ToNot(BeNil())
Expect(response).To(BeNil())
Expect(result).To(BeNil())
})
AfterEach(func() {
testServer.Close()
})
})
})
Describe(`Service constructor tests`, func() {
It(`Instantiate service client`, func() {
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1(&appconfigurationv1.AppConfigurationV1Options{
Authenticator: &core.NoAuthAuthenticator{},
})
Expect(appConfigurationService).ToNot(BeNil())
Expect(serviceErr).To(BeNil())
})
It(`Instantiate service client with error: Invalid URL`, func() {
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1(&appconfigurationv1.AppConfigurationV1Options{
URL: "{BAD_URL_STRING",
})
Expect(appConfigurationService).To(BeNil())
Expect(serviceErr).ToNot(BeNil())
})
It(`Instantiate service client with error: Invalid Auth`, func() {
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1(&appconfigurationv1.AppConfigurationV1Options{
URL: "https://appconfigurationv1/api",
Authenticator: &core.BasicAuthenticator{
Username: "",
Password: "",
},
})
Expect(appConfigurationService).To(BeNil())
Expect(serviceErr).ToNot(BeNil())
})
})
Describe(`Service constructor tests using external config`, func() {
Context(`Using external config, construct service client instances`, func() {
// Map containing environment variables used in testing.
var testEnvironment = map[string]string{
"APP_CONFIGURATION_URL": "https://appconfigurationv1/api",
"APP_CONFIGURATION_AUTH_TYPE": "noauth",
}
It(`Create service client using external config successfully`, func() {
SetTestEnvironment(testEnvironment)
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1UsingExternalConfig(&appconfigurationv1.AppConfigurationV1Options{})
Expect(appConfigurationService).ToNot(BeNil())
Expect(serviceErr).To(BeNil())
ClearTestEnvironment(testEnvironment)
clone := appConfigurationService.Clone()
Expect(clone).ToNot(BeNil())
Expect(clone.Service != appConfigurationService.Service).To(BeTrue())
Expect(clone.GetServiceURL()).To(Equal(appConfigurationService.GetServiceURL()))
Expect(clone.Service.Options.Authenticator).To(Equal(appConfigurationService.Service.Options.Authenticator))
})
It(`Create service client using external config and set url from constructor successfully`, func() {
SetTestEnvironment(testEnvironment)
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1UsingExternalConfig(&appconfigurationv1.AppConfigurationV1Options{
URL: "https://testService/api",
})
Expect(appConfigurationService).ToNot(BeNil())
Expect(serviceErr).To(BeNil())
Expect(appConfigurationService.Service.GetServiceURL()).To(Equal("https://testService/api"))
ClearTestEnvironment(testEnvironment)
clone := appConfigurationService.Clone()
Expect(clone).ToNot(BeNil())
Expect(clone.Service != appConfigurationService.Service).To(BeTrue())
Expect(clone.GetServiceURL()).To(Equal(appConfigurationService.GetServiceURL()))
Expect(clone.Service.Options.Authenticator).To(Equal(appConfigurationService.Service.Options.Authenticator))
})
It(`Create service client using external config and set url programatically successfully`, func() {
SetTestEnvironment(testEnvironment)
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1UsingExternalConfig(&appconfigurationv1.AppConfigurationV1Options{})
err := appConfigurationService.SetServiceURL("https://testService/api")
Expect(err).To(BeNil())
Expect(appConfigurationService).ToNot(BeNil())
Expect(serviceErr).To(BeNil())
Expect(appConfigurationService.Service.GetServiceURL()).To(Equal("https://testService/api"))
ClearTestEnvironment(testEnvironment)
clone := appConfigurationService.Clone()
Expect(clone).ToNot(BeNil())
Expect(clone.Service != appConfigurationService.Service).To(BeTrue())
Expect(clone.GetServiceURL()).To(Equal(appConfigurationService.GetServiceURL()))
Expect(clone.Service.Options.Authenticator).To(Equal(appConfigurationService.Service.Options.Authenticator))
})
})
Context(`Using external config, construct service client instances with error: Invalid Auth`, func() {
// Map containing environment variables used in testing.
var testEnvironment = map[string]string{
"APP_CONFIGURATION_URL": "https://appconfigurationv1/api",
"APP_CONFIGURATION_AUTH_TYPE": "someOtherAuth",
}
SetTestEnvironment(testEnvironment)
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1UsingExternalConfig(&appconfigurationv1.AppConfigurationV1Options{})
It(`Instantiate service client with error`, func() {
Expect(appConfigurationService).To(BeNil())
Expect(serviceErr).ToNot(BeNil())
ClearTestEnvironment(testEnvironment)
})
})
Context(`Using external config, construct service client instances with error: Invalid URL`, func() {
// Map containing environment variables used in testing.
var testEnvironment = map[string]string{
"APP_CONFIGURATION_AUTH_TYPE": "NOAuth",
}
SetTestEnvironment(testEnvironment)
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1UsingExternalConfig(&appconfigurationv1.AppConfigurationV1Options{
URL: "{BAD_URL_STRING",
})
It(`Instantiate service client with error`, func() {
Expect(appConfigurationService).To(BeNil())
Expect(serviceErr).ToNot(BeNil())
ClearTestEnvironment(testEnvironment)
})
})
})
Describe(`Regional endpoint tests`, func() {
It(`GetServiceURLForRegion(region string)`, func() {
var url string
var err error
url, err = appconfigurationv1.GetServiceURLForRegion("INVALID_REGION")
Expect(url).To(BeEmpty())
Expect(err).ToNot(BeNil())
fmt.Fprintf(GinkgoWriter, "Expected error: %s\n", err.Error())
})
})
Describe(`ListProperties(listPropertiesOptions *ListPropertiesOptions) - Operation response error`, func() {
listPropertiesPath := "/environments/testString/properties"
Context(`Using mock server endpoint`, func() {
BeforeEach(func() {
testServer = httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
defer GinkgoRecover()
// Verify the contents of the request
Expect(req.URL.EscapedPath()).To(Equal(listPropertiesPath))
Expect(req.Method).To(Equal("GET"))
// TODO: Add check for expand query parameter
Expect(req.URL.Query()["sort"]).To(Equal([]string{"created_time"}))
Expect(req.URL.Query()["tags"]).To(Equal([]string{"version 1.1, pre-release"}))
Expect(req.URL.Query()["limit"]).To(Equal([]string{fmt.Sprint(int64(1))}))
Expect(req.URL.Query()["offset"]).To(Equal([]string{fmt.Sprint(int64(0))}))
res.Header().Set("Content-type", "application/json")
res.WriteHeader(200)
fmt.Fprintf(res, `} this is not valid json {`)
}))
})
It(`Invoke ListProperties with error: Operation response processing error`, func() {
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1(&appconfigurationv1.AppConfigurationV1Options{
URL: testServer.URL,
Authenticator: &core.NoAuthAuthenticator{},
})
Expect(serviceErr).To(BeNil())
Expect(appConfigurationService).ToNot(BeNil())
// Construct an instance of the ListPropertiesOptions model
listPropertiesOptionsModel := new(appconfigurationv1.ListPropertiesOptions)
listPropertiesOptionsModel.EnvironmentID = core.StringPtr("testString")
listPropertiesOptionsModel.Expand = core.BoolPtr(true)
listPropertiesOptionsModel.Sort = core.StringPtr("created_time")
listPropertiesOptionsModel.Tags = core.StringPtr("version 1.1, pre-release")
listPropertiesOptionsModel.Collections = []string{"testString"}
listPropertiesOptionsModel.Segments = []string{"testString"}
listPropertiesOptionsModel.Include = []string{"collections"}
listPropertiesOptionsModel.Limit = core.Int64Ptr(int64(1))
listPropertiesOptionsModel.Offset = core.Int64Ptr(int64(0))
listPropertiesOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"}
// Expect response parsing to fail since we are receiving a text/plain response
result, response, operationErr := appConfigurationService.ListProperties(listPropertiesOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(response).ToNot(BeNil())
Expect(result).To(BeNil())
// Enable retries and test again
appConfigurationService.EnableRetries(0, 0)
result, response, operationErr = appConfigurationService.ListProperties(listPropertiesOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(response).ToNot(BeNil())
Expect(result).To(BeNil())
})
AfterEach(func() {
testServer.Close()
})
})
})
Describe(`ListProperties(listPropertiesOptions *ListPropertiesOptions)`, func() {
listPropertiesPath := "/environments/testString/properties"
var serverSleepTime time.Duration
Context(`Using mock server endpoint`, func() {
BeforeEach(func() {
serverSleepTime = 0
testServer = httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
defer GinkgoRecover()
// Verify the contents of the request
Expect(req.URL.EscapedPath()).To(Equal(listPropertiesPath))
Expect(req.Method).To(Equal("GET"))
// TODO: Add check for expand query parameter
Expect(req.URL.Query()["sort"]).To(Equal([]string{"created_time"}))
Expect(req.URL.Query()["tags"]).To(Equal([]string{"version 1.1, pre-release"}))
Expect(req.URL.Query()["limit"]).To(Equal([]string{fmt.Sprint(int64(1))}))
Expect(req.URL.Query()["offset"]).To(Equal([]string{fmt.Sprint(int64(0))}))
// Sleep a short time to support a timeout test
time.Sleep(serverSleepTime)
// Set mock response
res.Header().Set("Content-type", "application/json")
res.WriteHeader(200)
fmt.Fprintf(res, "%s", `{"properties": [{"name": "Name", "property_id": "PropertyID", "description": "Description", "type": "BOOLEAN", "value": "anyValue", "tags": "Tags", "segment_rules": [{"rules": [{"segments": ["Segments"]}], "value": "anyValue", "order": 5}], "segment_exists": false, "collections": [{"collection_id": "CollectionID", "name": "Name"}], "created_time": "2019-01-01T12:00:00", "updated_time": "2019-01-01T12:00:00", "evaluation_time": "2019-01-01T12:00:00", "href": "Href"}], "limit": 5, "offset": 6, "total_count": 10, "first": {"href": "Href"}, "previous": {"href": "Href"}, "next": {"href": "Href"}, "last": {"href": "Href"}}`)
}))
})
It(`Invoke ListProperties successfully`, func() {
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1(&appconfigurationv1.AppConfigurationV1Options{
URL: testServer.URL,
Authenticator: &core.NoAuthAuthenticator{},
})
Expect(serviceErr).To(BeNil())
Expect(appConfigurationService).ToNot(BeNil())
appConfigurationService.EnableRetries(0, 0)
// Invoke operation with nil options model (negative test)
result, response, operationErr := appConfigurationService.ListProperties(nil)
Expect(operationErr).NotTo(BeNil())
Expect(response).To(BeNil())
Expect(result).To(BeNil())
// Construct an instance of the ListPropertiesOptions model
listPropertiesOptionsModel := new(appconfigurationv1.ListPropertiesOptions)
listPropertiesOptionsModel.EnvironmentID = core.StringPtr("testString")
listPropertiesOptionsModel.Expand = core.BoolPtr(true)
listPropertiesOptionsModel.Sort = core.StringPtr("created_time")
listPropertiesOptionsModel.Tags = core.StringPtr("version 1.1, pre-release")
listPropertiesOptionsModel.Collections = []string{"testString"}
listPropertiesOptionsModel.Segments = []string{"testString"}
listPropertiesOptionsModel.Include = []string{"collections"}
listPropertiesOptionsModel.Limit = core.Int64Ptr(int64(1))
listPropertiesOptionsModel.Offset = core.Int64Ptr(int64(0))
listPropertiesOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"}
// Invoke operation with valid options model (positive test)
result, response, operationErr = appConfigurationService.ListProperties(listPropertiesOptionsModel)
Expect(operationErr).To(BeNil())
Expect(response).ToNot(BeNil())
Expect(result).ToNot(BeNil())
// Invoke operation with a Context to test a timeout error
ctx, cancelFunc := context.WithTimeout(context.Background(), 80*time.Millisecond)
defer cancelFunc()
serverSleepTime = 100 * time.Millisecond
_, _, operationErr = appConfigurationService.ListPropertiesWithContext(ctx, listPropertiesOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(operationErr.Error()).To(ContainSubstring("deadline exceeded"))
serverSleepTime = time.Duration(0)
// Disable retries and test again
appConfigurationService.DisableRetries()
result, response, operationErr = appConfigurationService.ListProperties(listPropertiesOptionsModel)
Expect(operationErr).To(BeNil())
Expect(response).ToNot(BeNil())
Expect(result).ToNot(BeNil())
// Re-test the timeout error with retries disabled
ctx, cancelFunc2 := context.WithTimeout(context.Background(), 80*time.Millisecond)
defer cancelFunc2()
serverSleepTime = 100 * time.Millisecond
_, _, operationErr = appConfigurationService.ListPropertiesWithContext(ctx, listPropertiesOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(operationErr.Error()).To(ContainSubstring("deadline exceeded"))
serverSleepTime = time.Duration(0)
})
It(`Invoke ListProperties with error: Operation validation and request error`, func() {
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1(&appconfigurationv1.AppConfigurationV1Options{
URL: testServer.URL,
Authenticator: &core.NoAuthAuthenticator{},
})
Expect(serviceErr).To(BeNil())
Expect(appConfigurationService).ToNot(BeNil())
// Construct an instance of the ListPropertiesOptions model
listPropertiesOptionsModel := new(appconfigurationv1.ListPropertiesOptions)
listPropertiesOptionsModel.EnvironmentID = core.StringPtr("testString")
listPropertiesOptionsModel.Expand = core.BoolPtr(true)
listPropertiesOptionsModel.Sort = core.StringPtr("created_time")
listPropertiesOptionsModel.Tags = core.StringPtr("version 1.1, pre-release")
listPropertiesOptionsModel.Collections = []string{"testString"}
listPropertiesOptionsModel.Segments = []string{"testString"}
listPropertiesOptionsModel.Include = []string{"collections"}
listPropertiesOptionsModel.Limit = core.Int64Ptr(int64(1))
listPropertiesOptionsModel.Offset = core.Int64Ptr(int64(0))
listPropertiesOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"}
// Invoke operation with empty URL (negative test)
err := appConfigurationService.SetServiceURL("")
Expect(err).To(BeNil())
result, response, operationErr := appConfigurationService.ListProperties(listPropertiesOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(operationErr.Error()).To(ContainSubstring(core.ERRORMSG_SERVICE_URL_MISSING))
Expect(response).To(BeNil())
Expect(result).To(BeNil())
// Construct a second instance of the ListPropertiesOptions model with no property values
listPropertiesOptionsModelNew := new(appconfigurationv1.ListPropertiesOptions)
// Invoke operation with invalid model (negative test)
result, response, operationErr = appConfigurationService.ListProperties(listPropertiesOptionsModelNew)
Expect(operationErr).ToNot(BeNil())
Expect(response).To(BeNil())
Expect(result).To(BeNil())
})
AfterEach(func() {
testServer.Close()
})
})
})
Describe(`CreateProperty(createPropertyOptions *CreatePropertyOptions) - Operation response error`, func() {
createPropertyPath := "/environments/testString/properties"
Context(`Using mock server endpoint`, func() {
BeforeEach(func() {
testServer = httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
defer GinkgoRecover()
// Verify the contents of the request
Expect(req.URL.EscapedPath()).To(Equal(createPropertyPath))
Expect(req.Method).To(Equal("POST"))
res.Header().Set("Content-type", "application/json")
res.WriteHeader(201)
fmt.Fprintf(res, `} this is not valid json {`)
}))
})
It(`Invoke CreateProperty with error: Operation response processing error`, func() {
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1(&appconfigurationv1.AppConfigurationV1Options{
URL: testServer.URL,
Authenticator: &core.NoAuthAuthenticator{},
})
Expect(serviceErr).To(BeNil())
Expect(appConfigurationService).ToNot(BeNil())
// Construct an instance of the TargetSegments model
targetSegmentsModel := new(appconfigurationv1.TargetSegments)
targetSegmentsModel.Segments = []string{"testString"}
// Construct an instance of the SegmentRule model
segmentRuleModel := new(appconfigurationv1.SegmentRule)
segmentRuleModel.Rules = []appconfigurationv1.TargetSegments{*targetSegmentsModel}
segmentRuleModel.Value = core.StringPtr("true")
segmentRuleModel.Order = core.Int64Ptr(int64(1))
// Construct an instance of the CollectionRef model
collectionRefModel := new(appconfigurationv1.CollectionRef)
collectionRefModel.CollectionID = core.StringPtr("ghzinc")
// Construct an instance of the CreatePropertyOptions model
createPropertyOptionsModel := new(appconfigurationv1.CreatePropertyOptions)
createPropertyOptionsModel.EnvironmentID = core.StringPtr("testString")
createPropertyOptionsModel.Name = core.StringPtr("Email property")
createPropertyOptionsModel.PropertyID = core.StringPtr("email-property")
createPropertyOptionsModel.Type = core.StringPtr("BOOLEAN")
createPropertyOptionsModel.Value = core.StringPtr("true")
createPropertyOptionsModel.Description = core.StringPtr("Property for email")
createPropertyOptionsModel.Tags = core.StringPtr("version: 1.1, pre-release")
createPropertyOptionsModel.SegmentRules = []appconfigurationv1.SegmentRule{*segmentRuleModel}
createPropertyOptionsModel.Collections = []appconfigurationv1.CollectionRef{*collectionRefModel}
createPropertyOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"}
// Expect response parsing to fail since we are receiving a text/plain response
result, response, operationErr := appConfigurationService.CreateProperty(createPropertyOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(response).ToNot(BeNil())
Expect(result).To(BeNil())
// Enable retries and test again
appConfigurationService.EnableRetries(0, 0)
result, response, operationErr = appConfigurationService.CreateProperty(createPropertyOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(response).ToNot(BeNil())
Expect(result).To(BeNil())
})
AfterEach(func() {
testServer.Close()
})
})
})
Describe(`CreateProperty(createPropertyOptions *CreatePropertyOptions)`, func() {
createPropertyPath := "/environments/testString/properties"
var serverSleepTime time.Duration
Context(`Using mock server endpoint`, func() {
BeforeEach(func() {
serverSleepTime = 0
testServer = httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
defer GinkgoRecover()
// Verify the contents of the request
Expect(req.URL.EscapedPath()).To(Equal(createPropertyPath))
Expect(req.Method).To(Equal("POST"))
// For gzip-disabled operation, verify Content-Encoding is not set.
Expect(req.Header.Get("Content-Encoding")).To(BeEmpty())
// If there is a body, then make sure we can read it
bodyBuf := new(bytes.Buffer)
if req.Header.Get("Content-Encoding") == "gzip" {
body, err := core.NewGzipDecompressionReader(req.Body)
Expect(err).To(BeNil())
_, err = bodyBuf.ReadFrom(body)
Expect(err).To(BeNil())
} else {
_, err := bodyBuf.ReadFrom(req.Body)
Expect(err).To(BeNil())
}
fmt.Fprintf(GinkgoWriter, " Request body: %s", bodyBuf.String())
// Sleep a short time to support a timeout test
time.Sleep(serverSleepTime)
// Set mock response
res.Header().Set("Content-type", "application/json")
res.WriteHeader(201)
fmt.Fprintf(res, "%s", `{"name": "Name", "property_id": "PropertyID", "description": "Description", "type": "BOOLEAN", "value": "anyValue", "tags": "Tags", "segment_rules": [{"rules": [{"segments": ["Segments"]}], "value": "anyValue", "order": 5}], "segment_exists": false, "collections": [{"collection_id": "CollectionID", "name": "Name"}], "created_time": "2019-01-01T12:00:00", "updated_time": "2019-01-01T12:00:00", "evaluation_time": "2019-01-01T12:00:00", "href": "Href"}`)
}))
})
It(`Invoke CreateProperty successfully`, func() {
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1(&appconfigurationv1.AppConfigurationV1Options{
URL: testServer.URL,
Authenticator: &core.NoAuthAuthenticator{},
})
Expect(serviceErr).To(BeNil())
Expect(appConfigurationService).ToNot(BeNil())
appConfigurationService.EnableRetries(0, 0)
// Invoke operation with nil options model (negative test)
result, response, operationErr := appConfigurationService.CreateProperty(nil)
Expect(operationErr).NotTo(BeNil())
Expect(response).To(BeNil())
Expect(result).To(BeNil())
// Construct an instance of the TargetSegments model
targetSegmentsModel := new(appconfigurationv1.TargetSegments)
targetSegmentsModel.Segments = []string{"testString"}
// Construct an instance of the SegmentRule model
segmentRuleModel := new(appconfigurationv1.SegmentRule)
segmentRuleModel.Rules = []appconfigurationv1.TargetSegments{*targetSegmentsModel}
segmentRuleModel.Value = core.StringPtr("true")
segmentRuleModel.Order = core.Int64Ptr(int64(1))
// Construct an instance of the CollectionRef model
collectionRefModel := new(appconfigurationv1.CollectionRef)
collectionRefModel.CollectionID = core.StringPtr("ghzinc")
// Construct an instance of the CreatePropertyOptions model
createPropertyOptionsModel := new(appconfigurationv1.CreatePropertyOptions)
createPropertyOptionsModel.EnvironmentID = core.StringPtr("testString")
createPropertyOptionsModel.Name = core.StringPtr("Email property")
createPropertyOptionsModel.PropertyID = core.StringPtr("email-property")
createPropertyOptionsModel.Type = core.StringPtr("BOOLEAN")
createPropertyOptionsModel.Value = core.StringPtr("true")
createPropertyOptionsModel.Description = core.StringPtr("Property for email")
createPropertyOptionsModel.Tags = core.StringPtr("version: 1.1, pre-release")
createPropertyOptionsModel.SegmentRules = []appconfigurationv1.SegmentRule{*segmentRuleModel}
createPropertyOptionsModel.Collections = []appconfigurationv1.CollectionRef{*collectionRefModel}
createPropertyOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"}
// Invoke operation with valid options model (positive test)
result, response, operationErr = appConfigurationService.CreateProperty(createPropertyOptionsModel)
Expect(operationErr).To(BeNil())
Expect(response).ToNot(BeNil())
Expect(result).ToNot(BeNil())
// Invoke operation with a Context to test a timeout error
ctx, cancelFunc := context.WithTimeout(context.Background(), 80*time.Millisecond)
defer cancelFunc()
serverSleepTime = 100 * time.Millisecond
_, _, operationErr = appConfigurationService.CreatePropertyWithContext(ctx, createPropertyOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(operationErr.Error()).To(ContainSubstring("deadline exceeded"))
serverSleepTime = time.Duration(0)
// Disable retries and test again
appConfigurationService.DisableRetries()
result, response, operationErr = appConfigurationService.CreateProperty(createPropertyOptionsModel)
Expect(operationErr).To(BeNil())
Expect(response).ToNot(BeNil())
Expect(result).ToNot(BeNil())
// Re-test the timeout error with retries disabled
ctx, cancelFunc2 := context.WithTimeout(context.Background(), 80*time.Millisecond)
defer cancelFunc2()
serverSleepTime = 100 * time.Millisecond
_, _, operationErr = appConfigurationService.CreatePropertyWithContext(ctx, createPropertyOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(operationErr.Error()).To(ContainSubstring("deadline exceeded"))
serverSleepTime = time.Duration(0)
})
It(`Invoke CreateProperty with error: Operation validation and request error`, func() {
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1(&appconfigurationv1.AppConfigurationV1Options{
URL: testServer.URL,
Authenticator: &core.NoAuthAuthenticator{},
})
Expect(serviceErr).To(BeNil())
Expect(appConfigurationService).ToNot(BeNil())
// Construct an instance of the TargetSegments model
targetSegmentsModel := new(appconfigurationv1.TargetSegments)
targetSegmentsModel.Segments = []string{"testString"}
// Construct an instance of the SegmentRule model
segmentRuleModel := new(appconfigurationv1.SegmentRule)
segmentRuleModel.Rules = []appconfigurationv1.TargetSegments{*targetSegmentsModel}
segmentRuleModel.Value = core.StringPtr("true")
segmentRuleModel.Order = core.Int64Ptr(int64(1))
// Construct an instance of the CollectionRef model
collectionRefModel := new(appconfigurationv1.CollectionRef)
collectionRefModel.CollectionID = core.StringPtr("ghzinc")
// Construct an instance of the CreatePropertyOptions model
createPropertyOptionsModel := new(appconfigurationv1.CreatePropertyOptions)
createPropertyOptionsModel.EnvironmentID = core.StringPtr("testString")
createPropertyOptionsModel.Name = core.StringPtr("Email property")
createPropertyOptionsModel.PropertyID = core.StringPtr("email-property")
createPropertyOptionsModel.Type = core.StringPtr("BOOLEAN")
createPropertyOptionsModel.Value = core.StringPtr("true")
createPropertyOptionsModel.Description = core.StringPtr("Property for email")
createPropertyOptionsModel.Tags = core.StringPtr("version: 1.1, pre-release")
createPropertyOptionsModel.SegmentRules = []appconfigurationv1.SegmentRule{*segmentRuleModel}
createPropertyOptionsModel.Collections = []appconfigurationv1.CollectionRef{*collectionRefModel}
createPropertyOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"}
// Invoke operation with empty URL (negative test)
err := appConfigurationService.SetServiceURL("")
Expect(err).To(BeNil())
result, response, operationErr := appConfigurationService.CreateProperty(createPropertyOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(operationErr.Error()).To(ContainSubstring(core.ERRORMSG_SERVICE_URL_MISSING))
Expect(response).To(BeNil())
Expect(result).To(BeNil())
// Construct a second instance of the CreatePropertyOptions model with no property values
createPropertyOptionsModelNew := new(appconfigurationv1.CreatePropertyOptions)
// Invoke operation with invalid model (negative test)
result, response, operationErr = appConfigurationService.CreateProperty(createPropertyOptionsModelNew)
Expect(operationErr).ToNot(BeNil())
Expect(response).To(BeNil())
Expect(result).To(BeNil())
})
AfterEach(func() {
testServer.Close()
})
})
})
Describe(`UpdateProperty(updatePropertyOptions *UpdatePropertyOptions) - Operation response error`, func() {
updatePropertyPath := "/environments/testString/properties/testString"
Context(`Using mock server endpoint`, func() {
BeforeEach(func() {
testServer = httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
defer GinkgoRecover()
// Verify the contents of the request
Expect(req.URL.EscapedPath()).To(Equal(updatePropertyPath))
Expect(req.Method).To(Equal("PUT"))
res.Header().Set("Content-type", "application/json")
res.WriteHeader(200)
fmt.Fprintf(res, `} this is not valid json {`)
}))
})
It(`Invoke UpdateProperty with error: Operation response processing error`, func() {
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1(&appconfigurationv1.AppConfigurationV1Options{
URL: testServer.URL,
Authenticator: &core.NoAuthAuthenticator{},
})
Expect(serviceErr).To(BeNil())
Expect(appConfigurationService).ToNot(BeNil())
// Construct an instance of the TargetSegments model
targetSegmentsModel := new(appconfigurationv1.TargetSegments)
targetSegmentsModel.Segments = []string{"testString"}
// Construct an instance of the SegmentRule model
segmentRuleModel := new(appconfigurationv1.SegmentRule)
segmentRuleModel.Rules = []appconfigurationv1.TargetSegments{*targetSegmentsModel}
segmentRuleModel.Value = core.StringPtr("testString")
segmentRuleModel.Order = core.Int64Ptr(int64(38))
// Construct an instance of the CollectionRef model
collectionRefModel := new(appconfigurationv1.CollectionRef)
collectionRefModel.CollectionID = core.StringPtr("testString")
// Construct an instance of the UpdatePropertyOptions model
updatePropertyOptionsModel := new(appconfigurationv1.UpdatePropertyOptions)
updatePropertyOptionsModel.EnvironmentID = core.StringPtr("testString")
updatePropertyOptionsModel.PropertyID = core.StringPtr("testString")
updatePropertyOptionsModel.Name = core.StringPtr("testString")
updatePropertyOptionsModel.Description = core.StringPtr("testString")
updatePropertyOptionsModel.Value = core.StringPtr("testString")
updatePropertyOptionsModel.Tags = core.StringPtr("testString")
updatePropertyOptionsModel.SegmentRules = []appconfigurationv1.SegmentRule{*segmentRuleModel}
updatePropertyOptionsModel.Collections = []appconfigurationv1.CollectionRef{*collectionRefModel}
updatePropertyOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"}
// Expect response parsing to fail since we are receiving a text/plain response
result, response, operationErr := appConfigurationService.UpdateProperty(updatePropertyOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(response).ToNot(BeNil())
Expect(result).To(BeNil())
// Enable retries and test again
appConfigurationService.EnableRetries(0, 0)
result, response, operationErr = appConfigurationService.UpdateProperty(updatePropertyOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(response).ToNot(BeNil())
Expect(result).To(BeNil())
})
AfterEach(func() {
testServer.Close()
})
})
})
Describe(`UpdateProperty(updatePropertyOptions *UpdatePropertyOptions)`, func() {
updatePropertyPath := "/environments/testString/properties/testString"
var serverSleepTime time.Duration
Context(`Using mock server endpoint`, func() {
BeforeEach(func() {
serverSleepTime = 0
testServer = httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
defer GinkgoRecover()
// Verify the contents of the request
Expect(req.URL.EscapedPath()).To(Equal(updatePropertyPath))
Expect(req.Method).To(Equal("PUT"))
// For gzip-disabled operation, verify Content-Encoding is not set.
Expect(req.Header.Get("Content-Encoding")).To(BeEmpty())
// If there is a body, then make sure we can read it
bodyBuf := new(bytes.Buffer)
if req.Header.Get("Content-Encoding") == "gzip" {
body, err := core.NewGzipDecompressionReader(req.Body)
Expect(err).To(BeNil())
_, err = bodyBuf.ReadFrom(body)
Expect(err).To(BeNil())
} else {
_, err := bodyBuf.ReadFrom(req.Body)
Expect(err).To(BeNil())
}
fmt.Fprintf(GinkgoWriter, " Request body: %s", bodyBuf.String())
// Sleep a short time to support a timeout test
time.Sleep(serverSleepTime)
// Set mock response
res.Header().Set("Content-type", "application/json")
res.WriteHeader(200)
fmt.Fprintf(res, "%s", `{"name": "Name", "property_id": "PropertyID", "description": "Description", "type": "BOOLEAN", "value": "anyValue", "tags": "Tags", "segment_rules": [{"rules": [{"segments": ["Segments"]}], "value": "anyValue", "order": 5}], "segment_exists": false, "collections": [{"collection_id": "CollectionID", "name": "Name"}], "created_time": "2019-01-01T12:00:00", "updated_time": "2019-01-01T12:00:00", "evaluation_time": "2019-01-01T12:00:00", "href": "Href"}`)
}))
})
It(`Invoke UpdateProperty successfully`, func() {
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1(&appconfigurationv1.AppConfigurationV1Options{
URL: testServer.URL,
Authenticator: &core.NoAuthAuthenticator{},
})
Expect(serviceErr).To(BeNil())
Expect(appConfigurationService).ToNot(BeNil())
appConfigurationService.EnableRetries(0, 0)
// Invoke operation with nil options model (negative test)
result, response, operationErr := appConfigurationService.UpdateProperty(nil)
Expect(operationErr).NotTo(BeNil())
Expect(response).To(BeNil())
Expect(result).To(BeNil())
// Construct an instance of the TargetSegments model
targetSegmentsModel := new(appconfigurationv1.TargetSegments)
targetSegmentsModel.Segments = []string{"testString"}
// Construct an instance of the SegmentRule model
segmentRuleModel := new(appconfigurationv1.SegmentRule)
segmentRuleModel.Rules = []appconfigurationv1.TargetSegments{*targetSegmentsModel}
segmentRuleModel.Value = core.StringPtr("testString")
segmentRuleModel.Order = core.Int64Ptr(int64(38))
// Construct an instance of the CollectionRef model
collectionRefModel := new(appconfigurationv1.CollectionRef)
collectionRefModel.CollectionID = core.StringPtr("testString")
// Construct an instance of the UpdatePropertyOptions model
updatePropertyOptionsModel := new(appconfigurationv1.UpdatePropertyOptions)
updatePropertyOptionsModel.EnvironmentID = core.StringPtr("testString")
updatePropertyOptionsModel.PropertyID = core.StringPtr("testString")
updatePropertyOptionsModel.Name = core.StringPtr("testString")
updatePropertyOptionsModel.Description = core.StringPtr("testString")
updatePropertyOptionsModel.Value = core.StringPtr("testString")
updatePropertyOptionsModel.Tags = core.StringPtr("testString")
updatePropertyOptionsModel.SegmentRules = []appconfigurationv1.SegmentRule{*segmentRuleModel}
updatePropertyOptionsModel.Collections = []appconfigurationv1.CollectionRef{*collectionRefModel}
updatePropertyOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"}
// Invoke operation with valid options model (positive test)
result, response, operationErr = appConfigurationService.UpdateProperty(updatePropertyOptionsModel)
Expect(operationErr).To(BeNil())
Expect(response).ToNot(BeNil())
Expect(result).ToNot(BeNil())
// Invoke operation with a Context to test a timeout error
ctx, cancelFunc := context.WithTimeout(context.Background(), 80*time.Millisecond)
defer cancelFunc()
serverSleepTime = 100 * time.Millisecond
_, _, operationErr = appConfigurationService.UpdatePropertyWithContext(ctx, updatePropertyOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(operationErr.Error()).To(ContainSubstring("deadline exceeded"))
serverSleepTime = time.Duration(0)
// Disable retries and test again
appConfigurationService.DisableRetries()
result, response, operationErr = appConfigurationService.UpdateProperty(updatePropertyOptionsModel)
Expect(operationErr).To(BeNil())
Expect(response).ToNot(BeNil())
Expect(result).ToNot(BeNil())
// Re-test the timeout error with retries disabled
ctx, cancelFunc2 := context.WithTimeout(context.Background(), 80*time.Millisecond)
defer cancelFunc2()
serverSleepTime = 100 * time.Millisecond
_, _, operationErr = appConfigurationService.UpdatePropertyWithContext(ctx, updatePropertyOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(operationErr.Error()).To(ContainSubstring("deadline exceeded"))
serverSleepTime = time.Duration(0)
})
It(`Invoke UpdateProperty with error: Operation validation and request error`, func() {
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1(&appconfigurationv1.AppConfigurationV1Options{
URL: testServer.URL,
Authenticator: &core.NoAuthAuthenticator{},
})
Expect(serviceErr).To(BeNil())
Expect(appConfigurationService).ToNot(BeNil())
// Construct an instance of the TargetSegments model
targetSegmentsModel := new(appconfigurationv1.TargetSegments)
targetSegmentsModel.Segments = []string{"testString"}
// Construct an instance of the SegmentRule model
segmentRuleModel := new(appconfigurationv1.SegmentRule)
segmentRuleModel.Rules = []appconfigurationv1.TargetSegments{*targetSegmentsModel}
segmentRuleModel.Value = core.StringPtr("testString")
segmentRuleModel.Order = core.Int64Ptr(int64(38))
// Construct an instance of the CollectionRef model
collectionRefModel := new(appconfigurationv1.CollectionRef)
collectionRefModel.CollectionID = core.StringPtr("testString")
// Construct an instance of the UpdatePropertyOptions model
updatePropertyOptionsModel := new(appconfigurationv1.UpdatePropertyOptions)
updatePropertyOptionsModel.EnvironmentID = core.StringPtr("testString")
updatePropertyOptionsModel.PropertyID = core.StringPtr("testString")
updatePropertyOptionsModel.Name = core.StringPtr("testString")
updatePropertyOptionsModel.Description = core.StringPtr("testString")
updatePropertyOptionsModel.Value = core.StringPtr("testString")
updatePropertyOptionsModel.Tags = core.StringPtr("testString")
updatePropertyOptionsModel.SegmentRules = []appconfigurationv1.SegmentRule{*segmentRuleModel}
updatePropertyOptionsModel.Collections = []appconfigurationv1.CollectionRef{*collectionRefModel}
updatePropertyOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"}
// Invoke operation with empty URL (negative test)
err := appConfigurationService.SetServiceURL("")
Expect(err).To(BeNil())
result, response, operationErr := appConfigurationService.UpdateProperty(updatePropertyOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(operationErr.Error()).To(ContainSubstring(core.ERRORMSG_SERVICE_URL_MISSING))
Expect(response).To(BeNil())
Expect(result).To(BeNil())
// Construct a second instance of the UpdatePropertyOptions model with no property values
updatePropertyOptionsModelNew := new(appconfigurationv1.UpdatePropertyOptions)
// Invoke operation with invalid model (negative test)
result, response, operationErr = appConfigurationService.UpdateProperty(updatePropertyOptionsModelNew)
Expect(operationErr).ToNot(BeNil())
Expect(response).To(BeNil())
Expect(result).To(BeNil())
})
AfterEach(func() {
testServer.Close()
})
})
})
Describe(`UpdatePropertyValues(updatePropertyValuesOptions *UpdatePropertyValuesOptions) - Operation response error`, func() {
updatePropertyValuesPath := "/environments/testString/properties/testString"
Context(`Using mock server endpoint`, func() {
BeforeEach(func() {
testServer = httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
defer GinkgoRecover()
// Verify the contents of the request
Expect(req.URL.EscapedPath()).To(Equal(updatePropertyValuesPath))
Expect(req.Method).To(Equal("PATCH"))
res.Header().Set("Content-type", "application/json")
res.WriteHeader(200)
fmt.Fprintf(res, `} this is not valid json {`)
}))
})
It(`Invoke UpdatePropertyValues with error: Operation response processing error`, func() {
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1(&appconfigurationv1.AppConfigurationV1Options{
URL: testServer.URL,
Authenticator: &core.NoAuthAuthenticator{},
})
Expect(serviceErr).To(BeNil())
Expect(appConfigurationService).ToNot(BeNil())
// Construct an instance of the TargetSegments model
targetSegmentsModel := new(appconfigurationv1.TargetSegments)
targetSegmentsModel.Segments = []string{"testString"}
// Construct an instance of the SegmentRule model
segmentRuleModel := new(appconfigurationv1.SegmentRule)
segmentRuleModel.Rules = []appconfigurationv1.TargetSegments{*targetSegmentsModel}
segmentRuleModel.Value = core.StringPtr("testString")
segmentRuleModel.Order = core.Int64Ptr(int64(38))
// Construct an instance of the UpdatePropertyValuesOptions model
updatePropertyValuesOptionsModel := new(appconfigurationv1.UpdatePropertyValuesOptions)
updatePropertyValuesOptionsModel.EnvironmentID = core.StringPtr("testString")
updatePropertyValuesOptionsModel.PropertyID = core.StringPtr("testString")
updatePropertyValuesOptionsModel.Name = core.StringPtr("testString")
updatePropertyValuesOptionsModel.Description = core.StringPtr("testString")
updatePropertyValuesOptionsModel.Tags = core.StringPtr("testString")
updatePropertyValuesOptionsModel.Value = core.StringPtr("testString")
updatePropertyValuesOptionsModel.SegmentRules = []appconfigurationv1.SegmentRule{*segmentRuleModel}
updatePropertyValuesOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"}
// Expect response parsing to fail since we are receiving a text/plain response
result, response, operationErr := appConfigurationService.UpdatePropertyValues(updatePropertyValuesOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(response).ToNot(BeNil())
Expect(result).To(BeNil())
// Enable retries and test again
appConfigurationService.EnableRetries(0, 0)
result, response, operationErr = appConfigurationService.UpdatePropertyValues(updatePropertyValuesOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(response).ToNot(BeNil())
Expect(result).To(BeNil())
})
AfterEach(func() {
testServer.Close()
})
})
})
Describe(`UpdatePropertyValues(updatePropertyValuesOptions *UpdatePropertyValuesOptions)`, func() {
updatePropertyValuesPath := "/environments/testString/properties/testString"
var serverSleepTime time.Duration
Context(`Using mock server endpoint`, func() {
BeforeEach(func() {
serverSleepTime = 0
testServer = httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
defer GinkgoRecover()
// Verify the contents of the request
Expect(req.URL.EscapedPath()).To(Equal(updatePropertyValuesPath))
Expect(req.Method).To(Equal("PATCH"))
// For gzip-disabled operation, verify Content-Encoding is not set.
Expect(req.Header.Get("Content-Encoding")).To(BeEmpty())
// If there is a body, then make sure we can read it
bodyBuf := new(bytes.Buffer)
if req.Header.Get("Content-Encoding") == "gzip" {
body, err := core.NewGzipDecompressionReader(req.Body)
Expect(err).To(BeNil())
_, err = bodyBuf.ReadFrom(body)
Expect(err).To(BeNil())
} else {
_, err := bodyBuf.ReadFrom(req.Body)
Expect(err).To(BeNil())
}
fmt.Fprintf(GinkgoWriter, " Request body: %s", bodyBuf.String())
// Sleep a short time to support a timeout test
time.Sleep(serverSleepTime)
// Set mock response
res.Header().Set("Content-type", "application/json")
res.WriteHeader(200)
fmt.Fprintf(res, "%s", `{"name": "Name", "property_id": "PropertyID", "description": "Description", "type": "BOOLEAN", "value": "anyValue", "tags": "Tags", "segment_rules": [{"rules": [{"segments": ["Segments"]}], "value": "anyValue", "order": 5}], "segment_exists": false, "collections": [{"collection_id": "CollectionID", "name": "Name"}], "created_time": "2019-01-01T12:00:00", "updated_time": "2019-01-01T12:00:00", "evaluation_time": "2019-01-01T12:00:00", "href": "Href"}`)
}))
})
It(`Invoke UpdatePropertyValues successfully`, func() {
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1(&appconfigurationv1.AppConfigurationV1Options{
URL: testServer.URL,
Authenticator: &core.NoAuthAuthenticator{},
})
Expect(serviceErr).To(BeNil())
Expect(appConfigurationService).ToNot(BeNil())
appConfigurationService.EnableRetries(0, 0)
// Invoke operation with nil options model (negative test)
result, response, operationErr := appConfigurationService.UpdatePropertyValues(nil)
Expect(operationErr).NotTo(BeNil())
Expect(response).To(BeNil())
Expect(result).To(BeNil())
// Construct an instance of the TargetSegments model
targetSegmentsModel := new(appconfigurationv1.TargetSegments)
targetSegmentsModel.Segments = []string{"testString"}
// Construct an instance of the SegmentRule model
segmentRuleModel := new(appconfigurationv1.SegmentRule)
segmentRuleModel.Rules = []appconfigurationv1.TargetSegments{*targetSegmentsModel}
segmentRuleModel.Value = core.StringPtr("testString")
segmentRuleModel.Order = core.Int64Ptr(int64(38))
// Construct an instance of the UpdatePropertyValuesOptions model
updatePropertyValuesOptionsModel := new(appconfigurationv1.UpdatePropertyValuesOptions)
updatePropertyValuesOptionsModel.EnvironmentID = core.StringPtr("testString")
updatePropertyValuesOptionsModel.PropertyID = core.StringPtr("testString")
updatePropertyValuesOptionsModel.Name = core.StringPtr("testString")
updatePropertyValuesOptionsModel.Description = core.StringPtr("testString")
updatePropertyValuesOptionsModel.Tags = core.StringPtr("testString")
updatePropertyValuesOptionsModel.Value = core.StringPtr("testString")
updatePropertyValuesOptionsModel.SegmentRules = []appconfigurationv1.SegmentRule{*segmentRuleModel}
updatePropertyValuesOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"}
// Invoke operation with valid options model (positive test)
result, response, operationErr = appConfigurationService.UpdatePropertyValues(updatePropertyValuesOptionsModel)
Expect(operationErr).To(BeNil())
Expect(response).ToNot(BeNil())
Expect(result).ToNot(BeNil())
// Invoke operation with a Context to test a timeout error
ctx, cancelFunc := context.WithTimeout(context.Background(), 80*time.Millisecond)
defer cancelFunc()
serverSleepTime = 100 * time.Millisecond
_, _, operationErr = appConfigurationService.UpdatePropertyValuesWithContext(ctx, updatePropertyValuesOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(operationErr.Error()).To(ContainSubstring("deadline exceeded"))
serverSleepTime = time.Duration(0)
// Disable retries and test again
appConfigurationService.DisableRetries()
result, response, operationErr = appConfigurationService.UpdatePropertyValues(updatePropertyValuesOptionsModel)
Expect(operationErr).To(BeNil())
Expect(response).ToNot(BeNil())
Expect(result).ToNot(BeNil())
// Re-test the timeout error with retries disabled
ctx, cancelFunc2 := context.WithTimeout(context.Background(), 80*time.Millisecond)
defer cancelFunc2()
serverSleepTime = 100 * time.Millisecond
_, _, operationErr = appConfigurationService.UpdatePropertyValuesWithContext(ctx, updatePropertyValuesOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(operationErr.Error()).To(ContainSubstring("deadline exceeded"))
serverSleepTime = time.Duration(0)
})
It(`Invoke UpdatePropertyValues with error: Operation validation and request error`, func() {
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1(&appconfigurationv1.AppConfigurationV1Options{
URL: testServer.URL,
Authenticator: &core.NoAuthAuthenticator{},
})
Expect(serviceErr).To(BeNil())
Expect(appConfigurationService).ToNot(BeNil())
// Construct an instance of the TargetSegments model
targetSegmentsModel := new(appconfigurationv1.TargetSegments)
targetSegmentsModel.Segments = []string{"testString"}
// Construct an instance of the SegmentRule model
segmentRuleModel := new(appconfigurationv1.SegmentRule)
segmentRuleModel.Rules = []appconfigurationv1.TargetSegments{*targetSegmentsModel}
segmentRuleModel.Value = core.StringPtr("testString")
segmentRuleModel.Order = core.Int64Ptr(int64(38))
// Construct an instance of the UpdatePropertyValuesOptions model
updatePropertyValuesOptionsModel := new(appconfigurationv1.UpdatePropertyValuesOptions)
updatePropertyValuesOptionsModel.EnvironmentID = core.StringPtr("testString")
updatePropertyValuesOptionsModel.PropertyID = core.StringPtr("testString")
updatePropertyValuesOptionsModel.Name = core.StringPtr("testString")
updatePropertyValuesOptionsModel.Description = core.StringPtr("testString")
updatePropertyValuesOptionsModel.Tags = core.StringPtr("testString")
updatePropertyValuesOptionsModel.Value = core.StringPtr("testString")
updatePropertyValuesOptionsModel.SegmentRules = []appconfigurationv1.SegmentRule{*segmentRuleModel}
updatePropertyValuesOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"}
// Invoke operation with empty URL (negative test)
err := appConfigurationService.SetServiceURL("")
Expect(err).To(BeNil())
result, response, operationErr := appConfigurationService.UpdatePropertyValues(updatePropertyValuesOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(operationErr.Error()).To(ContainSubstring(core.ERRORMSG_SERVICE_URL_MISSING))
Expect(response).To(BeNil())
Expect(result).To(BeNil())
// Construct a second instance of the UpdatePropertyValuesOptions model with no property values
updatePropertyValuesOptionsModelNew := new(appconfigurationv1.UpdatePropertyValuesOptions)
// Invoke operation with invalid model (negative test)
result, response, operationErr = appConfigurationService.UpdatePropertyValues(updatePropertyValuesOptionsModelNew)
Expect(operationErr).ToNot(BeNil())
Expect(response).To(BeNil())
Expect(result).To(BeNil())
})
AfterEach(func() {
testServer.Close()
})
})
})
Describe(`GetProperty(getPropertyOptions *GetPropertyOptions) - Operation response error`, func() {
getPropertyPath := "/environments/testString/properties/testString"
Context(`Using mock server endpoint`, func() {
BeforeEach(func() {
testServer = httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
defer GinkgoRecover()
// Verify the contents of the request
Expect(req.URL.EscapedPath()).To(Equal(getPropertyPath))
Expect(req.Method).To(Equal("GET"))
Expect(req.URL.Query()["include"]).To(Equal([]string{"collections"}))
res.Header().Set("Content-type", "application/json")
res.WriteHeader(200)
fmt.Fprintf(res, `} this is not valid json {`)
}))
})
It(`Invoke GetProperty with error: Operation response processing error`, func() {
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1(&appconfigurationv1.AppConfigurationV1Options{
URL: testServer.URL,
Authenticator: &core.NoAuthAuthenticator{},
})
Expect(serviceErr).To(BeNil())
Expect(appConfigurationService).ToNot(BeNil())
// Construct an instance of the GetPropertyOptions model
getPropertyOptionsModel := new(appconfigurationv1.GetPropertyOptions)
getPropertyOptionsModel.EnvironmentID = core.StringPtr("testString")
getPropertyOptionsModel.PropertyID = core.StringPtr("testString")
getPropertyOptionsModel.Include = core.StringPtr("collections")
getPropertyOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"}
// Expect response parsing to fail since we are receiving a text/plain response
result, response, operationErr := appConfigurationService.GetProperty(getPropertyOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(response).ToNot(BeNil())
Expect(result).To(BeNil())
// Enable retries and test again
appConfigurationService.EnableRetries(0, 0)
result, response, operationErr = appConfigurationService.GetProperty(getPropertyOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(response).ToNot(BeNil())
Expect(result).To(BeNil())
})
AfterEach(func() {
testServer.Close()
})
})
})
Describe(`GetProperty(getPropertyOptions *GetPropertyOptions)`, func() {
getPropertyPath := "/environments/testString/properties/testString"
var serverSleepTime time.Duration
Context(`Using mock server endpoint`, func() {
BeforeEach(func() {
serverSleepTime = 0
testServer = httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
defer GinkgoRecover()
// Verify the contents of the request
Expect(req.URL.EscapedPath()).To(Equal(getPropertyPath))
Expect(req.Method).To(Equal("GET"))
Expect(req.URL.Query()["include"]).To(Equal([]string{"collections"}))
// Sleep a short time to support a timeout test
time.Sleep(serverSleepTime)
// Set mock response
res.Header().Set("Content-type", "application/json")
res.WriteHeader(200)
fmt.Fprintf(res, "%s", `{"name": "Name", "property_id": "PropertyID", "description": "Description", "type": "BOOLEAN", "value": "anyValue", "tags": "Tags", "segment_rules": [{"rules": [{"segments": ["Segments"]}], "value": "anyValue", "order": 5}], "segment_exists": false, "collections": [{"collection_id": "CollectionID", "name": "Name"}], "created_time": "2019-01-01T12:00:00", "updated_time": "2019-01-01T12:00:00", "evaluation_time": "2019-01-01T12:00:00", "href": "Href"}`)
}))
})
It(`Invoke GetProperty successfully`, func() {
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1(&appconfigurationv1.AppConfigurationV1Options{
URL: testServer.URL,
Authenticator: &core.NoAuthAuthenticator{},
})
Expect(serviceErr).To(BeNil())
Expect(appConfigurationService).ToNot(BeNil())
appConfigurationService.EnableRetries(0, 0)
// Invoke operation with nil options model (negative test)
result, response, operationErr := appConfigurationService.GetProperty(nil)
Expect(operationErr).NotTo(BeNil())
Expect(response).To(BeNil())
Expect(result).To(BeNil())
// Construct an instance of the GetPropertyOptions model
getPropertyOptionsModel := new(appconfigurationv1.GetPropertyOptions)
getPropertyOptionsModel.EnvironmentID = core.StringPtr("testString")
getPropertyOptionsModel.PropertyID = core.StringPtr("testString")
getPropertyOptionsModel.Include = core.StringPtr("collections")
getPropertyOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"}
// Invoke operation with valid options model (positive test)
result, response, operationErr = appConfigurationService.GetProperty(getPropertyOptionsModel)
Expect(operationErr).To(BeNil())
Expect(response).ToNot(BeNil())
Expect(result).ToNot(BeNil())
// Invoke operation with a Context to test a timeout error
ctx, cancelFunc := context.WithTimeout(context.Background(), 80*time.Millisecond)
defer cancelFunc()
serverSleepTime = 100 * time.Millisecond
_, _, operationErr = appConfigurationService.GetPropertyWithContext(ctx, getPropertyOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(operationErr.Error()).To(ContainSubstring("deadline exceeded"))
serverSleepTime = time.Duration(0)
// Disable retries and test again
appConfigurationService.DisableRetries()
result, response, operationErr = appConfigurationService.GetProperty(getPropertyOptionsModel)
Expect(operationErr).To(BeNil())
Expect(response).ToNot(BeNil())
Expect(result).ToNot(BeNil())
// Re-test the timeout error with retries disabled
ctx, cancelFunc2 := context.WithTimeout(context.Background(), 80*time.Millisecond)
defer cancelFunc2()
serverSleepTime = 100 * time.Millisecond
_, _, operationErr = appConfigurationService.GetPropertyWithContext(ctx, getPropertyOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(operationErr.Error()).To(ContainSubstring("deadline exceeded"))
serverSleepTime = time.Duration(0)
})
It(`Invoke GetProperty with error: Operation validation and request error`, func() {
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1(&appconfigurationv1.AppConfigurationV1Options{
URL: testServer.URL,
Authenticator: &core.NoAuthAuthenticator{},
})
Expect(serviceErr).To(BeNil())
Expect(appConfigurationService).ToNot(BeNil())
// Construct an instance of the GetPropertyOptions model
getPropertyOptionsModel := new(appconfigurationv1.GetPropertyOptions)
getPropertyOptionsModel.EnvironmentID = core.StringPtr("testString")
getPropertyOptionsModel.PropertyID = core.StringPtr("testString")
getPropertyOptionsModel.Include = core.StringPtr("collections")
getPropertyOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"}
// Invoke operation with empty URL (negative test)
err := appConfigurationService.SetServiceURL("")
Expect(err).To(BeNil())
result, response, operationErr := appConfigurationService.GetProperty(getPropertyOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(operationErr.Error()).To(ContainSubstring(core.ERRORMSG_SERVICE_URL_MISSING))
Expect(response).To(BeNil())
Expect(result).To(BeNil())
// Construct a second instance of the GetPropertyOptions model with no property values
getPropertyOptionsModelNew := new(appconfigurationv1.GetPropertyOptions)
// Invoke operation with invalid model (negative test)
result, response, operationErr = appConfigurationService.GetProperty(getPropertyOptionsModelNew)
Expect(operationErr).ToNot(BeNil())
Expect(response).To(BeNil())
Expect(result).To(BeNil())
})
AfterEach(func() {
testServer.Close()
})
})
})
Describe(`DeleteProperty(deletePropertyOptions *DeletePropertyOptions)`, func() {
deletePropertyPath := "/environments/testString/properties/testString"
Context(`Using mock server endpoint`, func() {
BeforeEach(func() {
testServer = httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
defer GinkgoRecover()
// Verify the contents of the request
Expect(req.URL.EscapedPath()).To(Equal(deletePropertyPath))
Expect(req.Method).To(Equal("DELETE"))
res.WriteHeader(204)
}))
})
It(`Invoke DeleteProperty successfully`, func() {
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1(&appconfigurationv1.AppConfigurationV1Options{
URL: testServer.URL,
Authenticator: &core.NoAuthAuthenticator{},
})
Expect(serviceErr).To(BeNil())
Expect(appConfigurationService).ToNot(BeNil())
appConfigurationService.EnableRetries(0, 0)
// Invoke operation with nil options model (negative test)
response, operationErr := appConfigurationService.DeleteProperty(nil)
Expect(operationErr).NotTo(BeNil())
Expect(response).To(BeNil())
// Construct an instance of the DeletePropertyOptions model
deletePropertyOptionsModel := new(appconfigurationv1.DeletePropertyOptions)
deletePropertyOptionsModel.EnvironmentID = core.StringPtr("testString")
deletePropertyOptionsModel.PropertyID = core.StringPtr("testString")
deletePropertyOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"}
// Invoke operation with valid options model (positive test)
response, operationErr = appConfigurationService.DeleteProperty(deletePropertyOptionsModel)
Expect(operationErr).To(BeNil())
Expect(response).ToNot(BeNil())
// Disable retries and test again
appConfigurationService.DisableRetries()
response, operationErr = appConfigurationService.DeleteProperty(deletePropertyOptionsModel)
Expect(operationErr).To(BeNil())
Expect(response).ToNot(BeNil())
})
It(`Invoke DeleteProperty with error: Operation validation and request error`, func() {
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1(&appconfigurationv1.AppConfigurationV1Options{
URL: testServer.URL,
Authenticator: &core.NoAuthAuthenticator{},
})
Expect(serviceErr).To(BeNil())
Expect(appConfigurationService).ToNot(BeNil())
// Construct an instance of the DeletePropertyOptions model
deletePropertyOptionsModel := new(appconfigurationv1.DeletePropertyOptions)
deletePropertyOptionsModel.EnvironmentID = core.StringPtr("testString")
deletePropertyOptionsModel.PropertyID = core.StringPtr("testString")
deletePropertyOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"}
// Invoke operation with empty URL (negative test)
err := appConfigurationService.SetServiceURL("")
Expect(err).To(BeNil())
response, operationErr := appConfigurationService.DeleteProperty(deletePropertyOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(operationErr.Error()).To(ContainSubstring(core.ERRORMSG_SERVICE_URL_MISSING))
Expect(response).To(BeNil())
// Construct a second instance of the DeletePropertyOptions model with no property values
deletePropertyOptionsModelNew := new(appconfigurationv1.DeletePropertyOptions)
// Invoke operation with invalid model (negative test)
response, operationErr = appConfigurationService.DeleteProperty(deletePropertyOptionsModelNew)
Expect(operationErr).ToNot(BeNil())
Expect(response).To(BeNil())
})
AfterEach(func() {
testServer.Close()
})
})
})
Describe(`Service constructor tests`, func() {
It(`Instantiate service client`, func() {
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1(&appconfigurationv1.AppConfigurationV1Options{
Authenticator: &core.NoAuthAuthenticator{},
})
Expect(appConfigurationService).ToNot(BeNil())
Expect(serviceErr).To(BeNil())
})
It(`Instantiate service client with error: Invalid URL`, func() {
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1(&appconfigurationv1.AppConfigurationV1Options{
URL: "{BAD_URL_STRING",
})
Expect(appConfigurationService).To(BeNil())
Expect(serviceErr).ToNot(BeNil())
})
It(`Instantiate service client with error: Invalid Auth`, func() {
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1(&appconfigurationv1.AppConfigurationV1Options{
URL: "https://appconfigurationv1/api",
Authenticator: &core.BasicAuthenticator{
Username: "",
Password: "",
},
})
Expect(appConfigurationService).To(BeNil())
Expect(serviceErr).ToNot(BeNil())
})
})
Describe(`Service constructor tests using external config`, func() {
Context(`Using external config, construct service client instances`, func() {
// Map containing environment variables used in testing.
var testEnvironment = map[string]string{
"APP_CONFIGURATION_URL": "https://appconfigurationv1/api",
"APP_CONFIGURATION_AUTH_TYPE": "noauth",
}
It(`Create service client using external config successfully`, func() {
SetTestEnvironment(testEnvironment)
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1UsingExternalConfig(&appconfigurationv1.AppConfigurationV1Options{})
Expect(appConfigurationService).ToNot(BeNil())
Expect(serviceErr).To(BeNil())
ClearTestEnvironment(testEnvironment)
clone := appConfigurationService.Clone()
Expect(clone).ToNot(BeNil())
Expect(clone.Service != appConfigurationService.Service).To(BeTrue())
Expect(clone.GetServiceURL()).To(Equal(appConfigurationService.GetServiceURL()))
Expect(clone.Service.Options.Authenticator).To(Equal(appConfigurationService.Service.Options.Authenticator))
})
It(`Create service client using external config and set url from constructor successfully`, func() {
SetTestEnvironment(testEnvironment)
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1UsingExternalConfig(&appconfigurationv1.AppConfigurationV1Options{
URL: "https://testService/api",
})
Expect(appConfigurationService).ToNot(BeNil())
Expect(serviceErr).To(BeNil())
Expect(appConfigurationService.Service.GetServiceURL()).To(Equal("https://testService/api"))
ClearTestEnvironment(testEnvironment)
clone := appConfigurationService.Clone()
Expect(clone).ToNot(BeNil())
Expect(clone.Service != appConfigurationService.Service).To(BeTrue())
Expect(clone.GetServiceURL()).To(Equal(appConfigurationService.GetServiceURL()))
Expect(clone.Service.Options.Authenticator).To(Equal(appConfigurationService.Service.Options.Authenticator))
})
It(`Create service client using external config and set url programatically successfully`, func() {
SetTestEnvironment(testEnvironment)
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1UsingExternalConfig(&appconfigurationv1.AppConfigurationV1Options{})
err := appConfigurationService.SetServiceURL("https://testService/api")
Expect(err).To(BeNil())
Expect(appConfigurationService).ToNot(BeNil())
Expect(serviceErr).To(BeNil())
Expect(appConfigurationService.Service.GetServiceURL()).To(Equal("https://testService/api"))
ClearTestEnvironment(testEnvironment)
clone := appConfigurationService.Clone()
Expect(clone).ToNot(BeNil())
Expect(clone.Service != appConfigurationService.Service).To(BeTrue())
Expect(clone.GetServiceURL()).To(Equal(appConfigurationService.GetServiceURL()))
Expect(clone.Service.Options.Authenticator).To(Equal(appConfigurationService.Service.Options.Authenticator))
})
})
Context(`Using external config, construct service client instances with error: Invalid Auth`, func() {
// Map containing environment variables used in testing.
var testEnvironment = map[string]string{
"APP_CONFIGURATION_URL": "https://appconfigurationv1/api",
"APP_CONFIGURATION_AUTH_TYPE": "someOtherAuth",
}
SetTestEnvironment(testEnvironment)
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1UsingExternalConfig(&appconfigurationv1.AppConfigurationV1Options{})
It(`Instantiate service client with error`, func() {
Expect(appConfigurationService).To(BeNil())
Expect(serviceErr).ToNot(BeNil())
ClearTestEnvironment(testEnvironment)
})
})
Context(`Using external config, construct service client instances with error: Invalid URL`, func() {
// Map containing environment variables used in testing.
var testEnvironment = map[string]string{
"APP_CONFIGURATION_AUTH_TYPE": "NOAuth",
}
SetTestEnvironment(testEnvironment)
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1UsingExternalConfig(&appconfigurationv1.AppConfigurationV1Options{
URL: "{BAD_URL_STRING",
})
It(`Instantiate service client with error`, func() {
Expect(appConfigurationService).To(BeNil())
Expect(serviceErr).ToNot(BeNil())
ClearTestEnvironment(testEnvironment)
})
})
})
Describe(`Regional endpoint tests`, func() {
It(`GetServiceURLForRegion(region string)`, func() {
var url string
var err error
url, err = appconfigurationv1.GetServiceURLForRegion("INVALID_REGION")
Expect(url).To(BeEmpty())
Expect(err).ToNot(BeNil())
fmt.Fprintf(GinkgoWriter, "Expected error: %s\n", err.Error())
})
})
Describe(`ListSegments(listSegmentsOptions *ListSegmentsOptions) - Operation response error`, func() {
listSegmentsPath := "/segments"
Context(`Using mock server endpoint`, func() {
BeforeEach(func() {
testServer = httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
defer GinkgoRecover()
// Verify the contents of the request
Expect(req.URL.EscapedPath()).To(Equal(listSegmentsPath))
Expect(req.Method).To(Equal("GET"))
// TODO: Add check for expand query parameter
Expect(req.URL.Query()["sort"]).To(Equal([]string{"created_time"}))
Expect(req.URL.Query()["tags"]).To(Equal([]string{"version 1.1, pre-release"}))
Expect(req.URL.Query()["include"]).To(Equal([]string{"rules"}))
Expect(req.URL.Query()["limit"]).To(Equal([]string{fmt.Sprint(int64(1))}))
Expect(req.URL.Query()["offset"]).To(Equal([]string{fmt.Sprint(int64(0))}))
res.Header().Set("Content-type", "application/json")
res.WriteHeader(200)
fmt.Fprintf(res, `} this is not valid json {`)
}))
})
It(`Invoke ListSegments with error: Operation response processing error`, func() {
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1(&appconfigurationv1.AppConfigurationV1Options{
URL: testServer.URL,
Authenticator: &core.NoAuthAuthenticator{},
})
Expect(serviceErr).To(BeNil())
Expect(appConfigurationService).ToNot(BeNil())
// Construct an instance of the ListSegmentsOptions model
listSegmentsOptionsModel := new(appconfigurationv1.ListSegmentsOptions)
listSegmentsOptionsModel.Expand = core.BoolPtr(true)
listSegmentsOptionsModel.Sort = core.StringPtr("created_time")
listSegmentsOptionsModel.Tags = core.StringPtr("version 1.1, pre-release")
listSegmentsOptionsModel.Include = core.StringPtr("rules")
listSegmentsOptionsModel.Limit = core.Int64Ptr(int64(1))
listSegmentsOptionsModel.Offset = core.Int64Ptr(int64(0))
listSegmentsOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"}
// Expect response parsing to fail since we are receiving a text/plain response
result, response, operationErr := appConfigurationService.ListSegments(listSegmentsOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(response).ToNot(BeNil())
Expect(result).To(BeNil())
// Enable retries and test again
appConfigurationService.EnableRetries(0, 0)
result, response, operationErr = appConfigurationService.ListSegments(listSegmentsOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(response).ToNot(BeNil())
Expect(result).To(BeNil())
})
AfterEach(func() {
testServer.Close()
})
})
})
Describe(`ListSegments(listSegmentsOptions *ListSegmentsOptions)`, func() {
listSegmentsPath := "/segments"
var serverSleepTime time.Duration
Context(`Using mock server endpoint`, func() {
BeforeEach(func() {
serverSleepTime = 0
testServer = httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
defer GinkgoRecover()
// Verify the contents of the request
Expect(req.URL.EscapedPath()).To(Equal(listSegmentsPath))
Expect(req.Method).To(Equal("GET"))
// TODO: Add check for expand query parameter
Expect(req.URL.Query()["sort"]).To(Equal([]string{"created_time"}))
Expect(req.URL.Query()["tags"]).To(Equal([]string{"version 1.1, pre-release"}))
Expect(req.URL.Query()["include"]).To(Equal([]string{"rules"}))
Expect(req.URL.Query()["limit"]).To(Equal([]string{fmt.Sprint(int64(1))}))
Expect(req.URL.Query()["offset"]).To(Equal([]string{fmt.Sprint(int64(0))}))
// Sleep a short time to support a timeout test
time.Sleep(serverSleepTime)
// Set mock response
res.Header().Set("Content-type", "application/json")
res.WriteHeader(200)
fmt.Fprintf(res, "%s", `{"segments": [{"name": "Name", "segment_id": "SegmentID", "description": "Description", "tags": "Tags", "rules": [{"attribute_name": "AttributeName", "operator": "is", "values": ["Values"]}], "created_time": "2019-01-01T12:00:00", "updated_time": "2019-01-01T12:00:00", "href": "Href", "features": [{"feature_id": "FeatureID", "name": "Name"}], "properties": [{"property_id": "PropertyID", "name": "Name"}]}], "limit": 5, "offset": 6, "total_count": 10, "first": {"href": "Href"}, "previous": {"href": "Href"}, "next": {"href": "Href"}, "last": {"href": "Href"}}`)
}))
})
It(`Invoke ListSegments successfully`, func() {
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1(&appconfigurationv1.AppConfigurationV1Options{
URL: testServer.URL,
Authenticator: &core.NoAuthAuthenticator{},
})
Expect(serviceErr).To(BeNil())
Expect(appConfigurationService).ToNot(BeNil())
appConfigurationService.EnableRetries(0, 0)
// Invoke operation with nil options model (negative test)
result, response, operationErr := appConfigurationService.ListSegments(nil)
Expect(operationErr).NotTo(BeNil())
Expect(response).To(BeNil())
Expect(result).To(BeNil())
// Construct an instance of the ListSegmentsOptions model
listSegmentsOptionsModel := new(appconfigurationv1.ListSegmentsOptions)
listSegmentsOptionsModel.Expand = core.BoolPtr(true)
listSegmentsOptionsModel.Sort = core.StringPtr("created_time")
listSegmentsOptionsModel.Tags = core.StringPtr("version 1.1, pre-release")
listSegmentsOptionsModel.Include = core.StringPtr("rules")
listSegmentsOptionsModel.Limit = core.Int64Ptr(int64(1))
listSegmentsOptionsModel.Offset = core.Int64Ptr(int64(0))
listSegmentsOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"}
// Invoke operation with valid options model (positive test)
result, response, operationErr = appConfigurationService.ListSegments(listSegmentsOptionsModel)
Expect(operationErr).To(BeNil())
Expect(response).ToNot(BeNil())
Expect(result).ToNot(BeNil())
// Invoke operation with a Context to test a timeout error
ctx, cancelFunc := context.WithTimeout(context.Background(), 80*time.Millisecond)
defer cancelFunc()
serverSleepTime = 100 * time.Millisecond
_, _, operationErr = appConfigurationService.ListSegmentsWithContext(ctx, listSegmentsOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(operationErr.Error()).To(ContainSubstring("deadline exceeded"))
serverSleepTime = time.Duration(0)
// Disable retries and test again
appConfigurationService.DisableRetries()
result, response, operationErr = appConfigurationService.ListSegments(listSegmentsOptionsModel)
Expect(operationErr).To(BeNil())
Expect(response).ToNot(BeNil())
Expect(result).ToNot(BeNil())
// Re-test the timeout error with retries disabled
ctx, cancelFunc2 := context.WithTimeout(context.Background(), 80*time.Millisecond)
defer cancelFunc2()
serverSleepTime = 100 * time.Millisecond
_, _, operationErr = appConfigurationService.ListSegmentsWithContext(ctx, listSegmentsOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(operationErr.Error()).To(ContainSubstring("deadline exceeded"))
serverSleepTime = time.Duration(0)
})
It(`Invoke ListSegments with error: Operation request error`, func() {
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1(&appconfigurationv1.AppConfigurationV1Options{
URL: testServer.URL,
Authenticator: &core.NoAuthAuthenticator{},
})
Expect(serviceErr).To(BeNil())
Expect(appConfigurationService).ToNot(BeNil())
// Construct an instance of the ListSegmentsOptions model
listSegmentsOptionsModel := new(appconfigurationv1.ListSegmentsOptions)
listSegmentsOptionsModel.Expand = core.BoolPtr(true)
listSegmentsOptionsModel.Sort = core.StringPtr("created_time")
listSegmentsOptionsModel.Tags = core.StringPtr("version 1.1, pre-release")
listSegmentsOptionsModel.Include = core.StringPtr("rules")
listSegmentsOptionsModel.Limit = core.Int64Ptr(int64(1))
listSegmentsOptionsModel.Offset = core.Int64Ptr(int64(0))
listSegmentsOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"}
// Invoke operation with empty URL (negative test)
err := appConfigurationService.SetServiceURL("")
Expect(err).To(BeNil())
result, response, operationErr := appConfigurationService.ListSegments(listSegmentsOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(operationErr.Error()).To(ContainSubstring(core.ERRORMSG_SERVICE_URL_MISSING))
Expect(response).To(BeNil())
Expect(result).To(BeNil())
})
AfterEach(func() {
testServer.Close()
})
})
})
Describe(`CreateSegment(createSegmentOptions *CreateSegmentOptions) - Operation response error`, func() {
createSegmentPath := "/segments"
Context(`Using mock server endpoint`, func() {
BeforeEach(func() {
testServer = httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
defer GinkgoRecover()
// Verify the contents of the request
Expect(req.URL.EscapedPath()).To(Equal(createSegmentPath))
Expect(req.Method).To(Equal("POST"))
res.Header().Set("Content-type", "application/json")
res.WriteHeader(201)
fmt.Fprintf(res, `} this is not valid json {`)
}))
})
It(`Invoke CreateSegment with error: Operation response processing error`, func() {
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1(&appconfigurationv1.AppConfigurationV1Options{
URL: testServer.URL,
Authenticator: &core.NoAuthAuthenticator{},
})
Expect(serviceErr).To(BeNil())
Expect(appConfigurationService).ToNot(BeNil())
// Construct an instance of the Rule model
ruleModel := new(appconfigurationv1.Rule)
ruleModel.AttributeName = core.StringPtr("email")
ruleModel.Operator = core.StringPtr("endsWith")
ruleModel.Values = []string{"testString"}
// Construct an instance of the CreateSegmentOptions model
createSegmentOptionsModel := new(appconfigurationv1.CreateSegmentOptions)
createSegmentOptionsModel.Name = core.StringPtr("Beta Users")
createSegmentOptionsModel.SegmentID = core.StringPtr("beta-users")
createSegmentOptionsModel.Description = core.StringPtr("Segment containing the beta users")
createSegmentOptionsModel.Tags = core.StringPtr("version: 1.1, stage")
createSegmentOptionsModel.Rules = []appconfigurationv1.Rule{*ruleModel}
createSegmentOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"}
// Expect response parsing to fail since we are receiving a text/plain response
result, response, operationErr := appConfigurationService.CreateSegment(createSegmentOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(response).ToNot(BeNil())
Expect(result).To(BeNil())
// Enable retries and test again
appConfigurationService.EnableRetries(0, 0)
result, response, operationErr = appConfigurationService.CreateSegment(createSegmentOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(response).ToNot(BeNil())
Expect(result).To(BeNil())
})
AfterEach(func() {
testServer.Close()
})
})
})
Describe(`CreateSegment(createSegmentOptions *CreateSegmentOptions)`, func() {
createSegmentPath := "/segments"
var serverSleepTime time.Duration
Context(`Using mock server endpoint`, func() {
BeforeEach(func() {
serverSleepTime = 0
testServer = httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
defer GinkgoRecover()
// Verify the contents of the request
Expect(req.URL.EscapedPath()).To(Equal(createSegmentPath))
Expect(req.Method).To(Equal("POST"))
// For gzip-disabled operation, verify Content-Encoding is not set.
Expect(req.Header.Get("Content-Encoding")).To(BeEmpty())
// If there is a body, then make sure we can read it
bodyBuf := new(bytes.Buffer)
if req.Header.Get("Content-Encoding") == "gzip" {
body, err := core.NewGzipDecompressionReader(req.Body)
Expect(err).To(BeNil())
_, err = bodyBuf.ReadFrom(body)
Expect(err).To(BeNil())
} else {
_, err := bodyBuf.ReadFrom(req.Body)
Expect(err).To(BeNil())
}
fmt.Fprintf(GinkgoWriter, " Request body: %s", bodyBuf.String())
// Sleep a short time to support a timeout test
time.Sleep(serverSleepTime)
// Set mock response
res.Header().Set("Content-type", "application/json")
res.WriteHeader(201)
fmt.Fprintf(res, "%s", `{"name": "Name", "segment_id": "SegmentID", "description": "Description", "tags": "Tags", "rules": [{"attribute_name": "AttributeName", "operator": "is", "values": ["Values"]}], "created_time": "2019-01-01T12:00:00", "updated_time": "2019-01-01T12:00:00", "href": "Href", "features": [{"feature_id": "FeatureID", "name": "Name"}], "properties": [{"property_id": "PropertyID", "name": "Name"}]}`)
}))
})
It(`Invoke CreateSegment successfully`, func() {
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1(&appconfigurationv1.AppConfigurationV1Options{
URL: testServer.URL,
Authenticator: &core.NoAuthAuthenticator{},
})
Expect(serviceErr).To(BeNil())
Expect(appConfigurationService).ToNot(BeNil())
appConfigurationService.EnableRetries(0, 0)
// Invoke operation with nil options model (negative test)
result, response, operationErr := appConfigurationService.CreateSegment(nil)
Expect(operationErr).NotTo(BeNil())
Expect(response).To(BeNil())
Expect(result).To(BeNil())
// Construct an instance of the Rule model
ruleModel := new(appconfigurationv1.Rule)
ruleModel.AttributeName = core.StringPtr("email")
ruleModel.Operator = core.StringPtr("endsWith")
ruleModel.Values = []string{"testString"}
// Construct an instance of the CreateSegmentOptions model
createSegmentOptionsModel := new(appconfigurationv1.CreateSegmentOptions)
createSegmentOptionsModel.Name = core.StringPtr("Beta Users")
createSegmentOptionsModel.SegmentID = core.StringPtr("beta-users")
createSegmentOptionsModel.Description = core.StringPtr("Segment containing the beta users")
createSegmentOptionsModel.Tags = core.StringPtr("version: 1.1, stage")
createSegmentOptionsModel.Rules = []appconfigurationv1.Rule{*ruleModel}
createSegmentOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"}
// Invoke operation with valid options model (positive test)
result, response, operationErr = appConfigurationService.CreateSegment(createSegmentOptionsModel)
Expect(operationErr).To(BeNil())
Expect(response).ToNot(BeNil())
Expect(result).ToNot(BeNil())
// Invoke operation with a Context to test a timeout error
ctx, cancelFunc := context.WithTimeout(context.Background(), 80*time.Millisecond)
defer cancelFunc()
serverSleepTime = 100 * time.Millisecond
_, _, operationErr = appConfigurationService.CreateSegmentWithContext(ctx, createSegmentOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(operationErr.Error()).To(ContainSubstring("deadline exceeded"))
serverSleepTime = time.Duration(0)
// Disable retries and test again
appConfigurationService.DisableRetries()
result, response, operationErr = appConfigurationService.CreateSegment(createSegmentOptionsModel)
Expect(operationErr).To(BeNil())
Expect(response).ToNot(BeNil())
Expect(result).ToNot(BeNil())
// Re-test the timeout error with retries disabled
ctx, cancelFunc2 := context.WithTimeout(context.Background(), 80*time.Millisecond)
defer cancelFunc2()
serverSleepTime = 100 * time.Millisecond
_, _, operationErr = appConfigurationService.CreateSegmentWithContext(ctx, createSegmentOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(operationErr.Error()).To(ContainSubstring("deadline exceeded"))
serverSleepTime = time.Duration(0)
})
It(`Invoke CreateSegment with error: Operation request error`, func() {
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1(&appconfigurationv1.AppConfigurationV1Options{
URL: testServer.URL,
Authenticator: &core.NoAuthAuthenticator{},
})
Expect(serviceErr).To(BeNil())
Expect(appConfigurationService).ToNot(BeNil())
// Construct an instance of the Rule model
ruleModel := new(appconfigurationv1.Rule)
ruleModel.AttributeName = core.StringPtr("email")
ruleModel.Operator = core.StringPtr("endsWith")
ruleModel.Values = []string{"testString"}
// Construct an instance of the CreateSegmentOptions model
createSegmentOptionsModel := new(appconfigurationv1.CreateSegmentOptions)
createSegmentOptionsModel.Name = core.StringPtr("Beta Users")
createSegmentOptionsModel.SegmentID = core.StringPtr("beta-users")
createSegmentOptionsModel.Description = core.StringPtr("Segment containing the beta users")
createSegmentOptionsModel.Tags = core.StringPtr("version: 1.1, stage")
createSegmentOptionsModel.Rules = []appconfigurationv1.Rule{*ruleModel}
createSegmentOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"}
// Invoke operation with empty URL (negative test)
err := appConfigurationService.SetServiceURL("")
Expect(err).To(BeNil())
result, response, operationErr := appConfigurationService.CreateSegment(createSegmentOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(operationErr.Error()).To(ContainSubstring(core.ERRORMSG_SERVICE_URL_MISSING))
Expect(response).To(BeNil())
Expect(result).To(BeNil())
})
AfterEach(func() {
testServer.Close()
})
})
})
Describe(`UpdateSegment(updateSegmentOptions *UpdateSegmentOptions) - Operation response error`, func() {
updateSegmentPath := "/segments/testString"
Context(`Using mock server endpoint`, func() {
BeforeEach(func() {
testServer = httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
defer GinkgoRecover()
// Verify the contents of the request
Expect(req.URL.EscapedPath()).To(Equal(updateSegmentPath))
Expect(req.Method).To(Equal("PUT"))
res.Header().Set("Content-type", "application/json")
res.WriteHeader(200)
fmt.Fprintf(res, `} this is not valid json {`)
}))
})
It(`Invoke UpdateSegment with error: Operation response processing error`, func() {
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1(&appconfigurationv1.AppConfigurationV1Options{
URL: testServer.URL,
Authenticator: &core.NoAuthAuthenticator{},
})
Expect(serviceErr).To(BeNil())
Expect(appConfigurationService).ToNot(BeNil())
// Construct an instance of the Rule model
ruleModel := new(appconfigurationv1.Rule)
ruleModel.AttributeName = core.StringPtr("testString")
ruleModel.Operator = core.StringPtr("is")
ruleModel.Values = []string{"testString"}
// Construct an instance of the UpdateSegmentOptions model
updateSegmentOptionsModel := new(appconfigurationv1.UpdateSegmentOptions)
updateSegmentOptionsModel.SegmentID = core.StringPtr("testString")
updateSegmentOptionsModel.Name = core.StringPtr("testString")
updateSegmentOptionsModel.Description = core.StringPtr("testString")
updateSegmentOptionsModel.Tags = core.StringPtr("testString")
updateSegmentOptionsModel.Rules = []appconfigurationv1.Rule{*ruleModel}
updateSegmentOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"}
// Expect response parsing to fail since we are receiving a text/plain response
result, response, operationErr := appConfigurationService.UpdateSegment(updateSegmentOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(response).ToNot(BeNil())
Expect(result).To(BeNil())
// Enable retries and test again
appConfigurationService.EnableRetries(0, 0)
result, response, operationErr = appConfigurationService.UpdateSegment(updateSegmentOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(response).ToNot(BeNil())
Expect(result).To(BeNil())
})
AfterEach(func() {
testServer.Close()
})
})
})
Describe(`UpdateSegment(updateSegmentOptions *UpdateSegmentOptions)`, func() {
updateSegmentPath := "/segments/testString"
var serverSleepTime time.Duration
Context(`Using mock server endpoint`, func() {
BeforeEach(func() {
serverSleepTime = 0
testServer = httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
defer GinkgoRecover()
// Verify the contents of the request
Expect(req.URL.EscapedPath()).To(Equal(updateSegmentPath))
Expect(req.Method).To(Equal("PUT"))
// For gzip-disabled operation, verify Content-Encoding is not set.
Expect(req.Header.Get("Content-Encoding")).To(BeEmpty())
// If there is a body, then make sure we can read it
bodyBuf := new(bytes.Buffer)
if req.Header.Get("Content-Encoding") == "gzip" {
body, err := core.NewGzipDecompressionReader(req.Body)
Expect(err).To(BeNil())
_, err = bodyBuf.ReadFrom(body)
Expect(err).To(BeNil())
} else {
_, err := bodyBuf.ReadFrom(req.Body)
Expect(err).To(BeNil())
}
fmt.Fprintf(GinkgoWriter, " Request body: %s", bodyBuf.String())
// Sleep a short time to support a timeout test
time.Sleep(serverSleepTime)
// Set mock response
res.Header().Set("Content-type", "application/json")
res.WriteHeader(200)
fmt.Fprintf(res, "%s", `{"name": "Name", "segment_id": "SegmentID", "description": "Description", "tags": "Tags", "rules": [{"attribute_name": "AttributeName", "operator": "is", "values": ["Values"]}], "created_time": "2019-01-01T12:00:00", "updated_time": "2019-01-01T12:00:00", "href": "Href", "features": [{"feature_id": "FeatureID", "name": "Name"}], "properties": [{"property_id": "PropertyID", "name": "Name"}]}`)
}))
})
It(`Invoke UpdateSegment successfully`, func() {
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1(&appconfigurationv1.AppConfigurationV1Options{
URL: testServer.URL,
Authenticator: &core.NoAuthAuthenticator{},
})
Expect(serviceErr).To(BeNil())
Expect(appConfigurationService).ToNot(BeNil())
appConfigurationService.EnableRetries(0, 0)
// Invoke operation with nil options model (negative test)
result, response, operationErr := appConfigurationService.UpdateSegment(nil)
Expect(operationErr).NotTo(BeNil())
Expect(response).To(BeNil())
Expect(result).To(BeNil())
// Construct an instance of the Rule model
ruleModel := new(appconfigurationv1.Rule)
ruleModel.AttributeName = core.StringPtr("testString")
ruleModel.Operator = core.StringPtr("is")
ruleModel.Values = []string{"testString"}
// Construct an instance of the UpdateSegmentOptions model
updateSegmentOptionsModel := new(appconfigurationv1.UpdateSegmentOptions)
updateSegmentOptionsModel.SegmentID = core.StringPtr("testString")
updateSegmentOptionsModel.Name = core.StringPtr("testString")
updateSegmentOptionsModel.Description = core.StringPtr("testString")
updateSegmentOptionsModel.Tags = core.StringPtr("testString")
updateSegmentOptionsModel.Rules = []appconfigurationv1.Rule{*ruleModel}
updateSegmentOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"}
// Invoke operation with valid options model (positive test)
result, response, operationErr = appConfigurationService.UpdateSegment(updateSegmentOptionsModel)
Expect(operationErr).To(BeNil())
Expect(response).ToNot(BeNil())
Expect(result).ToNot(BeNil())
// Invoke operation with a Context to test a timeout error
ctx, cancelFunc := context.WithTimeout(context.Background(), 80*time.Millisecond)
defer cancelFunc()
serverSleepTime = 100 * time.Millisecond
_, _, operationErr = appConfigurationService.UpdateSegmentWithContext(ctx, updateSegmentOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(operationErr.Error()).To(ContainSubstring("deadline exceeded"))
serverSleepTime = time.Duration(0)
// Disable retries and test again
appConfigurationService.DisableRetries()
result, response, operationErr = appConfigurationService.UpdateSegment(updateSegmentOptionsModel)
Expect(operationErr).To(BeNil())
Expect(response).ToNot(BeNil())
Expect(result).ToNot(BeNil())
// Re-test the timeout error with retries disabled
ctx, cancelFunc2 := context.WithTimeout(context.Background(), 80*time.Millisecond)
defer cancelFunc2()
serverSleepTime = 100 * time.Millisecond
_, _, operationErr = appConfigurationService.UpdateSegmentWithContext(ctx, updateSegmentOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(operationErr.Error()).To(ContainSubstring("deadline exceeded"))
serverSleepTime = time.Duration(0)
})
It(`Invoke UpdateSegment with error: Operation validation and request error`, func() {
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1(&appconfigurationv1.AppConfigurationV1Options{
URL: testServer.URL,
Authenticator: &core.NoAuthAuthenticator{},
})
Expect(serviceErr).To(BeNil())
Expect(appConfigurationService).ToNot(BeNil())
// Construct an instance of the Rule model
ruleModel := new(appconfigurationv1.Rule)
ruleModel.AttributeName = core.StringPtr("testString")
ruleModel.Operator = core.StringPtr("is")
ruleModel.Values = []string{"testString"}
// Construct an instance of the UpdateSegmentOptions model
updateSegmentOptionsModel := new(appconfigurationv1.UpdateSegmentOptions)
updateSegmentOptionsModel.SegmentID = core.StringPtr("testString")
updateSegmentOptionsModel.Name = core.StringPtr("testString")
updateSegmentOptionsModel.Description = core.StringPtr("testString")
updateSegmentOptionsModel.Tags = core.StringPtr("testString")
updateSegmentOptionsModel.Rules = []appconfigurationv1.Rule{*ruleModel}
updateSegmentOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"}
// Invoke operation with empty URL (negative test)
err := appConfigurationService.SetServiceURL("")
Expect(err).To(BeNil())
result, response, operationErr := appConfigurationService.UpdateSegment(updateSegmentOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(operationErr.Error()).To(ContainSubstring(core.ERRORMSG_SERVICE_URL_MISSING))
Expect(response).To(BeNil())
Expect(result).To(BeNil())
// Construct a second instance of the UpdateSegmentOptions model with no property values
updateSegmentOptionsModelNew := new(appconfigurationv1.UpdateSegmentOptions)
// Invoke operation with invalid model (negative test)
result, response, operationErr = appConfigurationService.UpdateSegment(updateSegmentOptionsModelNew)
Expect(operationErr).ToNot(BeNil())
Expect(response).To(BeNil())
Expect(result).To(BeNil())
})
AfterEach(func() {
testServer.Close()
})
})
})
Describe(`GetSegment(getSegmentOptions *GetSegmentOptions) - Operation response error`, func() {
getSegmentPath := "/segments/testString"
Context(`Using mock server endpoint`, func() {
BeforeEach(func() {
testServer = httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
defer GinkgoRecover()
// Verify the contents of the request
Expect(req.URL.EscapedPath()).To(Equal(getSegmentPath))
Expect(req.Method).To(Equal("GET"))
res.Header().Set("Content-type", "application/json")
res.WriteHeader(200)
fmt.Fprintf(res, `} this is not valid json {`)
}))
})
It(`Invoke GetSegment with error: Operation response processing error`, func() {
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1(&appconfigurationv1.AppConfigurationV1Options{
URL: testServer.URL,
Authenticator: &core.NoAuthAuthenticator{},
})
Expect(serviceErr).To(BeNil())
Expect(appConfigurationService).ToNot(BeNil())
// Construct an instance of the GetSegmentOptions model
getSegmentOptionsModel := new(appconfigurationv1.GetSegmentOptions)
getSegmentOptionsModel.SegmentID = core.StringPtr("testString")
getSegmentOptionsModel.Include = []string{"features"}
getSegmentOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"}
// Expect response parsing to fail since we are receiving a text/plain response
result, response, operationErr := appConfigurationService.GetSegment(getSegmentOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(response).ToNot(BeNil())
Expect(result).To(BeNil())
// Enable retries and test again
appConfigurationService.EnableRetries(0, 0)
result, response, operationErr = appConfigurationService.GetSegment(getSegmentOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(response).ToNot(BeNil())
Expect(result).To(BeNil())
})
AfterEach(func() {
testServer.Close()
})
})
})
Describe(`GetSegment(getSegmentOptions *GetSegmentOptions)`, func() {
getSegmentPath := "/segments/testString"
var serverSleepTime time.Duration
Context(`Using mock server endpoint`, func() {
BeforeEach(func() {
serverSleepTime = 0
testServer = httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
defer GinkgoRecover()
// Verify the contents of the request
Expect(req.URL.EscapedPath()).To(Equal(getSegmentPath))
Expect(req.Method).To(Equal("GET"))
// Sleep a short time to support a timeout test
time.Sleep(serverSleepTime)
// Set mock response
res.Header().Set("Content-type", "application/json")
res.WriteHeader(200)
fmt.Fprintf(res, "%s", `{"name": "Name", "segment_id": "SegmentID", "description": "Description", "tags": "Tags", "rules": [{"attribute_name": "AttributeName", "operator": "is", "values": ["Values"]}], "created_time": "2019-01-01T12:00:00", "updated_time": "2019-01-01T12:00:00", "href": "Href", "features": [{"feature_id": "FeatureID", "name": "Name"}], "properties": [{"property_id": "PropertyID", "name": "Name"}]}`)
}))
})
It(`Invoke GetSegment successfully`, func() {
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1(&appconfigurationv1.AppConfigurationV1Options{
URL: testServer.URL,
Authenticator: &core.NoAuthAuthenticator{},
})
Expect(serviceErr).To(BeNil())
Expect(appConfigurationService).ToNot(BeNil())
appConfigurationService.EnableRetries(0, 0)
// Invoke operation with nil options model (negative test)
result, response, operationErr := appConfigurationService.GetSegment(nil)
Expect(operationErr).NotTo(BeNil())
Expect(response).To(BeNil())
Expect(result).To(BeNil())
// Construct an instance of the GetSegmentOptions model
getSegmentOptionsModel := new(appconfigurationv1.GetSegmentOptions)
getSegmentOptionsModel.SegmentID = core.StringPtr("testString")
getSegmentOptionsModel.Include = []string{"features"}
getSegmentOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"}
// Invoke operation with valid options model (positive test)
result, response, operationErr = appConfigurationService.GetSegment(getSegmentOptionsModel)
Expect(operationErr).To(BeNil())
Expect(response).ToNot(BeNil())
Expect(result).ToNot(BeNil())
// Invoke operation with a Context to test a timeout error
ctx, cancelFunc := context.WithTimeout(context.Background(), 80*time.Millisecond)
defer cancelFunc()
serverSleepTime = 100 * time.Millisecond
_, _, operationErr = appConfigurationService.GetSegmentWithContext(ctx, getSegmentOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(operationErr.Error()).To(ContainSubstring("deadline exceeded"))
serverSleepTime = time.Duration(0)
// Disable retries and test again
appConfigurationService.DisableRetries()
result, response, operationErr = appConfigurationService.GetSegment(getSegmentOptionsModel)
Expect(operationErr).To(BeNil())
Expect(response).ToNot(BeNil())
Expect(result).ToNot(BeNil())
// Re-test the timeout error with retries disabled
ctx, cancelFunc2 := context.WithTimeout(context.Background(), 80*time.Millisecond)
defer cancelFunc2()
serverSleepTime = 100 * time.Millisecond
_, _, operationErr = appConfigurationService.GetSegmentWithContext(ctx, getSegmentOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(operationErr.Error()).To(ContainSubstring("deadline exceeded"))
serverSleepTime = time.Duration(0)
})
It(`Invoke GetSegment with error: Operation validation and request error`, func() {
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1(&appconfigurationv1.AppConfigurationV1Options{
URL: testServer.URL,
Authenticator: &core.NoAuthAuthenticator{},
})
Expect(serviceErr).To(BeNil())
Expect(appConfigurationService).ToNot(BeNil())
// Construct an instance of the GetSegmentOptions model
getSegmentOptionsModel := new(appconfigurationv1.GetSegmentOptions)
getSegmentOptionsModel.SegmentID = core.StringPtr("testString")
getSegmentOptionsModel.Include = []string{"features"}
getSegmentOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"}
// Invoke operation with empty URL (negative test)
err := appConfigurationService.SetServiceURL("")
Expect(err).To(BeNil())
result, response, operationErr := appConfigurationService.GetSegment(getSegmentOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(operationErr.Error()).To(ContainSubstring(core.ERRORMSG_SERVICE_URL_MISSING))
Expect(response).To(BeNil())
Expect(result).To(BeNil())
// Construct a second instance of the GetSegmentOptions model with no property values
getSegmentOptionsModelNew := new(appconfigurationv1.GetSegmentOptions)
// Invoke operation with invalid model (negative test)
result, response, operationErr = appConfigurationService.GetSegment(getSegmentOptionsModelNew)
Expect(operationErr).ToNot(BeNil())
Expect(response).To(BeNil())
Expect(result).To(BeNil())
})
AfterEach(func() {
testServer.Close()
})
})
})
Describe(`DeleteSegment(deleteSegmentOptions *DeleteSegmentOptions)`, func() {
deleteSegmentPath := "/segments/testString"
Context(`Using mock server endpoint`, func() {
BeforeEach(func() {
testServer = httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
defer GinkgoRecover()
// Verify the contents of the request
Expect(req.URL.EscapedPath()).To(Equal(deleteSegmentPath))
Expect(req.Method).To(Equal("DELETE"))
res.WriteHeader(204)
}))
})
It(`Invoke DeleteSegment successfully`, func() {
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1(&appconfigurationv1.AppConfigurationV1Options{
URL: testServer.URL,
Authenticator: &core.NoAuthAuthenticator{},
})
Expect(serviceErr).To(BeNil())
Expect(appConfigurationService).ToNot(BeNil())
appConfigurationService.EnableRetries(0, 0)
// Invoke operation with nil options model (negative test)
response, operationErr := appConfigurationService.DeleteSegment(nil)
Expect(operationErr).NotTo(BeNil())
Expect(response).To(BeNil())
// Construct an instance of the DeleteSegmentOptions model
deleteSegmentOptionsModel := new(appconfigurationv1.DeleteSegmentOptions)
deleteSegmentOptionsModel.SegmentID = core.StringPtr("testString")
deleteSegmentOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"}
// Invoke operation with valid options model (positive test)
response, operationErr = appConfigurationService.DeleteSegment(deleteSegmentOptionsModel)
Expect(operationErr).To(BeNil())
Expect(response).ToNot(BeNil())
// Disable retries and test again
appConfigurationService.DisableRetries()
response, operationErr = appConfigurationService.DeleteSegment(deleteSegmentOptionsModel)
Expect(operationErr).To(BeNil())
Expect(response).ToNot(BeNil())
})
It(`Invoke DeleteSegment with error: Operation validation and request error`, func() {
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1(&appconfigurationv1.AppConfigurationV1Options{
URL: testServer.URL,
Authenticator: &core.NoAuthAuthenticator{},
})
Expect(serviceErr).To(BeNil())
Expect(appConfigurationService).ToNot(BeNil())
// Construct an instance of the DeleteSegmentOptions model
deleteSegmentOptionsModel := new(appconfigurationv1.DeleteSegmentOptions)
deleteSegmentOptionsModel.SegmentID = core.StringPtr("testString")
deleteSegmentOptionsModel.Headers = map[string]string{"x-custom-header": "x-custom-value"}
// Invoke operation with empty URL (negative test)
err := appConfigurationService.SetServiceURL("")
Expect(err).To(BeNil())
response, operationErr := appConfigurationService.DeleteSegment(deleteSegmentOptionsModel)
Expect(operationErr).ToNot(BeNil())
Expect(operationErr.Error()).To(ContainSubstring(core.ERRORMSG_SERVICE_URL_MISSING))
Expect(response).To(BeNil())
// Construct a second instance of the DeleteSegmentOptions model with no property values
deleteSegmentOptionsModelNew := new(appconfigurationv1.DeleteSegmentOptions)
// Invoke operation with invalid model (negative test)
response, operationErr = appConfigurationService.DeleteSegment(deleteSegmentOptionsModelNew)
Expect(operationErr).ToNot(BeNil())
Expect(response).To(BeNil())
})
AfterEach(func() {
testServer.Close()
})
})
})
Describe(`Service constructor tests`, func() {
It(`Instantiate service client`, func() {
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1(&appconfigurationv1.AppConfigurationV1Options{
Authenticator: &core.NoAuthAuthenticator{},
})
Expect(appConfigurationService).ToNot(BeNil())
Expect(serviceErr).To(BeNil())
})
It(`Instantiate service client with error: Invalid URL`, func() {
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1(&appconfigurationv1.AppConfigurationV1Options{
URL: "{BAD_URL_STRING",
})
Expect(appConfigurationService).To(BeNil())
Expect(serviceErr).ToNot(BeNil())
})
It(`Instantiate service client with error: Invalid Auth`, func() {
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1(&appconfigurationv1.AppConfigurationV1Options{
URL: "https://appconfigurationv1/api",
Authenticator: &core.BasicAuthenticator{
Username: "",
Password: "",
},
})
Expect(appConfigurationService).To(BeNil())
Expect(serviceErr).ToNot(BeNil())
})
})
Describe(`Service constructor tests using external config`, func() {
Context(`Using external config, construct service client instances`, func() {
// Map containing environment variables used in testing.
var testEnvironment = map[string]string{
"APP_CONFIGURATION_URL": "https://appconfigurationv1/api",
"APP_CONFIGURATION_AUTH_TYPE": "noauth",
}
It(`Create service client using external config successfully`, func() {
SetTestEnvironment(testEnvironment)
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1UsingExternalConfig(&appconfigurationv1.AppConfigurationV1Options{})
Expect(appConfigurationService).ToNot(BeNil())
Expect(serviceErr).To(BeNil())
ClearTestEnvironment(testEnvironment)
clone := appConfigurationService.Clone()
Expect(clone).ToNot(BeNil())
Expect(clone.Service != appConfigurationService.Service).To(BeTrue())
Expect(clone.GetServiceURL()).To(Equal(appConfigurationService.GetServiceURL()))
Expect(clone.Service.Options.Authenticator).To(Equal(appConfigurationService.Service.Options.Authenticator))
})
It(`Create service client using external config and set url from constructor successfully`, func() {
SetTestEnvironment(testEnvironment)
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1UsingExternalConfig(&appconfigurationv1.AppConfigurationV1Options{
URL: "https://testService/api",
})
Expect(appConfigurationService).ToNot(BeNil())
Expect(serviceErr).To(BeNil())
Expect(appConfigurationService.Service.GetServiceURL()).To(Equal("https://testService/api"))
ClearTestEnvironment(testEnvironment)
clone := appConfigurationService.Clone()
Expect(clone).ToNot(BeNil())
Expect(clone.Service != appConfigurationService.Service).To(BeTrue())
Expect(clone.GetServiceURL()).To(Equal(appConfigurationService.GetServiceURL()))
Expect(clone.Service.Options.Authenticator).To(Equal(appConfigurationService.Service.Options.Authenticator))
})
It(`Create service client using external config and set url programatically successfully`, func() {
SetTestEnvironment(testEnvironment)
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1UsingExternalConfig(&appconfigurationv1.AppConfigurationV1Options{})
err := appConfigurationService.SetServiceURL("https://testService/api")
Expect(err).To(BeNil())
Expect(appConfigurationService).ToNot(BeNil())
Expect(serviceErr).To(BeNil())
Expect(appConfigurationService.Service.GetServiceURL()).To(Equal("https://testService/api"))
ClearTestEnvironment(testEnvironment)
clone := appConfigurationService.Clone()
Expect(clone).ToNot(BeNil())
Expect(clone.Service != appConfigurationService.Service).To(BeTrue())
Expect(clone.GetServiceURL()).To(Equal(appConfigurationService.GetServiceURL()))
Expect(clone.Service.Options.Authenticator).To(Equal(appConfigurationService.Service.Options.Authenticator))
})
})
Context(`Using external config, construct service client instances with error: Invalid Auth`, func() {
// Map containing environment variables used in testing.
var testEnvironment = map[string]string{
"APP_CONFIGURATION_URL": "https://appconfigurationv1/api",
"APP_CONFIGURATION_AUTH_TYPE": "someOtherAuth",
}
SetTestEnvironment(testEnvironment)
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1UsingExternalConfig(&appconfigurationv1.AppConfigurationV1Options{})
It(`Instantiate service client with error`, func() {
Expect(appConfigurationService).To(BeNil())
Expect(serviceErr).ToNot(BeNil())
ClearTestEnvironment(testEnvironment)
})
})
Context(`Using external config, construct service client instances with error: Invalid URL`, func() {
// Map containing environment variables used in testing.
var testEnvironment = map[string]string{
"APP_CONFIGURATION_AUTH_TYPE": "NOAuth",
}
SetTestEnvironment(testEnvironment)
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1UsingExternalConfig(&appconfigurationv1.AppConfigurationV1Options{
URL: "{BAD_URL_STRING",
})
It(`Instantiate service client with error`, func() {
Expect(appConfigurationService).To(BeNil())
Expect(serviceErr).ToNot(BeNil())
ClearTestEnvironment(testEnvironment)
})
})
})
Describe(`Regional endpoint tests`, func() {
It(`GetServiceURLForRegion(region string)`, func() {
var url string
var err error
url, err = appconfigurationv1.GetServiceURLForRegion("INVALID_REGION")
Expect(url).To(BeEmpty())
Expect(err).ToNot(BeNil())
fmt.Fprintf(GinkgoWriter, "Expected error: %s\n", err.Error())
})
})
Describe(`Service constructor tests`, func() {
It(`Instantiate service client`, func() {
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1(&appconfigurationv1.AppConfigurationV1Options{
Authenticator: &core.NoAuthAuthenticator{},
})
Expect(appConfigurationService).ToNot(BeNil())
Expect(serviceErr).To(BeNil())
})
It(`Instantiate service client with error: Invalid URL`, func() {
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1(&appconfigurationv1.AppConfigurationV1Options{
URL: "{BAD_URL_STRING",
})
Expect(appConfigurationService).To(BeNil())
Expect(serviceErr).ToNot(BeNil())
})
It(`Instantiate service client with error: Invalid Auth`, func() {
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1(&appconfigurationv1.AppConfigurationV1Options{
URL: "https://appconfigurationv1/api",
Authenticator: &core.BasicAuthenticator{
Username: "",
Password: "",
},
})
Expect(appConfigurationService).To(BeNil())
Expect(serviceErr).ToNot(BeNil())
})
})
Describe(`Service constructor tests using external config`, func() {
Context(`Using external config, construct service client instances`, func() {
// Map containing environment variables used in testing.
var testEnvironment = map[string]string{
"APP_CONFIGURATION_URL": "https://appconfigurationv1/api",
"APP_CONFIGURATION_AUTH_TYPE": "noauth",
}
It(`Create service client using external config successfully`, func() {
SetTestEnvironment(testEnvironment)
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1UsingExternalConfig(&appconfigurationv1.AppConfigurationV1Options{})
Expect(appConfigurationService).ToNot(BeNil())
Expect(serviceErr).To(BeNil())
ClearTestEnvironment(testEnvironment)
clone := appConfigurationService.Clone()
Expect(clone).ToNot(BeNil())
Expect(clone.Service != appConfigurationService.Service).To(BeTrue())
Expect(clone.GetServiceURL()).To(Equal(appConfigurationService.GetServiceURL()))
Expect(clone.Service.Options.Authenticator).To(Equal(appConfigurationService.Service.Options.Authenticator))
})
It(`Create service client using external config and set url from constructor successfully`, func() {
SetTestEnvironment(testEnvironment)
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1UsingExternalConfig(&appconfigurationv1.AppConfigurationV1Options{
URL: "https://testService/api",
})
Expect(appConfigurationService).ToNot(BeNil())
Expect(serviceErr).To(BeNil())
Expect(appConfigurationService.Service.GetServiceURL()).To(Equal("https://testService/api"))
ClearTestEnvironment(testEnvironment)
clone := appConfigurationService.Clone()
Expect(clone).ToNot(BeNil())
Expect(clone.Service != appConfigurationService.Service).To(BeTrue())
Expect(clone.GetServiceURL()).To(Equal(appConfigurationService.GetServiceURL()))
Expect(clone.Service.Options.Authenticator).To(Equal(appConfigurationService.Service.Options.Authenticator))
})
It(`Create service client using external config and set url programatically successfully`, func() {
SetTestEnvironment(testEnvironment)
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1UsingExternalConfig(&appconfigurationv1.AppConfigurationV1Options{})
err := appConfigurationService.SetServiceURL("https://testService/api")
Expect(err).To(BeNil())
Expect(appConfigurationService).ToNot(BeNil())
Expect(serviceErr).To(BeNil())
Expect(appConfigurationService.Service.GetServiceURL()).To(Equal("https://testService/api"))
ClearTestEnvironment(testEnvironment)
clone := appConfigurationService.Clone()
Expect(clone).ToNot(BeNil())
Expect(clone.Service != appConfigurationService.Service).To(BeTrue())
Expect(clone.GetServiceURL()).To(Equal(appConfigurationService.GetServiceURL()))
Expect(clone.Service.Options.Authenticator).To(Equal(appConfigurationService.Service.Options.Authenticator))
})
})
Context(`Using external config, construct service client instances with error: Invalid Auth`, func() {
// Map containing environment variables used in testing.
var testEnvironment = map[string]string{
"APP_CONFIGURATION_URL": "https://appconfigurationv1/api",
"APP_CONFIGURATION_AUTH_TYPE": "someOtherAuth",
}
SetTestEnvironment(testEnvironment)
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1UsingExternalConfig(&appconfigurationv1.AppConfigurationV1Options{})
It(`Instantiate service client with error`, func() {
Expect(appConfigurationService).To(BeNil())
Expect(serviceErr).ToNot(BeNil())
ClearTestEnvironment(testEnvironment)
})
})
Context(`Using external config, construct service client instances with error: Invalid URL`, func() {
// Map containing environment variables used in testing.
var testEnvironment = map[string]string{
"APP_CONFIGURATION_AUTH_TYPE": "NOAuth",
}
SetTestEnvironment(testEnvironment)
appConfigurationService, serviceErr := appconfigurationv1.NewAppConfigurationV1UsingExternalConfig(&appconfigurationv1.AppConfigurationV1Options{
URL: "{BAD_URL_STRING",
})
It(`Instantiate service client with error`, func() {
Expect(appConfigurationService).To(BeNil())
Expect(serviceErr).ToNot(BeNil())
ClearTestEnvironment(testEnvironment)
})
})
})
Describe(`Regional endpoint tests`, func() {
It(`GetServiceURLForRegion(region string)`, func() {
var url string
var err error
url, err = appconfigurationv1.GetServiceURLForRegion("INVALID_REGION")
Expect(url).To(BeEmpty())
Expect(err).ToNot(BeNil())
fmt.Fprintf(GinkgoWriter, "Expected error: %s\n", err.Error())
})
})
Describe(`Model constructor tests`, func() {
Context(`Using a service client instance`, func() {
appConfigurationService, _ := appconfigurationv1.NewAppConfigurationV1(&appconfigurationv1.AppConfigurationV1Options{
URL: "http://appconfigurationv1modelgenerator.com",
Authenticator: &core.NoAuthAuthenticator{},
})
It(`Invoke NewCollection successfully`, func() {
name := "testString"
collectionID := "testString"
model, err := appConfigurationService.NewCollection(name, collectionID)
Expect(model).ToNot(BeNil())
Expect(err).To(BeNil())
})
It(`Invoke NewCollectionRef successfully`, func() {
collectionID := "testString"
model, err := appConfigurationService.NewCollectionRef(collectionID)
Expect(model).ToNot(BeNil())
Expect(err).To(BeNil())
})
It(`Invoke NewCreateCollectionOptions successfully`, func() {
// Construct an instance of the CreateCollectionOptions model
createCollectionOptionsName := "Web App Collection"
createCollectionOptionsCollectionID := "web-app-collection"
createCollectionOptionsModel := appConfigurationService.NewCreateCollectionOptions(createCollectionOptionsName, createCollectionOptionsCollectionID)
createCollectionOptionsModel.SetName("Web App Collection")
createCollectionOptionsModel.SetCollectionID("web-app-collection")
createCollectionOptionsModel.SetDescription("Collection for Web application")
createCollectionOptionsModel.SetTags("version: 1.1, pre-release")
createCollectionOptionsModel.SetHeaders(map[string]string{"foo": "bar"})
Expect(createCollectionOptionsModel).ToNot(BeNil())
Expect(createCollectionOptionsModel.Name).To(Equal(core.StringPtr("Web App Collection")))
Expect(createCollectionOptionsModel.CollectionID).To(Equal(core.StringPtr("web-app-collection")))
Expect(createCollectionOptionsModel.Description).To(Equal(core.StringPtr("Collection for Web application")))
Expect(createCollectionOptionsModel.Tags).To(Equal(core.StringPtr("version: 1.1, pre-release")))
Expect(createCollectionOptionsModel.Headers).To(Equal(map[string]string{"foo": "bar"}))
})
It(`Invoke NewCreateEnvironmentOptions successfully`, func() {
// Construct an instance of the CreateEnvironmentOptions model
createEnvironmentOptionsName := "Dev environment"
createEnvironmentOptionsEnvironmentID := "dev-environment"
createEnvironmentOptionsModel := appConfigurationService.NewCreateEnvironmentOptions(createEnvironmentOptionsName, createEnvironmentOptionsEnvironmentID)
createEnvironmentOptionsModel.SetName("Dev environment")
createEnvironmentOptionsModel.SetEnvironmentID("dev-environment")
createEnvironmentOptionsModel.SetDescription("Dev environment description")
createEnvironmentOptionsModel.SetTags("development")
createEnvironmentOptionsModel.SetColorCode("#FDD13A")
createEnvironmentOptionsModel.SetHeaders(map[string]string{"foo": "bar"})
Expect(createEnvironmentOptionsModel).ToNot(BeNil())
Expect(createEnvironmentOptionsModel.Name).To(Equal(core.StringPtr("Dev environment")))
Expect(createEnvironmentOptionsModel.EnvironmentID).To(Equal(core.StringPtr("dev-environment")))
Expect(createEnvironmentOptionsModel.Description).To(Equal(core.StringPtr("Dev environment description")))
Expect(createEnvironmentOptionsModel.Tags).To(Equal(core.StringPtr("development")))
Expect(createEnvironmentOptionsModel.ColorCode).To(Equal(core.StringPtr("#FDD13A")))
Expect(createEnvironmentOptionsModel.Headers).To(Equal(map[string]string{"foo": "bar"}))
})
It(`Invoke NewCreateFeatureOptions successfully`, func() {
// Construct an instance of the TargetSegments model
targetSegmentsModel := new(appconfigurationv1.TargetSegments)
Expect(targetSegmentsModel).ToNot(BeNil())
targetSegmentsModel.Segments = []string{"testString"}
Expect(targetSegmentsModel.Segments).To(Equal([]string{"testString"}))
// Construct an instance of the SegmentRule model
segmentRuleModel := new(appconfigurationv1.SegmentRule)
Expect(segmentRuleModel).ToNot(BeNil())
segmentRuleModel.Rules = []appconfigurationv1.TargetSegments{*targetSegmentsModel}
segmentRuleModel.Value = core.StringPtr("true")
segmentRuleModel.Order = core.Int64Ptr(int64(1))
Expect(segmentRuleModel.Rules).To(Equal([]appconfigurationv1.TargetSegments{*targetSegmentsModel}))
Expect(segmentRuleModel.Value).To(Equal(core.StringPtr("true")))
Expect(segmentRuleModel.Order).To(Equal(core.Int64Ptr(int64(1))))
// Construct an instance of the CollectionRef model
collectionRefModel := new(appconfigurationv1.CollectionRef)
Expect(collectionRefModel).ToNot(BeNil())
collectionRefModel.CollectionID = core.StringPtr("ghzinc")
Expect(collectionRefModel.CollectionID).To(Equal(core.StringPtr("ghzinc")))
// Construct an instance of the CreateFeatureOptions model
environmentID := "testString"
createFeatureOptionsName := "Cycle Rentals"
createFeatureOptionsFeatureID := "cycle-rentals"
createFeatureOptionsType := "BOOLEAN"
createFeatureOptionsEnabledValue := core.StringPtr("true")
createFeatureOptionsDisabledValue := core.StringPtr("false")
createFeatureOptionsModel := appConfigurationService.NewCreateFeatureOptions(environmentID, createFeatureOptionsName, createFeatureOptionsFeatureID, createFeatureOptionsType, createFeatureOptionsEnabledValue, createFeatureOptionsDisabledValue)
createFeatureOptionsModel.SetEnvironmentID("testString")
createFeatureOptionsModel.SetName("Cycle Rentals")
createFeatureOptionsModel.SetFeatureID("cycle-rentals")
createFeatureOptionsModel.SetType("BOOLEAN")
createFeatureOptionsModel.SetEnabledValue(core.StringPtr("true"))
createFeatureOptionsModel.SetDisabledValue(core.StringPtr("false"))
createFeatureOptionsModel.SetDescription("Feature flag to enable Cycle Rentals")
createFeatureOptionsModel.SetEnabled(true)
createFeatureOptionsModel.SetTags("version: 1.1, pre-release")
createFeatureOptionsModel.SetSegmentRules([]appconfigurationv1.SegmentRule{*segmentRuleModel})
createFeatureOptionsModel.SetCollections([]appconfigurationv1.CollectionRef{*collectionRefModel})
createFeatureOptionsModel.SetHeaders(map[string]string{"foo": "bar"})
Expect(createFeatureOptionsModel).ToNot(BeNil())
Expect(createFeatureOptionsModel.EnvironmentID).To(Equal(core.StringPtr("testString")))
Expect(createFeatureOptionsModel.Name).To(Equal(core.StringPtr("Cycle Rentals")))
Expect(createFeatureOptionsModel.FeatureID).To(Equal(core.StringPtr("cycle-rentals")))
Expect(createFeatureOptionsModel.Type).To(Equal(core.StringPtr("BOOLEAN")))
Expect(createFeatureOptionsModel.EnabledValue).To(Equal(core.StringPtr("true")))
Expect(createFeatureOptionsModel.DisabledValue).To(Equal(core.StringPtr("false")))
Expect(createFeatureOptionsModel.Description).To(Equal(core.StringPtr("Feature flag to enable Cycle Rentals")))
Expect(createFeatureOptionsModel.Enabled).To(Equal(core.BoolPtr(true)))
Expect(createFeatureOptionsModel.Tags).To(Equal(core.StringPtr("version: 1.1, pre-release")))
Expect(createFeatureOptionsModel.SegmentRules).To(Equal([]appconfigurationv1.SegmentRule{*segmentRuleModel}))
Expect(createFeatureOptionsModel.Collections).To(Equal([]appconfigurationv1.CollectionRef{*collectionRefModel}))
Expect(createFeatureOptionsModel.Headers).To(Equal(map[string]string{"foo": "bar"}))
})
It(`Invoke NewCreatePropertyOptions successfully`, func() {
// Construct an instance of the TargetSegments model
targetSegmentsModel := new(appconfigurationv1.TargetSegments)
Expect(targetSegmentsModel).ToNot(BeNil())
targetSegmentsModel.Segments = []string{"testString"}
Expect(targetSegmentsModel.Segments).To(Equal([]string{"testString"}))
// Construct an instance of the SegmentRule model
segmentRuleModel := new(appconfigurationv1.SegmentRule)
Expect(segmentRuleModel).ToNot(BeNil())
segmentRuleModel.Rules = []appconfigurationv1.TargetSegments{*targetSegmentsModel}
segmentRuleModel.Value = core.StringPtr("true")
segmentRuleModel.Order = core.Int64Ptr(int64(1))
Expect(segmentRuleModel.Rules).To(Equal([]appconfigurationv1.TargetSegments{*targetSegmentsModel}))
Expect(segmentRuleModel.Value).To(Equal(core.StringPtr("true")))
Expect(segmentRuleModel.Order).To(Equal(core.Int64Ptr(int64(1))))
// Construct an instance of the CollectionRef model
collectionRefModel := new(appconfigurationv1.CollectionRef)
Expect(collectionRefModel).ToNot(BeNil())
collectionRefModel.CollectionID = core.StringPtr("ghzinc")
Expect(collectionRefModel.CollectionID).To(Equal(core.StringPtr("ghzinc")))
// Construct an instance of the CreatePropertyOptions model
environmentID := "testString"
createPropertyOptionsName := "Email property"
createPropertyOptionsPropertyID := "email-property"
createPropertyOptionsType := "BOOLEAN"
createPropertyOptionsValue := core.StringPtr("true")
createPropertyOptionsModel := appConfigurationService.NewCreatePropertyOptions(environmentID, createPropertyOptionsName, createPropertyOptionsPropertyID, createPropertyOptionsType, createPropertyOptionsValue)
createPropertyOptionsModel.SetEnvironmentID("testString")
createPropertyOptionsModel.SetName("Email property")
createPropertyOptionsModel.SetPropertyID("email-property")
createPropertyOptionsModel.SetType("BOOLEAN")
createPropertyOptionsModel.SetValue(core.StringPtr("true"))
createPropertyOptionsModel.SetDescription("Property for email")
createPropertyOptionsModel.SetTags("version: 1.1, pre-release")
createPropertyOptionsModel.SetSegmentRules([]appconfigurationv1.SegmentRule{*segmentRuleModel})
createPropertyOptionsModel.SetCollections([]appconfigurationv1.CollectionRef{*collectionRefModel})
createPropertyOptionsModel.SetHeaders(map[string]string{"foo": "bar"})
Expect(createPropertyOptionsModel).ToNot(BeNil())
Expect(createPropertyOptionsModel.EnvironmentID).To(Equal(core.StringPtr("testString")))
Expect(createPropertyOptionsModel.Name).To(Equal(core.StringPtr("Email property")))
Expect(createPropertyOptionsModel.PropertyID).To(Equal(core.StringPtr("email-property")))
Expect(createPropertyOptionsModel.Type).To(Equal(core.StringPtr("BOOLEAN")))
Expect(createPropertyOptionsModel.Value).To(Equal(core.StringPtr("true")))
Expect(createPropertyOptionsModel.Description).To(Equal(core.StringPtr("Property for email")))
Expect(createPropertyOptionsModel.Tags).To(Equal(core.StringPtr("version: 1.1, pre-release")))
Expect(createPropertyOptionsModel.SegmentRules).To(Equal([]appconfigurationv1.SegmentRule{*segmentRuleModel}))
Expect(createPropertyOptionsModel.Collections).To(Equal([]appconfigurationv1.CollectionRef{*collectionRefModel}))
Expect(createPropertyOptionsModel.Headers).To(Equal(map[string]string{"foo": "bar"}))
})
It(`Invoke NewCreateSegmentOptions successfully`, func() {
// Construct an instance of the Rule model
ruleModel := new(appconfigurationv1.Rule)
Expect(ruleModel).ToNot(BeNil())
ruleModel.AttributeName = core.StringPtr("email")
ruleModel.Operator = core.StringPtr("endsWith")
ruleModel.Values = []string{"testString"}
Expect(ruleModel.AttributeName).To(Equal(core.StringPtr("email")))
Expect(ruleModel.Operator).To(Equal(core.StringPtr("endsWith")))
Expect(ruleModel.Values).To(Equal([]string{"testString"}))
// Construct an instance of the CreateSegmentOptions model
createSegmentOptionsModel := appConfigurationService.NewCreateSegmentOptions()
createSegmentOptionsModel.SetName("Beta Users")
createSegmentOptionsModel.SetSegmentID("beta-users")
createSegmentOptionsModel.SetDescription("Segment containing the beta users")
createSegmentOptionsModel.SetTags("version: 1.1, stage")
createSegmentOptionsModel.SetRules([]appconfigurationv1.Rule{*ruleModel})
createSegmentOptionsModel.SetHeaders(map[string]string{"foo": "bar"})
Expect(createSegmentOptionsModel).ToNot(BeNil())
Expect(createSegmentOptionsModel.Name).To(Equal(core.StringPtr("Beta Users")))
Expect(createSegmentOptionsModel.SegmentID).To(Equal(core.StringPtr("beta-users")))
Expect(createSegmentOptionsModel.Description).To(Equal(core.StringPtr("Segment containing the beta users")))
Expect(createSegmentOptionsModel.Tags).To(Equal(core.StringPtr("version: 1.1, stage")))
Expect(createSegmentOptionsModel.Rules).To(Equal([]appconfigurationv1.Rule{*ruleModel}))
Expect(createSegmentOptionsModel.Headers).To(Equal(map[string]string{"foo": "bar"}))
})
It(`Invoke NewDeleteCollectionOptions successfully`, func() {
// Construct an instance of the DeleteCollectionOptions model
collectionID := "testString"
deleteCollectionOptionsModel := appConfigurationService.NewDeleteCollectionOptions(collectionID)
deleteCollectionOptionsModel.SetCollectionID("testString")
deleteCollectionOptionsModel.SetHeaders(map[string]string{"foo": "bar"})
Expect(deleteCollectionOptionsModel).ToNot(BeNil())
Expect(deleteCollectionOptionsModel.CollectionID).To(Equal(core.StringPtr("testString")))
Expect(deleteCollectionOptionsModel.Headers).To(Equal(map[string]string{"foo": "bar"}))
})
It(`Invoke NewDeleteEnvironmentOptions successfully`, func() {
// Construct an instance of the DeleteEnvironmentOptions model
environmentID := "testString"
deleteEnvironmentOptionsModel := appConfigurationService.NewDeleteEnvironmentOptions(environmentID)
deleteEnvironmentOptionsModel.SetEnvironmentID("testString")
deleteEnvironmentOptionsModel.SetHeaders(map[string]string{"foo": "bar"})
Expect(deleteEnvironmentOptionsModel).ToNot(BeNil())
Expect(deleteEnvironmentOptionsModel.EnvironmentID).To(Equal(core.StringPtr("testString")))
Expect(deleteEnvironmentOptionsModel.Headers).To(Equal(map[string]string{"foo": "bar"}))
})
It(`Invoke NewDeleteFeatureOptions successfully`, func() {
// Construct an instance of the DeleteFeatureOptions model
environmentID := "testString"
featureID := "testString"
deleteFeatureOptionsModel := appConfigurationService.NewDeleteFeatureOptions(environmentID, featureID)
deleteFeatureOptionsModel.SetEnvironmentID("testString")
deleteFeatureOptionsModel.SetFeatureID("testString")
deleteFeatureOptionsModel.SetHeaders(map[string]string{"foo": "bar"})
Expect(deleteFeatureOptionsModel).ToNot(BeNil())
Expect(deleteFeatureOptionsModel.EnvironmentID).To(Equal(core.StringPtr("testString")))
Expect(deleteFeatureOptionsModel.FeatureID).To(Equal(core.StringPtr("testString")))
Expect(deleteFeatureOptionsModel.Headers).To(Equal(map[string]string{"foo": "bar"}))
})
It(`Invoke NewDeletePropertyOptions successfully`, func() {
// Construct an instance of the DeletePropertyOptions model
environmentID := "testString"
propertyID := "testString"
deletePropertyOptionsModel := appConfigurationService.NewDeletePropertyOptions(environmentID, propertyID)
deletePropertyOptionsModel.SetEnvironmentID("testString")
deletePropertyOptionsModel.SetPropertyID("testString")
deletePropertyOptionsModel.SetHeaders(map[string]string{"foo": "bar"})
Expect(deletePropertyOptionsModel).ToNot(BeNil())
Expect(deletePropertyOptionsModel.EnvironmentID).To(Equal(core.StringPtr("testString")))
Expect(deletePropertyOptionsModel.PropertyID).To(Equal(core.StringPtr("testString")))
Expect(deletePropertyOptionsModel.Headers).To(Equal(map[string]string{"foo": "bar"}))
})
It(`Invoke NewDeleteSegmentOptions successfully`, func() {
// Construct an instance of the DeleteSegmentOptions model
segmentID := "testString"
deleteSegmentOptionsModel := appConfigurationService.NewDeleteSegmentOptions(segmentID)
deleteSegmentOptionsModel.SetSegmentID("testString")
deleteSegmentOptionsModel.SetHeaders(map[string]string{"foo": "bar"})
Expect(deleteSegmentOptionsModel).ToNot(BeNil())
Expect(deleteSegmentOptionsModel.SegmentID).To(Equal(core.StringPtr("testString")))
Expect(deleteSegmentOptionsModel.Headers).To(Equal(map[string]string{"foo": "bar"}))
})
It(`Invoke NewEnvironment successfully`, func() {
name := "testString"
environmentID := "testString"
model, err := appConfigurationService.NewEnvironment(name, environmentID)
Expect(model).ToNot(BeNil())
Expect(err).To(BeNil())
})
It(`Invoke NewFeature successfully`, func() {
name := "testString"
featureID := "testString"
typeVar := "BOOLEAN"
enabledValue := core.StringPtr("testString")
disabledValue := core.StringPtr("testString")
model, err := appConfigurationService.NewFeature(name, featureID, typeVar, enabledValue, disabledValue)
Expect(model).ToNot(BeNil())
Expect(err).To(BeNil())
})
It(`Invoke NewFeatureOutput successfully`, func() {
featureID := "testString"
name := "testString"
model, err := appConfigurationService.NewFeatureOutput(featureID, name)
Expect(model).ToNot(BeNil())
Expect(err).To(BeNil())
})
It(`Invoke NewGetCollectionOptions successfully`, func() {
// Construct an instance of the GetCollectionOptions model
collectionID := "testString"
getCollectionOptionsModel := appConfigurationService.NewGetCollectionOptions(collectionID)
getCollectionOptionsModel.SetCollectionID("testString")
getCollectionOptionsModel.SetExpand(true)
getCollectionOptionsModel.SetInclude([]string{"features"})
getCollectionOptionsModel.SetHeaders(map[string]string{"foo": "bar"})
Expect(getCollectionOptionsModel).ToNot(BeNil())
Expect(getCollectionOptionsModel.CollectionID).To(Equal(core.StringPtr("testString")))
Expect(getCollectionOptionsModel.Expand).To(Equal(core.BoolPtr(true)))
Expect(getCollectionOptionsModel.Include).To(Equal([]string{"features"}))
Expect(getCollectionOptionsModel.Headers).To(Equal(map[string]string{"foo": "bar"}))
})
It(`Invoke NewGetEnvironmentOptions successfully`, func() {
// Construct an instance of the GetEnvironmentOptions model
environmentID := "testString"
getEnvironmentOptionsModel := appConfigurationService.NewGetEnvironmentOptions(environmentID)
getEnvironmentOptionsModel.SetEnvironmentID("testString")
getEnvironmentOptionsModel.SetExpand(true)
getEnvironmentOptionsModel.SetInclude([]string{"features"})
getEnvironmentOptionsModel.SetHeaders(map[string]string{"foo": "bar"})
Expect(getEnvironmentOptionsModel).ToNot(BeNil())
Expect(getEnvironmentOptionsModel.EnvironmentID).To(Equal(core.StringPtr("testString")))
Expect(getEnvironmentOptionsModel.Expand).To(Equal(core.BoolPtr(true)))
Expect(getEnvironmentOptionsModel.Include).To(Equal([]string{"features"}))
Expect(getEnvironmentOptionsModel.Headers).To(Equal(map[string]string{"foo": "bar"}))
})
It(`Invoke NewGetFeatureOptions successfully`, func() {
// Construct an instance of the GetFeatureOptions model
environmentID := "testString"
featureID := "testString"
getFeatureOptionsModel := appConfigurationService.NewGetFeatureOptions(environmentID, featureID)
getFeatureOptionsModel.SetEnvironmentID("testString")
getFeatureOptionsModel.SetFeatureID("testString")
getFeatureOptionsModel.SetInclude("collections")
getFeatureOptionsModel.SetHeaders(map[string]string{"foo": "bar"})
Expect(getFeatureOptionsModel).ToNot(BeNil())
Expect(getFeatureOptionsModel.EnvironmentID).To(Equal(core.StringPtr("testString")))
Expect(getFeatureOptionsModel.FeatureID).To(Equal(core.StringPtr("testString")))
Expect(getFeatureOptionsModel.Include).To(Equal(core.StringPtr("collections")))
Expect(getFeatureOptionsModel.Headers).To(Equal(map[string]string{"foo": "bar"}))
})
It(`Invoke NewGetPropertyOptions successfully`, func() {
// Construct an instance of the GetPropertyOptions model
environmentID := "testString"
propertyID := "testString"
getPropertyOptionsModel := appConfigurationService.NewGetPropertyOptions(environmentID, propertyID)
getPropertyOptionsModel.SetEnvironmentID("testString")
getPropertyOptionsModel.SetPropertyID("testString")
getPropertyOptionsModel.SetInclude("collections")
getPropertyOptionsModel.SetHeaders(map[string]string{"foo": "bar"})
Expect(getPropertyOptionsModel).ToNot(BeNil())
Expect(getPropertyOptionsModel.EnvironmentID).To(Equal(core.StringPtr("testString")))
Expect(getPropertyOptionsModel.PropertyID).To(Equal(core.StringPtr("testString")))
Expect(getPropertyOptionsModel.Include).To(Equal(core.StringPtr("collections")))
Expect(getPropertyOptionsModel.Headers).To(Equal(map[string]string{"foo": "bar"}))
})
It(`Invoke NewGetSegmentOptions successfully`, func() {
// Construct an instance of the GetSegmentOptions model
segmentID := "testString"
getSegmentOptionsModel := appConfigurationService.NewGetSegmentOptions(segmentID)
getSegmentOptionsModel.SetSegmentID("testString")
getSegmentOptionsModel.SetInclude([]string{"features"})
getSegmentOptionsModel.SetHeaders(map[string]string{"foo": "bar"})
Expect(getSegmentOptionsModel).ToNot(BeNil())
Expect(getSegmentOptionsModel.SegmentID).To(Equal(core.StringPtr("testString")))
Expect(getSegmentOptionsModel.Include).To(Equal([]string{"features"}))
Expect(getSegmentOptionsModel.Headers).To(Equal(map[string]string{"foo": "bar"}))
})
It(`Invoke NewListCollectionsOptions successfully`, func() {
// Construct an instance of the ListCollectionsOptions model
listCollectionsOptionsModel := appConfigurationService.NewListCollectionsOptions()
listCollectionsOptionsModel.SetExpand(true)
listCollectionsOptionsModel.SetSort("created_time")
listCollectionsOptionsModel.SetTags("version 1.1, pre-release")
listCollectionsOptionsModel.SetFeatures([]string{"testString"})
listCollectionsOptionsModel.SetProperties([]string{"testString"})
listCollectionsOptionsModel.SetInclude([]string{"features"})
listCollectionsOptionsModel.SetLimit(int64(1))
listCollectionsOptionsModel.SetOffset(int64(0))
listCollectionsOptionsModel.SetHeaders(map[string]string{"foo": "bar"})
Expect(listCollectionsOptionsModel).ToNot(BeNil())
Expect(listCollectionsOptionsModel.Expand).To(Equal(core.BoolPtr(true)))
Expect(listCollectionsOptionsModel.Sort).To(Equal(core.StringPtr("created_time")))
Expect(listCollectionsOptionsModel.Tags).To(Equal(core.StringPtr("version 1.1, pre-release")))
Expect(listCollectionsOptionsModel.Features).To(Equal([]string{"testString"}))
Expect(listCollectionsOptionsModel.Properties).To(Equal([]string{"testString"}))
Expect(listCollectionsOptionsModel.Include).To(Equal([]string{"features"}))
Expect(listCollectionsOptionsModel.Limit).To(Equal(core.Int64Ptr(int64(1))))
Expect(listCollectionsOptionsModel.Offset).To(Equal(core.Int64Ptr(int64(0))))
Expect(listCollectionsOptionsModel.Headers).To(Equal(map[string]string{"foo": "bar"}))
})
It(`Invoke NewListEnvironmentsOptions successfully`, func() {
// Construct an instance of the ListEnvironmentsOptions model
listEnvironmentsOptionsModel := appConfigurationService.NewListEnvironmentsOptions()
listEnvironmentsOptionsModel.SetExpand(true)
listEnvironmentsOptionsModel.SetSort("created_time")
listEnvironmentsOptionsModel.SetTags("version 1.1, pre-release")
listEnvironmentsOptionsModel.SetInclude([]string{"features"})
listEnvironmentsOptionsModel.SetLimit(int64(1))
listEnvironmentsOptionsModel.SetOffset(int64(0))
listEnvironmentsOptionsModel.SetHeaders(map[string]string{"foo": "bar"})
Expect(listEnvironmentsOptionsModel).ToNot(BeNil())
Expect(listEnvironmentsOptionsModel.Expand).To(Equal(core.BoolPtr(true)))
Expect(listEnvironmentsOptionsModel.Sort).To(Equal(core.StringPtr("created_time")))
Expect(listEnvironmentsOptionsModel.Tags).To(Equal(core.StringPtr("version 1.1, pre-release")))
Expect(listEnvironmentsOptionsModel.Include).To(Equal([]string{"features"}))
Expect(listEnvironmentsOptionsModel.Limit).To(Equal(core.Int64Ptr(int64(1))))
Expect(listEnvironmentsOptionsModel.Offset).To(Equal(core.Int64Ptr(int64(0))))
Expect(listEnvironmentsOptionsModel.Headers).To(Equal(map[string]string{"foo": "bar"}))
})
It(`Invoke NewListFeaturesOptions successfully`, func() {
// Construct an instance of the ListFeaturesOptions model
environmentID := "testString"
listFeaturesOptionsModel := appConfigurationService.NewListFeaturesOptions(environmentID)
listFeaturesOptionsModel.SetEnvironmentID("testString")
listFeaturesOptionsModel.SetExpand(true)
listFeaturesOptionsModel.SetSort("created_time")
listFeaturesOptionsModel.SetTags("version 1.1, pre-release")
listFeaturesOptionsModel.SetCollections([]string{"testString"})
listFeaturesOptionsModel.SetSegments([]string{"testString"})
listFeaturesOptionsModel.SetInclude([]string{"collections"})
listFeaturesOptionsModel.SetLimit(int64(1))
listFeaturesOptionsModel.SetOffset(int64(0))
listFeaturesOptionsModel.SetHeaders(map[string]string{"foo": "bar"})
Expect(listFeaturesOptionsModel).ToNot(BeNil())
Expect(listFeaturesOptionsModel.EnvironmentID).To(Equal(core.StringPtr("testString")))
Expect(listFeaturesOptionsModel.Expand).To(Equal(core.BoolPtr(true)))
Expect(listFeaturesOptionsModel.Sort).To(Equal(core.StringPtr("created_time")))
Expect(listFeaturesOptionsModel.Tags).To(Equal(core.StringPtr("version 1.1, pre-release")))
Expect(listFeaturesOptionsModel.Collections).To(Equal([]string{"testString"}))
Expect(listFeaturesOptionsModel.Segments).To(Equal([]string{"testString"}))
Expect(listFeaturesOptionsModel.Include).To(Equal([]string{"collections"}))
Expect(listFeaturesOptionsModel.Limit).To(Equal(core.Int64Ptr(int64(1))))
Expect(listFeaturesOptionsModel.Offset).To(Equal(core.Int64Ptr(int64(0))))
Expect(listFeaturesOptionsModel.Headers).To(Equal(map[string]string{"foo": "bar"}))
})
It(`Invoke NewListPropertiesOptions successfully`, func() {
// Construct an instance of the ListPropertiesOptions model
environmentID := "testString"
listPropertiesOptionsModel := appConfigurationService.NewListPropertiesOptions(environmentID)
listPropertiesOptionsModel.SetEnvironmentID("testString")
listPropertiesOptionsModel.SetExpand(true)
listPropertiesOptionsModel.SetSort("created_time")
listPropertiesOptionsModel.SetTags("version 1.1, pre-release")
listPropertiesOptionsModel.SetCollections([]string{"testString"})
listPropertiesOptionsModel.SetSegments([]string{"testString"})
listPropertiesOptionsModel.SetInclude([]string{"collections"})
listPropertiesOptionsModel.SetLimit(int64(1))
listPropertiesOptionsModel.SetOffset(int64(0))
listPropertiesOptionsModel.SetHeaders(map[string]string{"foo": "bar"})
Expect(listPropertiesOptionsModel).ToNot(BeNil())
Expect(listPropertiesOptionsModel.EnvironmentID).To(Equal(core.StringPtr("testString")))
Expect(listPropertiesOptionsModel.Expand).To(Equal(core.BoolPtr(true)))
Expect(listPropertiesOptionsModel.Sort).To(Equal(core.StringPtr("created_time")))
Expect(listPropertiesOptionsModel.Tags).To(Equal(core.StringPtr("version 1.1, pre-release")))
Expect(listPropertiesOptionsModel.Collections).To(Equal([]string{"testString"}))
Expect(listPropertiesOptionsModel.Segments).To(Equal([]string{"testString"}))
Expect(listPropertiesOptionsModel.Include).To(Equal([]string{"collections"}))
Expect(listPropertiesOptionsModel.Limit).To(Equal(core.Int64Ptr(int64(1))))
Expect(listPropertiesOptionsModel.Offset).To(Equal(core.Int64Ptr(int64(0))))
Expect(listPropertiesOptionsModel.Headers).To(Equal(map[string]string{"foo": "bar"}))
})
It(`Invoke NewListSegmentsOptions successfully`, func() {
// Construct an instance of the ListSegmentsOptions model
listSegmentsOptionsModel := appConfigurationService.NewListSegmentsOptions()
listSegmentsOptionsModel.SetExpand(true)
listSegmentsOptionsModel.SetSort("created_time")
listSegmentsOptionsModel.SetTags("version 1.1, pre-release")
listSegmentsOptionsModel.SetInclude("rules")
listSegmentsOptionsModel.SetLimit(int64(1))
listSegmentsOptionsModel.SetOffset(int64(0))
listSegmentsOptionsModel.SetHeaders(map[string]string{"foo": "bar"})
Expect(listSegmentsOptionsModel).ToNot(BeNil())
Expect(listSegmentsOptionsModel.Expand).To(Equal(core.BoolPtr(true)))
Expect(listSegmentsOptionsModel.Sort).To(Equal(core.StringPtr("created_time")))
Expect(listSegmentsOptionsModel.Tags).To(Equal(core.StringPtr("version 1.1, pre-release")))
Expect(listSegmentsOptionsModel.Include).To(Equal(core.StringPtr("rules")))
Expect(listSegmentsOptionsModel.Limit).To(Equal(core.Int64Ptr(int64(1))))
Expect(listSegmentsOptionsModel.Offset).To(Equal(core.Int64Ptr(int64(0))))
Expect(listSegmentsOptionsModel.Headers).To(Equal(map[string]string{"foo": "bar"}))
})
It(`Invoke NewProperty successfully`, func() {
name := "testString"
propertyID := "testString"
typeVar := "BOOLEAN"
value := core.StringPtr("testString")
model, err := appConfigurationService.NewProperty(name, propertyID, typeVar, value)
Expect(model).ToNot(BeNil())
Expect(err).To(BeNil())
})
It(`Invoke NewPropertyOutput successfully`, func() {
propertyID := "testString"
name := "testString"
model, err := appConfigurationService.NewPropertyOutput(propertyID, name)
Expect(model).ToNot(BeNil())
Expect(err).To(BeNil())
})
It(`Invoke NewRule successfully`, func() {
attributeName := "testString"
operator := "is"
values := []string{"testString"}
model, err := appConfigurationService.NewRule(attributeName, operator, values)
Expect(model).ToNot(BeNil())
Expect(err).To(BeNil())
})
It(`Invoke NewSegment successfully`, func() {
name := "testString"
segmentID := "testString"
rules := []appconfigurationv1.Rule{}
model, err := appConfigurationService.NewSegment(name, segmentID, rules)
Expect(model).ToNot(BeNil())
Expect(err).To(BeNil())
})
It(`Invoke NewSegmentRule successfully`, func() {
rules := []appconfigurationv1.TargetSegments{}
value := core.StringPtr("testString")
order := int64(38)
model, err := appConfigurationService.NewSegmentRule(rules, value, order)
Expect(model).ToNot(BeNil())
Expect(err).To(BeNil())
})
It(`Invoke NewTargetSegments successfully`, func() {
segments := []string{"testString"}
model, err := appConfigurationService.NewTargetSegments(segments)
Expect(model).ToNot(BeNil())
Expect(err).To(BeNil())
})
It(`Invoke NewToggleFeatureOptions successfully`, func() {
// Construct an instance of the ToggleFeatureOptions model
environmentID := "testString"
featureID := "testString"
toggleFeatureOptionsModel := appConfigurationService.NewToggleFeatureOptions(environmentID, featureID)
toggleFeatureOptionsModel.SetEnvironmentID("testString")
toggleFeatureOptionsModel.SetFeatureID("testString")
toggleFeatureOptionsModel.SetEnabled(true)
toggleFeatureOptionsModel.SetHeaders(map[string]string{"foo": "bar"})
Expect(toggleFeatureOptionsModel).ToNot(BeNil())
Expect(toggleFeatureOptionsModel.EnvironmentID).To(Equal(core.StringPtr("testString")))
Expect(toggleFeatureOptionsModel.FeatureID).To(Equal(core.StringPtr("testString")))
Expect(toggleFeatureOptionsModel.Enabled).To(Equal(core.BoolPtr(true)))
Expect(toggleFeatureOptionsModel.Headers).To(Equal(map[string]string{"foo": "bar"}))
})
It(`Invoke NewUpdateCollectionOptions successfully`, func() {
// Construct an instance of the UpdateCollectionOptions model
collectionID := "testString"
updateCollectionOptionsModel := appConfigurationService.NewUpdateCollectionOptions(collectionID)
updateCollectionOptionsModel.SetCollectionID("testString")
updateCollectionOptionsModel.SetName("testString")
updateCollectionOptionsModel.SetDescription("testString")
updateCollectionOptionsModel.SetTags("testString")
updateCollectionOptionsModel.SetHeaders(map[string]string{"foo": "bar"})
Expect(updateCollectionOptionsModel).ToNot(BeNil())
Expect(updateCollectionOptionsModel.CollectionID).To(Equal(core.StringPtr("testString")))
Expect(updateCollectionOptionsModel.Name).To(Equal(core.StringPtr("testString")))
Expect(updateCollectionOptionsModel.Description).To(Equal(core.StringPtr("testString")))
Expect(updateCollectionOptionsModel.Tags).To(Equal(core.StringPtr("testString")))
Expect(updateCollectionOptionsModel.Headers).To(Equal(map[string]string{"foo": "bar"}))
})
It(`Invoke NewUpdateEnvironmentOptions successfully`, func() {
// Construct an instance of the UpdateEnvironmentOptions model
environmentID := "testString"
updateEnvironmentOptionsModel := appConfigurationService.NewUpdateEnvironmentOptions(environmentID)
updateEnvironmentOptionsModel.SetEnvironmentID("testString")
updateEnvironmentOptionsModel.SetName("testString")
updateEnvironmentOptionsModel.SetDescription("testString")
updateEnvironmentOptionsModel.SetTags("testString")
updateEnvironmentOptionsModel.SetColorCode("#FDD13A")
updateEnvironmentOptionsModel.SetHeaders(map[string]string{"foo": "bar"})
Expect(updateEnvironmentOptionsModel).ToNot(BeNil())
Expect(updateEnvironmentOptionsModel.EnvironmentID).To(Equal(core.StringPtr("testString")))
Expect(updateEnvironmentOptionsModel.Name).To(Equal(core.StringPtr("testString")))
Expect(updateEnvironmentOptionsModel.Description).To(Equal(core.StringPtr("testString")))
Expect(updateEnvironmentOptionsModel.Tags).To(Equal(core.StringPtr("testString")))
Expect(updateEnvironmentOptionsModel.ColorCode).To(Equal(core.StringPtr("#FDD13A")))
Expect(updateEnvironmentOptionsModel.Headers).To(Equal(map[string]string{"foo": "bar"}))
})
It(`Invoke NewUpdateFeatureOptions successfully`, func() {
// Construct an instance of the TargetSegments model
targetSegmentsModel := new(appconfigurationv1.TargetSegments)
Expect(targetSegmentsModel).ToNot(BeNil())
targetSegmentsModel.Segments = []string{"testString"}
Expect(targetSegmentsModel.Segments).To(Equal([]string{"testString"}))
// Construct an instance of the SegmentRule model
segmentRuleModel := new(appconfigurationv1.SegmentRule)
Expect(segmentRuleModel).ToNot(BeNil())
segmentRuleModel.Rules = []appconfigurationv1.TargetSegments{*targetSegmentsModel}
segmentRuleModel.Value = core.StringPtr("testString")
segmentRuleModel.Order = core.Int64Ptr(int64(38))
Expect(segmentRuleModel.Rules).To(Equal([]appconfigurationv1.TargetSegments{*targetSegmentsModel}))
Expect(segmentRuleModel.Value).To(Equal(core.StringPtr("testString")))
Expect(segmentRuleModel.Order).To(Equal(core.Int64Ptr(int64(38))))
// Construct an instance of the CollectionRef model
collectionRefModel := new(appconfigurationv1.CollectionRef)
Expect(collectionRefModel).ToNot(BeNil())
collectionRefModel.CollectionID = core.StringPtr("testString")
Expect(collectionRefModel.CollectionID).To(Equal(core.StringPtr("testString")))
// Construct an instance of the UpdateFeatureOptions model
environmentID := "testString"
featureID := "testString"
updateFeatureOptionsModel := appConfigurationService.NewUpdateFeatureOptions(environmentID, featureID)
updateFeatureOptionsModel.SetEnvironmentID("testString")
updateFeatureOptionsModel.SetFeatureID("testString")
updateFeatureOptionsModel.SetName("testString")
updateFeatureOptionsModel.SetDescription("testString")
updateFeatureOptionsModel.SetEnabledValue(core.StringPtr("testString"))
updateFeatureOptionsModel.SetDisabledValue(core.StringPtr("testString"))
updateFeatureOptionsModel.SetEnabled(true)
updateFeatureOptionsModel.SetTags("testString")
updateFeatureOptionsModel.SetSegmentRules([]appconfigurationv1.SegmentRule{*segmentRuleModel})
updateFeatureOptionsModel.SetCollections([]appconfigurationv1.CollectionRef{*collectionRefModel})
updateFeatureOptionsModel.SetHeaders(map[string]string{"foo": "bar"})
Expect(updateFeatureOptionsModel).ToNot(BeNil())
Expect(updateFeatureOptionsModel.EnvironmentID).To(Equal(core.StringPtr("testString")))
Expect(updateFeatureOptionsModel.FeatureID).To(Equal(core.StringPtr("testString")))
Expect(updateFeatureOptionsModel.Name).To(Equal(core.StringPtr("testString")))
Expect(updateFeatureOptionsModel.Description).To(Equal(core.StringPtr("testString")))
Expect(updateFeatureOptionsModel.EnabledValue).To(Equal(core.StringPtr("testString")))
Expect(updateFeatureOptionsModel.DisabledValue).To(Equal(core.StringPtr("testString")))
Expect(updateFeatureOptionsModel.Enabled).To(Equal(core.BoolPtr(true)))
Expect(updateFeatureOptionsModel.Tags).To(Equal(core.StringPtr("testString")))
Expect(updateFeatureOptionsModel.SegmentRules).To(Equal([]appconfigurationv1.SegmentRule{*segmentRuleModel}))
Expect(updateFeatureOptionsModel.Collections).To(Equal([]appconfigurationv1.CollectionRef{*collectionRefModel}))
Expect(updateFeatureOptionsModel.Headers).To(Equal(map[string]string{"foo": "bar"}))
})
It(`Invoke NewUpdateFeatureValuesOptions successfully`, func() {
// Construct an instance of the TargetSegments model
targetSegmentsModel := new(appconfigurationv1.TargetSegments)
Expect(targetSegmentsModel).ToNot(BeNil())
targetSegmentsModel.Segments = []string{"testString"}
Expect(targetSegmentsModel.Segments).To(Equal([]string{"testString"}))
// Construct an instance of the SegmentRule model
segmentRuleModel := new(appconfigurationv1.SegmentRule)
Expect(segmentRuleModel).ToNot(BeNil())
segmentRuleModel.Rules = []appconfigurationv1.TargetSegments{*targetSegmentsModel}
segmentRuleModel.Value = core.StringPtr("testString")
segmentRuleModel.Order = core.Int64Ptr(int64(38))
Expect(segmentRuleModel.Rules).To(Equal([]appconfigurationv1.TargetSegments{*targetSegmentsModel}))
Expect(segmentRuleModel.Value).To(Equal(core.StringPtr("testString")))
Expect(segmentRuleModel.Order).To(Equal(core.Int64Ptr(int64(38))))
// Construct an instance of the UpdateFeatureValuesOptions model
environmentID := "testString"
featureID := "testString"
updateFeatureValuesOptionsModel := appConfigurationService.NewUpdateFeatureValuesOptions(environmentID, featureID)
updateFeatureValuesOptionsModel.SetEnvironmentID("testString")
updateFeatureValuesOptionsModel.SetFeatureID("testString")
updateFeatureValuesOptionsModel.SetName("testString")
updateFeatureValuesOptionsModel.SetDescription("testString")
updateFeatureValuesOptionsModel.SetTags("testString")
updateFeatureValuesOptionsModel.SetEnabledValue(core.StringPtr("testString"))
updateFeatureValuesOptionsModel.SetDisabledValue(core.StringPtr("testString"))
updateFeatureValuesOptionsModel.SetSegmentRules([]appconfigurationv1.SegmentRule{*segmentRuleModel})
updateFeatureValuesOptionsModel.SetHeaders(map[string]string{"foo": "bar"})
Expect(updateFeatureValuesOptionsModel).ToNot(BeNil())
Expect(updateFeatureValuesOptionsModel.EnvironmentID).To(Equal(core.StringPtr("testString")))
Expect(updateFeatureValuesOptionsModel.FeatureID).To(Equal(core.StringPtr("testString")))
Expect(updateFeatureValuesOptionsModel.Name).To(Equal(core.StringPtr("testString")))
Expect(updateFeatureValuesOptionsModel.Description).To(Equal(core.StringPtr("testString")))
Expect(updateFeatureValuesOptionsModel.Tags).To(Equal(core.StringPtr("testString")))
Expect(updateFeatureValuesOptionsModel.EnabledValue).To(Equal(core.StringPtr("testString")))
Expect(updateFeatureValuesOptionsModel.DisabledValue).To(Equal(core.StringPtr("testString")))
Expect(updateFeatureValuesOptionsModel.SegmentRules).To(Equal([]appconfigurationv1.SegmentRule{*segmentRuleModel}))
Expect(updateFeatureValuesOptionsModel.Headers).To(Equal(map[string]string{"foo": "bar"}))
})
It(`Invoke NewUpdatePropertyOptions successfully`, func() {
// Construct an instance of the TargetSegments model
targetSegmentsModel := new(appconfigurationv1.TargetSegments)
Expect(targetSegmentsModel).ToNot(BeNil())
targetSegmentsModel.Segments = []string{"testString"}
Expect(targetSegmentsModel.Segments).To(Equal([]string{"testString"}))
// Construct an instance of the SegmentRule model
segmentRuleModel := new(appconfigurationv1.SegmentRule)
Expect(segmentRuleModel).ToNot(BeNil())
segmentRuleModel.Rules = []appconfigurationv1.TargetSegments{*targetSegmentsModel}
segmentRuleModel.Value = core.StringPtr("testString")
segmentRuleModel.Order = core.Int64Ptr(int64(38))
Expect(segmentRuleModel.Rules).To(Equal([]appconfigurationv1.TargetSegments{*targetSegmentsModel}))
Expect(segmentRuleModel.Value).To(Equal(core.StringPtr("testString")))
Expect(segmentRuleModel.Order).To(Equal(core.Int64Ptr(int64(38))))
// Construct an instance of the CollectionRef model
collectionRefModel := new(appconfigurationv1.CollectionRef)
Expect(collectionRefModel).ToNot(BeNil())
collectionRefModel.CollectionID = core.StringPtr("testString")
Expect(collectionRefModel.CollectionID).To(Equal(core.StringPtr("testString")))
// Construct an instance of the UpdatePropertyOptions model
environmentID := "testString"
propertyID := "testString"
updatePropertyOptionsModel := appConfigurationService.NewUpdatePropertyOptions(environmentID, propertyID)
updatePropertyOptionsModel.SetEnvironmentID("testString")
updatePropertyOptionsModel.SetPropertyID("testString")
updatePropertyOptionsModel.SetName("testString")
updatePropertyOptionsModel.SetDescription("testString")
updatePropertyOptionsModel.SetValue(core.StringPtr("testString"))
updatePropertyOptionsModel.SetTags("testString")
updatePropertyOptionsModel.SetSegmentRules([]appconfigurationv1.SegmentRule{*segmentRuleModel})
updatePropertyOptionsModel.SetCollections([]appconfigurationv1.CollectionRef{*collectionRefModel})
updatePropertyOptionsModel.SetHeaders(map[string]string{"foo": "bar"})
Expect(updatePropertyOptionsModel).ToNot(BeNil())
Expect(updatePropertyOptionsModel.EnvironmentID).To(Equal(core.StringPtr("testString")))
Expect(updatePropertyOptionsModel.PropertyID).To(Equal(core.StringPtr("testString")))
Expect(updatePropertyOptionsModel.Name).To(Equal(core.StringPtr("testString")))
Expect(updatePropertyOptionsModel.Description).To(Equal(core.StringPtr("testString")))
Expect(updatePropertyOptionsModel.Value).To(Equal(core.StringPtr("testString")))
Expect(updatePropertyOptionsModel.Tags).To(Equal(core.StringPtr("testString")))
Expect(updatePropertyOptionsModel.SegmentRules).To(Equal([]appconfigurationv1.SegmentRule{*segmentRuleModel}))
Expect(updatePropertyOptionsModel.Collections).To(Equal([]appconfigurationv1.CollectionRef{*collectionRefModel}))
Expect(updatePropertyOptionsModel.Headers).To(Equal(map[string]string{"foo": "bar"}))
})
It(`Invoke NewUpdatePropertyValuesOptions successfully`, func() {
// Construct an instance of the TargetSegments model
targetSegmentsModel := new(appconfigurationv1.TargetSegments)
Expect(targetSegmentsModel).ToNot(BeNil())
targetSegmentsModel.Segments = []string{"testString"}
Expect(targetSegmentsModel.Segments).To(Equal([]string{"testString"}))
// Construct an instance of the SegmentRule model
segmentRuleModel := new(appconfigurationv1.SegmentRule)
Expect(segmentRuleModel).ToNot(BeNil())
segmentRuleModel.Rules = []appconfigurationv1.TargetSegments{*targetSegmentsModel}
segmentRuleModel.Value = core.StringPtr("testString")
segmentRuleModel.Order = core.Int64Ptr(int64(38))
Expect(segmentRuleModel.Rules).To(Equal([]appconfigurationv1.TargetSegments{*targetSegmentsModel}))
Expect(segmentRuleModel.Value).To(Equal(core.StringPtr("testString")))
Expect(segmentRuleModel.Order).To(Equal(core.Int64Ptr(int64(38))))
// Construct an instance of the UpdatePropertyValuesOptions model
environmentID := "testString"
propertyID := "testString"
updatePropertyValuesOptionsModel := appConfigurationService.NewUpdatePropertyValuesOptions(environmentID, propertyID)
updatePropertyValuesOptionsModel.SetEnvironmentID("testString")
updatePropertyValuesOptionsModel.SetPropertyID("testString")
updatePropertyValuesOptionsModel.SetName("testString")
updatePropertyValuesOptionsModel.SetDescription("testString")
updatePropertyValuesOptionsModel.SetTags("testString")
updatePropertyValuesOptionsModel.SetValue(core.StringPtr("testString"))
updatePropertyValuesOptionsModel.SetSegmentRules([]appconfigurationv1.SegmentRule{*segmentRuleModel})
updatePropertyValuesOptionsModel.SetHeaders(map[string]string{"foo": "bar"})
Expect(updatePropertyValuesOptionsModel).ToNot(BeNil())
Expect(updatePropertyValuesOptionsModel.EnvironmentID).To(Equal(core.StringPtr("testString")))
Expect(updatePropertyValuesOptionsModel.PropertyID).To(Equal(core.StringPtr("testString")))
Expect(updatePropertyValuesOptionsModel.Name).To(Equal(core.StringPtr("testString")))
Expect(updatePropertyValuesOptionsModel.Description).To(Equal(core.StringPtr("testString")))
Expect(updatePropertyValuesOptionsModel.Tags).To(Equal(core.StringPtr("testString")))
Expect(updatePropertyValuesOptionsModel.Value).To(Equal(core.StringPtr("testString")))
Expect(updatePropertyValuesOptionsModel.SegmentRules).To(Equal([]appconfigurationv1.SegmentRule{*segmentRuleModel}))
Expect(updatePropertyValuesOptionsModel.Headers).To(Equal(map[string]string{"foo": "bar"}))
})
It(`Invoke NewUpdateSegmentOptions successfully`, func() {
// Construct an instance of the Rule model
ruleModel := new(appconfigurationv1.Rule)
Expect(ruleModel).ToNot(BeNil())
ruleModel.AttributeName = core.StringPtr("testString")
ruleModel.Operator = core.StringPtr("is")
ruleModel.Values = []string{"testString"}
Expect(ruleModel.AttributeName).To(Equal(core.StringPtr("testString")))
Expect(ruleModel.Operator).To(Equal(core.StringPtr("is")))
Expect(ruleModel.Values).To(Equal([]string{"testString"}))
// Construct an instance of the UpdateSegmentOptions model
segmentID := "testString"
updateSegmentOptionsModel := appConfigurationService.NewUpdateSegmentOptions(segmentID)
updateSegmentOptionsModel.SetSegmentID("testString")
updateSegmentOptionsModel.SetName("testString")
updateSegmentOptionsModel.SetDescription("testString")
updateSegmentOptionsModel.SetTags("testString")
updateSegmentOptionsModel.SetRules([]appconfigurationv1.Rule{*ruleModel})
updateSegmentOptionsModel.SetHeaders(map[string]string{"foo": "bar"})
Expect(updateSegmentOptionsModel).ToNot(BeNil())
Expect(updateSegmentOptionsModel.SegmentID).To(Equal(core.StringPtr("testString")))
Expect(updateSegmentOptionsModel.Name).To(Equal(core.StringPtr("testString")))
Expect(updateSegmentOptionsModel.Description).To(Equal(core.StringPtr("testString")))
Expect(updateSegmentOptionsModel.Tags).To(Equal(core.StringPtr("testString")))
Expect(updateSegmentOptionsModel.Rules).To(Equal([]appconfigurationv1.Rule{*ruleModel}))
Expect(updateSegmentOptionsModel.Headers).To(Equal(map[string]string{"foo": "bar"}))
})
})
})
Describe(`Utility function tests`, func() {
It(`Invoke CreateMockByteArray() successfully`, func() {
mockByteArray := CreateMockByteArray("This is a test")
Expect(mockByteArray).ToNot(BeNil())
})
It(`Invoke CreateMockUUID() successfully`, func() {
mockUUID := CreateMockUUID("9fab83da-98cb-4f18-a7ba-b6f0435c9673")
Expect(mockUUID).ToNot(BeNil())
})
It(`Invoke CreateMockReader() successfully`, func() {
mockReader := CreateMockReader("This is a test.")
Expect(mockReader).ToNot(BeNil())
})
It(`Invoke CreateMockDate() successfully`, func() {
mockDate := CreateMockDate()
Expect(mockDate).ToNot(BeNil())
})
It(`Invoke CreateMockDateTime() successfully`, func() {
mockDateTime := CreateMockDateTime()
Expect(mockDateTime).ToNot(BeNil())
})
})
})
//
// Utility functions used by the generated test code
//
func CreateMockByteArray(mockData string) *[]byte {
ba := make([]byte, 0)
ba = append(ba, mockData...)
return &ba
}
func CreateMockUUID(mockData string) *strfmt.UUID {
uuid := strfmt.UUID(mockData)
return &uuid
}
func CreateMockReader(mockData string) io.ReadCloser {
return ioutil.NopCloser(bytes.NewReader([]byte(mockData)))
}
func CreateMockDate() *strfmt.Date {
d := strfmt.Date(time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC))
return &d
}
func CreateMockDateTime() *strfmt.DateTime {
d := strfmt.DateTime(time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC))
return &d
}
func SetTestEnvironment(testEnvironment map[string]string) {
for key, value := range testEnvironment {
os.Setenv(key, value)
}
}
func ClearTestEnvironment(testEnvironment map[string]string) {
for key := range testEnvironment {
os.Unsetenv(key)
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.