无论如何,是否有使用Moq使用WPF测试Postgres的方法?

时间:2019-04-01 05:54:44

标签: c# wpf nunit moq

我尝试以https://developerhandbook.com/unit-testing/writing-unit-tests-with-nunit-and-moq/为例,但我不知道如何使用WPF和Postgres进行最小起订量来测试上传文件的功能。

**我想做的是-在WPF中使用上传功能,而无需触摸db来进行最小起订量。** 现在,我坚持使用WPF类中的上载函数,该函数包含与数据库连接有关的上载方法。

这是一些源代码

public static async Task<IDeviceFileViewModel> WriteDeviceFilesAsync(IDeviceFileViewModel device)
    {            

        IDeviceFileViewModel deviceResult = device;

        //check file storage path
        var filestoragepath = FileSystemEngine.CheckFileSystemStoragePath(device);

        //delete log file
        //Trace.WriteLine(device.DeviceId);
        DeleteLog("Logs", device);

        foreach (var deviceFile in device.DeviceFileStatisticsModel.DeviceFiles)
        {

            //Start modified by Prin Sooksong 08/13/2017
            //check corrupted file
            MediaFile fileStats = new MediaFile(deviceFile);

            var deviceFileExt = Path.GetExtension(deviceFile);
            if (deviceFileExt.Equals(".WAV") || deviceFileExt.Equals(".wav"))
            {
                var audioStat = fileStats.Audio.FirstOrDefault();

                if (audioStat != null)
                {
                    device.DeviceFileStatisticsModel.DeviceFile = new FileInfo(deviceFile);
                    var tuple = await Task.Run(() => WriteDeviceAudioFileAsync(device, filestoragepath));

                    deviceResult.DeviceFileStatisticsModel.DeviceFileToCheckSums.Add(tuple.Item1, tuple.Item2);
                }
                else
                {
                    //write log file
                    //var taskWriteLog = Task.Run(() => WriteLog("Logs", device, device.DeviceFileStatisticsModel.DeviceFile.Name + "\tSkipped! Corrupt File"));
                    WriteLog("Logs", device, device.DeviceFileStatisticsModel.DeviceFile.Name + "\tSkipped! Corrupt File");
                }
            }
            if (deviceFileExt.Equals(".MOV") || deviceFileExt.Equals(".mov") || deviceFileExt.Equals(".MP4") || deviceFileExt.Equals(".mp4"))
            {
                var videoStat = fileStats.Video.FirstOrDefault();

                if (videoStat != null)
                {

                    device.DeviceFileStatisticsModel.DeviceFile = new FileInfo(deviceFile);
                    var tuple = await Task.Run(() => WriteDeviceVideoFileAsync(device, filestoragepath));

                    deviceResult.DeviceFileStatisticsModel.DeviceFileToCheckSums.Add(tuple.Item1, tuple.Item2);
                }
                else
                {
                    //write log file
                    //var taskWriteLog = Task.Run(() => WriteLog("Logs", device, device.DeviceFileStatisticsModel.DeviceFile.Name + "\tSkipped! Corrupt File"));
                    WriteLog("Logs", device, device.DeviceFileStatisticsModel.DeviceFile.Name + "\tSkipped! Corrupt File");
                }
            }
            if (deviceFileExt.Equals(".JPG") || deviceFileExt.Equals(".jpg"))
            {
                var pictureStat = fileStats.Image.FirstOrDefault();

                if (pictureStat != null)
                {
                    device.DeviceFileStatisticsModel.DeviceFile = new FileInfo(deviceFile);
                    var tuple = await Task.Run(() => WriteDevicePictureFileAsync(device, filestoragepath));

                    deviceResult.DeviceFileStatisticsModel.DeviceFileToCheckSums.Add(tuple.Item1, tuple.Item2);
                }
                else
                {

                    //write log file
                    //var taskWriteLog = Task.Run(() => WriteLog("Logs", device, device.DeviceFileStatisticsModel.DeviceFile.Name + "\tSkipped! Corrupt File"));
                    WriteLog("Logs", device, device.DeviceFileStatisticsModel.DeviceFile.Name + "\tSkipped! Corrupt File");
                }
            }
            //End modified by Prin Sooksong 08/13/2017



        }            

        deviceResult.DeviceActiveStatus = false;


        return deviceResult;
    }

