コード例 #1
0
        internal static void Add(string mock, IMethodOptions methodOptions) {

            List<IMethodOptions> methodOptionsList = null;

            // Cria o registro para o mock especificado.
            if (MethodOptionsDictionary.ContainsKey(mock) == false) {

                methodOptionsList = new List<IMethodOptions>();
                MethodOptionsDictionary.Add(mock, methodOptionsList);
            }
            else{
                methodOptionsList = MethodOptionsDictionary[mock];
            }

            // Tenta localizar as opções para o método especificado.
            //IMethodOptions actualMethodOptions = methodOptionsList.FirstOrDefault(p => p.MethodName == methodOptions.MethodName);
			IMethodOptions actualMethodOptions = methodOptionsList.FirstOrDefault(p => p.MemberFullName == methodOptions.MemberFullName);

            // Caso as opções sejam encontradas, atualiza o método. Caso contrário, insere as novas opções.
            if (actualMethodOptions != null) { actualMethodOptions = methodOptions; }
            else { methodOptionsList.Add(methodOptions); }
        }
コード例 #2
0
        public (List <int> jobOrder, int minTardiness) Solve(IMethodOptions options, Stopwatch stopwatch)
        {
            DynamicProgrammingOptions dpaOptions = options as DynamicProgrammingOptions;
            var jobs    = dpaOptions.Data;
            var subsets = dpaOptions.Subsets;

            int    rozw   = int.MaxValue;
            int    result = 0;
            int    index  = 0;
            int    cmax   = 0;
            int    opt    = 0;
            string tmp    = string.Empty;

            options.GuiConnection?.LogText?.Invoke($"Start : {DateTime.Now:HH:mm:ss.fff}");

            if (!stopwatch.IsRunning)
            {
                stopwatch.Start();
            }
            try
            {
                for (int i = 1; i < dpaOptions.Subsets.Count; i++)
                {
                    tmp  = i.IntToBin(jobs.Count);
                    rozw = int.MaxValue;
                    cmax = 0;
                    options.GuiConnection?.LogText?.Invoke($"OPT({tmp}):");

                    for (int j = 0; j < tmp.Length; j++)
                    {
                        if (tmp[j].Equals('1'))
                        {
                            cmax += jobs[jobs.Count - j - 1].Time; // wyliczenie cmax calkowitego dla danego i
                        }
                    }

                    options.GuiConnection?.LogText?.Invoke($"\tCMAX : {cmax}");

                    for (int j = 0; j < tmp.Length; j++)
                    {
                        if (tmp[j].Equals('1'))
                        {
                            index  = jobs.Count - j - 1;
                            tmp    = tmp.ReplaceAt(j, '0');
                            opt    = jobs[index].CountPenalty(cmax);
                            result = subsets[tmp] + opt;   // OPT(xn,..,xi+1,xi-1,..,x0) + wx*Tx
                            options.GuiConnection?.LogText?.Invoke($"\tOPT({tmp}) + w{index}T{index} = {subsets[tmp]} + {opt} = {result}");
                            rozw = Math.Min(rozw, result); // wybranie najmniejszego kosztu dla danego i
                            tmp  = i.IntToBin(jobs.Count);
                        }
                    }
                    options.GuiConnection?.LogGraphics?.Invoke(jobs.JobsFromBitString(tmp));
                    subsets[tmp] = rozw;
                    options.CancellationToken.ThrowIfCancellationRequested();
                }
            }
            catch (OperationCanceledException)
            {
                options.GuiConnection?.LogText?.Invoke("Przerwano zadanie");
            }
            stopwatch.Stop();
            return(new List <int>(), rozw);
        }
コード例 #3
0
 static public IMethodOptions <ICollection <R> > it_will_return <R>(this IMethodOptions <ICollection <R> > options, params R[] items)
 {
     return(options.Return(items.ToList()));
 }
コード例 #4
0
 public static IMethodOptions <T> Return <T>(this IMethodOptions <T> opts, Func <T> factory)
 {
     opts.Return(default(T));    // required for Rhino.Mocks on non-void methods
     opts.WhenCalled(mi => mi.ReturnValue = factory());
     return(opts);
 }
コード例 #5
0
 /// <summary>
 /// Provides support for ordered Rhino.Mocks expectations without dedicated <see cref="MockRepository"/> instance. Create an
 /// <see cref="OrderedExpectationCounter"/>, then call this method with that counter for all expectations that should occur
 /// in the same order as declared.
 /// Uses <see cref="IMethodOptions{T}.WhenCalled"/> internally; use <see cref="WhenCalledOrdered{T}"/> when you need to specify your own
 /// <see cref="IMethodOptions{T}.WhenCalled"/> handler.
 /// </summary>
 public static IMethodOptions <T> Ordered <T> (this IMethodOptions <T> options, OrderedExpectationCounter counter, string message = null)
 {
     return(WhenCalledOrdered(options, counter, mi => { }, message));
 }
