From 75a5866418ffd37a6e0adcb79da7cfff5f617266 Mon Sep 17 00:00:00 2001 From: Vitaliy Turov Date: Tue, 25 Feb 2025 20:56:21 +0300 Subject: [PATCH] Lesson6 --- go/lesson6/linting/config/.golangci.yml | 47 ++++++++++ go/lesson6/linting/funlen/funlen.go | 86 +++++++++++++++++++ go/lesson6/linting/go.mod | 3 + go/lesson6/linting/gosimple/gosimple.go | 13 +++ go/lesson6/linting/inefassign/inefassign.go | 7 ++ go/lesson6/linting/unused/unused.go | 10 +++ go/lesson6/testingB/go.mod | 3 + go/lesson6/testingB/mySort/sort.go | 25 ++++++ go/lesson6/testingB/mySort/sort_test.go | 17 ++++ .../reportAllocs/reportAllocs_test.go | 16 ++++ .../reportMetric/reportMetric_test.go | 17 ++++ .../testingB/resetTimer/resetTimer_test.go | 22 +++++ .../testingB/runParallel/runParallel_test.go | 22 +++++ go/lesson6/testingB/setBytes/setBytes_test.go | 15 ++++ .../startStopTimer/startStopTimer_test.go | 25 ++++++ go/lesson6/testingF/fuzz_test.go | 63 ++++++++++++++ go/lesson6/testingF/go.mod | 3 + .../fuzz/FuzzReverse/28f36ef487f23e6c | 2 + go/lesson6/testingT/cleanup/cleanup_test.go | 40 +++++++++ go/lesson6/testingT/cleanup/output.txt | 1 + go/lesson6/testingT/go.mod | 3 + go/lesson6/testingT/helper/helper_test.go | 36 ++++++++ go/lesson6/testingT/mySort/profile | 17 ++++ go/lesson6/testingT/mySort/sort.go | 35 ++++++++ go/lesson6/testingT/mySort/sort_test.go | 60 +++++++++++++ go/lesson6/testingT/parallel/parallel_test.go | 31 +++++++ go/lesson6/testingT/run/sort.go | 11 +++ go/lesson6/testingT/run/sort_test.go | 37 ++++++++ go/lesson6/testingT/setenv/setenv_test.go | 21 +++++ go/lesson6/testingT/tempDir/temp_dir_test.go | 32 +++++++ 30 files changed, 720 insertions(+) create mode 100644 go/lesson6/linting/config/.golangci.yml create mode 100644 go/lesson6/linting/funlen/funlen.go create mode 100644 go/lesson6/linting/go.mod create mode 100644 go/lesson6/linting/gosimple/gosimple.go create mode 100644 go/lesson6/linting/inefassign/inefassign.go create mode 100644 go/lesson6/linting/unused/unused.go create mode 100644 go/lesson6/testingB/go.mod create mode 100644 go/lesson6/testingB/mySort/sort.go create mode 100644 go/lesson6/testingB/mySort/sort_test.go create mode 100644 go/lesson6/testingB/reportAllocs/reportAllocs_test.go create mode 100644 go/lesson6/testingB/reportMetric/reportMetric_test.go create mode 100644 go/lesson6/testingB/resetTimer/resetTimer_test.go create mode 100644 go/lesson6/testingB/runParallel/runParallel_test.go create mode 100644 go/lesson6/testingB/setBytes/setBytes_test.go create mode 100644 go/lesson6/testingB/startStopTimer/startStopTimer_test.go create mode 100644 go/lesson6/testingF/fuzz_test.go create mode 100644 go/lesson6/testingF/go.mod create mode 100644 go/lesson6/testingF/testdata/fuzz/FuzzReverse/28f36ef487f23e6c create mode 100644 go/lesson6/testingT/cleanup/cleanup_test.go create mode 100644 go/lesson6/testingT/cleanup/output.txt create mode 100644 go/lesson6/testingT/go.mod create mode 100644 go/lesson6/testingT/helper/helper_test.go create mode 100644 go/lesson6/testingT/mySort/profile create mode 100644 go/lesson6/testingT/mySort/sort.go create mode 100644 go/lesson6/testingT/mySort/sort_test.go create mode 100644 go/lesson6/testingT/parallel/parallel_test.go create mode 100644 go/lesson6/testingT/run/sort.go create mode 100644 go/lesson6/testingT/run/sort_test.go create mode 100644 go/lesson6/testingT/setenv/setenv_test.go create mode 100644 go/lesson6/testingT/tempDir/temp_dir_test.go diff --git a/go/lesson6/linting/config/.golangci.yml b/go/lesson6/linting/config/.golangci.yml new file mode 100644 index 0000000..62f4e8a --- /dev/null +++ b/go/lesson6/linting/config/.golangci.yml @@ -0,0 +1,47 @@ +# options for analysis running +run: + # timeout for analysis, e.g. 30s, 5m, default is 1m + timeout: 5m + + # include test files or not, default is true + tests: false + +# output configuration options +output: + # colored-line-number|line-number|json|tab|checkstyle|code-climate, default is "colored-line-number" + format: tab + +# all available settings of specific linters +linters-settings: + govet: + # report about shadowed variables + check-shadowing: false + +linters: + enable: + # mandatory linters + - govet + - revive + + # some default golangci-lint linters + - errcheck + - gosimple + - godot + - ineffassign + - staticcheck + - typecheck + - unused + + # extra linters + - bidichk + - durationcheck + - exhaustive + - exportloopref + - gofmt + - goimports + - misspell + - predeclared + - reassign + - whitespace + disable-all: true + diff --git a/go/lesson6/linting/funlen/funlen.go b/go/lesson6/linting/funlen/funlen.go new file mode 100644 index 0000000..f441fed --- /dev/null +++ b/go/lesson6/linting/funlen/funlen.go @@ -0,0 +1,86 @@ +package main + +import ( + "fmt" + "math" + "math/rand" +) + +func main() { + longFunc() +} + +func longFunc() { + // Создаем массив случайных чисел + nums := make([]int, 100) + for i := 0; i < len(nums); i++ { + nums[i] = rand.Intn(1000) + } + fmt.Println("Исходный массив:", nums) + + // Выполняем сортировку пузырьком + for i := 0; i < len(nums)-1; i++ { + for j := i + 1; j < len(nums); j++ { + if nums[i] > nums[j] { + nums[i], nums[j] = nums[j], nums[i] + } + } + } + fmt.Println("Отсортированный массив:", nums) + + // Вычисляем среднее значение + sum := 0 + for i := 0; i < len(nums); i++ { + sum += nums[i] + } + average := float64(sum) / float64(len(nums)) + fmt.Printf("Среднее значение: %.2f\n", average) + + // Вычисляем медиану + median := 0 + if len(nums)%2 == 0 { + median = (nums[len(nums)/2-1] + nums[len(nums)/2]) / 2 + } else { + median = nums[len(nums)/2] + } + fmt.Println("Медиана:", median) + + // Вычисляем стандартное отклонение + deviation := 0.0 + for i := 0; i < len(nums); i++ { + deviation += (float64(nums[i]) - average) * (float64(nums[i]) - average) + } + deviation = deviation / float64(len(nums)) + deviation = math.Sqrt(deviation) + fmt.Printf("Стандартное отклонение: %.2f\n", deviation) + + // Выполняем сортировку пузырьком повторно :-) + for i := 0; i < len(nums)-1; i++ { + for j := i + 1; j < len(nums); j++ { + if nums[i] > nums[j] { + nums[i], nums[j] = nums[j], nums[i] + } + } + } + fmt.Println("Отсортированный массив:", nums) + + // Выполняем сортировку пузырьком в третий раз для закрепления пройденного материала + for i := 0; i < len(nums)-1; i++ { + for j := i + 1; j < len(nums); j++ { + if nums[i] > nums[j] { + nums[i], nums[j] = nums[j], nums[i] + } + } + } + fmt.Println("Отсортированный массив:", nums) + + // Выполняем сортировку пузырьком в последний раз + for i := 0; i < len(nums)-1; i++ { + for j := i + 1; j < len(nums); j++ { + if nums[i] > nums[j] { + nums[i], nums[j] = nums[j], nums[i] + } + } + } + fmt.Println("Отсортированный массив:", nums) +} diff --git a/go/lesson6/linting/go.mod b/go/lesson6/linting/go.mod new file mode 100644 index 0000000..d9be0b8 --- /dev/null +++ b/go/lesson6/linting/go.mod @@ -0,0 +1,3 @@ +module linting + +go 1.24.0 diff --git a/go/lesson6/linting/gosimple/gosimple.go b/go/lesson6/linting/gosimple/gosimple.go new file mode 100644 index 0000000..8245e8c --- /dev/null +++ b/go/lesson6/linting/gosimple/gosimple.go @@ -0,0 +1,13 @@ +package main + +func main() { + _ = fn1() +} + +func fn1() bool { + x := true + if x { //@ diag(`should use 'return x'`) + return true + } + return false +} diff --git a/go/lesson6/linting/inefassign/inefassign.go b/go/lesson6/linting/inefassign/inefassign.go new file mode 100644 index 0000000..164046d --- /dev/null +++ b/go/lesson6/linting/inefassign/inefassign.go @@ -0,0 +1,7 @@ +package inefassign + +func _() { + x := true // want "ineffectual assignment to x" + x = false + _ = x +} diff --git a/go/lesson6/linting/unused/unused.go b/go/lesson6/linting/unused/unused.go new file mode 100644 index 0000000..5fe8931 --- /dev/null +++ b/go/lesson6/linting/unused/unused.go @@ -0,0 +1,10 @@ +package unused + +func fn1() int { + const y = 2 + return 5 +} + +func fn2() { + fn1() +} \ No newline at end of file diff --git a/go/lesson6/testingB/go.mod b/go/lesson6/testingB/go.mod new file mode 100644 index 0000000..1f5e0c5 --- /dev/null +++ b/go/lesson6/testingB/go.mod @@ -0,0 +1,3 @@ +module testingb + +go 1.24.0 diff --git a/go/lesson6/testingB/mySort/sort.go b/go/lesson6/testingB/mySort/sort.go new file mode 100644 index 0000000..890ec42 --- /dev/null +++ b/go/lesson6/testingB/mySort/sort.go @@ -0,0 +1,25 @@ +package mySort + +func BubbleSort(ar []int) { + for i := 0; i < len(ar); i++ { + for j := len(ar) - 1; j > i; j-- { + if ar[j-1] > ar[j] { + ar[j-1], ar[j] = ar[j], ar[j-1] + } + } + } +} + +func SelectSort(ar []int) { + for i := 0; i < len(ar)-1; i++ { + min := i + for j := i + 1; j < len(ar); j++ { + if ar[min] > ar[j] { + min = j + } + } + if min != i { + ar[i], ar[min] = ar[min], ar[i] + } + } +} diff --git a/go/lesson6/testingB/mySort/sort_test.go b/go/lesson6/testingB/mySort/sort_test.go new file mode 100644 index 0000000..c9aaf39 --- /dev/null +++ b/go/lesson6/testingB/mySort/sort_test.go @@ -0,0 +1,17 @@ +package mySort + +import ( + "testing" +) + +func BenchmarkBubbleSort(b *testing.B) { + for n := 0; n < b.N; n++ { + BubbleSort([]int{9, 8, 7, 6, 5, 4, 3, 2, 1}) + } +} + +func BenchmarkSelectSort(b *testing.B) { + for n := 0; n < b.N; n++ { + SelectSort([]int{9, 8, 7, 6, 5, 4, 3, 2, 1}) + } +} diff --git a/go/lesson6/testingB/reportAllocs/reportAllocs_test.go b/go/lesson6/testingB/reportAllocs/reportAllocs_test.go new file mode 100644 index 0000000..2c4f6a1 --- /dev/null +++ b/go/lesson6/testingB/reportAllocs/reportAllocs_test.go @@ -0,0 +1,16 @@ +package reportAllocs + +import ( + "fmt" + "testing" +) + +func BenchmarkSample(b *testing.B) { + b.ReportAllocs() + for i := 0; i < b.N; i++ { + x := fmt.Sprintf("%d", 42) + b := fmt.Sprintf("%d", 42) + _ = x + _ = b + } +} diff --git a/go/lesson6/testingB/reportMetric/reportMetric_test.go b/go/lesson6/testingB/reportMetric/reportMetric_test.go new file mode 100644 index 0000000..5611153 --- /dev/null +++ b/go/lesson6/testingB/reportMetric/reportMetric_test.go @@ -0,0 +1,17 @@ +package reportMetric + +import "testing" + +func BenchmarkProcessData(b *testing.B) { + var addOperations int + for n := 0; n < b.N; n++ { + a := 5 + c := 6 + d := a + c + addOperations++ + e := d + a + addOperations++ + _ = e + } + b.ReportMetric(float64(addOperations), "addOps") +} diff --git a/go/lesson6/testingB/resetTimer/resetTimer_test.go b/go/lesson6/testingB/resetTimer/resetTimer_test.go new file mode 100644 index 0000000..7f2931e --- /dev/null +++ b/go/lesson6/testingB/resetTimer/resetTimer_test.go @@ -0,0 +1,22 @@ +package resetTimer + +import "testing" + +func sum(data []int) int { + var sum int + for _, val := range data { + sum += val + } + return sum +} + +func BenchmarkSum(b *testing.B) { + var data []int + for i := 0; i < 100000000; i++ { + data = append(data, i) + } + b.ResetTimer() + for n := 0; n < b.N; n++ { + sum(data) // Обработка данных + } +} diff --git a/go/lesson6/testingB/runParallel/runParallel_test.go b/go/lesson6/testingB/runParallel/runParallel_test.go new file mode 100644 index 0000000..4dad7f6 --- /dev/null +++ b/go/lesson6/testingB/runParallel/runParallel_test.go @@ -0,0 +1,22 @@ +package runParallel + +import ( + "testing" +) + +func BenchmarkParallel(b *testing.B) { + var data []int + for i := 0; i < 100000000; i++ { + data = append(data, i) + } + b.ResetTimer() + + b.RunParallel(func(pb *testing.PB) { + var sum int + for pb.Next() { + for _, num := range data { + sum += num + } + } + }) +} diff --git a/go/lesson6/testingB/setBytes/setBytes_test.go b/go/lesson6/testingB/setBytes/setBytes_test.go new file mode 100644 index 0000000..b304340 --- /dev/null +++ b/go/lesson6/testingB/setBytes/setBytes_test.go @@ -0,0 +1,15 @@ +package setBytes + +import "testing" + +func myFunc(data []byte) int { + return len(data) +} + +func BenchmarkMyFunc(b *testing.B) { + input := make([]byte, 10) + b.SetBytes(int64(len(input))) + for i := 0; i < b.N; i++ { + _ = myFunc(input) + } +} diff --git a/go/lesson6/testingB/startStopTimer/startStopTimer_test.go b/go/lesson6/testingB/startStopTimer/startStopTimer_test.go new file mode 100644 index 0000000..74876b9 --- /dev/null +++ b/go/lesson6/testingB/startStopTimer/startStopTimer_test.go @@ -0,0 +1,25 @@ +package startStopTimer + +import "testing" + +func sum(data []int) int { + var sum int + for _, val := range data { + sum += val + } + return sum +} + +func BenchmarkSum(b *testing.B) { + b.StopTimer() + var data []int + for i := 0; i < 100000000; i++ { + data = append(data, i) + } + b.StartTimer() + for n := 0; n < b.N; n++ { + sum(data) // Обработка данных + } + b.StopTimer() + //некоторый код, который мы не хотим включать в результаты бенчмарка +} diff --git a/go/lesson6/testingF/fuzz_test.go b/go/lesson6/testingF/fuzz_test.go new file mode 100644 index 0000000..8784900 --- /dev/null +++ b/go/lesson6/testingF/fuzz_test.go @@ -0,0 +1,63 @@ +package main + +import ( + "errors" + "strings" + "testing" +) + +// Функция проверки, является ли строка палиндромом +func IsPalindrome(s string) (bool, error) { + // Ограничим размер строки для избежания чрезмерного использования памяти + if len(s) > 1000 { + return false, errors.New("input too long") + } + + // Приведем строку к нижнему регистру и уберем пробелы + processed := strings.ToLower(strings.ReplaceAll(s, " ", "")) + + // Проверяем, является ли строка палиндромом + for i := 0; i < len(processed)/2; i++ { + if processed[i] != processed[len(processed)-1-i] { + return false, nil + } + } + + return true, nil +} + +// Fuzz-тест для проверки функции IsPalindrome +func FuzzIsPalindrome(f *testing.F) { + // Добавляем базовые тестовые примеры + f.Add("madam") // палиндром + f.Add("racecar") // палиндром + f.Add("hello") // не палиндром + f.Add("A Santa at NASA") // палиндром с пробелами + f.Add("😊😊😊😊😊") // палиндром с эмодзи + f.Add("abc cba") // палиндром с пробелом + + f.Fuzz(func(t *testing.T, input string) { + result, err := IsPalindrome(input) + + // Проверяем, что функция не завершилась с ошибкой для строк допустимой длины + if len(input) <= 1000 && err != nil { + t.Errorf("unexpected error for input %q: %v", input, err) + } + + // Если строка перевернута и равна самой себе, это палиндром + reversed := reverseString(input) + expected := strings.ToLower(strings.ReplaceAll(input, " ", "")) + if result && reversed != expected { + t.Errorf("expected palindrome logic to pass, but got false for input %q", input) + } + }) +} + +// Вспомогательная функция: переворачивает строку +func reverseString(s string) string { + runes := []rune(strings.ToLower(strings.ReplaceAll(s, " ", ""))) + for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 { + runes[i], runes[j] = runes[j], runes[i] + } + return string(runes) +} diff --git a/go/lesson6/testingF/go.mod b/go/lesson6/testingF/go.mod new file mode 100644 index 0000000..4f92353 --- /dev/null +++ b/go/lesson6/testingF/go.mod @@ -0,0 +1,3 @@ +module testingF + +go 1.24.0 diff --git a/go/lesson6/testingF/testdata/fuzz/FuzzReverse/28f36ef487f23e6c b/go/lesson6/testingF/testdata/fuzz/FuzzReverse/28f36ef487f23e6c new file mode 100644 index 0000000..643a85b --- /dev/null +++ b/go/lesson6/testingF/testdata/fuzz/FuzzReverse/28f36ef487f23e6c @@ -0,0 +1,2 @@ +go test fuzz v1 +string("\xf0") diff --git a/go/lesson6/testingT/cleanup/cleanup_test.go b/go/lesson6/testingT/cleanup/cleanup_test.go new file mode 100644 index 0000000..83ed4f6 --- /dev/null +++ b/go/lesson6/testingT/cleanup/cleanup_test.go @@ -0,0 +1,40 @@ +package cleanup + +import ( + "fmt" + "os" + "testing" +) + +func HelloWordToFile() (string, error) { + f, err := os.Create("output.txt") + if err != nil { + return "", err + } + + _, err = fmt.Fprint(f, "Hello, world!") + if err != nil { + f.Close() + return "", err + } + + // закрытие файла + err = f.Close() + if err != nil { + return "", err + } + + return "output_2.txt", nil +} + +func TestHelloWordToFile(t *testing.T) { + + result, err := HelloWordToFile() + if err != nil { + t.Errorf("Ошибка при выполнении функции: %v", err) + } + + if _, err := os.Stat(result); os.IsNotExist(err) { + t.Errorf("Файл не был создан: %s", result) + } +} diff --git a/go/lesson6/testingT/cleanup/output.txt b/go/lesson6/testingT/cleanup/output.txt new file mode 100644 index 0000000..5dd01c1 --- /dev/null +++ b/go/lesson6/testingT/cleanup/output.txt @@ -0,0 +1 @@ +Hello, world! \ No newline at end of file diff --git a/go/lesson6/testingT/go.mod b/go/lesson6/testingT/go.mod new file mode 100644 index 0000000..c417c82 --- /dev/null +++ b/go/lesson6/testingT/go.mod @@ -0,0 +1,3 @@ +module testingt + +go 1.24.0 diff --git a/go/lesson6/testingT/helper/helper_test.go b/go/lesson6/testingT/helper/helper_test.go new file mode 100644 index 0000000..282f3f2 --- /dev/null +++ b/go/lesson6/testingT/helper/helper_test.go @@ -0,0 +1,36 @@ +package helper + +import "testing" + +func MaxInt(numbers []int) int { + if len(numbers) == 0 { + panic("Пустой массив передан в функцию MaxInt") + } + + max := numbers[0] + + for i := 1; i < len(numbers); i++ { + if numbers[i] > max { + max = numbers[i] + } + } + + return max +} + +func failure(t *testing.T) { + t.Helper() + t.Fatal("failure") +} + +func TestMaxInt(t *testing.T) { + + input := []int{1, 2, 3, 4, 5} + expectedOutput := 5 + + result := MaxInt(input) + + if result != expectedOutput { + failure(t) + } +} diff --git a/go/lesson6/testingT/mySort/profile b/go/lesson6/testingT/mySort/profile new file mode 100644 index 0000000..cf20df6 --- /dev/null +++ b/go/lesson6/testingT/mySort/profile @@ -0,0 +1,17 @@ +mode: set +go_testing/testingT/mySort/sort.go:5.33,6.18 1 1 +go_testing/testingT/mySort/sort.go:9.2,9.31 1 1 +go_testing/testingT/mySort/sort.go:16.2,16.12 1 1 +go_testing/testingT/mySort/sort.go:6.18,8.3 1 0 +go_testing/testingT/mySort/sort.go:9.31,10.36 1 1 +go_testing/testingT/mySort/sort.go:10.36,11.23 1 1 +go_testing/testingT/mySort/sort.go:11.23,13.5 1 1 +go_testing/testingT/mySort/sort.go:19.33,20.18 1 1 +go_testing/testingT/mySort/sort.go:23.2,23.33 1 1 +go_testing/testingT/mySort/sort.go:34.2,34.12 1 1 +go_testing/testingT/mySort/sort.go:20.18,22.3 1 0 +go_testing/testingT/mySort/sort.go:23.33,25.36 2 1 +go_testing/testingT/mySort/sort.go:30.3,30.15 1 1 +go_testing/testingT/mySort/sort.go:25.36,26.23 1 1 +go_testing/testingT/mySort/sort.go:26.23,28.5 1 1 +go_testing/testingT/mySort/sort.go:30.15,32.4 1 1 diff --git a/go/lesson6/testingT/mySort/sort.go b/go/lesson6/testingT/mySort/sort.go new file mode 100644 index 0000000..10fd91d --- /dev/null +++ b/go/lesson6/testingT/mySort/sort.go @@ -0,0 +1,35 @@ +package mySort + +import "errors" + +func BubbleSort(ar []int) error { + if len(ar) == 0 { + return errors.New("Array is empty") + } + for i := 0; i < len(ar); i++ { + for j := len(ar) - 1; j > i; j-- { + if ar[j-1] > ar[j] { + ar[j-1], ar[j] = ar[j], ar[j-1] + } + } + } + return nil +} + +func SelectSort(ar []int) error { + if len(ar) == 0 { + return errors.New("Array is empty") + } + for i := 0; i < len(ar)-1; i++ { + min := i + for j := i + 1; j < len(ar); j++ { + if ar[min] > ar[j] { + min = j + } + } + if min != i { + ar[i], ar[min] = ar[min], ar[i] + } + } + return nil +} diff --git a/go/lesson6/testingT/mySort/sort_test.go b/go/lesson6/testingT/mySort/sort_test.go new file mode 100644 index 0000000..6bd33a2 --- /dev/null +++ b/go/lesson6/testingT/mySort/sort_test.go @@ -0,0 +1,60 @@ +package mySort + +import ( + "testing" +) + +func TestBubbleSort(t *testing.T) { + testTable := []struct { + input []int + expected []int + }{ + { + input: []int{5, 35, 12, 24, 21, 98, 6, 10}, + expected: []int{5, 6, 10, 12, 21, 24, 35, 98}, + }, + { + input: []int{9, 8, 7, 6, 5, 4, 3, 2, 1}, + expected: []int{1, 2, 3, 4, 5, 6, 7, 8, 9}, + }, + } + + for _, testCase := range testTable { + BubbleSort(testCase.input) + + for inx, elem := range testCase.input { + if elem != testCase.expected[inx] { + t.Errorf("Bubble sort is not correct. Expect %d, got %d", testCase.expected, testCase.input) + break + } + } + } +} + +func TestSelectSort(t *testing.T) { + testTable := []struct { + input []int + expected []int + }{ + { + input: []int{5, 35, 12, 24, 21, 98, 6, 10}, + expected: []int{5, 6, 10, 12, 21, 24, 35, 98}, + }, + { + input: []int{9, 8, 7, 6, 5, 4, 3, 2, 1}, + expected: []int{1, 2, 3, 4, 5, 6, 7, 8, 9}, + }, + } + + for _, testCase := range testTable { + SelectSort(testCase.input) + + for inx, elem := range testCase.input { + if elem != testCase.expected[inx] { + t.Errorf("Select sort is not correct. Expect %d, got %d", testCase.expected, testCase.input) + break + } + } + } + +} diff --git a/go/lesson6/testingT/parallel/parallel_test.go b/go/lesson6/testingT/parallel/parallel_test.go new file mode 100644 index 0000000..62ee632 --- /dev/null +++ b/go/lesson6/testingT/parallel/parallel_test.go @@ -0,0 +1,31 @@ +package parallel + +import "testing" + +func MyFunctionParallel(n int) int { + return n * 2 +} + +func TestMyFunction1(t *testing.T) { + t.Parallel() + result := MyFunctionParallel(2) + if result != 4 { + t.Errorf("Expected MyFunction(2) to return 4, but got %d", result) + } +} + +func TestMyFunction2(t *testing.T) { + t.Parallel() + result := MyFunctionParallel(5) + if result != 10 { + t.Errorf("Expected MyFunction(5) to return 10, but got %d", result) + } +} + +func TestMyFunction3(t *testing.T) { + t.Parallel() + result := MyFunctionParallel(0) + if result != 0 { + t.Errorf("Expected MyFunction(0) to return 0, but got %d", result) + } +} diff --git a/go/lesson6/testingT/run/sort.go b/go/lesson6/testingT/run/sort.go new file mode 100644 index 0000000..04c17da --- /dev/null +++ b/go/lesson6/testingT/run/sort.go @@ -0,0 +1,11 @@ +package run + +func BubbleSort(ar []int) { + for i := 0; i < len(ar); i++ { + for j := len(ar) - 1; j > i; j-- { + if ar[j-1] > ar[j] { + ar[j-1], ar[j] = ar[j], ar[j-1] + } + } + } +} diff --git a/go/lesson6/testingT/run/sort_test.go b/go/lesson6/testingT/run/sort_test.go new file mode 100644 index 0000000..ee2f08e --- /dev/null +++ b/go/lesson6/testingT/run/sort_test.go @@ -0,0 +1,37 @@ +package run + +import ( + "testing" +) + +func TestBubbleSort(t *testing.T) { + testTable := []struct { + name string + input []int + expected []int + }{ + { + name: "Test1", + input: []int{5, 35, 12, 24, 21, 98, 6, 10}, + expected: []int{5, 6, 10, 12, 21, 24, 35, 98}, + }, + { + name: "Test2", + input: []int{9, 8, 7, 6, 5, 4, 3, 2, 1}, + expected: []int{1, 2, 3, 4, 5, 6, 7, 8, 9}, + }, + } + + for _, testCase := range testTable { + t.Run(testCase.name, func(t *testing.T) { + BubbleSort(testCase.input) + + for inx, elem := range testCase.input { + if elem != testCase.expected[inx] { + t.Errorf("Bubble sort is not correct. Expect %d, got %d", testCase.expected, testCase.input) + break + } + } + }) + } +} diff --git a/go/lesson6/testingT/setenv/setenv_test.go b/go/lesson6/testingT/setenv/setenv_test.go new file mode 100644 index 0000000..b5b801f --- /dev/null +++ b/go/lesson6/testingT/setenv/setenv_test.go @@ -0,0 +1,21 @@ +package setenv + +import ( + "os" + "testing" +) + +func MyFunction() string { + value := os.Getenv("MY_ENV_VAR") + return value +} + +func TestMyFunction(t *testing.T) { + // t.Setenv("MY_ENV_VAR", "some value") + + result := MyFunction() + expected := "some value" + if result != expected { + t.Errorf("MyFunction() returned %s, expected %s", result, expected) + } +} diff --git a/go/lesson6/testingT/tempDir/temp_dir_test.go b/go/lesson6/testingT/tempDir/temp_dir_test.go new file mode 100644 index 0000000..166b5c6 --- /dev/null +++ b/go/lesson6/testingT/tempDir/temp_dir_test.go @@ -0,0 +1,32 @@ +package tempDir + +import ( + "fmt" + "io/ioutil" + "path/filepath" + "testing" +) + +func FileLen(testFilePath string) int { + fileContents, _ := ioutil.ReadFile(testFilePath) + return len(fileContents) +} + +func TestMyFunction(t *testing.T) { + tempDir := t.TempDir() + fmt.Printf("TempDir %s\n", tempDir) + + testFilePath := filepath.Join(tempDir, "testfile.txt") + testFileContents := []byte("this is a test7") + err := ioutil.WriteFile(testFilePath, testFileContents, 0644) + if err != nil { + t.Fatal(err) + } + + result := FileLen(testFilePath) + + expectedSize := 14 + if result != expectedSize { + t.Errorf("MyFunction(%q) returned %q, expected %q", testFilePath, result, expectedSize) + } +}