| 1 | /* |
| 2 | * This file is part of the go-nft project |
| 3 | * |
| 4 | * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | * you may not use this file except in compliance with the License. |
| 6 | * You may obtain a copy of the License at |
| 7 | * |
| 8 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | * |
| 10 | * Unless required by applicable law or agreed to in writing, software |
| 11 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | * See the License for the specific language governing permissions and |
| 14 | * limitations under the License. |
| 15 | * |
| 16 | * Copyright 2021 Red Hat, Inc. |
| 17 | * |
| 18 | */ |
| 19 | |
| 20 | package testlib |
| 21 | |
| 22 | import ( |
| 23 | "sort" |
| 24 | "testing" |
| 25 | |
| 26 | "github.com/networkplumbing/go-nft/nft" |
| 27 | "github.com/networkplumbing/go-nft/nft/schema" |
| 28 | ) |
| 29 | |
| 30 | func RunTestWithFlushTable(t *testing.T, test func(t *testing.T)) { |
| 31 | t.Run("", func(t *testing.T) { |
| 32 | t.Cleanup(flushRuleset) |
| 33 | test(t) |
| 34 | }) |
| 35 | } |
| 36 | |
| 37 | func flushRuleset() { |
| 38 | _ = nft.ApplyConfig(&nft.Config{schema.Root{Nftables: []schema.Nftable{ |
| 39 | {Flush: &schema.Objects{Ruleset: true}}, |
| 40 | }}}) |
| 41 | } |
| 42 | |
| 43 | // NormalizeConfigForComparison returns the configuration ready for comparison with another by |
| 44 | // - removing the metainfo entry. |
| 45 | // - removing the handle + index parameters. |
| 46 | // - Sorting the list. |
| 47 | func NormalizeConfigForComparison(config *nft.Config) *nft.Config { |
| 48 | if len(config.Nftables) > 0 && config.Nftables[0].Metainfo != nil { |
| 49 | config.Nftables = config.Nftables[1:] |
| 50 | } |
| 51 | |
| 52 | for _, nftable := range config.Nftables { |
| 53 | if nftable.Rule != nil { |
| 54 | nftable.Rule.Index = nil |
| 55 | nftable.Rule.Handle = nil |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | sort.Slice(config.Nftables, func(i int, j int) bool { |
| 60 | s := config.Nftables |
| 61 | isTableFirst := s[i].Table != nil && (s[j].Chain != nil || s[j].Rule != nil) |
| 62 | isChainBeforeRule := s[i].Chain != nil && s[j].Rule != nil |
| 63 | return isTableFirst || isChainBeforeRule |
| 64 | }) |
| 65 | return config |
| 66 | } |