/// <summary> /// Extracts the torrent properties, file/files, size and even the magnet link. /// </summary> /// <param name="torrentFile">The torrent file.</param> /// <returns></returns> public static Tuple <string, string, string> TorrentInfoExtractor(string torrentFile) { var parser = new BencodeParser(); try { torrent = parser.Parse <Torrent>(torrentFile); } catch (Exception) { //add dialog } switch (torrent.FileMode) { case TorrentFileMode.Single: return(Tuple.Create(torrent.File.FileName, logic.TorrentHandler.SizeSuffix(torrent.File.FileSize), torrent.GetMagnetLink())); case TorrentFileMode.Multi: return(Tuple.Create(torrent.Files.DirectoryName, logic.TorrentHandler.SizeSuffix(torrent.TotalSize), torrent.GetMagnetLink())); default: return(Tuple.Create("Not recognized", "Not recognized", "Not recognized")); } }
public bool Prepare() { var query = from el in _context.SoftPosts where el.Id == 85 || el.Id == 132 || el.Id == 311 select el; IList <SoftPost> lst = query.ToList(); var parser = new BencodeParser(); Torrent file0 = parser.Parse <Torrent>(lst[0].TorrentFile); Torrent file1 = parser.Parse <Torrent>(lst[1].TorrentFile); Torrent file2 = parser.Parse <Torrent>(lst[2].TorrentFile); Torrent softFirefox = parser.Parse <Torrent>(@"F:\VS Projects\[Torrent-Soft.Net]_Firefox Browser 81.0.1.torrent"); Torrent nnmFirefox = parser.Parse <Torrent>(@"F:\VS Projects\nnm club firefox.torrent"); Torrent rutorFirefox = parser.Parse <Torrent>(@"F:\VS Projects\rutor firefox.torrent"); var trackers = softFirefox.Trackers.Union(rutorFirefox.Trackers); softFirefox.Trackers = trackers.ToList(); softFirefox.EncodeTo(@"F:\VS Projects\[Custom]rutor and soft firefox.torrent"); return(true); }
public static void printBEnc(string benc) { BencodeParser parser = new BencodeParser(); BDictionary bdic = parser.ParseString <BDictionary>(benc.Trim()); printDicRec(bdic, 0); }
private void ParseBEncodeDict(MemoryStream responseStream) { BencodeParser bParser = new BencodeParser(Encoding.GetEncoding(1252)); if ((ContentEncoding == "gzip") || (ContentEncoding == "x-gzip")) { using (GZipStream stream = new GZipStream(responseStream, CompressionMode.Decompress)) { try { Dico = bParser.Parse <BDictionary>(stream); } catch (Exception) { } } } try { Dico = bParser.Parse <BDictionary>(responseStream); } catch (Exception exception1) { Console.Write(exception1.StackTrace); } }
public static TorrentMetadata ReadTorrentFile(this Stream stream) { stream = stream ?? throw new ArgumentNullException(nameof(stream)); try { var parser = new BencodeParser(); var dict = parser.Parse <BDictionary>(stream); var torrent = new TorrentMetadata(); foreach (var item in dict) { var readableKey = item.Key.ToString(); if (Parsers.TryGetValue(readableKey, out Action <IBObject, TorrentMetadata> action)) { action(item.Value, torrent); } else { torrent.Extensions.Add(readableKey, item.Value); } } return(torrent); } catch (Exception e) { throw new DataMisalignedException("Torrent was not recognized", e); } }
public MainForm() { fileIsDownloading = false; standardParser = new BencodeParser(); if (!RestoreSessionIfPresent()) { filesList = new LinkedList <DownloadingFile>(); } myPeerID = GeneratePeerID(); DownloadingFile.messageHandler = new MessageHandler(400); if (!DownloadingFile.messageHandler.isStarted) { DownloadingFile.messageHandler.Start(); } try { FileWorker.CreateMainSession(); } catch { // cannot create new main session; it won't be saved // old file hasn't been rewritten, so restart the program // in new location or something } nowSelected = null; InitializeComponent(); }
public void InvalidFirstChars_ThrowsInvalidBencodeException(string bencode) { var bparser = new BencodeParser(); Action action = () => bparser.ParseString(bencode); action.ShouldThrow <InvalidBencodeException <IBObject> >(); }
public ExtendedTorrent(string filePath) { var parser = new BencodeParser(); var torrent = parser.Parse <Torrent>(filePath); CopyFields(torrent); }
public Tuple <string, string> TorrentLoader(string torrent_file) { Debug.WriteLine(torrent_file); var parser = new BencodeParser(); try { this.torrent = parser.Parse <Torrent>(torrent_file); } catch (Exception) { //ADD DIALOG } switch (torrent.FileMode) { case TorrentFileMode.Single: return(Tuple.Create(torrent.File.FileName, SizeSuffix(torrent.File.FileSize).ToString())); case TorrentFileMode.Multi: return(Tuple.Create(torrent.Files.DirectoryName, "N/A")); ///FIX SIZE default: return(Tuple.Create("Not recognized", "Not recognized")); } }
public void TorrentInfo_UbuntuFile() { TorrentInfo torrentFile = new TorrentInfo(); torrentFile.Announce = "http://torrent.ubuntu.com:6969/announce"; torrentFile.Comment = "Ubuntu CD releases.ubuntu.com"; torrentFile.PieceLength = 524288; torrentFile.AnnounceList = new System.Collections.Generic.List <string> { "http://torrent.ubuntu.com:6969/announce", "http://ipv6.torrent.ubuntu.com:6969/announce" }; torrentFile.Files = new System.Collections.Generic.List <(string, long)> { ("ubuntu-19.04-desktop-amd64.iso", 2097152000) }; BencodeParser parser = new BencodeParser(_ubuntuFIlePath); TorrentInfo expectedTorrentFile = parser.GetTorrentInfo(); torrentFile.InfoHash = new Sha1Encryptor().GetHash(parser.ReadInfoValue()); Assert.AreEqual(expectedTorrentFile.Announce, torrentFile.Announce); Assert.AreEqual(expectedTorrentFile.Comment, torrentFile.Comment); Assert.AreEqual(expectedTorrentFile.PieceLength, torrentFile.PieceLength); CollectionAssert.AreEqual(expectedTorrentFile.AnnounceList, torrentFile.AnnounceList); CollectionAssert.AreEqual(expectedTorrentFile.Files, expectedTorrentFile.Files); }
public async Task <HttpResponseMessage> Download(string indexerID, string path, string jackett_apikey, string file) { try { var indexer = indexerService.GetWebIndexer(indexerID); if (!indexer.IsConfigured) { logger.Warn(string.Format("Rejected a request to {0} which is unconfigured.", indexer.DisplayName)); return(Request.CreateResponse(HttpStatusCode.Forbidden, "This indexer is not configured.")); } path = Encoding.UTF8.GetString(HttpServerUtility.UrlTokenDecode(path)); path = protectionService.UnProtect(path); if (config.APIKey != jackett_apikey) { return(new HttpResponseMessage(HttpStatusCode.Unauthorized)); } var target = new Uri(path, UriKind.RelativeOrAbsolute); var downloadBytes = await indexer.Download(target); // handle magnet URLs if (downloadBytes.Length >= 7 && downloadBytes[0] == 0x6d && // m downloadBytes[1] == 0x61 && // a downloadBytes[2] == 0x67 && // g downloadBytes[3] == 0x6e && // n downloadBytes[4] == 0x65 && // e downloadBytes[5] == 0x74 && // t downloadBytes[6] == 0x3a // : ) { var magneturi = Encoding.UTF8.GetString(downloadBytes); var response = Request.CreateResponse(HttpStatusCode.Moved); response.Headers.Location = new Uri(magneturi); return(response); } // This will fix torrents where the keys are not sorted, and thereby not supported by Sonarr. var parser = new BencodeParser(); var torrentDictionary = parser.Parse(downloadBytes); byte[] sortedDownloadBytes = torrentDictionary.EncodeAsBytes(); var result = new HttpResponseMessage(HttpStatusCode.OK); result.Content = new ByteArrayContent(sortedDownloadBytes); result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/x-bittorrent"); result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = StringUtil.MakeValidFileName(file, '_', false) + ".torrent" // call MakeValidFileName again to avoid any kind of injection attack }; return(result); } catch (Exception e) { logger.Error(e, "Error downloading " + indexerID + " " + path); return(new HttpResponseMessage(HttpStatusCode.NotFound)); } }
static void Main(string[] args) { string torrentPath = AppDomain.CurrentDomain.BaseDirectory + "a.torrent"; #region BencodeNET // Parse torrent by specifying the file path var parser = new BencodeParser(); // Default encoding is Encoding.UT8F, but you can specify another if you need to //非BT种子文件 会解析异常 var torrent = parser.Parse <Torrent>(torrentPath); string MagnetLink = torrent.GetMagnetLink(MagnetLinkOptions.None); Console.WriteLine(MagnetLink); Console.WriteLine(torrent.CreationDate); #endregion MonoTorrent.Common.Torrent mtorrent = MonoTorrent.Common.Torrent.Load(torrentPath); string link1 = "magnet:?xt=urn:btih:5623641b93b175e9b2c8fb0466427ca59de25d32&dn=SAMA-327r-avi"; string magnetLink = "magnet:?xt=urn:btih:" + BitConverter.ToString(mtorrent.InfoHash.ToArray()).Replace("-", ""); Console.WriteLine(magnetLink); MonoTorrent.MagnetLink link = new MonoTorrent.MagnetLink(link1); Console.WriteLine(link.Name); }
public void TorrentInfo_ViyFile() { TorrentInfo torrentFile = new TorrentInfo(); torrentFile.Announce = "http://bt4.rutracker.org/ann?uk=wa36F12BA3"; torrentFile.Comment = "http://rutracker.org/forum/viewtopic.php?t=4390356"; torrentFile.PieceLength = 262144; torrentFile.AnnounceList = new System.Collections.Generic.List <string> { "http://bt4.rutracker.org/ann?uk=wa36F12BA3", "http://retracker.local/announce" }; torrentFile.Files = new System.Collections.Generic.List <(string, long)> { ("Soft7/DirectX14/dxwebsetup.exe", 299864), ("Soft6/Redist16/vcredist_x86.exe", 4995416), ("Soft6/Redist16/vcredist_x64.exe", 4877648), ("Data.bin", 180935132), ("Setup.exe", 7389257), ("Survivors Viy.ico", 118921), ("autorun.inf", 70), }; BencodeParser parser = new BencodeParser(_viyFilePath); TorrentInfo expectedTorrentFile = parser.GetTorrentInfo(); torrentFile.InfoHash = new Sha1Encryptor().GetHash(parser.ReadInfoValue()); Assert.AreEqual(expectedTorrentFile.Announce, torrentFile.Announce); Assert.AreEqual(expectedTorrentFile.Comment, torrentFile.Comment); Assert.AreEqual(expectedTorrentFile.PieceLength, torrentFile.PieceLength); CollectionAssert.AreEqual(expectedTorrentFile.AnnounceList, torrentFile.AnnounceList); CollectionAssert.AreEqual(expectedTorrentFile.Files, expectedTorrentFile.Files); }
public void EmptyString_ReturnsNull() { var bparser = new BencodeParser(); var result = bparser.ParseString(""); result.Should().BeNull(); }
// Initiates an HTTP request for the torrent // returns a tracker response dictionary containg info on all the peers public Connection(Torrent torrent) { url.Append(torrent.Trackers[0][0].ToString() + "?"); string hash = torrent.GetInfoHash(); hash = Formatter.HashToPercentEncoding(hash); string peerid = GeneratePeerID(); string port = GeneratePort(); string left = torrent.File.FileSize.ToString(); url.Append("info_hash=" + hash + "&"); url.Append("peer_id=" + peerid + "&"); url.Append("port=" + port + "&"); url.Append("left=" + left + "&"); url.Append("uploaded=0&downloaded=0&compact=0&no_peer_id=&event=started"); string URL = url.ToString(); WebClient client = new WebClient(); byte[] databuffer = client.DownloadData(URL); var parser = new BencodeParser(); trackerResponse = parser.Parse <BDictionary>(databuffer); GetPeers(); }
public TorrentParserTests() { BencodeParser = Substitute.For <IBencodeParser>(); BencodeParser.Parse <BDictionary>(null).ReturnsForAnyArgs(x => ParsedData); ValidSingleFileTorrentData = new BDictionary { [TorrentFields.Info] = new BDictionary { [TorrentInfoFields.Name] = (BString)"", [TorrentInfoFields.NameUtf8] = (BString)"", [TorrentInfoFields.Pieces] = (BString)"", [TorrentInfoFields.PieceLength] = (BNumber)0, [TorrentInfoFields.Length] = (BNumber)0 }, }; ValidMultiFileTorrentData = new BDictionary { [TorrentFields.Info] = new BDictionary { [TorrentInfoFields.Name] = (BString)"", [TorrentInfoFields.NameUtf8] = (BString)"", [TorrentInfoFields.Pieces] = (BString)"", [TorrentInfoFields.PieceLength] = (BNumber)0, [TorrentInfoFields.Files] = new BList() }, }; }
private void AddTorrentFileButton_Click(object sender, EventArgs e) { var openfile = new OpenFileDialog { Filter = "Torrent Files|*.torrent", Title = "Select Torrent File" }; openfile.ShowDialog(); var parser = new BencodeParser(); var torrent = parser.Parse <Torrent>(openfile.FileName); var addTorrent = new AddTorrentDialog(); var drive = new DriveInfo("C"); // Formatting Labels ((Label)addTorrent.Controls["TorrentSizeLabel"]).Text = Formatter.BytesToEnglish(torrent.TotalSize) + " (Space Left on drive: " + Formatter.BytesToEnglish(drive.AvailableFreeSpace) + ")"; ((Label)addTorrent.Controls["TorrentDateLabel"]).Text = torrent.CreationDate.ToString(); ((Label)addTorrent.Controls["TorrentHashLabel"]).Text = Formatter.HashFormatter(torrent.GetInfoHash()); ((Label)addTorrent.Controls["TorrentCommentLabel"]).Text = torrent.Comment; // Display Torrent Files in the AddTorrentMenu Window var listview = ((ListView)addTorrent.Controls["FilesList"]); var T = torrent.File; // Only One File Exists if (torrent.Files == null) { var item = new ListViewItem(new string[] { T.FileName, Formatter.BytesToEnglish(T.FileSize), "Normal" }); //var test = item.SubItems; listview.Items.Add(item); item.Checked = true; } // Multiple Files in the torrent else { MultiFileInfoList files = torrent.Files; foreach (MultiFileInfo f in files) { listview.Items.Add(new ListViewItem(new string[] { f.FileName, Formatter.BytesToEnglish(f.FileSize), "Normal" })); } } ((ComboBox)addTorrent.Controls["TorrentDirectory"]).Text = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory); DialogResult result = addTorrent.ShowDialog(); if (result == DialogResult.OK) { var row = new ListViewItem(new string[] { (MainWindowListView.Items.Count + 1).ToString(), T.FileName, Formatter.BytesToEnglish(T.FileSize) }); MainWindowListView.Items.Add(row); row.Selected = true; var test2 = new Connection(torrent); } }
public bool AnnounceTCP(Int32 num_want = -1, Int64 downloaded = 0, Int64 left = 0, Int64 uploaded = 0) { if (!ConnectTCP()) { return(false); } try { byte[] sendBuff = System.Text.Encoding.UTF8.GetBytes($"GET {uri.AbsolutePath}?info_hash={Utils.StringHexToUrlEncode(options.InfoHash)}&peer_id={Utils.StringHexToUrlEncode(BitConverter.ToString(options.PeerId).Replace("-",""))}&port=11111&left={left}&downloaded={downloaded}&uploaded={uploaded}&event=started&compact=1&numwant={num_want} HTTP/1.1\r\nHost: {host}:{port}\r\nConection: close\r\n\r\n"); if (type == Type.HTTP) { netStream.Write(sendBuff, 0, sendBuff.Length); } else { sslStream.Write(sendBuff, 0, sendBuff.Length); } if (!ReceiveTCP()) { return(false); } BencodeParser parser = new BencodeParser(); BDictionary extDic = parser.Parse <BDictionary>(recvBuff); byte[] hashBytes = ((BString)extDic["peers"]).Value.ToArray(); Dictionary <string, int> peers = new Dictionary <string, int>(); for (int i = 0; i < hashBytes.Length; i += 6) { IPAddress curIP = new IPAddress(Utils.ArraySub(ref hashBytes, (uint)i, 4, false)); UInt16 curPort = (UInt16)BitConverter.ToInt16(Utils.ArraySub(ref hashBytes, (uint)i + 4, 2, true), 0); if (curPort > 0) { peers[curIP.ToString()] = curPort; } } if (options.Verbosity > 0) { Log($"Success ({peers.Count} Peers)"); } if (peers.Count > 0) { Beggar.FillPeers(peers, BitSwarm.PeersStorage.TRACKER); } } catch (Exception e) { Log($"Failed {e.Message}\r\n{e.StackTrace}"); return(false); } return(true); }
public void CalculateInfoHash_CompleteTorrentFile() { var bdictionary = new BencodeParser().Parse <BDictionary>(UbuntuTorrentFile); var info = bdictionary.Get <BDictionary>(TorrentFields.Info); var hash = TorrentUtil.CalculateInfoHash(info); hash.Should().Be("B415C913643E5FF49FE37D304BBB5E6E11AD5101"); }
public void FirstCharDigit_CallsStringParser(string bencode, IBObjectParser<BString> stringParser) { var bparser = new BencodeParser(); bparser.Parsers.AddOrReplace(stringParser); bparser.ParseString(bencode); stringParser.Received(1).Parse(Arg.Any<BencodeStream>()); }
public void CalculateInfoHash_CompleteTorrentFile() { var bdictionary = new BencodeParser().Parse<BDictionary>(UbuntuTorrentFile); var info = bdictionary.Get<BDictionary>(TorrentFields.Info); var hash = TorrentUtil.CalculateInfoHash(info); hash.Should().Be("B415C913643E5FF49FE37D304BBB5E6E11AD5101"); }
public PodHandler(Stream inputStream, Stream outputStream) { _inputStream = inputStream; _outputStream = outputStream; _reader = PipeReader.Create(inputStream); _writer = PipeWriter.Create(outputStream, new StreamPipeWriterOptions(leaveOpen: true)); _parser = new BencodeParser(); }
private void BtnZipIt_Click(object sender, RoutedEventArgs e) { string[] torrentFiles = Directory.GetFiles(torrentFolder); var parser = new BencodeParser(); // Default encoding is Encoding.UTF8, but you can specify another if you need to ConcurrentBag <string> matchingTorrents = new ConcurrentBag <string>(); //foreach (string torrentFile in torrentFiles) Parallel.ForEach(torrentFiles, new ParallelOptions { }, (torrentFile, loopState) => // foreach (string srcFileName in filesInSourceFolder) { Torrent torrent; // Parse torrent by specifying the file path try { torrent = parser.Parse <Torrent>(torrentFile); } catch (Exception) { return; } // Calculate the info hash string infoHash = torrent.GetInfoHash(); int index = Array.FindIndex(hashes, t => t.Trim().Equals(infoHash, StringComparison.InvariantCultureIgnoreCase)); if (index != -1) { matchingTorrents.Add(torrentFile); } }); if (matchingTorrents.Count == 0) { MessageBox.Show("No matching torrents found."); } else { SaveFileDialog sfd = new SaveFileDialog(); sfd.Filter = "Zip file (.zip)|*.zip"; sfd.Title = "Where to save .zip file of matching torrents?"; if (sfd.ShowDialog() == true) { using (ZipFile zip = new ZipFile()) { foreach (string matchingTorrentFile in matchingTorrents) { zip.AddFile(matchingTorrentFile, ""); } zip.Save(sfd.FileName); } } } }
public void FirstChar_L_CallsNumberParser(string bencode, IBObjectParser <BList> listParser) { var bparser = new BencodeParser(); bparser.Parsers.AddOrReplace(listParser); bparser.ParseString(bencode); listParser.Received(1).Parse(Arg.Any <BencodeStream>()); }
public void ComputeInfoHash_ViyFile() { BencodeParser parser = new BencodeParser(_viyFilePath); TorrentInfo torrentFile = new TorrentInfo(); torrentFile.InfoHash = new Sha1Encryptor().GetHash(parser.ReadInfoValue()); Assert.AreEqual("FA96C95C4DD0174BEC025A78ABEB6AC286A757BA", torrentFile.InfoHash); }
public void FirstCharDigit_CallsStringParser(string bencode, IBObjectParser <BString> stringParser) { var bparser = new BencodeParser(); bparser.Parsers.AddOrReplace(stringParser); bparser.ParseString(bencode); stringParser.Received(1).Parse(Arg.Any <BencodeStream>()); }
public void FirstChar_D_CallsNumberParser(string bencode, IBObjectParser <BDictionary> dictionaryParser) { var bparser = new BencodeParser(); bparser.Parsers.AddOrReplace(dictionaryParser); bparser.ParseString(bencode); dictionaryParser.Received(1).Parse(Arg.Any <BencodeStream>()); }
public void ComputeInfoHash_UbuntuFile() { BencodeParser parser = new BencodeParser(_ubuntuFIlePath); TorrentInfo torrentFile = new TorrentInfo(); torrentFile.InfoHash = new Sha1Encryptor().GetHash(parser.ReadInfoValue()); Assert.AreEqual("D540FC48EB12F2833163EED6421D449DD8F1CE1F", torrentFile.InfoHash); }
private void AddTorrent_Load(object sender, EventArgs e) { List <string> SavePathsList = WebWorker.GetSavePaths(); foreach (string SavePath in SavePathsList) { SavePathComboBox.Items.Add(SavePath); } if (Properties.Settings.Default.DefaultSavePath == String.Empty) { SavePathComboBox.Text = SavePathsList[0]; } else { SavePathComboBox.Text = Properties.Settings.Default.DefaultSavePath; } List <string> CategoriesList = WebWorker.GetCategories(); foreach (string Category in CategoriesList) { CategoriesComboBox.Items.Add(Category); } if (Properties.Settings.Default.DefaultCategory != String.Empty) { CategoriesComboBox.Text = Properties.Settings.Default.DefaultCategory; } BencodeParser TorrentParser = new BencodeParser(); Torrent ParsedTorrent = TorrentParser.Parse <Torrent>(TorrentFilePath); this.Text = ParsedTorrent.DisplayName; Sizelbl.Text = "Size: " + SizeConverter.SizeSuffix(ParsedTorrent.TotalSize); Datelbl.Text = "Date: " + ParsedTorrent.CreationDate; Hashlbl.Text = "Hash: " + ParsedTorrent.OriginalInfoHash.ToLower(); /*Uri uriResult; * if (Uri.TryCreate(ParsedTorrent.Comment, UriKind.Absolute, out uriResult) && (uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps)) * Console.WriteLine("LINK");*/ Commentlbl.Text = "Comment: " + ParsedTorrent.Comment; if (ParsedTorrent.File == null) { Console.WriteLine(ParsedTorrent.Files); } else if (ParsedTorrent.Files == null) { Console.WriteLine(ParsedTorrent.File); } }
public TorrentDownloader(string filePath) { if (!File.Exists(filePath)) { throw new FileNotFoundException("File not found: " + filePath); //uh oh } this.BCodeParser = new BencodeParser(); this.TorrentFile = BCodeParser.Parse <Torrent>(filePath); this.TrackerManager = new TrackerManager(this.TorrentFile); }
public TorrentFile(string fileName) { BencodeParser parser = new BencodeParser(); Torrent = parser.Parse <Torrent>(fileName); if (Torrent.Trackers.Any()) { Announce = Torrent.Trackers.First().FirstOrDefault(); } }
private string GetMagnetLink(string path) { var parser = new BencodeParser(); Torrent torrent = parser.Parse <Torrent>(path); // Calculate the info hash //string infoHash = torrent.GetInfoHash(); //byte[] infoHashBytes = torrent.GetInfoHashBytes(); string magnetLink = torrent.GetMagnetLink(); return(magnetLink); }
public void CanParse_ListOfStrings() { var bencode = "l4:spam3:egge"; var bparser = new BencodeParser(); var blist = bparser.ParseString(bencode) as BList; blist.Should().HaveCount(2); blist[0].Should().BeOfType<BString>(); blist[0].Should().Be((BString)"spam"); blist[1].Should().BeOfType<BString>(); blist[1].Should().Be((BString)"egg"); }
public void CanParse_SimpleDictionary() { var bencode = "d4:spam3:egg3:fooi42ee"; var bparser = new BencodeParser(); var bdictionary = bparser.ParseString<BDictionary>(bencode); bdictionary.Should().HaveCount(2); bdictionary.Should().ContainKey("spam"); bdictionary.Should().ContainKey("foo"); bdictionary["spam"].Should().BeOfType(typeof (BString)); bdictionary["spam"].Should().Be((BString) "egg"); bdictionary["foo"].Should().BeOfType(typeof (BNumber)); bdictionary["foo"].Should().Be((BNumber) 42); }
public void FirstChar_L_CallsNumberParser(string bencode, IBObjectParser<BList> listParser) { var bparser = new BencodeParser(); bparser.Parsers.AddOrReplace(listParser); bparser.ParseString(bencode); listParser.Received(1).Parse(Arg.Any<BencodeStream>()); }
public void InvalidFirstChars_ThrowsInvalidBencodeException(string bencode) { var bparser = new BencodeParser(); Action action = () => bparser.ParseString(bencode); action.ShouldThrow<InvalidBencodeException<IBObject>>(); }
public void FirstChar_D_CallsNumberParser(string bencode, IBObjectParser<BDictionary> dictionaryParser) { var bparser = new BencodeParser(); bparser.Parsers.AddOrReplace(dictionaryParser); bparser.ParseString(bencode); dictionaryParser.Received(1).Parse(Arg.Any<BencodeStream>()); }