liaoxujun@qq.com
2024-02-19 c32275f697e1541694836c47e1682e3291673dbc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using System.Linq;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Options;
using Moq;
using WalkingTec.Mvvm.Core;
using WalkingTec.Mvvm.Core.Implement;
using WalkingTec.Mvvm.Core.Support.FileHandlers;
using WalkingTec.Mvvm.Mvc;
using System.Reflection;
using WalkingTec.Mvvm.Core.Support.Json;
 
namespace cy_scdz.Test
{
    public class MockController
    {
        public static T CreateController<T>(IDataContext dataContext, string usercode) where T : BaseController, new()
        {
            var _controller = new T();
            _controller.Wtm = MockWtmContext.CreateWtmContext(dataContext, usercode);
            Mock<HttpContext> mockHttpContext = new Mock<HttpContext>();
            MockHttpSession mockSession = new MockHttpSession();
            mockHttpContext.Setup(s => s.Session).Returns(mockSession);
            mockHttpContext.Setup(x => x.Request).Returns(new DefaultHttpContext().Request);
            _controller.ControllerContext.HttpContext = mockHttpContext.Object;
            _controller.Wtm.MSD = new ModelStateServiceProvider(_controller.ModelState);
            return _controller;
        }
 
        public static T CreateApi<T>(IDataContext dataContext, string usercode) where T : BaseApiController, new()
        {
            var _controller = new T();
            _controller.Wtm = MockWtmContext.CreateWtmContext(dataContext, usercode);
            Mock<HttpContext> mockHttpContext = new Mock<HttpContext>();
            MockHttpSession mockSession = new MockHttpSession();
            mockHttpContext.Setup(s => s.Session).Returns(mockSession);
            mockHttpContext.Setup(x => x.Request).Returns(new DefaultHttpContext().Request);
            _controller.ControllerContext.HttpContext = mockHttpContext.Object;
            _controller.Wtm.MSD = new ModelStateServiceProvider(_controller.ModelState);
            return _controller;
        }
 
    }
 
    public class MockCookie : IRequestCookieCollection
    {
 
        public Dictionary<string, string> Kvs = new Dictionary<string, string>();
 
        public string this[string key] => Kvs[key];
 
        public int Count => Kvs.Count;
 
        public ICollection<string> Keys => Kvs.Keys;
 
        public bool ContainsKey(string key)
        {
            return Kvs.ContainsKey(key);
        }
 
        public IEnumerator<KeyValuePair<string, string>> GetEnumerator()
        {
            return Kvs.GetEnumerator();
        }
 
        public bool TryGetValue(string key, out string value)
        {
            return Kvs.TryGetValue(key, out value);
        }
 
        IEnumerator IEnumerable.GetEnumerator()
        {
            return Kvs.GetEnumerator();
        }
 
        public void Add(string key, string value)
        {
            Kvs.Add(key, value);
        }
    }
 
    public class MockHttpSession : ISession
    {
        Dictionary<string, object> sessionStorage = new Dictionary<string, object>();
        public object this[string name]
        {
            get { return sessionStorage[name]; }
            set { sessionStorage[name] = value; }
        }
 
        string ISession.Id
        {
            get
            {
                throw new NotImplementedException();
            }
        }
        bool ISession.IsAvailable
        {
            get
            {
                throw new NotImplementedException();
            }
        }
        IEnumerable<string> ISession.Keys
        {
            get { return sessionStorage.Keys; }
        }
        void ISession.Clear()
        {
            sessionStorage.Clear();
        }
        Task ISession.CommitAsync(CancellationToken cancellationToken)
        {
            Task t = new Task(() =>
            {
            });
            t.Start();
            return t;
        }
 
        Task ISession.LoadAsync(CancellationToken cancellationToken)
        {
            throw new NotImplementedException();
        }
 
        void ISession.Remove(string key)
        {
            sessionStorage.Remove(key);
        }
 
        void ISession.Set(string key, byte[] value)
        {
            sessionStorage[key] = value;
        }
 