WPF可以识别文件扩展名的另一种方法

 internal static async Task<Tuple<string, byte[]>> WriteDeviceAudioFileAsync(IDeviceFileViewModel device, string FileStoragePath)
    {
        var config = configurationManager.GetConfiguration<ExtractorConfiguration>();


        NpgsqlConnection.MapEnumGlobally<ActivityTypes.Action>();
        using (NpgsqlConnection connection = new NpgsqlConnection("Server=" + config.DatabaseSetting.Host + ";" +
                                                                  "Port=" + config.DatabaseSetting.Port + ";" +
                                                                  "Database=" + config.DatabaseSetting.Database + ";" +
                                                                  "User Id=" + config.DatabaseSetting.UserName + ";" +
                                                                  "Password=" + config.DatabaseSetting.Password + ";")
        )
        {

            try
            {
                await connection.OpenAsync();
            }
            catch (Exception e)
            {
                Trace.WriteLine(e.Message);
                throw e;
            }

            try
            {

                    //var fileOid = await WriteFileOid(connection, device, device.DeviceFileStatisticsModel.DeviceFile);
                    //convert .wav to .mp3 file
                    Tuple<FileInfo, DirectoryInfo> transcoded = StreamEngine.TranscodeDeviceAudioFile(device.DeviceFileStatisticsModel.DeviceFile);
                    device.DeviceFileStatisticsModel.DeviceAudioFileTranscoded = transcoded.Item1;
                    device.DeviceFileStatisticsModel.DeviceAudioTranscodedDirectory = transcoded.Item2;


                    //write raw file to ubuntu file system
                    var filestoreRaw = FileStoragePath + @"\" + device.DeviceFileStatisticsModel.DeviceFile.Name;
                    await WriteFile(device, device.DeviceFileStatisticsModel.DeviceFile, FileStoragePath);                       

                    //var transcodedAudioFileOid = await WriteFileOid(connection, device, device.DeviceFileStatisticsModel.DeviceAudioFileTranscoded);

                    //write mp3 file to ubuntu file system
                    var filestoreMp3 = FileStoragePath + @"\" + device.DeviceFileStatisticsModel.DeviceAudioFileTranscoded.Name;
                    await WriteFileMP3(device, device.DeviceFileStatisticsModel.DeviceAudioFileTranscoded, FileStoragePath);

                    var fileChecksum = SecurityEngine.WriteFileCheckSum(device,device.DeviceFileStatisticsModel.DeviceFile);

                    MediaFile fileStats = new MediaFile(device.DeviceFileStatisticsModel.DeviceFile.FullName);
                    //MediaFile fileStats = new MediaFile(device.DeviceFileStatisticsModel.DeviceAudioFileTranscoded.FullName);
                    var audioStat = fileStats.Audio.FirstOrDefault();

                    //var audioSize = audioStat.Size;
                    var audioSize = fileStats.General.Size;

                var durationTime = audioStat.Duration;
                    TimeSpan t = TimeSpan.FromMilliseconds(durationTime);
                    TimeSpan fileDuration = new TimeSpan(t.Hours, t.Minutes, t.Seconds);

                    var fileCreated = device.DeviceFileStatisticsModel.DeviceFile.CreationTime;
                    var fileChanged = device.DeviceFileStatisticsModel.DeviceFile.LastWriteTime;

                    if (fileCreated.Kind == DateTimeKind.Local)
                    {
                        fileCreated = fileCreated.ToUniversalTime();
                    }
                    else if (fileCreated.Kind == DateTimeKind.Unspecified)
                    {
                        fileCreated = fileCreated.ToLocalTime().ToUniversalTime();
                    }

                    if (fileChanged.Kind == DateTimeKind.Local)
                    {
                        fileChanged = fileChanged.ToUniversalTime();
                    }
                    else if (fileChanged.Kind == DateTimeKind.Unspecified)
                    {
                        fileChanged = fileChanged.ToLocalTime().ToUniversalTime();
                    }

                    //Trace.WriteLine(fileCreated.Kind);
                    //Trace.WriteLine(fileChanged.Kind);

                    //var fileMimeType = System.Web.MimeMapping.GetMimeMapping(device.DeviceFileStatisticsModel.DeviceFile.FullName);
                    var fileMimeType = getFileMimeType(device.DeviceFileStatisticsModel.DeviceFile.FullName.ToUpper());

                    Guid deviceUserUuid = Guid.Parse(device.DeviceUserUuId.ToString());
                    Guid deviceIDUuid = Guid.Parse(device.DeviceIdUuid.ToString());
                    Guid id = Guid.Parse(Guid.NewGuid().ToString());

                    byte[] bytes = Encoding.Default.GetBytes(device.DeviceId);
                    var deviceId = Encoding.ASCII.GetString(bytes);

                    Guid activityId = Guid.Parse(Guid.NewGuid().ToString());

                    var fileTitle = getMediaTitle(device);

                    var metadatainfo = MetaDataEngine.getMetaDataInfo(device);


                //DoEvents();

                if (metadatainfo != null)
                {

                    var sqlInsertGrp = "INSERT INTO " +
                                                "audios (id, created, duration, device_id, user_id, modified, checksum, file_path, file_extension, file_size,prev_file_path,mime_type,title, classification, description) " +
                                                    " VALUES (@p1, @p2, @p3, @p4, @p5, @p6, @p7, @p8, @p9, @p10, @p11, @p12::mime,@p13,@p14::classification,@p15);" +
                                       "INSERT INTO " +
                                                "activity (id, user_id, entity_id, user_ip, action, entity_type) " +
                                                    " VALUES (@a1, @a2, @a3, @a4, @a5, @a6);";

                    using (var sqlGrp = new NpgsqlCommand(sqlInsertGrp, connection))
                    {
                        //Audio part
                        sqlGrp.Parameters.AddWithValue("@p1", NpgsqlDbType.Uuid, id);
                        sqlGrp.Parameters.AddWithValue("@p2", NpgsqlDbType.Timestamp, fileCreated);
                        sqlGrp.Parameters.AddWithValue("@p3", NpgsqlDbType.Interval, fileDuration);
                        sqlGrp.Parameters.AddWithValue("@p4", NpgsqlDbType.Uuid, deviceIDUuid);
                        sqlGrp.Parameters.AddWithValue("@p5", NpgsqlDbType.Uuid, deviceUserUuid);
                        sqlGrp.Parameters.AddWithValue("@p6", NpgsqlDbType.Timestamp, fileChanged);
                        sqlGrp.Parameters.AddWithValue("@p7", NpgsqlDbType.Bytea, fileChecksum);
                        sqlGrp.Parameters.AddWithValue("@p8", NpgsqlDbType.Text, filestoreRaw);
                        sqlGrp.Parameters.AddWithValue("@p9", NpgsqlDbType.Text, "WAV");
                        sqlGrp.Parameters.AddWithValue("@p10", NpgsqlDbType.Text, audioSize);
                        sqlGrp.Parameters.AddWithValue("@p11", NpgsqlDbType.Text, filestoreMp3);
                        sqlGrp.Parameters.AddWithValue("@p12", NpgsqlDbType.Text, fileMimeType);

                        //audio file meta data                            
                        sqlGrp.Parameters.AddWithValue("@p13", NpgsqlDbType.Text, metadatainfo.Title);
                        sqlGrp.Parameters.AddWithValue("@p14", NpgsqlDbType.Text, metadatainfo.ClassificationData);
                        sqlGrp.Parameters.AddWithValue("@p15", NpgsqlDbType.Text, metadatainfo.Note);

                        //Activity part
                        sqlGrp.Parameters.AddWithValue("@a1", NpgsqlDbType.Uuid, activityId);
                        sqlGrp.Parameters.AddWithValue("@a2", NpgsqlDbType.Uuid, deviceUserUuid);
                        sqlGrp.Parameters.AddWithValue("@a3", NpgsqlDbType.Uuid, id);

                        //IPAddress ip = Dns.GetHostEntry(Dns.GetHostName())
                        //                                  .AddressList.(f => f.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork);

                        IPAddress ip = GetIP();

                        var ipStr = Utf16ToUtf8(ip.ToString());
                        sqlGrp.Parameters.AddWithValue("@a4", NpgsqlDbType.Text, ipStr);
                        sqlGrp.Parameters.AddWithValue("@a5", NpgsqlDbType.Enum, ActivityTypes.Action.upload_audio);
                        //Start modified by Prin Sooksong 08/07/2017                    
                        sqlGrp.Parameters.AddWithValue("@a6", NpgsqlDbType.Text, "audios");
                        //End modified by Prin Sooksong 08/07/2017

                        sqlGrp.Prepare();
                        await sqlGrp.ExecuteNonQueryAsync();

                    }
                }
                else
                {

                    var sqlInsertGrp = "INSERT INTO " +
                                                "audios (id, created, duration, device_id, user_id, modified, checksum, file_path, file_extension, file_size,prev_file_path,mime_type,title) " +
                                                    " VALUES (@p1, @p2, @p3, @p4, @p5, @p6, @p7, @p8, @p9, @p10, @p11, @p12::mime,@p13);" +
                                       "INSERT INTO " +
                                                "activity (id, user_id, entity_id, user_ip, action, entity_type) " +
                                                    " VALUES (@a1, @a2, @a3, @a4, @a5, @a6);";

                    using (var sqlGrp = new NpgsqlCommand(sqlInsertGrp, connection))
                    {
                        //Audio part
                        sqlGrp.Parameters.AddWithValue("@p1", NpgsqlDbType.Uuid, id);
                        sqlGrp.Parameters.AddWithValue("@p2", NpgsqlDbType.Timestamp, fileCreated);
                        sqlGrp.Parameters.AddWithValue("@p3", NpgsqlDbType.Interval, fileDuration);
                        sqlGrp.Parameters.AddWithValue("@p4", NpgsqlDbType.Uuid, deviceIDUuid);
                        sqlGrp.Parameters.AddWithValue("@p5", NpgsqlDbType.Uuid, deviceUserUuid);
                        sqlGrp.Parameters.AddWithValue("@p6", NpgsqlDbType.Timestamp, fileChanged);
                        sqlGrp.Parameters.AddWithValue("@p7", NpgsqlDbType.Bytea, fileChecksum);
                        sqlGrp.Parameters.AddWithValue("@p8", NpgsqlDbType.Text, filestoreRaw);
                        sqlGrp.Parameters.AddWithValue("@p9", NpgsqlDbType.Text, "WAV");
                        sqlGrp.Parameters.AddWithValue("@p10", NpgsqlDbType.Text, audioSize);
                        sqlGrp.Parameters.AddWithValue("@p11", NpgsqlDbType.Text, filestoreMp3);
                        sqlGrp.Parameters.AddWithValue("@p12", NpgsqlDbType.Text, fileMimeType);
                        sqlGrp.Parameters.AddWithValue("@p13", NpgsqlDbType.Text, fileTitle);


                        //Activity part
                        sqlGrp.Parameters.AddWithValue("@a1", NpgsqlDbType.Uuid, activityId);
                        sqlGrp.Parameters.AddWithValue("@a2", NpgsqlDbType.Uuid, deviceUserUuid);
                        sqlGrp.Parameters.AddWithValue("@a3", NpgsqlDbType.Uuid, id);

                        //IPAddress ip = Dns.GetHostEntry(Dns.GetHostName())
                        //                                  .AddressList.(f => f.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork);

                        IPAddress ip = GetIP();

                        var ipStr = Utf16ToUtf8(ip.ToString());
                        sqlGrp.Parameters.AddWithValue("@a4", NpgsqlDbType.Text, ipStr);
                        sqlGrp.Parameters.AddWithValue("@a5", NpgsqlDbType.Enum, ActivityTypes.Action.upload_audio);
                        //Start modified by Prin Sooksong 08/07/2017                    
                        sqlGrp.Parameters.AddWithValue("@a6", NpgsqlDbType.Text, "audios");
                        //End modified by Prin Sooksong 08/07/2017

                        sqlGrp.Prepare();
                        await sqlGrp.ExecuteNonQueryAsync();

                    }
                }

                //write file to ubuntu file system
                //var filestoreRaw = FileStoragePath + @"\" + device.DeviceFileStatisticsModel.DeviceFile.Name;
                //await WriteFile(device, device.DeviceFileStatisticsModel.DeviceFile, FileStoragePath);
                //write file to ubuntu file system
                //var filestoreMp3 = FileStoragePath + @"\" + device.DeviceFileStatisticsModel.DeviceAudioFileTranscoded.Name;
                //await WriteFile(device, device.DeviceFileStatisticsModel.DeviceAudioFileTranscoded, FileStoragePath);

                //delete temp mp3 file
                await StreamEngine.DeleteMP3File(transcoded.Item1);

                    disconnected = false;
                //write log file
                //var taskWriteLog = Task.Run(() => WriteLog("Logs", device, device.DeviceFileStatisticsModel.DeviceFile.Name + "\tUploaded successfully"));
                    WriteLog("Logs", device, device.DeviceFileStatisticsModel.DeviceFile.Name + "\tUploaded successfully");

                    var tupleChecksum = new Tuple<string, byte[]>(device.DeviceFileStatisticsModel.DeviceFile.FullName, fileChecksum);
                    return tupleChecksum;

            }
            catch (Exception e)
            {
                if (e.Message.Contains("duplicate key value"))
                {
                    device.DuplicateFileErrorCount++;

                    disconnected = false;
                    //write log file
                    //var taskWriteLog = Task.Run(() => WriteLog("Logs", device, device.DeviceFileStatisticsModel.DeviceFile.Name + "\tSkipped! File already exists"));
                    WriteLog("Logs", device, device.DeviceFileStatisticsModel.DeviceFile.Name + "\tSkipped! File already exists");

                    //delete duplicate file on samba server
                    FileSystemEngine.DeleteFile(device, FileStoragePath);

                    //Application.Current.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() =>
                    //{
                    //    MessageBox.Show(Application.Current.MainWindow, "Duplicate file '" + device.DeviceFileStatisticsModel.DeviceFile.Name + "' found in camera '" + device.DeviceId + "'.\r\nClick OK to continue.", "", MessageBoxButton.OK, MessageBoxImage.Warning);
                    //}));
                }
                else
                {
                    device.UnknownErrorCount++;

                    disconnected = true;

                    //write log file
                    //var taskWriteLog = Task.Run(() => WriteLog("Logs", device, device.DeviceFileStatisticsModel.DeviceFile.Name + "\t" + e.Message));
                    WriteLog("Logs", device, device.DeviceFileStatisticsModel.DeviceFile.Name + "\t" + e.Message);

                    //Application.Current.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() =>
                    //{
                    //    MessageBox.Show(Application.Current.MainWindow, "Error with camera '" + device.DeviceId + "'.\r\nDescription : " + e.Message + ".\r\nClick OK to continue.", "", MessageBoxButton.OK, MessageBoxImage.Error);
                    //}));

                }

                var tupleChecksum = new Tuple<string, byte[]>(device.DeviceFileStatisticsModel.DeviceFile.FullName, new byte[] { });
                return tupleChecksum;
            }

        }
    }

谢谢。

1 个答案:

答案 0 :(得分:0)

您是否尝试过使用单元测试来测试UI和数据库? 第一件事-您只需要测试应用程序逻辑-并且您必须“信任”外部库。 第二件事-数据层和用户界面层应彼此分开-因此它们不应出现在一项测试中 第三件事-请在函数的参数中使用接口,并包装外部内容以使代码可测试。

例如,您可以使用流利的nhibernate与DB进行集成测试。对于WPF-您不需要使用它-只需测试您的视图模型即可。

上传功能也很难测试-因为您需要将文件加载到某个地方(例如IO,内存...),将其保存在某个地方,并检查文件是否位于正确的位置,并检查文件的内容是否相同-无论有没有UI和DB,对于单元测试来说都是太多了。

您要测试哪种逻辑?