├── .gitattributes
├── .gitignore
├── LICENSE
├── README.md
├── Sisters.WudiLib.Tests
├── EndpointTests.cs
├── ListenerTests.cs
├── SectionTests.cs
├── SendingMessageTests.cs
└── Sisters.WudiLib.Tests.csproj
├── Sisters.WudiLib.WebSocket.Test
├── Program.cs
└── Sisters.WudiLib.WebSocket.Test.csproj
├── Sisters.WudiLib.WebSocket
├── CqHttpWebSocketApiClient.cs
├── CqHttpWebSocketEvent.cs
├── HttpApiClientExtentions.cs
├── IEventReceiver.cs
├── IRequestSender.cs
├── PositiveWebSocketManager.cs
├── Properties
│ └── PublishProfiles
│ │ └── FolderProfile.pubxml
├── Reverse
│ ├── NegativeWebSocketEventListener.cs
│ ├── NegativeWebSocketManager.cs
│ ├── ReverseConnectionInfo.cs
│ └── ReverseWebSocketServer.cs
├── Sisters.WudiLib.WebSocket.csproj
├── WebSocketEventExtensions.cs
├── WebSocketManager.cs
└── WebSocketUtility.cs
├── Sisters.WudiLib.sln
├── Sisters.WudiLib
├── Builders
│ ├── Annotations
│ │ └── PostAttribute.cs
│ ├── DispatcherBuilder.cs
│ ├── PostTreeNode.cs
│ └── WudiLibBuilderException.cs
├── Dispatcher.cs
├── Exceptions.cs
├── HttpApiClient.cs
├── Message.cs
├── MessageEscapingExtensions.cs
├── MessageInterpolatedStringHandler.cs
├── Posts
│ ├── AnonymousInfo.cs
│ ├── ApiPostListener.GetPost.cs
│ ├── ApiPostListener.cs
│ ├── Endpoint.cs
│ ├── EventHandler.cs
│ ├── GroupBanType.cs
│ ├── MessageSource.cs
│ ├── Post.Message.cs
│ ├── Post.Notice.cs
│ ├── Post.cs
│ ├── ReceivedMessage.cs
│ ├── Responses.cs
│ └── SenderInfo.cs
├── Properties
│ └── PublishProfiles
│ │ └── FolderProfile.pubxml
├── RawMessage.cs
├── Responses
│ ├── CqHttpApiResponse.cs
│ ├── Friend.cs
│ ├── GetMessageResponseData.cs
│ ├── GroupInfo.cs
│ ├── GroupMemberInfo.cs
│ ├── LoginInfo.cs
│ ├── SendDiscussMessageResponseData.cs
│ ├── SendGroupMessageResponseData.cs
│ ├── SendMessageResponseData.cs
│ ├── SendPrivateMessageResponseData.cs
│ ├── Sex.cs
│ └── Status.cs
├── Section.cs
├── SectionMessage.cs
├── SendingMessage.cs
├── Sisters.WudiLib.csproj
├── System.Collections.Generic
│ └── CollectionExtensions.cs
├── TODO.md
└── Utilities.cs
└── Sisters.WudiLibTest
├── Program.cs
├── Properties
└── PublishProfiles
│ └── FolderProfile.pubxml
└── Sisters.WudiLibTest.csproj
/.gitattributes:
--------------------------------------------------------------------------------
1 | ###############################################################################
2 | # Set default behavior to automatically normalize line endings.
3 | ###############################################################################
4 | * text=auto
5 |
6 | ###############################################################################
7 | # Set default behavior for command prompt diff.
8 | #
9 | # This is need for earlier builds of msysgit that does not have it on by
10 | # default for csharp files.
11 | # Note: This is only used by command line
12 | ###############################################################################
13 | #*.cs diff=csharp
14 |
15 | ###############################################################################
16 | # Set the merge driver for project and solution files
17 | #
18 | # Merging from the command prompt will add diff markers to the files if there
19 | # are conflicts (Merging from VS is not affected by the settings below, in VS
20 | # the diff markers are never inserted). Diff markers may cause the following
21 | # file extensions to fail to load in VS. An alternative would be to treat
22 | # these files as binary and thus will always conflict and require user
23 | # intervention with every merge. To do so, just uncomment the entries below
24 | ###############################################################################
25 | #*.sln merge=binary
26 | #*.csproj merge=binary
27 | #*.vbproj merge=binary
28 | #*.vcxproj merge=binary
29 | #*.vcproj merge=binary
30 | #*.dbproj merge=binary
31 | #*.fsproj merge=binary
32 | #*.lsproj merge=binary
33 | #*.wixproj merge=binary
34 | #*.modelproj merge=binary
35 | #*.sqlproj merge=binary
36 | #*.wwaproj merge=binary
37 |
38 | ###############################################################################
39 | # behavior for image files
40 | #
41 | # image files are treated as binary by default.
42 | ###############################################################################
43 | #*.jpg binary
44 | #*.png binary
45 | #*.gif binary
46 |
47 | ###############################################################################
48 | # diff behavior for common document formats
49 | #
50 | # Convert binary document formats to text before diffing them. This feature
51 | # is only available from the command line. Turn it on by uncommenting the
52 | # entries below.
53 | ###############################################################################
54 | #*.doc diff=astextplain
55 | #*.DOC diff=astextplain
56 | #*.docx diff=astextplain
57 | #*.DOCX diff=astextplain
58 | #*.dot diff=astextplain
59 | #*.DOT diff=astextplain
60 | #*.pdf diff=astextplain
61 | #*.PDF diff=astextplain
62 | #*.rtf diff=astextplain
63 | #*.RTF diff=astextplain
64 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | ## Ignore Visual Studio temporary files, build results, and
2 | ## files generated by popular Visual Studio add-ons.
3 |
4 | # User-specific files
5 | *.suo
6 | *.user
7 | *.userosscache
8 | *.sln.docstates
9 |
10 | # User-specific files (MonoDevelop/Xamarin Studio)
11 | *.userprefs
12 |
13 | # Build results
14 | [Dd]ebug/
15 | [Dd]ebugPublic/
16 | [Rr]elease/
17 | [Rr]eleases/
18 | x64/
19 | x86/
20 | bld/
21 | [Bb]in/
22 | [Oo]bj/
23 | [Ll]og/
24 |
25 | # Visual Studio 2015 cache/options directory
26 | .vs/
27 | # Uncomment if you have tasks that create the project's static files in wwwroot
28 | #wwwroot/
29 |
30 | # MSTest test Results
31 | [Tt]est[Rr]esult*/
32 | [Bb]uild[Ll]og.*
33 |
34 | # NUNIT
35 | *.VisualState.xml
36 | TestResult.xml
37 |
38 | # Build Results of an ATL Project
39 | [Dd]ebugPS/
40 | [Rr]eleasePS/
41 | dlldata.c
42 |
43 | # DNX
44 | project.lock.json
45 | project.fragment.lock.json
46 | artifacts/
47 |
48 | *_i.c
49 | *_p.c
50 | *_i.h
51 | *.ilk
52 | *.meta
53 | *.obj
54 | *.pch
55 | *.pdb
56 | *.pgc
57 | *.pgd
58 | *.rsp
59 | *.sbr
60 | *.tlb
61 | *.tli
62 | *.tlh
63 | *.tmp
64 | *.tmp_proj
65 | *.log
66 | *.vspscc
67 | *.vssscc
68 | .builds
69 | *.pidb
70 | *.svclog
71 | *.scc
72 |
73 | # Chutzpah Test files
74 | _Chutzpah*
75 |
76 | # Visual C++ cache files
77 | ipch/
78 | *.aps
79 | *.ncb
80 | *.opendb
81 | *.opensdf
82 | *.sdf
83 | *.cachefile
84 | *.VC.db
85 | *.VC.VC.opendb
86 |
87 | # Visual Studio profiler
88 | *.psess
89 | *.vsp
90 | *.vspx
91 | *.sap
92 |
93 | # TFS 2012 Local Workspace
94 | $tf/
95 |
96 | # Guidance Automation Toolkit
97 | *.gpState
98 |
99 | # ReSharper is a .NET coding add-in
100 | _ReSharper*/
101 | *.[Rr]e[Ss]harper
102 | *.DotSettings.user
103 |
104 | # JustCode is a .NET coding add-in
105 | .JustCode
106 |
107 | # TeamCity is a build add-in
108 | _TeamCity*
109 |
110 | # DotCover is a Code Coverage Tool
111 | *.dotCover
112 |
113 | # NCrunch
114 | _NCrunch_*
115 | .*crunch*.local.xml
116 | nCrunchTemp_*
117 |
118 | # MightyMoose
119 | *.mm.*
120 | AutoTest.Net/
121 |
122 | # Web workbench (sass)
123 | .sass-cache/
124 |
125 | # Installshield output folder
126 | [Ee]xpress/
127 |
128 | # DocProject is a documentation generator add-in
129 | DocProject/buildhelp/
130 | DocProject/Help/*.HxT
131 | DocProject/Help/*.HxC
132 | DocProject/Help/*.hhc
133 | DocProject/Help/*.hhk
134 | DocProject/Help/*.hhp
135 | DocProject/Help/Html2
136 | DocProject/Help/html
137 |
138 | # Click-Once directory
139 | publish/
140 |
141 | # Publish Web Output
142 | *.[Pp]ublish.xml
143 | *.azurePubxml
144 | # TODO: Comment the next line if you want to checkin your web deploy settings
145 | # but database connection strings (with potential passwords) will be unencrypted
146 | #*.pubxml
147 | *.publishproj
148 |
149 | # Microsoft Azure Web App publish settings. Comment the next line if you want to
150 | # checkin your Azure Web App publish settings, but sensitive information contained
151 | # in these scripts will be unencrypted
152 | PublishScripts/
153 |
154 | # NuGet Packages
155 | *.nupkg
156 | # The packages folder can be ignored because of Package Restore
157 | **/packages/*
158 | # except build/, which is used as an MSBuild target.
159 | !**/packages/build/
160 | # Uncomment if necessary however generally it will be regenerated when needed
161 | #!**/packages/repositories.config
162 | # NuGet v3's project.json files produces more ignoreable files
163 | *.nuget.props
164 | *.nuget.targets
165 |
166 | # Microsoft Azure Build Output
167 | csx/
168 | *.build.csdef
169 |
170 | # Microsoft Azure Emulator
171 | ecf/
172 | rcf/
173 |
174 | # Windows Store app package directories and files
175 | AppPackages/
176 | BundleArtifacts/
177 | Package.StoreAssociation.xml
178 | _pkginfo.txt
179 |
180 | # Visual Studio cache files
181 | # files ending in .cache can be ignored
182 | *.[Cc]ache
183 | # but keep track of directories ending in .cache
184 | !*.[Cc]ache/
185 |
186 | # Others
187 | ClientBin/
188 | ~$*
189 | *~
190 | *.dbmdl
191 | *.dbproj.schemaview
192 | *.jfm
193 | *.pfx
194 | *.publishsettings
195 | node_modules/
196 | orleans.codegen.cs
197 |
198 | # Since there are multiple workflows, uncomment next line to ignore bower_components
199 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
200 | #bower_components/
201 |
202 | # RIA/Silverlight projects
203 | Generated_Code/
204 |
205 | # Backup & report files from converting an old project file
206 | # to a newer Visual Studio version. Backup files are not needed,
207 | # because we have git ;-)
208 | _UpgradeReport_Files/
209 | Backup*/
210 | UpgradeLog*.XML
211 | UpgradeLog*.htm
212 |
213 | # SQL Server files
214 | *.mdf
215 | *.ldf
216 |
217 | # Business Intelligence projects
218 | *.rdl.data
219 | *.bim.layout
220 | *.bim_*.settings
221 |
222 | # Microsoft Fakes
223 | FakesAssemblies/
224 |
225 | # GhostDoc plugin setting file
226 | *.GhostDoc.xml
227 |
228 | # Node.js Tools for Visual Studio
229 | .ntvs_analysis.dat
230 |
231 | # Visual Studio 6 build log
232 | *.plg
233 |
234 | # Visual Studio 6 workspace options file
235 | *.opt
236 |
237 | # Visual Studio LightSwitch build output
238 | **/*.HTMLClient/GeneratedArtifacts
239 | **/*.DesktopClient/GeneratedArtifacts
240 | **/*.DesktopClient/ModelManifest.xml
241 | **/*.Server/GeneratedArtifacts
242 | **/*.Server/ModelManifest.xml
243 | _Pvt_Extensions
244 |
245 | # Paket dependency manager
246 | .paket/paket.exe
247 | paket-files/
248 |
249 | # FAKE - F# Make
250 | .fake/
251 |
252 | # JetBrains Rider
253 | .idea/
254 | *.sln.iml
255 |
256 | # CodeRush
257 | .cr/
258 |
259 | # Python Tools for Visual Studio (PTVS)
260 | __pycache__/
261 | *.pyc
262 | /Sisters.WudiLib/Sisters.WudiLib.xml
263 | /Sisters.WudiLib.WebSocket/Sisters.WudiLib.WebSocket.xml
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2018 Bleatingsheep
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 | # 无敌lib
4 | 为方便 C# 调用酷 Q [HTTP API](https://github.com/richardchien/coolq-http-api) 插件而开发的lib。
5 |
6 | [](https://www.nuget.org/packages/Sisters.WudiLib/)
7 | [](https://www.nuget.org/packages/Sisters.WudiLib.WebSocket/)
8 |
9 | [查看文档](https://wudilib.b11p.com/) | [文档仓库](https://github.com/b11p/Sisters.WudiLib-docs)
10 |
11 | - Named by [int100](https://github.com/1004121460)
12 |
13 | ## 如何使用
14 | ### 发送消息、调用 API、监听事件
15 | 见:[快速上手](https://wudilib.b11p.com/zhinan/kuaisushangshou.html)。
16 |
17 | ### 发送图片、语音等消息
18 | 见:[进阶 WudiLib](https://wudilib.b11p.com/zhinan/jinjie-wudilib.html)
19 |
20 | ### Token 和 Secret
21 | #### Token
22 | 可以为每个客户端设置不同的 AccessToken。
23 | ```C#
24 | httpApi.AccessToken = "this-is-your-token";
25 | ```
26 |
27 | #### Secret
28 | 可以为每个监听实例设置不同的 Secret。
29 | ```C#
30 | listener.SetSecret("this-is-your-secret");
31 | ```
32 | 设置后,每次收到上报都会验证上报数据的哈希。如果验证失败,将忽略此次上报。
33 |
34 | ## WebSocket 和其他通信方式
35 | - [正向 WebSocket](https://wudilib.b11p.com/tongxinfangshi/zhengxiang-websocket.html)
36 | - [反向 WebSocket](https://wudilib.b11p.com/tongxinfangshi/fanxiang-websocket.html)
37 | - [扩展其他通信方式](https://wudilib.b11p.com/kuozhan/tongxinfangshi.html)
38 |
39 |
47 |
48 | ## 开发现状
49 | 积极开发中。可以在[路线图](https://wudilib.b11p.com/luxiantu.html)中查看当前开发的目标。也欢迎提出任何 Issue 和 Pull Request。
50 |
51 | ### 小建议
52 | 由于 `Sisters.WudiLib.Message` 和 `Sisters.WudiLib.Posts.Message` 类的类名相同,使用起来有诸多不便,建议您在每个**新**代码文件开头添加下列 `using`:
53 | ```C#
54 | using Message = Sisters.WudiLib.SendingMessage;
55 | using MessageContext = Sisters.WudiLib.Posts.Message;
56 | ```
57 | 这样,就可以用 `MessageContext` 表示收到的消息上报,用 `Message` 表示要发送的消息了。
58 |
59 | ## 帮助
60 | 如果您需要帮助,请联系 QQ:962549599,注明“WudiLib”和您的称呼。更欢迎直接提出 Issue。
61 |
62 |
--------------------------------------------------------------------------------
/Sisters.WudiLib.Tests/EndpointTests.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Text;
4 | using Sisters.WudiLib.Posts;
5 | using Xunit;
6 |
7 | namespace Sisters.WudiLib.Tests
8 | {
9 | public class EndpointTests
10 | {
11 | [Fact]
12 | public void Endpoint_ToString()
13 | {
14 | var endpoints = new Endpoint[] { new PrivateEndpoint(111), new GroupEndpoint(222), new DiscussEndpoint(333) };
15 | var strings = new[] { "private/111", "group/222", "discuss/333" };
16 |
17 | for (int i = 0; i < endpoints.Length; i++)
18 | {
19 | Assert.Equal(strings[i], endpoints[i].ToString());
20 | }
21 | }
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/Sisters.WudiLib.Tests/ListenerTests.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.Generic;
2 | using Sisters.WudiLib.Posts;
3 | using Xunit;
4 |
5 | namespace Sisters.WudiLib.Tests
6 | {
7 | public class ListenerTests
8 | {
9 | ///
10 | /// 测试文本上报类型中,获取 列表时能否正确地处理转义字符。
11 | ///
12 | [Fact]
13 | public void TextPostTypeSectionsUnescape()
14 | {
15 | string json = @"{""anonymous"":null,""font"":336542616,""group_id"":514661057,""message"":""绑定[CQ:at,qq=962549599] [ Morion ]:测试"",""message_id"":745339,""message_type"":""group"",""post_type"":""message"",""raw_message"":""绑定[CQ:at,qq=962549599] [ Morion ]:测试"",""self_id"":122866607,""sender"":{""age"":21,""card"":""钻石 | 动漫站建不成了"",""nickname"":""ymy😂/pch"",""sex"":""male"",""user_id"":962549599},""sub_type"":""normal"",""time"":1541558577,""user_id"":962549599}";
16 | var listener = new ApiPostListener();
17 | IReadOnlyList sections = null;
18 | listener.MessageEvent += (api, e) =>
19 | {
20 | var content = e.Content;
21 | sections = content.Sections;
22 | };
23 | listener.ProcessPost(json);
24 |
25 | //
26 | Assert.NotNull(sections);
27 | Assert.Equal(3, sections.Count);
28 |
29 | // Section 1
30 |
31 | // Section 2
32 | Assert.Equal>(new SortedDictionary
33 | {
34 | ["qq"] = "962549599"
35 | }, sections[1].Data);
36 | Assert.Equal("at", sections[1].Type);
37 |
38 | // Section 3
39 | // 应该正确转义 " [ Morion ]:测试" 为下面的内容。
40 | Assert.Equal(" [ Morion ]:测试", sections[2].ToString());
41 | }
42 |
43 | [Fact]
44 | public void Request_MultiFriendRequest()
45 | {
46 | string json = @"{""comment"":""hmmmmmm"",""flag"":""747576"",""post_type"":""request"",""request_type"":""friend"",""self_id"":12345678,""time"":1541601678,""user_id"":87654321}";
47 | var listener = new ApiPostListener();
48 | bool invo1 = false, invo2 = false, invo3 = false;
49 | listener.FriendRequestEvent += (api, e) =>
50 | {
51 | invo1 = true;
52 | return null;
53 | };
54 | listener.FriendRequestEvent += (api, e) =>
55 | {
56 | invo2 = true;
57 | return new FriendRequestResponse { Approve = false };
58 | };
59 | listener.FriendRequestEvent += (api, e) =>
60 | {
61 | invo3 = true;
62 | return null;
63 | };
64 | listener.ProcessPost(json);
65 | Assert.True(invo1);
66 | Assert.True(invo2);
67 | Assert.False(invo3);
68 | }
69 |
70 | [Fact]
71 | public void ArrayMessage_Normal()
72 | {
73 | string json = "{\"anonymous\":null,\"font\":236846192,\"group_id\":123456789,\"message\":[{\"data\":{\"text\":\"去2\"},\"type\":\"text\"}],\"message_id\":282,\"message_type\":\"group\",\"post_type\":\"message\",\"raw_message\":\"去2\",\"self_id\":1131545658,\"sender\":{\"age\":21,\"area\":\"青岛\",\"card\":\"\",\"level\":\"冒泡\",\"nickname\":\"ymy😂/pch\",\"role\":\"owner\",\"sex\":\"female\",\"title\":\"\",\"user_id\":962549599},\"sub_type\":\"normal\",\"time\":1547742375,\"user_id\":962549599}";
74 | var listener = new ApiPostListener();
75 | Posts.Message context = null;
76 | listener.MessageEvent += (api, e) =>
77 | {
78 | context = e;
79 | };
80 | listener.ProcessPost(json);
81 |
82 | Assert.IsType(context);
83 | Assert.Equal(1, context.Content.Sections.Count);
84 | }
85 | }
86 | }
87 |
--------------------------------------------------------------------------------
/Sisters.WudiLib.Tests/SectionTests.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Collections.ObjectModel;
4 | using Newtonsoft.Json;
5 | using Newtonsoft.Json.Linq;
6 | using Xunit;
7 |
8 | namespace Sisters.WudiLib.Tests
9 | {
10 | public class SectionTests
11 | {
12 | [Fact]
13 | public void CreateAndEqualTest()
14 | {
15 | var atAll = SendingMessage.AtAll();
16 | Assert.Equal("[CQ:at,qq=all]", atAll.Raw);
17 |
18 | //var section = new Section(Section.MusicType, ("type", "cus"), ("source", "test"));
19 | var section = new Section(Section.MusicType, new Dictionary
20 | {
21 | { "type", "cus" },
22 | { "source", "test" },
23 | });
24 | var section2 = new Section(Section.MusicType, ("source", "test"), ("type", "cus"));
25 | var json = JsonConvert.SerializeObject(section);
26 | var jObj = JsonConvert.DeserializeObject(json);
27 | Assert.Equal(Section.MusicType, jObj["type"].ToObject());
28 | var desSection = jObj.ToObject();
29 | Assert.Equal(section, desSection);
30 | Assert.Equal(section, section2);
31 | Assert.Equal(desSection, section2);
32 | Assert.Equal(section.GetHashCode(), desSection.GetHashCode());
33 | Assert.Equal(section.GetHashCode(), section2.GetHashCode());
34 | Assert.Equal(desSection.GetHashCode(), section2.GetHashCode());
35 | Assert.NotEqual(section.Raw, section2.Raw);
36 | }
37 |
38 | [Fact]
39 | public void Equal_DataOrder()
40 | {
41 | var dic1 = new Dictionary
42 | {
43 | { "para1", "arg1" },
44 | { "para2", "arg2" },
45 | };
46 | var dic2 = new Dictionary
47 | {
48 | { "para2", "arg2" },
49 | { "para1", "arg1" },
50 | };
51 | var section1 = new Section("type", dic1);
52 | var section2 = new Section("type", dic2);
53 |
54 | Assert.Equal(section1, section2);
55 | }
56 |
57 | [Fact]
58 | public void Constructor_ArgNull()
59 | {
60 | Assert.Throws("data", () => new Section("text", ((string, string)[])null));
61 | Assert.Throws("data", () => new Section("text", (IReadOnlyDictionary)null));
62 | Assert.Throws("type", () => new Section(null, ("p", "a")));
63 | Assert.Throws("type", () => new Section(null, new Dictionary()));
64 | }
65 |
66 | [Fact]
67 | public void Constructor_ArgIllegal()
68 | {
69 | new Section("m.0_-", ("key", "value"));
70 | Assert.Throws("type", () => new Section("m.0_- "));
71 | Assert.Throws("type", () => new Section(""));
72 | Assert.Throws("type", () => new Section(" "));
73 | Assert.Throws("data", () => new Section("sss", ("!", "123")));
74 | Assert.Throws("data", () => new Section("sss", ("", "233")));
75 | Assert.Throws("data", () => new Section("sss", (" ", "233")));
76 | }
77 |
78 | [Fact]
79 | public void Data_CheckReadOnly()
80 | {
81 | var data = new NotReadOnlyDictionary(new Dictionary
82 | {
83 | ["para"] = "arg",
84 | });
85 | var section = new Section("some_type", data);
86 |
87 | var count1 = section.Data.Count;
88 | data.Add("keykey", "vvv");
89 | var count2 = section.Data.Count;
90 |
91 | Assert.Equal(1, count1);
92 | Assert.Equal(count1, count2);
93 |
94 | var dictionary = new Dictionary
95 | {
96 | ["para"] = "arg",
97 | };
98 | var data2 = new ReadOnlyDictionary(dictionary);
99 | var section2 = new Section("some_type", data2);
100 | dictionary.Add("diff_key", "val");
101 | var count = section2.Data.Count;
102 | Assert.Equal(1, count);
103 | }
104 |
105 | class NotReadOnlyDictionary : ReadOnlyDictionary
106 | {
107 | public NotReadOnlyDictionary(IDictionary dictionary) : base(dictionary)
108 | {
109 | }
110 |
111 | public void Add(TKey key, TValue value)
112 | {
113 | Dictionary.Add(key, value);
114 | }
115 | }
116 | }
117 | }
118 |
--------------------------------------------------------------------------------
/Sisters.WudiLib.Tests/SendingMessageTests.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using Xunit;
6 |
7 | namespace Sisters.WudiLib.Tests
8 | {
9 | public class SendingMessageTests
10 | {
11 | [Fact]
12 | public void Ctor()
13 | {
14 | string message = "123[";
15 | string raw = "123[";
16 | var msg1 = new SendingMessage(message);
17 | Assert.Equal(raw, msg1.Raw);
18 | //Assert.Equal(message, msg1.ToString());
19 |
20 | var atSection = new Section("at", ("qq", "all"));
21 | var atMsg = SendingMessage.AtAll();
22 | Section atMsgSingleSection = atMsg.Sections.Single();
23 | Assert.Equal(atSection, atMsgSingleSection);
24 | }
25 |
26 | [Theory]
27 | [InlineData("a.jpg", "a.jpg")]
28 | [InlineData("/a b.jpg", "file:///a%20b.jpg")]
29 | [InlineData(@"c:\a.jpg", "file:///c:/a.jpg")]
30 | [InlineData("/dir name%20/file?ww=33", "file:///dir%20name%2520/file%3Fww=33")]
31 | public void LocalImageTests(string path, string expected)
32 | {
33 | var image = SendingMessage.LocalImage(path);
34 | Assert.Equal(new KeyValuePair("file", expected), image.Sections.Single().Data.Single());
35 | }
36 |
37 | [Fact]
38 | public void Concat()
39 | {
40 | var msg1 = new SendingMessage("1");
41 | var msg2 = msg1 + "2";
42 | var msg3 = "3" + msg2;
43 | Assert.IsType(msg2);
44 | Assert.IsType(msg3);
45 | }
46 |
47 | [Fact]
48 | public void ConcatNull()
49 | {
50 | SendingMessage message1 = null, message2 = null;
51 | Assert.NotNull(message1 + message2);
52 | Assert.False((message1 + message2)?.Sections.Count > 0);
53 |
54 | SendingMessage text = "hello";
55 | Assert.Equal(text.Sections, (message1 + text).Sections);
56 | Assert.Equal(text.Sections, (text + message1).Sections);
57 | }
58 |
59 | public static IEnumerable