        bool ISession.TryGetValue(string key, out byte[] value)
        {
            if (sessionStorage.ContainsKey(key) && sessionStorage[key] != null)
            {
                value = (byte[])sessionStorage[key];
                return true;
            }
            else
            {
                value = null;
                return false;
            }
        }
    }
 
    public class MockMSD : IModelStateService
    {
        private Dictionary<string,string> _states;
 
        public MockMSD()
        {
            this._states = new Dictionary<string, string>();
        }
 
        public List<MsdError> this[string name]
        {
            get
            {
                return _states.Where(x=>x.Key == name).Select(x => new MsdError { ErrorMessage = x.Value}).ToList();
            }
        }
 
        public void AddModelError(string key, string errorMessage)
        {
            _states.Add(key, errorMessage);
        }
 
        public void RemoveModelError(string key)
        {
            _states.Remove(key);
        }
 
        public void Clear()
        {
            _states.Clear();
        }
 
        public string GetFirstError()
        {
            string rv = "";
            foreach (var key in Keys)
            {
                if (this[key].Count > 0)
                {
                    rv = this[key].First().ErrorMessage;
                }
            }
            return rv;
        }
 
        public int Count => _states.Count;
 
        public IEnumerable<string> Keys => _states.Keys;
 
        bool IModelStateService.IsValid => _states.Count>0?true:false;
    }
 
    public static class MockWtmContext
    {
        public static WTMContext CreateWtmContext(IDataContext dataContext= null, string usercode = null)
        {
            GlobalData gd = new GlobalData();
            gd.AllAccessUrls = new List<string>();
            gd.AllAssembly = new List<System.Reflection.Assembly>();
            gd.AllModule = new List<SimpleModule>();
 
            Mock<HttpContext> mockHttpContext = new Mock<HttpContext>();
            Mock<HttpRequest> mockHttpRequest = new Mock<HttpRequest>();
            Mock<IServiceProvider> mockService = new Mock<IServiceProvider>();
            MockHttpSession mockSession = new MockHttpSession();
            mockHttpRequest.Setup(x => x.Cookies).Returns(new MockCookie());
            var cache = new MemoryDistributedCache(Options.Create<MemoryDistributedCacheOptions>(new MemoryDistributedCacheOptions()));
            var res = new ResourceManagerStringLocalizerFactory(Options.Create<LocalizationOptions>(new LocalizationOptions { ResourcesPath = "Resources" }), new Microsoft.Extensions.Logging.LoggerFactory());
            mockService.Setup(x => x.GetService(typeof(IDistributedCache))).Returns(cache);
            mockHttpContext.Setup(x => x.Request).Returns(mockHttpRequest.Object);
            mockHttpContext.Setup(x => x.RequestServices).Returns(mockService.Object);
            var httpa = new HttpContextAccessor();
            httpa.HttpContext = mockHttpContext.Object;
            var wtmcontext = new WTMContext(null, new GlobalData(), httpa, new DefaultUIService(), null, dataContext, res, cache: cache);
            wtmcontext.MSD = new BasicMSD();
            wtmcontext.Session = new SessionServiceProvider(mockSession);
            if (dataContext == null)
            {
                wtmcontext.DC = new EmptyContext(Guid.NewGuid().ToString(), DBTypeEnum.Memory);
            }
            else
            {
                wtmcontext.DC = dataContext;
            }
            wtmcontext.LoginUserInfo = new LoginUserInfo { ITCode = usercode ?? "user" };
            wtmcontext.GlobaInfo.AllAccessUrls = new List<string>();
            wtmcontext.GlobaInfo.AllAssembly = new List<System.Reflection.Assembly>();
            wtmcontext.GlobaInfo.AllModule = new List<SimpleModule>();
            mockService.Setup(x => x.GetService(typeof(WtmFileProvider))).Returns(new WtmFileProvider(wtmcontext));
            return wtmcontext;
        }
 
    }
}