├── .github
└── workflows
│ ├── metrics.yml
│ ├── nuget.yml
│ └── test.yml
├── .gitignore
├── CODE_METRICS.md
├── Directory.Build.props
├── LICENSE
├── README.md
├── Resources
└── Images
│ ├── Banner.afdesign
│ ├── Banner.jpg
│ ├── Banner.png
│ ├── Demos
│ └── networkcreationtool.jpg
│ ├── Logo.afdesign
│ ├── Logo.png
│ └── StateNetLogo.ico
├── StateNet.Tests
├── Engine
│ ├── Engine_Tests.cs
│ └── TransitionHistory_Tests.cs
├── Network
│ ├── Data
│ │ └── StateNetwork_Constructor_TestData.cs
│ ├── Helpers
│ │ ├── StateNetworkBuilder_Helpers.cs
│ │ ├── StateNetworkDictionary_Helpers.cs
│ │ └── StateNetwork_Helpers.cs
│ ├── StateNetworkBuilder_Tests.cs
│ ├── StateNetwork_Tests.cs
│ └── Validator
│ │ ├── StateNetworkValidator_TestData.cs
│ │ └── StateNetworkValidator_Tests.cs
├── StateNet.Tests.csproj
└── packages.lock.json
├── StateNet.sln
├── StateNet
├── Documentation
│ ├── core_classes.md
│ ├── game_playing_bot_machine.png
│ ├── planned_features.md
│ └── sample_project.md
├── Engine
│ ├── StateNetEngine.cs
│ └── Transitions
│ │ ├── Transition.cs
│ │ ├── TransitionHistory.cs
│ │ ├── TransitionHistoryExtensions.cs
│ │ └── TransitionResult.cs
├── Logo.ico
├── Network
│ ├── Connection.cs
│ ├── NetworkBuilder.cs
│ ├── StateNetwork.cs
│ ├── StateNetworkResult.cs
│ └── Validator
│ │ ├── MatchesVisitor.cs
│ │ ├── StateNetworkValidationResult.cs
│ │ └── StateNetworkValidator.cs
├── PatternMatching
│ ├── Expressions
│ │ ├── Matches.cs
│ │ ├── StateCount.cs
│ │ ├── StateCountFromEnd.cs
│ │ ├── StateCountFromStart.cs
│ │ ├── TransitionCount.cs
│ │ ├── TransitionCountFromEnd.cs
│ │ └── TransitionCountFromStart.cs
│ ├── Pattern.cs
│ ├── PatternMatcher.cs
│ └── StringExtensions.cs
├── Random
│ ├── IRandomNumberGenerator.cs
│ └── SystemRandomNumberGenerator.cs
├── Resources.cs
├── StateNet.csproj
└── packages.lock.json
└── azure-pipelines.yml
/.github/workflows/metrics.yml:
--------------------------------------------------------------------------------
1 | name: 'code metrics'
2 |
3 | on:
4 | push:
5 | branches: [ main ]
6 | paths:
7 | - '!./CODE_METRICS.md' # ignore this file
8 |
9 | workflow_dispatch:
10 | inputs:
11 | reason:
12 | description: 'The reason for running the workflow'
13 | required: true
14 | default: 'Manual run'
15 |
16 | jobs:
17 | build:
18 |
19 | runs-on: ubuntu-latest
20 |
21 | steps:
22 | - uses: actions/checkout@v2
23 |
24 | - name: 'Print manual run reason'
25 | if: ${{ github.event_name == 'workflow_dispatch' }}
26 | run: |
27 | echo 'Reason: ${{ github.event.inputs.reason }}'
28 | - name: .NET code metrics
29 | id: dotnet-code-metrics
30 | uses: dotnet/samples/github-actions/DotNet.GitHubAction@main
31 | env:
32 | GREETINGS: 'Hello, .NET developers!' # ${{ secrets.GITHUB_TOKEN }}
33 | with:
34 | owner: ${{ github.repository_owner }}
35 | name: ${{ github.repository }}
36 | branch: ${{ github.ref }}
37 | dir: ${{ './' }}
38 |
39 | - name: Create pull request
40 | uses: peter-evans/create-pull-request@v3.4.1
41 | if: ${{ steps.dotnet-code-metrics.outputs.updated-metrics }} == 'true'
42 | with:
43 | title: '${{ steps.dotnet-code-metrics.outputs.summary-title }}'
44 | body: '${{ steps.dotnet-code-metrics.outputs.summary-details }}'
45 | commit-message: '.NET code metrics, automated pull request.'
46 |
--------------------------------------------------------------------------------
/.github/workflows/nuget.yml:
--------------------------------------------------------------------------------
1 | name: nuget
2 | env:
3 | dotnet_version: 6.0.x
4 | on:
5 | push:
6 | branches:
7 | - main
8 | pull_request:
9 | types: [closed]
10 | branches:
11 | - main
12 |
13 | jobs:
14 | build:
15 | runs-on: ubuntu-18.04
16 | name: Update NuGet package
17 | steps:
18 | - uses: actions/checkout@v2
19 | - name: Setup .NET
20 | uses: actions/setup-dotnet@v1
21 | with:
22 | dotnet-version: ${{ env.dotnet_version }}
23 | - name: Restore
24 | run: dotnet restore
25 | - name: Build
26 | run: dotnet build -c Release --no-restore
27 | - name: Pack
28 | run: dotnet pack -c Release -o out
29 | - name: Push
30 | run: dotnet nuget push ./out/*.nupkg --source https://api.nuget.org/v3/index.json --api-key ${{secrets.NUGET_TOKEN}} --skip-duplicate --no-symbols true
31 |
--------------------------------------------------------------------------------
/.github/workflows/test.yml:
--------------------------------------------------------------------------------
1 | # The name of the workflow.
2 | # This is the name that's displayed for status
3 | # badges (commonly embedded in README.md files).
4 | name: tests
5 |
6 | # Trigger this workflow on a push, or pull request to
7 | # the production branch, when either C# or project files changed
8 | on:
9 | push:
10 | pull_request:
11 | branches: [ main ]
12 | paths-ignore:
13 | - 'README.md'
14 |
15 | # Create an environment variable named DOTNET_VERSION
16 | # and set it as "6.0.x"
17 | env:
18 | DOTNET_VERSION: '6.0.x' # The .NET SDK version to use
19 |
20 | # Defines a single job named "build-and-test"
21 | jobs:
22 | build-and-test:
23 |
24 | # When the workflow runs, this is the name that is logged
25 | # This job will run three times, once for each "os" defined
26 | name: build-and-test-${{matrix.os}}
27 | runs-on: ${{ matrix.os }}
28 | strategy:
29 | matrix:
30 | os: [ubuntu-latest, windows-latest, macOS-latest]
31 |
32 | # Each job run contains these five steps
33 | steps:
34 |
35 | # 1) Check out the source code so that the workflow can access it.
36 | - uses: actions/checkout@v2
37 |
38 | # 2) Set up the .NET CLI environment for the workflow to use.
39 | # The .NET version is specified by the environment variable.
40 | - name: Setup .NET
41 | uses: actions/setup-dotnet@v1
42 | with:
43 | dotnet-version: ${{ env.DOTNET_VERSION }}
44 |
45 | # 3) Restore the dependencies and tools of a project or solution.
46 | - name: Install dependencies
47 | run: dotnet restore
48 |
49 | # 4) Build a project or solution and all of its dependencies.
50 | - name: Build
51 | run: dotnet build --configuration Release --no-restore
52 |
53 | # 5) Test a project or solution.
54 | - name: Test
55 | run: dotnet test --no-restore --verbosity normal
56 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | ## Ignore Visual Studio temporary files, build results, and
2 | ## files generated by popular Visual Studio add-ons.
3 | ##
4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
5 |
6 | # User-specific files
7 | *.suo
8 | *.user
9 | *.userosscache
10 | *.sln.docstates
11 |
12 | # User-specific files (MonoDevelop/Xamarin Studio)
13 | *.userprefs
14 |
15 | # Build results
16 | [Dd]ebug/
17 | [Dd]ebugPublic/
18 | [Rr]elease/
19 | [Rr]eleases/
20 | x64/
21 | x86/
22 | bld/
23 | [Bb]in/
24 | [Oo]bj/
25 | [Ll]og/
26 |
27 | # Visual Studio 2015/2017 cache/options directory
28 | .vs/
29 | # Uncomment if you have tasks that create the project's static files in wwwroot
30 | #wwwroot/
31 |
32 | # Visual Studio 2017 auto generated files
33 | Generated\ Files/
34 |
35 | # MSTest test Results
36 | [Tt]est[Rr]esult*/
37 | [Bb]uild[Ll]og.*
38 |
39 | # NUNIT
40 | *.VisualState.xml
41 | TestResult.xml
42 |
43 | # Build Results of an ATL Project
44 | [Dd]ebugPS/
45 | [Rr]eleasePS/
46 | dlldata.c
47 |
48 | # Benchmark Results
49 | BenchmarkDotNet.Artifacts/
50 |
51 | # .NET Core
52 | project.lock.json
53 | project.fragment.lock.json
54 | artifacts/
55 | **/Properties/launchSettings.json
56 |
57 | # StyleCop
58 | StyleCopReport.xml
59 |
60 | # Files built by Visual Studio
61 | *_i.c
62 | *_p.c
63 | *_i.h
64 | *.ilk
65 | *.meta
66 | *.obj
67 | *.iobj
68 | *.pch
69 | *.pdb
70 | *.ipdb
71 | *.pgc
72 | *.pgd
73 | *.rsp
74 | *.sbr
75 | *.tlb
76 | *.tli
77 | *.tlh
78 | *.tmp
79 | *.tmp_proj
80 | *.log
81 | *.vspscc
82 | *.vssscc
83 | .builds
84 | *.pidb
85 | *.svclog
86 | *.scc
87 |
88 | # Chutzpah Test files
89 | _Chutzpah*
90 |
91 | # Visual C++ cache files
92 | ipch/
93 | *.aps
94 | *.ncb
95 | *.opendb
96 | *.opensdf
97 | *.sdf
98 | *.cachefile
99 | *.VC.db
100 | *.VC.VC.opendb
101 |
102 | # Visual Studio profiler
103 | *.psess
104 | *.vsp
105 | *.vspx
106 | *.sap
107 |
108 | # Visual Studio Trace Files
109 | *.e2e
110 |
111 | # TFS 2012 Local Workspace
112 | $tf/
113 |
114 | # Guidance Automation Toolkit
115 | *.gpState
116 |
117 | # ReSharper is a .NET coding add-in
118 | _ReSharper*/
119 | *.[Rr]e[Ss]harper
120 | *.DotSettings.user
121 |
122 | # JustCode is a .NET coding add-in
123 | .JustCode
124 |
125 | # TeamCity is a build add-in
126 | _TeamCity*
127 |
128 | # DotCover is a Code Coverage Tool
129 | *.dotCover
130 |
131 | # AxoCover is a Code Coverage Tool
132 | .axoCover/*
133 | !.axoCover/settings.json
134 |
135 | # Visual Studio code coverage results
136 | *.coverage
137 | *.coveragexml
138 |
139 | # NCrunch
140 | _NCrunch_*
141 | .*crunch*.local.xml
142 | nCrunchTemp_*
143 |
144 | # MightyMoose
145 | *.mm.*
146 | AutoTest.Net/
147 |
148 | # Web workbench (sass)
149 | .sass-cache/
150 |
151 | # Installshield output folder
152 | [Ee]xpress/
153 |
154 | # DocProject is a documentation generator add-in
155 | DocProject/buildhelp/
156 | DocProject/Help/*.HxT
157 | DocProject/Help/*.HxC
158 | DocProject/Help/*.hhc
159 | DocProject/Help/*.hhk
160 | DocProject/Help/*.hhp
161 | DocProject/Help/Html2
162 | DocProject/Help/html
163 |
164 | # Click-Once directory
165 | publish/
166 |
167 | # Publish Web Output
168 | *.[Pp]ublish.xml
169 | *.azurePubxml
170 | # Note: Comment the next line if you want to checkin your web deploy settings,
171 | # but database connection strings (with potential passwords) will be unencrypted
172 | *.pubxml
173 | *.publishproj
174 |
175 | # Microsoft Azure Web App publish settings. Comment the next line if you want to
176 | # checkin your Azure Web App publish settings, but sensitive information contained
177 | # in these scripts will be unencrypted
178 | PublishScripts/
179 |
180 | # NuGet Packages
181 | *.nupkg
182 | # The packages folder can be ignored because of Package Restore
183 | **/[Pp]ackages/*
184 | # except build/, which is used as an MSBuild target.
185 | !**/[Pp]ackages/build/
186 | # Uncomment if necessary however generally it will be regenerated when needed
187 | #!**/[Pp]ackages/repositories.config
188 | # NuGet v3's project.json files produces more ignorable files
189 | *.nuget.props
190 | *.nuget.targets
191 |
192 | # Microsoft Azure Build Output
193 | csx/
194 | *.build.csdef
195 |
196 | # Microsoft Azure Emulator
197 | ecf/
198 | rcf/
199 |
200 | # Windows Store app package directories and files
201 | AppPackages/
202 | BundleArtifacts/
203 | Package.StoreAssociation.xml
204 | _pkginfo.txt
205 | *.appx
206 |
207 | # Visual Studio cache files
208 | # files ending in .cache can be ignored
209 | *.[Cc]ache
210 | # but keep track of directories ending in .cache
211 | !*.[Cc]ache/
212 |
213 | # Others
214 | ClientBin/
215 | ~$*
216 | *~
217 | *.dbmdl
218 | *.dbproj.schemaview
219 | *.jfm
220 | *.pfx
221 | *.publishsettings
222 | orleans.codegen.cs
223 |
224 | # Including strong name files can present a security risk
225 | # (https://github.com/github/gitignore/pull/2483#issue-259490424)
226 | #*.snk
227 |
228 | # Since there are multiple workflows, uncomment next line to ignore bower_components
229 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
230 | #bower_components/
231 |
232 | # RIA/Silverlight projects
233 | Generated_Code/
234 |
235 | # Backup & report files from converting an old project file
236 | # to a newer Visual Studio version. Backup files are not needed,
237 | # because we have git ;-)
238 | _UpgradeReport_Files/
239 | Backup*/
240 | UpgradeLog*.XML
241 | UpgradeLog*.htm
242 | ServiceFabricBackup/
243 | *.rptproj.bak
244 |
245 | # SQL Server files
246 | *.mdf
247 | *.ldf
248 | *.ndf
249 |
250 | # Business Intelligence projects
251 | *.rdl.data
252 | *.bim.layout
253 | *.bim_*.settings
254 | *.rptproj.rsuser
255 |
256 | # Microsoft Fakes
257 | FakesAssemblies/
258 |
259 | # GhostDoc plugin setting file
260 | *.GhostDoc.xml
261 |
262 | # Node.js Tools for Visual Studio
263 | .ntvs_analysis.dat
264 | node_modules/
265 |
266 | # Visual Studio 6 build log
267 | *.plg
268 |
269 | # Visual Studio 6 workspace options file
270 | *.opt
271 |
272 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
273 | *.vbw
274 |
275 | # Visual Studio LightSwitch build output
276 | **/*.HTMLClient/GeneratedArtifacts
277 | **/*.DesktopClient/GeneratedArtifacts
278 | **/*.DesktopClient/ModelManifest.xml
279 | **/*.Server/GeneratedArtifacts
280 | **/*.Server/ModelManifest.xml
281 | _Pvt_Extensions
282 |
283 | # Paket dependency manager
284 | .paket/paket.exe
285 | paket-files/
286 |
287 | # FAKE - F# Make
288 | .fake/
289 |
290 | # JetBrains Rider
291 | .idea/
292 | *.sln.iml
293 |
294 | # CodeRush
295 | .cr/
296 |
297 | # Python Tools for Visual Studio (PTVS)
298 | __pycache__/
299 | *.pyc
300 |
301 | # Cake - Uncomment if you are using it
302 | # tools/**
303 | # !tools/packages.config
304 |
305 | # Tabs Studio
306 | *.tss
307 |
308 | # Telerik's JustMock configuration file
309 | *.jmconfig
310 |
311 | # BizTalk build output
312 | *.btp.cs
313 | *.btm.cs
314 | *.odx.cs
315 | *.xsd.cs
316 |
317 | # OpenCover UI analysis results
318 | OpenCover/
319 |
320 | # Azure Stream Analytics local run output
321 | ASALocalRun/
322 |
323 | # MSBuild Binary and Structured Log
324 | *.binlog
325 |
326 | # NVidia Nsight GPU debugger configuration file
327 | *.nvuser
328 |
329 | # MFractors (Xamarin productivity tool) working folder
330 | .mfractor/
331 |
--------------------------------------------------------------------------------
/Directory.Build.props:
--------------------------------------------------------------------------------
1 |
2 |
3 | true
4 | true
5 |
6 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) [year] [fullname]
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 |
3 |

4 |
5 |
6 |
7 | ## A .Net Standard library used to model complicated State Machines
8 |
9 | [](https://discord.gg/D8MSXJB)
10 | [](https://www.nuget.org/packages/Aptacode.StateNet/)
11 | [](https://www.codacy.com/gh/Aptacode/StateNet/dashboard?utm_source=github.com&utm_medium=referral&utm_content=Aptacode/StateNet&utm_campaign=Badge_Grade)
12 | 
13 | [](https://dev.azure.com/Aptacode/StateNet/_build/latest?definitionId=21&branchName=Development)
14 |
15 | ### Overview
16 |
17 | StateNet's primary purpose is to create a simple way to define and control the flow through pages of an application. However, since its inception the library has grown versatile with usecases ranging from X to Y.
18 |
19 | ### Usage
20 |
21 | At its core, StateNet works by defining a network of states, and how those states are connected. Inter-state connections are defined by a list of 'Connections' for a given 'Input' each of which have dynamically-computed probabilities.
22 |
23 | For example, consider a network that defines the traffic lights at a pedestrian crossing. The network will have these states:
24 | -Red
25 | -Yellow
26 | -Green
27 | -Pending Pedestrians
28 |
29 | The network's state will be `Green` until a pedestrian Triggers `Crossing`. An equation will then check if the `Green` state has been active for long enough. If it has, then the odds of moving to `Yellow` are 100%. If it hasn't been long enough, then the probability of transitioning to `Pending Pedestrians` is 100%. Once in either the `Yellow` or `Red` state, a Trigger such as 'timer-check' might fire every second. Every time `timer-check` fires, the state will only change back to `Green` if enough time has passed for pedestrians to have crossed.
30 |
31 | #### How to Configure the Network
32 | List all of the states your application needs. Then consider the relationships between those states in order to determine your system's Inputs (state transition trigger events). Create a connection by defining a source state, input, destination state and an expression which determines the weight of the connection at runtime.
33 |
34 | Weights can be as simple or dynamic as you need. For example, a dice will have 6 states, 1 Trigger (`roll`), and each state-connection (all 36 of them [6X6]) has a hard coded weight of 16.66%. A more complex system might use boolean logic, comparisons or arithmatic expressions to determine the connection weight based on the transition history.
35 |
36 |
37 | ```csharp
38 | //Defining the network
39 | var network = NetworkBuilder.New.SetStartState("A")
40 | .AddConnection("A", "Next", "B", new ConstantInteger(1))
41 | .AddConnection("B", "Next", "A", new ConstantInteger(1))
42 | .Build().Network;
43 |
44 | //Running the engine
45 | var engine = new StateNetEngine(network, new SystemRandomNumberGenerator());
46 | engine.OnTransition += (transition) => Console.WriteLine(transition);
47 | var state1 = engine.CurrentState; //A
48 | var state2 = engine.Apply("Next"); //B
49 | var state2 = engine.Apply("Next"); //A
50 |
51 | ```
52 |
53 | ## License
54 |
55 | MIT License
56 |
--------------------------------------------------------------------------------
/Resources/Images/Banner.afdesign:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Aptacode/StateNet/8c637af4501524546e4ae88dbe5e38397358f186/Resources/Images/Banner.afdesign
--------------------------------------------------------------------------------
/Resources/Images/Banner.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Aptacode/StateNet/8c637af4501524546e4ae88dbe5e38397358f186/Resources/Images/Banner.jpg
--------------------------------------------------------------------------------
/Resources/Images/Banner.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Aptacode/StateNet/8c637af4501524546e4ae88dbe5e38397358f186/Resources/Images/Banner.png
--------------------------------------------------------------------------------
/Resources/Images/Demos/networkcreationtool.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Aptacode/StateNet/8c637af4501524546e4ae88dbe5e38397358f186/Resources/Images/Demos/networkcreationtool.jpg
--------------------------------------------------------------------------------
/Resources/Images/Logo.afdesign:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Aptacode/StateNet/8c637af4501524546e4ae88dbe5e38397358f186/Resources/Images/Logo.afdesign
--------------------------------------------------------------------------------
/Resources/Images/Logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Aptacode/StateNet/8c637af4501524546e4ae88dbe5e38397358f186/Resources/Images/Logo.png
--------------------------------------------------------------------------------
/Resources/Images/StateNetLogo.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Aptacode/StateNet/8c637af4501524546e4ae88dbe5e38397358f186/Resources/Images/StateNetLogo.ico
--------------------------------------------------------------------------------
/StateNet.Tests/Engine/Engine_Tests.cs:
--------------------------------------------------------------------------------
1 | using System.Linq;
2 | using Aptacode.Expressions;
3 | using Aptacode.StateNet.Engine;
4 | using Aptacode.StateNet.Engine.Transitions;
5 | using Aptacode.StateNet.Network;
6 | using Aptacode.StateNet.PatternMatching;
7 | using Aptacode.StateNet.PatternMatching.Expressions;
8 | using Aptacode.StateNet.Random;
9 | using Moq;
10 | using StateNet.Tests.Network.Helpers;
11 | using Xunit;
12 |
13 | namespace StateNet.Tests.Engine;
14 |
15 | public class Engine_Tests
16 | {
17 | private readonly ExpressionFactory _expressions = new();
18 |
19 | [Fact]
20 | public void CurrentStateChanges_After_SuccessfulTransition()
21 | {
22 | //Arrange
23 | var networkResponse = StateNetworkBuilder_Helpers.Minimal_Valid_Connected_StaticWeight_NetworkBuilder
24 | .Build().Network;
25 |
26 | var sut = new StateNetEngine(networkResponse, new SystemRandomNumberGenerator());
27 |
28 | //Act
29 | sut.Apply("1");
30 |
31 | //Assert
32 | Assert.Equal("b", sut.CurrentState);
33 | }
34 |
35 | [Fact]
36 | public void CurrentStateDoesNotChange_After_FailedTransition()
37 | {
38 | //Arrange
39 | var networkResponse = StateNetworkBuilder_Helpers.Minimal_Valid_Connected_StaticWeight_NetworkBuilder
40 | .Build().Network;
41 |
42 | var sut = new StateNetEngine(networkResponse, new SystemRandomNumberGenerator());
43 |
44 | //Act
45 | sut.Apply("2");
46 |
47 | //Assert
48 | Assert.Equal("a", sut.CurrentState);
49 | }
50 |
51 |
52 | [Fact]
53 | public void Engine_Chooses_CorrectConnection_GivenWeights()
54 | {
55 | //Arrange
56 | var network = StateNetworkBuilder_Helpers.Minimal_Valid_Connected_StaticWeight_NetworkBuilder
57 | .AddConnection("a", "1", "c", _expressions.Int(1))
58 | .Build().Network;
59 |
60 | var mockRandomNumberGenerator = new Mock();
61 | mockRandomNumberGenerator
62 | .Setup(r => r.Generate(It.IsAny(), It.IsAny()))
63 | .Returns(1);
64 | //Act
65 | var sut = new StateNetEngine(network, mockRandomNumberGenerator.Object);
66 |
67 | var startState = sut.CurrentState;
68 | var secondState = sut.Apply("1");
69 |
70 | //Assert
71 | Assert.Equal("a", startState);
72 | Assert.Equal("c", secondState.Transition.Destination);
73 | }
74 |
75 | [Fact]
76 | public void Engine_Chooses_CorrectConnection_GivenWeights_NetworkWithMultipleBranches()
77 | {
78 | //Arrange
79 | var network = StateNetworkBuilder_Helpers.Minimal_Valid_Connected_StaticWeight_NetworkBuilder
80 | .AddConnection("a", "1", "c", _expressions.Int(1))
81 | .AddConnection("c", "1", "a", _expressions.Int(1))
82 | .AddConnection("c", "1", "b", _expressions.Int(1))
83 | .Build().Network;
84 |
85 | var mockRandomNumberGenerator = new Mock();
86 | mockRandomNumberGenerator
87 | .Setup(r => r.Generate(It.IsAny(), It.IsAny()))
88 | .Returns(1);
89 | //Act
90 | var sut = new StateNetEngine(network, mockRandomNumberGenerator.Object);
91 |
92 | var startState = sut.CurrentState;
93 | var secondState = sut.Apply("1");
94 | var thirdState = sut.Apply("1");
95 |
96 | //Assert
97 | Assert.Equal("a", startState);
98 | Assert.Equal("c", secondState.Transition.Destination);
99 | Assert.Equal("b", thirdState.Transition.Destination);
100 | }
101 |
102 |
103 | [Fact]
104 | public void EngineReverseTransition()
105 | {
106 | //Arrange
107 | var network = StateNetworkBuilder_Helpers.Minimal_Valid_Connected_StaticWeight_NetworkBuilder
108 | .AddConnection("b", "1", "a", _expressions.Int(1))
109 | .Build().Network;
110 |
111 | //Act
112 | var sut = new StateNetEngine(network, new SystemRandomNumberGenerator());
113 |
114 | var startState = sut.CurrentState;
115 | var secondState = sut.Apply("1");
116 | var thirdState = sut.Apply("1");
117 |
118 | //Assert
119 | Assert.Equal("a", startState);
120 | Assert.Equal("b", secondState.Transition.Destination);
121 | Assert.Equal("a", thirdState.Transition.Destination);
122 | }
123 |
124 | [Fact]
125 | public void EngineSingleTransition()
126 | {
127 | var network = StateNetworkBuilder_Helpers.Minimal_Valid_Connected_StaticWeight_NetworkBuilder
128 | .Build()
129 | .Network;
130 |
131 | var sut = new StateNetEngine(network, new SystemRandomNumberGenerator());
132 |
133 | var startState = sut.CurrentState;
134 | var secondState = sut.Apply("1");
135 |
136 | Assert.Equal("a", startState);
137 | Assert.Equal("b", secondState.Transition.Destination);
138 | }
139 |
140 | [Fact]
141 | public void EngineTransitionHistory()
142 | {
143 | var network = NetworkBuilder.New.SetStartState("A")
144 | .AddConnection("A", "Next", "B",
145 | _expressions.Conditional(
146 | _expressions.LessThan(_expressions.Count(new Matches(new Pattern("B")))
147 | ,
148 | _expressions.Int(1)),
149 | _expressions.Int(1),
150 | _expressions.Int(0)))
151 | .AddConnection("A", "Next", "C",
152 | _expressions.Conditional(
153 | _expressions.GreaterThanOrEqualTo(
154 | _expressions.Count(new Matches(new Pattern("B"))),
155 | _expressions.Int(1)),
156 | _expressions.Int(1),
157 | _expressions.Int(0)))
158 | .AddConnection("B", "Next", "A", _expressions.Int(1))
159 | .AddConnection("C", "Next", "D", _expressions.Int(1))
160 | .Build().Network;
161 |
162 | var sut = new StateNetEngine(network, new SystemRandomNumberGenerator());
163 |
164 | var state1 = sut.CurrentState;
165 | var state2 = sut.Apply("Next");
166 | var state3 = sut.Apply("Next");
167 | var state4 = sut.Apply("Next");
168 | var state5 = sut.Apply("Next");
169 |
170 | Assert.Equal("A", state1);
171 | Assert.Equal("B", state2.Transition.Destination);
172 | Assert.Equal("A", state3.Transition.Destination);
173 | Assert.Equal("C", state4.Transition.Destination);
174 | Assert.Equal("D", state5.Transition.Destination);
175 | }
176 |
177 | [Fact]
178 | public void GetAvailableConnections_Returns_CorrectList_WhenConnectionsExistForCurrentStateAndInput()
179 | {
180 | //Arrange
181 | var networkResponse = NetworkBuilder.New
182 | .SetStartState("Start").AddConnection("Start", "Next", "A", _expressions.Int(1))
183 | .Build().Network;
184 | var sut = new StateNetEngine(networkResponse, new SystemRandomNumberGenerator());
185 | //Act
186 | var connections = sut.GetAvailableConnections("Next");
187 | //Assert
188 | Assert.Equal("A", connections.FirstOrDefault().Target);
189 | }
190 |
191 | [Fact]
192 | public void GetAvailableConnections_Returns_EmptyList_WhenNoConnectionsExistsForCurrentStateAndInput()
193 | {
194 | //Arrange
195 | var networkResponse = NetworkBuilder.New
196 | .SetStartState("Start")
197 | .Build().Network;
198 | var sut = new StateNetEngine(networkResponse, new SystemRandomNumberGenerator());
199 | //Act
200 | var connections = sut.GetAvailableConnections("Next");
201 | //Assert
202 | Assert.Empty(connections);
203 | }
204 |
205 | [Fact]
206 | public void GetAvailableInputs_Returns_CorrectList_WhenInputExistsForCurrentState()
207 | {
208 | //Arrange
209 | var networkResponse = NetworkBuilder.New
210 | .SetStartState("Start").AddConnection("Start", "Next", "A", _expressions.Int(1))
211 | .Build().Network;
212 |
213 | var sut = new StateNetEngine(networkResponse, new SystemRandomNumberGenerator());
214 | //Act
215 | var inputs = sut.GetAvailableInputs();
216 | //Assert
217 | Assert.Equal("Next", inputs.FirstOrDefault());
218 | }
219 |
220 | [Fact]
221 | public void GetAvailableInputs_Returns_EmptyList_WhenNoInputExistsForCurrentState()
222 | {
223 | //Arrange
224 | var networkResponse = NetworkBuilder.New
225 | .SetStartState("Start")
226 | .Build().Network;
227 | var sut = new StateNetEngine(networkResponse, new SystemRandomNumberGenerator());
228 | //Act
229 | var inputs = sut.GetAvailableInputs();
230 | //Assert
231 | Assert.Empty(inputs);
232 | }
233 |
234 | [Fact]
235 | public void InputNotDefined_ReturnsFailTransition()
236 | {
237 | //Arrange
238 | var networkResponse = StateNetworkBuilder_Helpers.Minimal_Valid_Connected_StaticWeight_NetworkBuilder
239 | .Build().Network;
240 |
241 | var sut = new StateNetEngine(networkResponse, new SystemRandomNumberGenerator());
242 |
243 | //Act
244 | var transitionResult = sut.Apply("2");
245 |
246 | //Assert
247 | Assert.False(transitionResult.Success);
248 | }
249 |
250 |
251 | [Fact]
252 | public void OnTransition_Invoked_After_SuccessfulTransition()
253 | {
254 | //Arrange
255 | var networkResponse = StateNetworkBuilder_Helpers.Minimal_Valid_Connected_StaticWeight_NetworkBuilder
256 | .Build().Network;
257 |
258 | var sut = new StateNetEngine(networkResponse, new SystemRandomNumberGenerator());
259 | var onTransitionWasCalled = false;
260 | sut.OnTransition += (_, __) => { onTransitionWasCalled = true; };
261 | //Act
262 | sut.Apply("1");
263 |
264 | //Assert
265 | Assert.True(onTransitionWasCalled);
266 | }
267 |
268 | [Fact]
269 | public void OnTransition_NotInvoked_After_FailedTransition()
270 | {
271 | //Arrange
272 | var networkResponse = NetworkBuilder.New
273 | .SetStartState("Start")
274 | .Build().Network;
275 |
276 | var sut = new StateNetEngine(networkResponse, new SystemRandomNumberGenerator());
277 | var onTransitionWasCalled = false;
278 | sut.OnTransition += (_, __) => { onTransitionWasCalled = true; };
279 | //Act
280 | sut.Apply("Next");
281 |
282 | //Assert
283 | Assert.False(onTransitionWasCalled);
284 | }
285 | }
--------------------------------------------------------------------------------
/StateNet.Tests/Engine/TransitionHistory_Tests.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Linq;
3 | using Aptacode.StateNet.Engine.Transitions;
4 | using Aptacode.StateNet.PatternMatching;
5 | using StateNet.Tests.Network.Helpers;
6 | using Xunit;
7 |
8 | namespace StateNet.Tests.Engine;
9 |
10 | public class TransitionHistory_Tests
11 | {
12 | [Fact]
13 | public void Constructor_Throws_ArgumentNullException_WhenStartStateIsNull()
14 | {
15 | //Assert
16 | Assert.Throws(() =>
17 | {
18 | //Arrange
19 | //Act
20 | new TransitionHistory(null);
21 | });
22 | }
23 |
24 | [Fact]
25 | public void GetMatches_Returns_CorrectMatches_SingleMatch()
26 | {
27 | //Arrange
28 | var sut = new TransitionHistory(StateNetwork_Helpers
29 | .Minimal_Valid_Connected_StaticWeight_Network_WithPattern);
30 | sut.Add("1", "b");
31 | //Act
32 | var pattern = new Pattern(StateNetwork_Helpers.StateB);
33 | var matches = sut.GetMatches(pattern);
34 | //Assert
35 | Assert.Equal("1", matches.First().ToString());
36 | }
37 |
38 | //GetMatchesTest
39 | //AddTest
40 | [Fact]
41 | public void ToString_Returns_CorrectHistory_WithMultipleTransitions()
42 | {
43 | //Arrange
44 | var sut = new TransitionHistory(StateNetwork_Helpers.Minimal_Valid_Connected_StaticWeight_Network);
45 | sut.Add("1", "b");
46 | sut.Add("2", "c");
47 | //Act
48 | var actualResult = sut.ToString();
49 |
50 | //Assert
51 | Assert.Equal("a,1,b,2,c", actualResult);
52 | }
53 |
54 | [Fact]
55 | public void ToString_Returns_CorrectHistory_WithOneTransition()
56 | {
57 | //Arrange
58 | var sut = new TransitionHistory(StateNetwork_Helpers.Minimal_Valid_Connected_StaticWeight_Network);
59 | sut.Add("next", "b");
60 | //Act
61 | var actualResult = sut.ToString();
62 |
63 | //Assert
64 | Assert.Equal("a,next,b", actualResult);
65 | }
66 |
67 | [Fact]
68 | public void ToString_Returns_StartState_WhenNoTransition()
69 | {
70 | //Arrange
71 | var sut = new TransitionHistory(StateNetwork_Helpers.Minimal_Valid_Connected_StaticWeight_Network);
72 | //Act
73 | var actualResult = sut.ToString();
74 |
75 | //Assert
76 | Assert.Equal("a", actualResult);
77 | }
78 | }
--------------------------------------------------------------------------------
/StateNet.Tests/Network/Data/StateNetwork_Constructor_TestData.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections;
3 | using System.Collections.Generic;
4 | using StateNet.Tests.Network.Helpers;
5 |
6 | namespace StateNet.Tests.Network.Data;
7 |
8 | public class StateNetwork_Constructor_TestData : IEnumerable