<commit_before>/*
Copyright 2019 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 portforward

import (
	"bytes"
	"context"
	"os/exec"
	"strings"
	"sync"
	"testing"
	"time"

	"github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/latest"
)

func TestUnavailablePort(t *testing.T) {

	original := isPortFree
	defer func() { isPortFree = original }()

	// Return that the port is false, while also
	// adding a sync group so we know when isPortFree
	// has been called
	portFreeWG := &sync.WaitGroup{}
	portFreeWG.Add(1)
	isPortFree = func(_ int) bool {
		defer portFreeWG.Done()
		return false
	}

	// Create a wait group that will only be
	// fulfilled when the forward function returns
	forwardFunctionWG := &sync.WaitGroup{}
	forwardFunctionWG.Add(1)
	originalDefer := deferFunc
	defer func() { deferFunc = originalDefer }()
	deferFunc = func() { defer forwardFunctionWG.Done() }

	buf := bytes.NewBuffer([]byte{})
	k := KubectlForwarder{
		out: buf,
	}
	pfe := newPortForwardEntry(0, latest.PortForwardResource{}, "", "", "", 8080, false)
	k.Forward(context.Background(), pfe)

	// wait for isPortFree to be called
	portFreeWG.Wait()

	// then, end port forwarding and wait for the forward function to return.
	pfe.terminationLock.Lock()
	pfe.terminated = true
	pfe.terminationLock.Unlock()
	forwardFunctionWG.Wait()

	// read output to make sure logs are expected
	output := buf.String()
	if !strings.Contains(output, "port 8080 is taken") {
		t.Fatalf("port wasn't available but didn't get warning, got: \n%s", output)
	}
}

func TestTerminate(t *testing.T) {
	ctx, cancel := context.WithCancel(context.Background())

	pfe := newPortForwardEntry(0, latest.PortForwardResource{}, "", "", "", 8080, false)
	pfe.cancel = cancel

	k := &KubectlForwarder{}
	k.Terminate(pfe)
	if pfe.terminated != true {
		t.Fatalf("expected pfe.terminated to be true after termination")
	}
	if ctx.Err() != context.Canceled {
		t.Fatalf("expected cancel to be called")
	}
}

func TestMonitorErrorLogs(t *testing.T) {
	tests := []struct {
		description string
		input       string
		cmdRunning  bool
	}{
		{
			description: "no error logs appear",<commit_msg>Fix call to newPortForwardEntry constructor in kubectl_forwarder_test to fix build<commit_after>/*
Copyright 2019 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 portforward

import (
	"bytes"
	"context"
	"os/exec"
	"strings"
	"sync"
	"testing"
	"time"

	"github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/latest"
)

func TestUnavailablePort(t *testing.T) {

	original := isPortFree
	defer func() { isPortFree = original }()

	// Return that the port is false, while also
	// adding a sync group so we know when isPortFree
	// has been called
	portFreeWG := &sync.WaitGroup{}
	portFreeWG.Add(1)
	isPortFree = func(_ int) bool {
		defer portFreeWG.Done()
		return false
	}

	// Create a wait group that will only be
	// fulfilled when the forward function returns
	forwardFunctionWG := &sync.WaitGroup{}
	forwardFunctionWG.Add(1)
	originalDefer := deferFunc
	defer func() { deferFunc = originalDefer }()
	deferFunc = func() { defer forwardFunctionWG.Done() }

	buf := bytes.NewBuffer([]byte{})
	k := KubectlForwarder{
		out: buf,
	}
	pfe := newPortForwardEntry(0, latest.PortForwardResource{}, "", "", "", "", 8080, false)

	k.Forward(context.Background(), pfe)

	// wait for isPortFree to be called
	portFreeWG.Wait()

	// then, end port forwarding and wait for the forward function to return.
	pfe.terminationLock.Lock()
	pfe.terminated = true
	pfe.terminationLock.Unlock()
	forwardFunctionWG.Wait()

	// read output to make sure logs are expected
	output := buf.String()
	if !strings.Contains(output, "port 8080 is taken") {
		t.Fatalf("port wasn't available but didn't get warning, got: \n%s", output)
	}
}

func TestTerminate(t *testing.T) {
	ctx, cancel := context.WithCancel(context.Background())

	pfe := newPortForwardEntry(0, latest.PortForwardResource{}, "", "", "", "", 8080, false)
	pfe.cancel = cancel

	k := &KubectlForwarder{}
	k.Terminate(pfe)
	if pfe.terminated != true {
		t.Fatalf("expected pfe.terminated to be true after termination")
	}
	if ctx.Err() != context.Canceled {
		t.Fatalf("expected cancel to be called")
	}
}

func TestMonitorErrorLogs(t *testing.T) {
	tests := []struct {
		description string
		input       string
		cmdRunning  bool
	}{
		{
			description: "no error logs appear",
{'fraction_non_alphanumeric': 0.11308861698183166, 'fraction_numerical': 0.008898776418242492, 'mean_word_length': 4.21256038647343, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2890708', 'n_tokens_mistral': 1786, 'n_tokens_neox': 1686, 'n_words': 558}