github.com/joomcode/cue@v0.4.4-0.20221111115225-539fe3512047/tools/flow/cycle_test.go (about)

     1  // Copyright 2020 CUE Authors
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package flow
    16  
    17  import (
    18  	"strconv"
    19  	"strings"
    20  	"testing"
    21  )
    22  
    23  func TestIsCyclic(t *testing.T) {
    24  	testCases := []struct {
    25  		// semi-colon-separated list of nodes with comma-separated list
    26  		// of dependencies.
    27  		tasks string
    28  		cycle bool
    29  	}{{
    30  		tasks: "",
    31  	}, {
    32  		tasks: "0",
    33  		cycle: true,
    34  	}, {
    35  		tasks: "1; 0",
    36  		cycle: true,
    37  	}, {
    38  		tasks: "1; 2; 3; 4;",
    39  	}, {
    40  		tasks: "1; 2; ; 4; 5; ",
    41  	}, {
    42  		tasks: "1; 2; 3; 4; 0",
    43  		cycle: true,
    44  	}, {
    45  		tasks: "1,2,3,4; 2,3,4; 3,4; 4;",
    46  	}, {
    47  		tasks: ";0;0,1;0,1,2;0,1,2,3;",
    48  	}, {
    49  		tasks: "1,2,3,4; 2,3,4; 2; 4;",
    50  		cycle: true,
    51  	}}
    52  	for _, tc := range testCases {
    53  		t.Run(tc.tasks, func(t *testing.T) {
    54  			deps := strings.Split(tc.tasks, ";")
    55  			tasks := make([]*Task, len(deps))
    56  			for i := range tasks {
    57  				tasks[i] = &Task{index: i}
    58  			}
    59  			for i, d := range deps {
    60  				if d == "" {
    61  					continue
    62  				}
    63  				for _, num := range strings.Split(d, ",") {
    64  					num = strings.TrimSpace(num)
    65  					if num == "" {
    66  						continue
    67  					}
    68  					x, err := strconv.Atoi(num)
    69  					if err != nil {
    70  						t.Fatal(err)
    71  					}
    72  					t.Logf("%d -> %d", i, x)
    73  					tasks[i].depTasks = append(tasks[i].depTasks, tasks[x])
    74  				}
    75  			}
    76  			if got := checkCycle(tasks) != nil; got != tc.cycle {
    77  				t.Errorf("got %v; want %v", got, tc.cycle)
    78  			}
    79  		})
    80  	}
    81  }