コード例 #6
0
 /// <summary>
 /// Usage:
 ///     _mockRepository.Stub(r => r.Method(active: null)).ReturnAsync(object);
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="options"></param>
 /// <param name="objToReturn"></param>
 /// <returns></returns>
 public static IMethodOptions <Task <T> > ReturnAsync <T>(this IMethodOptions <Task <T> > options, T objToReturn)
 {
     return(options.Return(Task.FromResult(objToReturn)));
 }
コード例 #7
0
 /// <summary>
 /// Assigns the argument found at the specified <paramref name="index"/> of the stub (or expected) call
 /// through the <paramref name="assign"/> lambda received.
 /// <para> An exception is thrown if the method doesn't have the specified argument or he is not of the expected type. </para>
 /// </summary>
 ///
 /// <typeparam name="T"> Type of the mocked object </typeparam>
 /// <typeparam name="TArgument"> Type of the argument.</typeparam>
 /// <param name="options"></param>
 /// <param name="index">The index of the argument we are looking for</param>
 /// <param name="assign">The lambda that will be called with the argument value (C#: x => ... / VB: Sub(x) ...) </param>
 public static IMethodOptions <T> AssignArgument <T, TArgument>(this IMethodOptions <T> options, int index, Action <TArgument> assign)
 {
     return(options.WhenCalled(i => assign(GetArgument <TArgument>(i, index))));
 }
コード例 #8
0
 /// <summary>
 /// Assigns the first argument of the stub (or expected) call through the <paramref name="assign"/> lambda
 /// received.
 /// <para> An exception is thrown if the method has no argument or the first one is not of the expected type. </para>
 /// </summary>
 ///
 /// <typeparam name="T"> Type of the mocked object </typeparam>
 /// <typeparam name="TFirstArgument"> Type of the first argument.</typeparam>
 /// <param name="options"></param>
 /// <param name="assign">The lambda that will be called with the first argument value (C#: x => ... / VB: Sub(x) ...) </param>
 public static IMethodOptions <T> AssignFirstArgument <T, TFirstArgument>(this IMethodOptions <T> options, Action <TFirstArgument> assign)
 {
     return(options.AssignArgument <T, TFirstArgument>(0, assign));
 }
コード例 #9
0
        public (List <int> jobOrder, int minTardiness) Solve(IMethodOptions imethodoptions, Stopwatch stopwatch)
        {
            var        options      = imethodoptions as AlphaDominantGeneticOptions;
            var        minTardiness = options.Data.CountPenalty();
            int        dataCount    = options.Data.Count;
            List <int> best         = options.Data.Select(x => x.Index).ToList();
            List <(List <int> indiv, double fitness)> pop;
            string prev = "";

            options.OldPopCount = (int)(options.PopulationSize * (1 - options.CrossoverRate));
            options.GuiConnection?.LogText?.Invoke($"Wielkość starej populacji: {options.OldPopCount}");

            options.GuiConnection?.LogText?.Invoke($"Start : {DateTime.Now:HH:mm:ss.fff}");
            stopwatch.Start();
            try
            {
                options.GuiConnection?.LogText?.Invoke("Generowanie populacji startowej");
                pop = GenerateStartingPopulation(options.Data, options.PopulationSize);

                options.GuiConnection?.LogText?.Invoke("Sortowanie");
                pop.Sort((x, y) => y.fitness.CompareTo(x.fitness));
                best = pop[0].indiv;
                int iter = 0;
                while (iter < options.IterationCount)
                {
                    options.GuiConnection?.LogText?.Invoke($"Osobnik alpha o F = {pop[0].fitness}");
                    options.GuiConnection?.LogText?.Invoke($"Iteracja: {iter}, generowanie nowej populacji");

                    pop = GenerateNewPopulation(pop, options);

                    for (int i = 0; i < pop.Count; i++)
                    {
                        if (ThreadSafeRandom.GetRandomDouble() < options.MutationChance)
                        {
                            if (options.GuiConnection != null)
                            {
                                prev = $"{string.Join(',', pop[i].indiv)}, F = {pop[i].fitness}";
                            }
                            int index1 = ThreadSafeRandom.ThisThreadsRandom.Next(dataCount);
                            int index2 = ThreadSafeRandom.ThisThreadsRandom.Next(dataCount);
                            pop[i].indiv.Swap(index1, index2);
                            pop[i] = (pop[i].indiv, CalculateFitness(pop[i].indiv, options.Data));
                            options.GuiConnection?.LogText?.Invoke($"   Mutacja: i = {i} | {prev} -> {string.Join(',', pop[i].indiv)}, F = {pop[i].fitness}");
                        }
                    }

                    options.GuiConnection?.LogText?.Invoke("    Sortowanie");
                    pop.Sort((x, y) => y.fitness.CompareTo(x.fitness));
                    best = pop[0].indiv;

                    iter += 1;
                    options.CancellationToken.ThrowIfCancellationRequested();
                }
            }
            catch (OperationCanceledException)
            {
                imethodoptions.GuiConnection?.LogText("Przerwano wykonwanie zadania");
            }
            stopwatch.Stop();
            options.GuiConnection?.LogText?.Invoke($"Koniec : {DateTime.Now:HH:mm:ss.fff}");
            minTardiness = options.Data.JobsFromIndexList(best).CountPenalty();
            return(best, minTardiness);
        }
