...

Source file src/cuelang.org/go/tools/flow/cycle_test.go

Documentation: cuelang.org/go/tools/flow

     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  // MermaidGraph exports mermaidGraph for external tests
    24  var MermaidGraph = mermaidGraph
    25  
    26  func TestIsCyclic(t *testing.T) {
    27  	testCases := []struct {
    28  		// semi-colon-separated list of nodes with comma-separated list
    29  		// of dependencies.
    30  		tasks string
    31  		cycle bool
    32  	}{{
    33  		tasks: "",
    34  	}, {
    35  		tasks: "0",
    36  		cycle: true,
    37  	}, {
    38  		tasks: "1; 0",
    39  		cycle: true,
    40  	}, {
    41  		tasks: "1; 2; 3; 4;",
    42  	}, {
    43  		tasks: "1; 2; ; 4; 5; ",
    44  	}, {
    45  		tasks: "1; 2; 3; 4; 0",
    46  		cycle: true,
    47  	}, {
    48  		tasks: "1,2,3,4; 2,3,4; 3,4; 4;",
    49  	}, {
    50  		tasks: ";0;0,1;0,1,2;0,1,2,3;",
    51  	}, {
    52  		tasks: "1,2,3,4; 2,3,4; 2; 4;",
    53  		cycle: true,
    54  	}}
    55  	for _, tc := range testCases {
    56  		t.Run(tc.tasks, func(t *testing.T) {
    57  			deps := strings.Split(tc.tasks, ";")
    58  			tasks := make([]*Task, len(deps))
    59  			for i := range tasks {
    60  				tasks[i] = &Task{index: i}
    61  			}
    62  			for i, d := range deps {
    63  				if d == "" {
    64  					continue
    65  				}
    66  				for _, num := range strings.Split(d, ",") {
    67  					num = strings.TrimSpace(num)
    68  					if num == "" {
    69  						continue
    70  					}
    71  					x, err := strconv.Atoi(num)
    72  					if err != nil {
    73  						t.Fatal(err)
    74  					}
    75  					t.Logf("%d -> %d", i, x)
    76  					tasks[i].depTasks = append(tasks[i].depTasks, tasks[x])
    77  				}
    78  			}
    79  			if got := checkCycle(tasks) != nil; got != tc.cycle {
    80  				t.Errorf("got %v; want %v", got, tc.cycle)
    81  			}
    82  		})
    83  	}
    84  }
    85  

View as plain text