コード例 #10
0
        public IMethodOptions Prepare(IMethodOptions options)
        {
            var methodOptions = options as AlphaDominantGeneticOptions;

            return(methodOptions);
        }
コード例 #11
0
        public RhinoQueryOptions(IMethodOptions <TReturnValue> methodOptions)
        {
            Guard.AgainstArgumentNull(methodOptions, "methodOptions");

            _methodOptions = methodOptions;
        }
コード例 #12
0
 static public void it_will_throw <R>(this IMethodOptions <R> options, Exception item)
 {
     options.Throw(item);
 }
コード例 #13
0
 static public IMethodOptions <IEnumerable <R> > it_will_return_nothing <R>(this IMethodOptions <IEnumerable <R> > options)
 {
     return(options.it_will_return());
 }
コード例 #14
0
 static public IMethodOptions <IEnumerable <R> > it_will_return <R>(this IMethodOptions <IEnumerable <R> > options, params R[] items)
 {
     return(options.Return(items.AsEnumerable()));
 }
コード例 #15
0
 public static IMethodOptions <T> returns <T>(
     this IMethodOptions <T> options,
     T value)
 {
     return(options.Return(value));
 }
コード例 #16
0
        public RhinoCommandOptions(IMethodOptions <object> methodOptions)
        {
            Guard.AgainstArgumentNull(methodOptions, "methodOptions");

            _methodOptions = methodOptions;
        }
コード例 #17
0
        public IMethodOptions Prepare(IMethodOptions options)
        {
            var methodOptions = options as SimulatedAnnealingOptions;

            return(methodOptions);
        }
コード例 #18
0
 /// <summary>
 /// Assigns the first argument of the stub (or expected) call through the <paramref name="assign"/> lambda
 /// received.
 /// <para> An exception is thrown if the method has no argument or the first one is not of the expected type. </para>
 /// </summary>
 ///
 /// <typeparam name="TFirstArgument"> Type of the first argument.</typeparam>
 /// <param name="options"></param>
 /// <param name="assign">The lambda that will be called with the first argument value (C#: x => ... / VB: Sub(x) ...) </param>
 public static IMethodOptions <object> AssignFirstArgument <TFirstArgument>(this IMethodOptions <object> options, Action <TFirstArgument> assign)
 {
     return(options.AssignFirstArgument <Object, TFirstArgument>(assign));
 }
コード例 #19
0
        //public static IMethodOptions Stub<T>(this T mockObject, Expression<Action<T>> action) where T : class {

        //	throw new NotImplementedException();
        //}

        public static IMethodOptions <R> Stub <T, R>(this T mockObject, Expression <Func <T, R> > action) where T : class
        {
            if (mockObject == null)
            {
                throw new ArgumentNullException("mockObject", "You cannot mock a null instance.");
            }

            string mockName = mockObject.GetType().FullName;

            string memberName = null;

            string memberFullName = null;

            string parametersMd5 = string.Empty;

            if (action.Body is MethodCallExpression)
            {
                MethodCallExpression methodCallExpression = (MethodCallExpression)action.Body;
                memberName = methodCallExpression.Method.Name;

                memberFullName = memberName + "(";

                ReadOnlyCollection <Expression> args = methodCallExpression.Arguments;

                // Processa todos os parâmetros, executando qualquer método que tenha sido especificado e obtendo seu resultado.
                for (int i = 0; i < methodCallExpression.Arguments.Count; i++)
                {
                    Expression argumentExpression = methodCallExpression.Arguments[i];

                    // Verifica se o parâmetro é uma chamada a um método. Caso positivo, o método será executado e o resultado será usado como parâmetro.
                    if (argumentExpression is MethodCallExpression || argumentExpression is MemberExpression)
                    {
                        // Executa o método e obtém o resultado.
                        object result = Expression.Lambda(argumentExpression).Compile().DynamicInvoke();

                        // Adiciona o resultado no nome completo para identificar o método principal.
                        memberFullName += result.ToString().Trim('"');

                        parametersMd5 += Serializer.JsonSerialize(result).Trim('"');
                    }
                    else
                    {
                        memberFullName += argumentExpression.ToString().Trim('"');

                        parametersMd5 += argumentExpression.ToString().Trim('"');
                    }

                    // Caso existam mais parâmetros, adiciona um separador para o próximo parâmetro.
                    if (i < methodCallExpression.Arguments.Count - 1)
                    {
                        memberFullName += ", ";

                        parametersMd5 += ", ";
                    }
                }

                memberFullName += ")";
            }
            else if (action.Body is MemberExpression)
            {
                MemberExpression memberExpression = (MemberExpression)action.Body;
                memberName     = memberExpression.Member.Name;
                memberFullName = memberName;
            }

            string _fullName = memberName;

            if (string.IsNullOrWhiteSpace(parametersMd5) == false)
            {
                parametersMd5 = parametersMd5.CalculateMd5(mockName);

                _fullName += "(" + parametersMd5 + ")";

                memberFullName = _fullName;
            }

            // Carrega as configurações do método.
            IMethodOptions methodOptions = MockRepository.Load(mockName, memberFullName);

            // Caso ainda não existam opções definidas, cria um novo objeto e adiciona ao repositório.
            if (methodOptions == null)
            {
                methodOptions = new MethodOptions <R>();
                methodOptions.MemberFullName = memberFullName;
                methodOptions.MethodName     = memberName;
                MockRepository.Add(mockName, methodOptions);
            }

            // TODO: Redefinir as opções, caso já exista o IMethodOptions.

            return(methodOptions as IMethodOptions <R>);
        }
コード例 #20
0
 /// <summary>
 /// Assigns the argument found at the specified <paramref name="index"/> of the stub (or expected) call
 /// through the <paramref name="assign"/> lambda received.
 /// <para> An exception is thrown if the method doesn't have the specified argument or he is not of the expected type. </para>
 /// </summary>
 ///
 /// <typeparam name="TArgument"> Type of the argument.</typeparam>
 /// <param name="options"></param>
 /// <param name="index">The index of the argument we are looking for</param>
 /// <param name="assign">The lambda that will be called with the argument value (C#: x => ... / VB: Sub(x) ...) </param>
 public static IMethodOptions <object> AssignArgument <TArgument>(this IMethodOptions <object> options, int index, Action <TArgument> assign)
 {
     return(options.AssignArgument <object, TArgument>(index, assign));
 }
コード例 #21
0
 public CallOptions(IMethodOptions <T> methodOptions)
 {
     m_methodOptions = methodOptions;
 }
コード例 #22
0
 private static void DefaultConstraintSetup(IMethodOptions <object> options)
 {
 }
コード例 #23
0
 public static CallOptions <T> Call <T>(this IMethodOptions <T> methodOptions)
 {
     return(new CallOptions <T>(methodOptions));
 }
コード例 #24
0
 public static IMethodOptions <T> WithCurrentTransaction <T> (this IMethodOptions <T> options, ClientTransaction expectedTransaction)
 {
     return(options.WhenCalled(mi => Assert.That(ClientTransaction.Current, Is.SameAs(expectedTransaction))));
 }
コード例 #25
0
 public RhinoMockSetupResult(IMethodOptions <T> result)
     : base(result, MockingFrameworkType.RhinoMock)
 {
 }
コード例 #26
0
 /// <summary>
 /// Allows a method to be stubbed with a supplied action.
 /// </summary>
 /// <remarks>This method is the same as Do but does not require IgnoreArguments() to be specified.</remarks>
 public static IMethodOptions <TResult> AlwaysDo <T1, T2, TResult>(this IMethodOptions <TResult> options, Func <T1, T2, TResult> action)
 {
     return(options.IgnoreArguments().Do(action));
 }
コード例 #27
0
 static public IMethodOptions <R> it_will_return <R>(this IMethodOptions <R> options, R item)
 {
     return(options.Return(item));
 }